From 85fd81cc51051266d6e2f920f868b703b6e00181 Mon Sep 17 00:00:00 2001 From: wilsonge Date: Thu, 8 May 2014 17:09:26 +0100 Subject: [PATCH] Forgot to add new files --- libraries/autoload.php | 7 + libraries/composer/ClassLoader.php | 378 ++ libraries/composer/autoload_classmap.php | 14 + libraries/composer/autoload_files.php | 10 + libraries/composer/autoload_namespaces.php | 10 + libraries/composer/autoload_psr4.php | 17 + libraries/composer/autoload_real.php | 58 + libraries/composer/installed.json | 359 ++ .../ircmaxell/password-compat/.travis.yml | 8 + .../ircmaxell/password-compat/LICENSE.md | 7 + libraries/ircmaxell/password-compat/README.md | 75 + .../ircmaxell/password-compat/composer.json | 18 + .../password-compat/lib/password.php | 222 ++ .../password-compat/phpunit.xml.dist | 29 + .../test/Unit/PasswordGetInfoTest.php | 26 + .../test/Unit/PasswordHashTest.php | 84 + .../test/Unit/PasswordNeedsRehashTest.php | 26 + .../test/Unit/PasswordVerifyTest.php | 29 + .../password-compat/version-test.php | 8 + libraries/joomla/compat/LICENSE | 340 ++ libraries/joomla/compat/README.md | 53 + libraries/joomla/compat/composer.json | 14 + .../joomla/compat/src/JsonSerializable.php | 26 + libraries/joomla/di/LICENSE | 340 ++ libraries/joomla/di/README.md | 431 +++ libraries/joomla/di/Tests/ContainerTest.php | 949 +++++ libraries/joomla/di/Tests/Stubs/stubs.php | 81 + libraries/joomla/di/composer.json | 17 + .../di/docs/why-dependency-injection.md | 175 + libraries/joomla/di/phpunit.xml.dist | 8 + libraries/joomla/di/src/Container.php | 428 +++ .../joomla/di/src/ContainerAwareInterface.php | 39 + .../joomla/di/src/ContainerAwareTrait.php | 64 + .../DependencyResolutionException.php | 18 + .../di/src/ServiceProviderInterface.php | 28 + libraries/joomla/registry/LICENSE | 340 ++ libraries/joomla/registry/README.md | 279 ++ .../joomla/registry/Tests/FormatTest.php | 69 + .../joomla/registry/Tests/RegistryTest.php | 749 ++++ .../joomla/registry/Tests/Stubs/jregistry.ini | 2 + .../registry/Tests/Stubs/jregistry.json | 3 + .../registry/Tests/format/FormatIniTest.php | 112 + .../registry/Tests/format/FormatJsonTest.php | 121 + .../registry/Tests/format/FormatPhpTest.php | 73 + .../registry/Tests/format/FormatXmlTest.php | 111 + .../registry/Tests/format/FormatYamlTest.php | 161 + libraries/joomla/registry/composer.json | 26 + libraries/joomla/registry/phpunit.xml.dist | 8 + .../registry/src/AbstractRegistryFormat.php | 79 + libraries/joomla/registry/src/Format/Ini.php | 238 ++ libraries/joomla/registry/src/Format/Json.php | 63 + libraries/joomla/registry/src/Format/Php.php | 111 + libraries/joomla/registry/src/Format/Xml.php | 164 + libraries/joomla/registry/src/Format/Yaml.php | 86 + libraries/joomla/registry/src/Registry.php | 538 +++ libraries/joomla/string/LICENSE | 340 ++ libraries/joomla/string/README.md | 22 + .../joomla/string/Tests/InflectorTest.php | 513 +++ .../joomla/string/Tests/NormaliseTest.php | 314 ++ libraries/joomla/string/Tests/StringTest.php | 1000 +++++ libraries/joomla/string/composer.json | 20 + libraries/joomla/string/phpunit.xml.dist | 8 + libraries/joomla/string/src/Inflector.php | 468 +++ libraries/joomla/string/src/Normalise.php | 162 + libraries/joomla/string/src/String.php | 945 +++++ libraries/joomla/string/src/phputf8/LICENSE | 504 +++ libraries/joomla/string/src/phputf8/README | 82 + .../string/src/phputf8/mbstring/core.php | 132 + .../joomla/string/src/phputf8/native/core.php | 430 +++ libraries/joomla/string/src/phputf8/ord.php | 90 + .../string/src/phputf8/str_ireplace.php | 77 + .../joomla/string/src/phputf8/str_pad.php | 54 + .../joomla/string/src/phputf8/str_split.php | 32 + .../joomla/string/src/phputf8/strcasecmp.php | 23 + .../joomla/string/src/phputf8/strcspn.php | 38 + .../joomla/string/src/phputf8/stristr.php | 35 + .../joomla/string/src/phputf8/strrev.php | 19 + .../joomla/string/src/phputf8/strspn.php | 38 + .../string/src/phputf8/substr_replace.php | 22 + libraries/joomla/string/src/phputf8/trim.php | 63 + .../joomla/string/src/phputf8/ucfirst.php | 31 + .../joomla/string/src/phputf8/ucwords.php | 40 + libraries/joomla/string/src/phputf8/utf8.php | 74 + .../joomla/string/src/phputf8/utils/ascii.php | 214 ++ .../joomla/string/src/phputf8/utils/bad.php | 406 ++ .../string/src/phputf8/utils/patterns.php | 64 + .../string/src/phputf8/utils/position.php | 168 + .../string/src/phputf8/utils/specials.php | 126 + .../string/src/phputf8/utils/unicode.php | 265 ++ .../string/src/phputf8/utils/validation.php | 181 + libraries/joomla/utilities/LICENSE | 340 ++ libraries/joomla/utilities/README.md | 381 ++ .../utilities/Tests/ArrayHelperTest.php | 1686 +++++++++ libraries/joomla/utilities/composer.json | 18 + libraries/joomla/utilities/phpunit.xml.dist | 8 + .../joomla/utilities/src/ArrayHelper.php | 577 +++ libraries/phpmailer/phpmailer/.gitignore | 4 + libraries/phpmailer/phpmailer/.travis.yml | 20 + libraries/phpmailer/phpmailer/LICENSE | 504 +++ .../phpmailer/phpmailer/PHPMailerAutoload.php | 33 + libraries/phpmailer/phpmailer/README.md | 134 + libraries/phpmailer/phpmailer/changelog.md | 540 +++ .../phpmailer/phpmailer/class.phpmailer.php | 3268 +++++++++++++++++ libraries/phpmailer/phpmailer/class.pop3.php | 419 +++ libraries/phpmailer/phpmailer/class.smtp.php | 943 +++++ libraries/phpmailer/phpmailer/composer.json | 33 + .../docs/Callback_function_notes.txt | 17 + .../phpmailer/docs/DomainKeys_notes.txt | 55 + .../docs/Note_for_SMTP_debugging.txt | 17 + .../phpmailer/phpmailer/docs/extending.html | 145 + libraries/phpmailer/phpmailer/docs/faq.html | 67 + .../phpmailer/phpmailer/docs/generatedocs.sh | 5 + .../phpmailer/phpmailer/docs/pop3_article.txt | 50 + .../phpmailer/phpmailer/examples/LGPLv3.txt | 165 + .../phpmailer/examples/code_generator.phps | 596 +++ .../phpmailer/examples/contents.html | 17 + .../phpmailer/examples/exceptions.phps | 41 + .../phpmailer/phpmailer/examples/gmail.phps | 63 + .../phpmailer/examples/images/phpmailer.png | Bin 0 -> 8670 bytes .../examples/images/phpmailer_mini.gif | Bin 0 -> 1042 bytes .../phpmailer/phpmailer/examples/index.html | 45 + .../phpmailer/phpmailer/examples/mail.phps | 37 + .../phpmailer/examples/mailing_list.phps | 51 + .../phpmailer/examples/pop_before_smtp.phps | 60 + .../phpmailer/examples/scripts/XRegExp.js | 664 ++++ .../examples/scripts/shAutoloader.js | 122 + .../phpmailer/examples/scripts/shBrushPhp.js | 72 + .../phpmailer/examples/scripts/shCore.js | 1 + .../phpmailer/examples/scripts/shLegacy.js | 141 + .../phpmailer/examples/sendmail.phps | 39 + .../phpmailer/phpmailer/examples/smtp.phps | 61 + .../phpmailer/examples/smtp_no_auth.phps | 57 + .../phpmailer/examples/styles/shCore.css | 46 + .../examples/styles/shCoreDefault.css | 77 + .../examples/styles/shCoreDjango.css | 78 + .../examples/styles/shCoreEclipse.css | 80 + .../phpmailer/examples/styles/shCoreEmacs.css | 76 + .../examples/styles/shCoreFadeToGrey.css | 77 + .../examples/styles/shCoreMDUltra.css | 76 + .../examples/styles/shCoreMidnight.css | 76 + .../phpmailer/examples/styles/shCoreRDark.css | 76 + .../examples/styles/shThemeAppleScript.css | 21 + .../examples/styles/shThemeDefault.css | 31 + .../examples/styles/shThemeDjango.css | 32 + .../examples/styles/shThemeEclipse.css | 34 + .../examples/styles/shThemeEmacs.css | 30 + .../examples/styles/shThemeFadeToGrey.css | 31 + .../examples/styles/shThemeMDUltra.css | 30 + .../examples/styles/shThemeMidnight.css | 30 + .../examples/styles/shThemeRDark.css | 30 + .../examples/styles/shThemeVisualStudio.css | 31 + .../phpmailer/examples/styles/wrapping.png | Bin 0 -> 631 bytes .../phpmailer/extras/EasyPeasyICS.php | 90 + .../phpmailer/extras/class.html2text.php | 696 ++++ .../phpmailer/phpmailer/extras/htmlfilter.php | 861 +++++ .../phpmailer/extras/ntlm_sasl_client.php | 185 + .../phpmailer/language/phpmailer.lang-ar.php | 26 + .../phpmailer/language/phpmailer.lang-br.php | 26 + .../phpmailer/language/phpmailer.lang-ca.php | 25 + .../phpmailer/language/phpmailer.lang-ch.php | 25 + .../phpmailer/language/phpmailer.lang-cz.php | 24 + .../phpmailer/language/phpmailer.lang-de.php | 24 + .../phpmailer/language/phpmailer.lang-dk.php | 25 + .../phpmailer/language/phpmailer.lang-eo.php | 24 + .../phpmailer/language/phpmailer.lang-es.php | 26 + .../phpmailer/language/phpmailer.lang-et.php | 26 + .../phpmailer/language/phpmailer.lang-fa.php | 25 + .../phpmailer/language/phpmailer.lang-fi.php | 26 + .../phpmailer/language/phpmailer.lang-fo.php | 26 + .../phpmailer/language/phpmailer.lang-fr.php | 29 + .../phpmailer/language/phpmailer.lang-he.php | 25 + .../phpmailer/language/phpmailer.lang-hu.php | 24 + .../phpmailer/language/phpmailer.lang-it.php | 26 + .../phpmailer/language/phpmailer.lang-ja.php | 26 + .../phpmailer/language/phpmailer.lang-lt.php | 24 + .../phpmailer/language/phpmailer.lang-nl.php | 24 + .../phpmailer/language/phpmailer.lang-no.php | 24 + .../phpmailer/language/phpmailer.lang-pl.php | 24 + .../phpmailer/language/phpmailer.lang-ro.php | 26 + .../phpmailer/language/phpmailer.lang-ru.php | 24 + .../phpmailer/language/phpmailer.lang-se.php | 25 + .../phpmailer/language/phpmailer.lang-sk.php | 25 + .../phpmailer/language/phpmailer.lang-tr.php | 26 + .../phpmailer/language/phpmailer.lang-uk.php | 24 + .../phpmailer/language/phpmailer.lang-zh.php | 25 + .../language/phpmailer.lang-zh_cn.php | 25 + .../phpmailer/phpmailer/test/fakepopserver.sh | 125 + .../phpmailer/phpmailer/test/fakesendmail.sh | 22 + .../phpmailer/test/phpmailerLangTest.php | 340 ++ .../phpmailer/test/phpmailerTest.php | 1402 +++++++ .../phpmailer/test/runfakepopserver.sh | 10 + .../phpmailer/test/test_callback.php | 82 + .../phpmailer/test/testbootstrap-dist.php | 7 + .../yaml/Symfony/Component/Yaml/.gitignore | 3 + .../yaml/Symfony/Component/Yaml/CHANGELOG.md | 8 + .../yaml/Symfony/Component/Yaml/Dumper.php | 73 + .../yaml/Symfony/Component/Yaml/Escaper.php | 89 + .../Yaml/Exception/DumpException.php | 23 + .../Yaml/Exception/ExceptionInterface.php | 23 + .../Yaml/Exception/ParseException.php | 148 + .../Yaml/Exception/RuntimeException.php | 23 + .../yaml/Symfony/Component/Yaml/Inline.php | 469 +++ .../yaml/Symfony/Component/Yaml/LICENSE | 19 + .../yaml/Symfony/Component/Yaml/Parser.php | 638 ++++ .../yaml/Symfony/Component/Yaml/README.md | 19 + .../Component/Yaml/Tests/DumperTest.php | 207 ++ .../Yaml/Tests/Fixtures/YtsAnchorAlias.yml | 31 + .../Yaml/Tests/Fixtures/YtsBasicTests.yml | 178 + .../Yaml/Tests/Fixtures/YtsBlockMapping.yml | 51 + .../Tests/Fixtures/YtsDocumentSeparator.yml | 85 + .../Yaml/Tests/Fixtures/YtsErrorTests.yml | 25 + .../Tests/Fixtures/YtsFlowCollections.yml | 60 + .../Yaml/Tests/Fixtures/YtsFoldedScalars.yml | 176 + .../Tests/Fixtures/YtsNullsAndEmpties.yml | 45 + .../Fixtures/YtsSpecificationExamples.yml | 1695 +++++++++ .../Yaml/Tests/Fixtures/YtsTypeTransfers.yml | 244 ++ .../Yaml/Tests/Fixtures/embededPhp.yml | 1 + .../Yaml/Tests/Fixtures/escapedCharacters.yml | 147 + .../Component/Yaml/Tests/Fixtures/index.yml | 18 + .../Yaml/Tests/Fixtures/sfComments.yml | 65 + .../Yaml/Tests/Fixtures/sfCompact.yml | 159 + .../Yaml/Tests/Fixtures/sfMergeKey.yml | 27 + .../Yaml/Tests/Fixtures/sfObjects.yml | 11 + .../Yaml/Tests/Fixtures/sfQuotes.yml | 33 + .../Component/Yaml/Tests/Fixtures/sfTests.yml | 135 + .../Tests/Fixtures/unindentedCollections.yml | 62 + .../Component/Yaml/Tests/InlineTest.php | 231 ++ .../Yaml/Tests/ParseExceptionTest.php | 30 + .../Component/Yaml/Tests/ParserTest.php | 619 ++++ .../Symfony/Component/Yaml/Tests/YamlTest.php | 31 + .../yaml/Symfony/Component/Yaml/Unescaper.php | 146 + .../yaml/Symfony/Component/Yaml/Yaml.php | 100 + .../yaml/Symfony/Component/Yaml/composer.json | 31 + .../Symfony/Component/Yaml/phpunit.xml.dist | 29 + 234 files changed, 37968 insertions(+) create mode 100644 libraries/autoload.php create mode 100644 libraries/composer/ClassLoader.php create mode 100644 libraries/composer/autoload_classmap.php create mode 100644 libraries/composer/autoload_files.php create mode 100644 libraries/composer/autoload_namespaces.php create mode 100644 libraries/composer/autoload_psr4.php create mode 100644 libraries/composer/autoload_real.php create mode 100644 libraries/composer/installed.json create mode 100644 libraries/ircmaxell/password-compat/.travis.yml create mode 100644 libraries/ircmaxell/password-compat/LICENSE.md create mode 100644 libraries/ircmaxell/password-compat/README.md create mode 100644 libraries/ircmaxell/password-compat/composer.json create mode 100644 libraries/ircmaxell/password-compat/lib/password.php create mode 100644 libraries/ircmaxell/password-compat/phpunit.xml.dist create mode 100644 libraries/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php create mode 100644 libraries/ircmaxell/password-compat/test/Unit/PasswordHashTest.php create mode 100644 libraries/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php create mode 100644 libraries/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php create mode 100644 libraries/ircmaxell/password-compat/version-test.php create mode 100644 libraries/joomla/compat/LICENSE create mode 100644 libraries/joomla/compat/README.md create mode 100644 libraries/joomla/compat/composer.json create mode 100644 libraries/joomla/compat/src/JsonSerializable.php create mode 100644 libraries/joomla/di/LICENSE create mode 100644 libraries/joomla/di/README.md create mode 100644 libraries/joomla/di/Tests/ContainerTest.php create mode 100644 libraries/joomla/di/Tests/Stubs/stubs.php create mode 100644 libraries/joomla/di/composer.json create mode 100644 libraries/joomla/di/docs/why-dependency-injection.md create mode 100644 libraries/joomla/di/phpunit.xml.dist create mode 100644 libraries/joomla/di/src/Container.php create mode 100644 libraries/joomla/di/src/ContainerAwareInterface.php create mode 100644 libraries/joomla/di/src/ContainerAwareTrait.php create mode 100644 libraries/joomla/di/src/Exception/DependencyResolutionException.php create mode 100644 libraries/joomla/di/src/ServiceProviderInterface.php create mode 100644 libraries/joomla/registry/LICENSE create mode 100644 libraries/joomla/registry/README.md create mode 100644 libraries/joomla/registry/Tests/FormatTest.php create mode 100644 libraries/joomla/registry/Tests/RegistryTest.php create mode 100644 libraries/joomla/registry/Tests/Stubs/jregistry.ini create mode 100644 libraries/joomla/registry/Tests/Stubs/jregistry.json create mode 100644 libraries/joomla/registry/Tests/format/FormatIniTest.php create mode 100644 libraries/joomla/registry/Tests/format/FormatJsonTest.php create mode 100644 libraries/joomla/registry/Tests/format/FormatPhpTest.php create mode 100644 libraries/joomla/registry/Tests/format/FormatXmlTest.php create mode 100644 libraries/joomla/registry/Tests/format/FormatYamlTest.php create mode 100644 libraries/joomla/registry/composer.json create mode 100644 libraries/joomla/registry/phpunit.xml.dist create mode 100644 libraries/joomla/registry/src/AbstractRegistryFormat.php create mode 100644 libraries/joomla/registry/src/Format/Ini.php create mode 100644 libraries/joomla/registry/src/Format/Json.php create mode 100644 libraries/joomla/registry/src/Format/Php.php create mode 100644 libraries/joomla/registry/src/Format/Xml.php create mode 100644 libraries/joomla/registry/src/Format/Yaml.php create mode 100644 libraries/joomla/registry/src/Registry.php create mode 100644 libraries/joomla/string/LICENSE create mode 100644 libraries/joomla/string/README.md create mode 100644 libraries/joomla/string/Tests/InflectorTest.php create mode 100644 libraries/joomla/string/Tests/NormaliseTest.php create mode 100644 libraries/joomla/string/Tests/StringTest.php create mode 100644 libraries/joomla/string/composer.json create mode 100644 libraries/joomla/string/phpunit.xml.dist create mode 100644 libraries/joomla/string/src/Inflector.php create mode 100644 libraries/joomla/string/src/Normalise.php create mode 100644 libraries/joomla/string/src/String.php create mode 100644 libraries/joomla/string/src/phputf8/LICENSE create mode 100644 libraries/joomla/string/src/phputf8/README create mode 100644 libraries/joomla/string/src/phputf8/mbstring/core.php create mode 100644 libraries/joomla/string/src/phputf8/native/core.php create mode 100644 libraries/joomla/string/src/phputf8/ord.php create mode 100644 libraries/joomla/string/src/phputf8/str_ireplace.php create mode 100644 libraries/joomla/string/src/phputf8/str_pad.php create mode 100644 libraries/joomla/string/src/phputf8/str_split.php create mode 100644 libraries/joomla/string/src/phputf8/strcasecmp.php create mode 100644 libraries/joomla/string/src/phputf8/strcspn.php create mode 100644 libraries/joomla/string/src/phputf8/stristr.php create mode 100644 libraries/joomla/string/src/phputf8/strrev.php create mode 100644 libraries/joomla/string/src/phputf8/strspn.php create mode 100644 libraries/joomla/string/src/phputf8/substr_replace.php create mode 100644 libraries/joomla/string/src/phputf8/trim.php create mode 100644 libraries/joomla/string/src/phputf8/ucfirst.php create mode 100644 libraries/joomla/string/src/phputf8/ucwords.php create mode 100644 libraries/joomla/string/src/phputf8/utf8.php create mode 100644 libraries/joomla/string/src/phputf8/utils/ascii.php create mode 100644 libraries/joomla/string/src/phputf8/utils/bad.php create mode 100644 libraries/joomla/string/src/phputf8/utils/patterns.php create mode 100644 libraries/joomla/string/src/phputf8/utils/position.php create mode 100644 libraries/joomla/string/src/phputf8/utils/specials.php create mode 100644 libraries/joomla/string/src/phputf8/utils/unicode.php create mode 100644 libraries/joomla/string/src/phputf8/utils/validation.php create mode 100644 libraries/joomla/utilities/LICENSE create mode 100644 libraries/joomla/utilities/README.md create mode 100644 libraries/joomla/utilities/Tests/ArrayHelperTest.php create mode 100644 libraries/joomla/utilities/composer.json create mode 100644 libraries/joomla/utilities/phpunit.xml.dist create mode 100644 libraries/joomla/utilities/src/ArrayHelper.php create mode 100644 libraries/phpmailer/phpmailer/.gitignore create mode 100644 libraries/phpmailer/phpmailer/.travis.yml create mode 100644 libraries/phpmailer/phpmailer/LICENSE create mode 100644 libraries/phpmailer/phpmailer/PHPMailerAutoload.php create mode 100644 libraries/phpmailer/phpmailer/README.md create mode 100644 libraries/phpmailer/phpmailer/changelog.md create mode 100644 libraries/phpmailer/phpmailer/class.phpmailer.php create mode 100644 libraries/phpmailer/phpmailer/class.pop3.php create mode 100644 libraries/phpmailer/phpmailer/class.smtp.php create mode 100644 libraries/phpmailer/phpmailer/composer.json create mode 100644 libraries/phpmailer/phpmailer/docs/Callback_function_notes.txt create mode 100644 libraries/phpmailer/phpmailer/docs/DomainKeys_notes.txt create mode 100644 libraries/phpmailer/phpmailer/docs/Note_for_SMTP_debugging.txt create mode 100644 libraries/phpmailer/phpmailer/docs/extending.html create mode 100644 libraries/phpmailer/phpmailer/docs/faq.html create mode 100644 libraries/phpmailer/phpmailer/docs/generatedocs.sh create mode 100644 libraries/phpmailer/phpmailer/docs/pop3_article.txt create mode 100644 libraries/phpmailer/phpmailer/examples/LGPLv3.txt create mode 100644 libraries/phpmailer/phpmailer/examples/code_generator.phps create mode 100644 libraries/phpmailer/phpmailer/examples/contents.html create mode 100644 libraries/phpmailer/phpmailer/examples/exceptions.phps create mode 100644 libraries/phpmailer/phpmailer/examples/gmail.phps create mode 100644 libraries/phpmailer/phpmailer/examples/images/phpmailer.png create mode 100644 libraries/phpmailer/phpmailer/examples/images/phpmailer_mini.gif create mode 100644 libraries/phpmailer/phpmailer/examples/index.html create mode 100644 libraries/phpmailer/phpmailer/examples/mail.phps create mode 100644 libraries/phpmailer/phpmailer/examples/mailing_list.phps create mode 100644 libraries/phpmailer/phpmailer/examples/pop_before_smtp.phps create mode 100644 libraries/phpmailer/phpmailer/examples/scripts/XRegExp.js create mode 100644 libraries/phpmailer/phpmailer/examples/scripts/shAutoloader.js create mode 100644 libraries/phpmailer/phpmailer/examples/scripts/shBrushPhp.js create mode 100644 libraries/phpmailer/phpmailer/examples/scripts/shCore.js create mode 100644 libraries/phpmailer/phpmailer/examples/scripts/shLegacy.js create mode 100644 libraries/phpmailer/phpmailer/examples/sendmail.phps create mode 100644 libraries/phpmailer/phpmailer/examples/smtp.phps create mode 100644 libraries/phpmailer/phpmailer/examples/smtp_no_auth.phps create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCore.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreDefault.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreDjango.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreEclipse.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreEmacs.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreFadeToGrey.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreMDUltra.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreMidnight.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shCoreRDark.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeAppleScript.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeDefault.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeDjango.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeEclipse.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeEmacs.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeFadeToGrey.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeMDUltra.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeMidnight.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeRDark.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/shThemeVisualStudio.css create mode 100644 libraries/phpmailer/phpmailer/examples/styles/wrapping.png create mode 100644 libraries/phpmailer/phpmailer/extras/EasyPeasyICS.php create mode 100644 libraries/phpmailer/phpmailer/extras/class.html2text.php create mode 100644 libraries/phpmailer/phpmailer/extras/htmlfilter.php create mode 100644 libraries/phpmailer/phpmailer/extras/ntlm_sasl_client.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-ar.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-br.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-ca.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-ch.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-cz.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-de.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-dk.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-eo.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-es.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-et.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-fa.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-fi.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-fo.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-fr.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-he.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-hu.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-it.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-ja.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-lt.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-nl.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-no.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-pl.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-ro.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-ru.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-se.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-sk.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-tr.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-uk.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-zh.php create mode 100644 libraries/phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php create mode 100644 libraries/phpmailer/phpmailer/test/fakepopserver.sh create mode 100644 libraries/phpmailer/phpmailer/test/fakesendmail.sh create mode 100644 libraries/phpmailer/phpmailer/test/phpmailerLangTest.php create mode 100644 libraries/phpmailer/phpmailer/test/phpmailerTest.php create mode 100644 libraries/phpmailer/phpmailer/test/runfakepopserver.sh create mode 100644 libraries/phpmailer/phpmailer/test/test_callback.php create mode 100644 libraries/phpmailer/phpmailer/test/testbootstrap-dist.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/.gitignore create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/CHANGELOG.md create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Dumper.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Escaper.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Exception/DumpException.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Exception/ExceptionInterface.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Exception/ParseException.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Exception/RuntimeException.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Inline.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/LICENSE create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Parser.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/README.md create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/DumperTest.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsAnchorAlias.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsBasicTests.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsBlockMapping.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsDocumentSeparator.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsErrorTests.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsFlowCollections.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsFoldedScalars.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsNullsAndEmpties.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsSpecificationExamples.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsTypeTransfers.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/embededPhp.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/escapedCharacters.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/index.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/sfComments.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/sfCompact.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/sfMergeKey.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/sfObjects.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/sfQuotes.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/sfTests.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/Fixtures/unindentedCollections.yml create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/InlineTest.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/ParseExceptionTest.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/ParserTest.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Tests/YamlTest.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Unescaper.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/Yaml.php create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/composer.json create mode 100644 libraries/symfony/yaml/Symfony/Component/Yaml/phpunit.xml.dist diff --git a/libraries/autoload.php b/libraries/autoload.php new file mode 100644 index 0000000000000..81305020bc372 --- /dev/null +++ b/libraries/autoload.php @@ -0,0 +1,7 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0 class loader + * + * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + */ +class ClassLoader +{ + // PSR-4 + private $prefixLengthsPsr4 = array(); + private $prefixDirsPsr4 = array(); + private $fallbackDirsPsr4 = array(); + + // PSR-0 + private $prefixesPsr0 = array(); + private $fallbackDirsPsr0 = array(); + + private $useIncludePath = false; + private $classMap = array(); + + public function getPrefixes() + { + return call_user_func_array('array_merge', $this->prefixesPsr0); + } + + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-0 base directories + * @param bool $prepend Whether to prepend the directories + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 base directories + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + */ + public function setPsr4($prefix, $paths) { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + } + + /** + * Unregisters this instance as an autoloader. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return bool|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 + if ('\\' == $class[0]) { + $class = substr($class, 1); + } + + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if ($file === null && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if ($file === null) { + // Remember that this class does not exist. + return $this->classMap[$class] = false; + } + + return $file; + } + + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) { + if (0 === strpos($class, $prefix)) { + foreach ($this->prefixDirsPsr4[$prefix] as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + */ +function includeFile($file) +{ + include $file; +} diff --git a/libraries/composer/autoload_classmap.php b/libraries/composer/autoload_classmap.php new file mode 100644 index 0000000000000..9296e6639f005 --- /dev/null +++ b/libraries/composer/autoload_classmap.php @@ -0,0 +1,14 @@ + $vendorDir . '/joomla/compat/src/JsonSerializable.php', + 'PHPMailer' => $vendorDir . '/phpmailer/phpmailer/class.phpmailer.php', + 'POP3' => $vendorDir . '/phpmailer/phpmailer/class.pop3.php', + 'SMTP' => $vendorDir . '/phpmailer/phpmailer/class.smtp.php', + 'phpmailerException' => $vendorDir . '/phpmailer/phpmailer/class.phpmailer.php', +); diff --git a/libraries/composer/autoload_files.php b/libraries/composer/autoload_files.php new file mode 100644 index 0000000000000..746d7b8f1b4cb --- /dev/null +++ b/libraries/composer/autoload_files.php @@ -0,0 +1,10 @@ + array($vendorDir . '/symfony/yaml'), +); diff --git a/libraries/composer/autoload_psr4.php b/libraries/composer/autoload_psr4.php new file mode 100644 index 0000000000000..1cc6c530c1fd5 --- /dev/null +++ b/libraries/composer/autoload_psr4.php @@ -0,0 +1,17 @@ + array($vendorDir . '/joomla/utilities/Tests'), + 'Joomla\\Utilities\\' => array($vendorDir . '/joomla/utilities/src'), + 'Joomla\\String\\Tests\\' => array($vendorDir . '/joomla/string/Tests'), + 'Joomla\\String\\' => array($vendorDir . '/joomla/string/src'), + 'Joomla\\Registry\\Tests\\' => array($vendorDir . '/joomla/registry/Tests'), + 'Joomla\\Registry\\' => array($vendorDir . '/joomla/registry/src'), + 'Joomla\\DI\\Tests\\' => array($vendorDir . '/joomla/di/Tests'), + 'Joomla\\DI\\' => array($vendorDir . '/joomla/di/src'), +); diff --git a/libraries/composer/autoload_real.php b/libraries/composer/autoload_real.php new file mode 100644 index 0000000000000..dd9ac9b81a82b --- /dev/null +++ b/libraries/composer/autoload_real.php @@ -0,0 +1,58 @@ + $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + + $loader->register(true); + + $includeFiles = require __DIR__ . '/autoload_files.php'; + foreach ($includeFiles as $file) { + composerRequire4a38f5b21c123516e83fe8e48aac4df1($file); + } + + return $loader; + } +} + +function composerRequire4a38f5b21c123516e83fe8e48aac4df1($file) +{ + require $file; +} diff --git a/libraries/composer/installed.json b/libraries/composer/installed.json new file mode 100644 index 0000000000000..03504b26645f5 --- /dev/null +++ b/libraries/composer/installed.json @@ -0,0 +1,359 @@ +[ + { + "name": "joomla/di", + "version": "1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/joomla-framework/di.git", + "reference": "4866c58e92ce4e851cd87d5d9d31b069b7284267" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/joomla-framework/di/zipball/4866c58e92ce4e851cd87d5d9d31b069b7284267", + "reference": "4866c58e92ce4e851cd87d5d9d31b069b7284267", + "shasum": "" + }, + "require": { + "php": ">=5.3.10" + }, + "time": "2014-03-21 13:20:34", + "type": "joomla-package", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Joomla\\DI\\": "src/", + "Joomla\\DI\\Tests\\": "Tests/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0+" + ], + "description": "Joomla DI Package", + "homepage": "https://github.com/joomla-framework/di", + "keywords": [ + "container", + "dependency injection", + "di", + "framework", + "ioc", + "joomla" + ] + }, + { + "name": "joomla/string", + "version": "1.1.1", + "version_normalized": "1.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/joomla-framework/string.git", + "reference": "bd2b2c9bbb6846680cbeb955c90288587d56df2a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/joomla-framework/string/zipball/bd2b2c9bbb6846680cbeb955c90288587d56df2a", + "reference": "bd2b2c9bbb6846680cbeb955c90288587d56df2a", + "shasum": "" + }, + "require": { + "php": ">=5.3.10" + }, + "require-dev": { + "joomla/test": "~1.0" + }, + "time": "2014-02-09 02:48:39", + "type": "joomla-package", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Joomla\\String\\": "src/", + "Joomla\\String\\Tests\\": "Tests/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0+" + ], + "description": "Joomla String Package", + "homepage": "https://github.com/joomla-framework/string", + "keywords": [ + "framework", + "joomla", + "string" + ] + }, + { + "name": "joomla/utilities", + "version": "1.1.1", + "version_normalized": "1.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/joomla-framework/utilities.git", + "reference": "de31259372d049f2a3fabe7b1c412cece134ca31" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/joomla-framework/utilities/zipball/de31259372d049f2a3fabe7b1c412cece134ca31", + "reference": "de31259372d049f2a3fabe7b1c412cece134ca31", + "shasum": "" + }, + "require": { + "joomla/string": "~1.0", + "php": ">=5.3.10" + }, + "time": "2014-02-09 02:57:39", + "type": "joomla-package", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Joomla\\Utilities\\": "src/", + "Joomla\\Utilities\\Tests\\": "Tests/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0+" + ], + "description": "Joomla Utilities Package", + "homepage": "https://github.com/joomla-framework/utilities", + "keywords": [ + "framework", + "joomla", + "utilities" + ] + }, + { + "name": "joomla/compat", + "version": "1.1.1", + "version_normalized": "1.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/joomla-framework/compat.git", + "reference": "92ba45e9cfdca4c912691bf04ef13e0c03660348" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/joomla-framework/compat/zipball/92ba45e9cfdca4c912691bf04ef13e0c03660348", + "reference": "92ba45e9cfdca4c912691bf04ef13e0c03660348", + "shasum": "" + }, + "require": { + "php": ">=5.3.10" + }, + "time": "2014-02-09 19:29:20", + "type": "joomla-package", + "installation-source": "dist", + "autoload": { + "classmap": [ + "src/JsonSerializable.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0+" + ], + "description": "Joomla Compat Package", + "homepage": "https://github.com/joomla-framework/compat", + "keywords": [ + "compat", + "framework", + "joomla" + ] + }, + { + "name": "joomla/registry", + "version": "1.1.2", + "version_normalized": "1.1.2.0", + "source": { + "type": "git", + "url": "https://github.com/joomla-framework/registry.git", + "reference": "d4526f2fb6295fbd3c688fa817e72a1821d7c0e4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/joomla-framework/registry/zipball/d4526f2fb6295fbd3c688fa817e72a1821d7c0e4", + "reference": "d4526f2fb6295fbd3c688fa817e72a1821d7c0e4", + "shasum": "" + }, + "require": { + "joomla/compat": "~1.0", + "joomla/utilities": "~1.0", + "php": ">=5.3.10" + }, + "require-dev": { + "joomla/test": "~1.0", + "symfony/yaml": "~2.0" + }, + "suggest": { + "symfony/yaml": "Install 2.* if you require YAML support." + }, + "time": "2014-02-09 07:19:55", + "type": "joomla-package", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Joomla\\Registry\\": "src/", + "Joomla\\Registry\\Tests\\": "Tests/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0+" + ], + "description": "Joomla Registry Package", + "homepage": "https://github.com/joomla-framework/registry", + "keywords": [ + "framework", + "joomla", + "registry" + ] + }, + { + "name": "ircmaxell/password-compat", + "version": "1.0.3", + "version_normalized": "1.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/password_compat.git", + "reference": "1fc1521b5e9794ea77e4eca30717be9635f1d4f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/password_compat/zipball/1fc1521b5e9794ea77e4eca30717be9635f1d4f4", + "reference": "1fc1521b5e9794ea77e4eca30717be9635f1d4f4", + "shasum": "" + }, + "time": "2013-04-30 19:58:08", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "lib/password.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "homepage": "https://github.com/ircmaxell/password_compat", + "keywords": [ + "hashing", + "password" + ] + }, + { + "name": "phpmailer/phpmailer", + "version": "v5.2.7", + "version_normalized": "5.2.7.0", + "source": { + "type": "git", + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "8717a79565b2c0ed67f851d70e1949febdf3b226" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/8717a79565b2c0ed67f851d70e1949febdf3b226", + "reference": "8717a79565b2c0ed67f851d70e1949febdf3b226", + "shasum": "" + }, + "require": { + "php": ">=5.0.0" + }, + "require-dev": { + "phpdocumentor/phpdocumentor": "*", + "phpunit/phpunit": "*" + }, + "time": "2013-09-12 07:52:38", + "type": "library", + "installation-source": "dist", + "autoload": { + "classmap": [ + "class.phpmailer.php", + "class.pop3.php", + "class.smtp.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1" + ], + "authors": [ + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP" + }, + { + "name": "symfony/yaml", + "version": "v2.4.4", + "version_normalized": "2.4.4.0", + "target-dir": "Symfony/Component/Yaml", + "source": { + "type": "git", + "url": "https://github.com/symfony/Yaml.git", + "reference": "65539ecde838f9c0d18b006b2101e3deb4b5c9ff" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Yaml/zipball/65539ecde838f9c0d18b006b2101e3deb4b5c9ff", + "reference": "65539ecde838f9c0d18b006b2101e3deb4b5c9ff", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "time": "2014-04-18 20:37:09", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Symfony\\Component\\Yaml\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "http://symfony.com" + } +] diff --git a/libraries/ircmaxell/password-compat/.travis.yml b/libraries/ircmaxell/password-compat/.travis.yml new file mode 100644 index 0000000000000..a960061ca8089 --- /dev/null +++ b/libraries/ircmaxell/password-compat/.travis.yml @@ -0,0 +1,8 @@ +language: php + +php: + - 5.5 + - 5.4 + - 5.3 + +script: phpunit --configuration phpunit.xml.dist \ No newline at end of file diff --git a/libraries/ircmaxell/password-compat/LICENSE.md b/libraries/ircmaxell/password-compat/LICENSE.md new file mode 100644 index 0000000000000..1efc565fcf2bb --- /dev/null +++ b/libraries/ircmaxell/password-compat/LICENSE.md @@ -0,0 +1,7 @@ +Copyright (c) 2012 Anthony Ferrara + +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. \ No newline at end of file diff --git a/libraries/ircmaxell/password-compat/README.md b/libraries/ircmaxell/password-compat/README.md new file mode 100644 index 0000000000000..e158f7d0ca8ba --- /dev/null +++ b/libraries/ircmaxell/password-compat/README.md @@ -0,0 +1,75 @@ +password_compat +=============== + +[![Build Status](https://travis-ci.org/ircmaxell/password_compat.png?branch=master)](https://travis-ci.org/ircmaxell/password_compat) + +This library is intended to provide forward compatibility with the password_* functions being worked on for PHP 5.5. + +See [the RFC](https://wiki.php.net/rfc/password_hash) for more detailed information. + + +Requirements +============ + +This library requires `PHP >= 5.3.7` OR a version that has the `$2y` fix backported into it (such as Debian provides). + +The runtime checks have been removed due to this version issue. To see if password_compat is available for your system, run the included `version-test.php`. If it outputs "Pass", you can safely use the library. If not, you cannot. + +If you attempt to use password-compat on an unsupported version, attempts to create or verify hashes will return `false`. You have been warned! + +The reason for this is that PHP prior to 5.3.7 contains a security issue with its BCRYPT implementation. Therefore, it's highly recommended that you upgrade to a newer version of PHP prior to using this layer. + +Installation +============ + +To install, simply `require` the `password.php` file under `lib`. + +You can also install it via `Composer` by using the [Packagist archive](http://packagist.org/packages/ircmaxell/password-compat). + +Usage +===== + +**Creating Password Hashes** + +To create a password hash from a password, simply use the `password_hash` function. + + $hash = password_hash($password, PASSWORD_BCRYPT); + +Note that the algorithm that we chose is `PASSWORD_BCRYPT`. That's the current strongest algorithm supported. This is the `BCRYPT` crypt algorithm. It produces a 60 character hash as the result. + +`BCRYPT` also allows for you to define a `cost` parameter in the options array. This allows for you to change the CPU cost of the algorithm: + + $hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 10]); + +That's the same as the default. The cost can range from `4` to `31`. I would suggest that you use the highest cost that you can, while keeping response time reasonable (I target between 0.1 and 0.5 seconds for a hash, depending on use-case). + +Another algorithm name is supported: + + PASSWORD_DEFAULT + +This will use the strongest algorithm available to PHP at the current time. Presently, this is the same as specifying `PASSWORD_BCRYPT`. But in future versions of PHP, it may be updated to use a stronger algorithm if one is introduced. It can also be changed if a problem is identified with the BCRYPT algorithm. Note that if you use this option, you are **strongly** encouraged to store it in a `VARCHAR(255)` column to avoid truncation issues if a future algorithm increases the length of the generated hash. + +It is very important that you should check the return value of `password_hash` prior to storing it, because a `false` may be returned if it encountered an error. + +**Verifying Password Hashes** + +To verify a hash created by `password_hash`, simply call: + + if (password_verify($password, $hash)) { + /* Valid */ + } else { + /* Invalid */ + } + +That's all there is to it. + +**Rehashing Passwords** + +From time to time you may update your hashing parameters (algorithm, cost, etc). So a function to determine if rehashing is necessary is available: + + if (password_verify($password, $hash)) { + if (password_needs_rehash($hash, $algorithm, $options)) { + $hash = password_hash($password, $algorithm, $options); + /* Store new hash in db */ + } + } diff --git a/libraries/ircmaxell/password-compat/composer.json b/libraries/ircmaxell/password-compat/composer.json new file mode 100644 index 0000000000000..e0d4f14c55d47 --- /dev/null +++ b/libraries/ircmaxell/password-compat/composer.json @@ -0,0 +1,18 @@ +{ + "name": "ircmaxell/password-compat", + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "version": "1.0.3", + "keywords": ["password", "hashing"], + "homepage": "https://github.com/ircmaxell/password_compat", + "license": "MIT", + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "autoload": { + "files": ["lib/password.php"] + } +} \ No newline at end of file diff --git a/libraries/ircmaxell/password-compat/lib/password.php b/libraries/ircmaxell/password-compat/lib/password.php new file mode 100644 index 0000000000000..4d0e8b7a63789 --- /dev/null +++ b/libraries/ircmaxell/password-compat/lib/password.php @@ -0,0 +1,222 @@ + + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @copyright 2012 The Authors + */ + +if (!defined('PASSWORD_BCRYPT')) { + + define('PASSWORD_BCRYPT', 1); + define('PASSWORD_DEFAULT', PASSWORD_BCRYPT); + + /** + * Hash the password using the specified algorithm + * + * @param string $password The password to hash + * @param int $algo The algorithm to use (Defined by PASSWORD_* constants) + * @param array $options The options for the algorithm to use + * + * @return string|false The hashed password, or false on error. + */ + function password_hash($password, $algo, array $options = array()) { + if (!function_exists('crypt')) { + trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING); + return null; + } + if (!is_string($password)) { + trigger_error("password_hash(): Password must be a string", E_USER_WARNING); + return null; + } + if (!is_int($algo)) { + trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING); + return null; + } + switch ($algo) { + case PASSWORD_BCRYPT: + // Note that this is a C constant, but not exposed to PHP, so we don't define it here. + $cost = 10; + if (isset($options['cost'])) { + $cost = $options['cost']; + if ($cost < 4 || $cost > 31) { + trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING); + return null; + } + } + // The length of salt to generate + $raw_salt_len = 16; + // The length required in the final serialization + $required_salt_len = 22; + $hash_format = sprintf("$2y$%02d$", $cost); + break; + default: + trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING); + return null; + } + if (isset($options['salt'])) { + switch (gettype($options['salt'])) { + case 'NULL': + case 'boolean': + case 'integer': + case 'double': + case 'string': + $salt = (string) $options['salt']; + break; + case 'object': + if (method_exists($options['salt'], '__tostring')) { + $salt = (string) $options['salt']; + break; + } + case 'array': + case 'resource': + default: + trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING); + return null; + } + if (strlen($salt) < $required_salt_len) { + trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING); + return null; + } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) { + $salt = str_replace('+', '.', base64_encode($salt)); + } + } else { + $buffer = ''; + $buffer_valid = false; + if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) { + $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) { + $buffer = openssl_random_pseudo_bytes($raw_salt_len); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && is_readable('/dev/urandom')) { + $f = fopen('/dev/urandom', 'r'); + $read = strlen($buffer); + while ($read < $raw_salt_len) { + $buffer .= fread($f, $raw_salt_len - $read); + $read = strlen($buffer); + } + fclose($f); + if ($read >= $raw_salt_len) { + $buffer_valid = true; + } + } + if (!$buffer_valid || strlen($buffer) < $raw_salt_len) { + $bl = strlen($buffer); + for ($i = 0; $i < $raw_salt_len; $i++) { + if ($i < $bl) { + $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255)); + } else { + $buffer .= chr(mt_rand(0, 255)); + } + } + } + $salt = str_replace('+', '.', base64_encode($buffer)); + } + $salt = substr($salt, 0, $required_salt_len); + + $hash = $hash_format . $salt; + + $ret = crypt($password, $hash); + + if (!is_string($ret) || strlen($ret) <= 13) { + return false; + } + + return $ret; + } + + /** + * Get information about the password hash. Returns an array of the information + * that was used to generate the password hash. + * + * array( + * 'algo' => 1, + * 'algoName' => 'bcrypt', + * 'options' => array( + * 'cost' => 10, + * ), + * ) + * + * @param string $hash The password hash to extract info from + * + * @return array The array of information about the hash. + */ + function password_get_info($hash) { + $return = array( + 'algo' => 0, + 'algoName' => 'unknown', + 'options' => array(), + ); + if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) { + $return['algo'] = PASSWORD_BCRYPT; + $return['algoName'] = 'bcrypt'; + list($cost) = sscanf($hash, "$2y$%d$"); + $return['options']['cost'] = $cost; + } + return $return; + } + + /** + * Determine if the password hash needs to be rehashed according to the options provided + * + * If the answer is true, after validating the password using password_verify, rehash it. + * + * @param string $hash The hash to test + * @param int $algo The algorithm used for new password hashes + * @param array $options The options array passed to password_hash + * + * @return boolean True if the password needs to be rehashed. + */ + function password_needs_rehash($hash, $algo, array $options = array()) { + $info = password_get_info($hash); + if ($info['algo'] != $algo) { + return true; + } + switch ($algo) { + case PASSWORD_BCRYPT: + $cost = isset($options['cost']) ? $options['cost'] : 10; + if ($cost != $info['options']['cost']) { + return true; + } + break; + } + return false; + } + + /** + * Verify a password against a hash using a timing attack resistant approach + * + * @param string $password The password to verify + * @param string $hash The hash to verify against + * + * @return boolean If the password matches the hash + */ + function password_verify($password, $hash) { + if (!function_exists('crypt')) { + trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING); + return false; + } + $ret = crypt($password, $hash); + if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) { + return false; + } + + $status = 0; + for ($i = 0; $i < strlen($ret); $i++) { + $status |= (ord($ret[$i]) ^ ord($hash[$i])); + } + + return $status === 0; + } +} + + + diff --git a/libraries/ircmaxell/password-compat/phpunit.xml.dist b/libraries/ircmaxell/password-compat/phpunit.xml.dist new file mode 100644 index 0000000000000..b2b3afbd97720 --- /dev/null +++ b/libraries/ircmaxell/password-compat/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + + test/Unit + + + + + lib/ + + + diff --git a/libraries/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php b/libraries/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php new file mode 100644 index 0000000000000..6aab976adcbc7 --- /dev/null +++ b/libraries/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php @@ -0,0 +1,26 @@ + 0, 'algoName' => 'unknown', 'options' => array())), + array('$2y$', array('algo' => 0, 'algoName' => 'unknown', 'options' => array())), + array('$2y$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi', array('algo' => PASSWORD_BCRYPT, 'algoName' => 'bcrypt', 'options' => array('cost' => 7))), + array('$2y$10$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi', array('algo' => PASSWORD_BCRYPT, 'algoName' => 'bcrypt', 'options' => array('cost' => 10))), + + ); + } + + public function testFuncExists() { + $this->assertTrue(function_exists('password_get_info')); + } + + /** + * @dataProvider provideInfo + */ + public function testInfo($hash, $info) { + $this->assertEquals($info, password_get_info($hash)); + } + +} \ No newline at end of file diff --git a/libraries/ircmaxell/password-compat/test/Unit/PasswordHashTest.php b/libraries/ircmaxell/password-compat/test/Unit/PasswordHashTest.php new file mode 100644 index 0000000000000..9e5e9ec641965 --- /dev/null +++ b/libraries/ircmaxell/password-compat/test/Unit/PasswordHashTest.php @@ -0,0 +1,84 @@ +assertTrue(function_exists('password_hash')); + } + + public function testStringLength() { + $this->assertEquals(60, strlen(password_hash('foo', PASSWORD_BCRYPT))); + } + + public function testHash() { + $hash = password_hash('foo', PASSWORD_BCRYPT); + $this->assertEquals($hash, crypt('foo', $hash)); + } + + public function testKnownSalt() { + $hash = password_hash("rasmuslerdorf", PASSWORD_BCRYPT, array("cost" => 7, "salt" => "usesomesillystringforsalt")); + $this->assertEquals('$2y$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi', $hash); + } + + public function testRawSalt() { + $hash = password_hash("test", PASSWORD_BCRYPT, array("salt" => "123456789012345678901" . chr(0))); + $this->assertEquals('$2y$10$MTIzNDU2Nzg5MDEyMzQ1Nej0NmcAWSLR.oP7XOR9HD/vjUuOj100y', $hash); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidAlgo() { + password_hash('foo', array()); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidAlgo2() { + password_hash('foo', 2); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidPassword() { + password_hash(array(), 1); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidSalt() { + password_hash('foo', PASSWORD_BCRYPT, array('salt' => array())); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptCostLow() { + password_hash('foo', PASSWORD_BCRYPT, array('cost' => 3)); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptCostHigh() { + password_hash('foo', PASSWORD_BCRYPT, array('cost' => 32)); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptCostInvalid() { + password_hash('foo', PASSWORD_BCRYPT, array('cost' => 'foo')); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptSaltShort() { + password_hash('foo', PASSWORD_BCRYPT, array('salt' => 'abc')); + } + +} \ No newline at end of file diff --git a/libraries/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php b/libraries/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php new file mode 100644 index 0000000000000..c2932dc6c03a5 --- /dev/null +++ b/libraries/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php @@ -0,0 +1,26 @@ + 7), false), + array('$2y$07$usesomesillystringfore2udlvp1ii2e./u9c8sbjqp8i90dh6hi', PASSWORD_BCRYPT, array('cost' => 5), true), + ); + } + + public function testFuncExists() { + $this->assertTrue(function_exists('password_needs_rehash')); + } + + /** + * @dataProvider provideCases + */ + public function testCases($hash, $algo, $options, $valid) { + $this->assertEquals($valid, password_needs_rehash($hash, $algo, $options)); + } + +} \ No newline at end of file diff --git a/libraries/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php b/libraries/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php new file mode 100644 index 0000000000000..9f67bb9f7b216 --- /dev/null +++ b/libraries/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php @@ -0,0 +1,29 @@ +assertTrue(function_exists('password_verify')); + } + + public function testFailedType() { + $this->assertFalse(password_verify(123, 123)); + } + + public function testSaltOnly() { + $this->assertFalse(password_verify('foo', '$2a$07$usesomesillystringforsalt$')); + } + + public function testInvalidPassword() { + $this->assertFalse(password_verify('rasmusler', '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi')); + } + + public function testValidPassword() { + $this->assertTrue(password_verify('rasmuslerdorf', '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi')); + } + + public function testInValidHash() { + $this->assertFalse(password_verify('rasmuslerdorf', '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hj')); + } + +} \ No newline at end of file diff --git a/libraries/ircmaxell/password-compat/version-test.php b/libraries/ircmaxell/password-compat/version-test.php new file mode 100644 index 0000000000000..f527e30f93457 --- /dev/null +++ b/libraries/ircmaxell/password-compat/version-test.php @@ -0,0 +1,8 @@ + + Copyright (C) + + 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 2 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, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/libraries/joomla/compat/README.md b/libraries/joomla/compat/README.md new file mode 100644 index 0000000000000..cd158d7e64181 --- /dev/null +++ b/libraries/joomla/compat/README.md @@ -0,0 +1,53 @@ +# The Compat Package + +This is a simple package that contains forward compatibility classes and interfaces that are registered to the global namespace + +## JsonSerializable + +`JsonSerializable` is a PHP 5.4 interface that allows you to specify what data to serialize to JSON when you `json_encode` an object that implements the interface. + +### Usage + +Since this is a PHP 5.4 interface, the `jsonSerialize()` method does not get called automatically when `json_encode`-ing an instance of the class when used in 5.3. To work around this, simply call the `jsonSerialize()` method directly when passing it to `json_encode`. This is forward-compatible with PHP 5.4. + +```php +class MyClass implements \JsonSerializable +{ + /** + * @var array Holds the data this class uses. + */ + protected $data; + + public function __construct(array $data) + { + $this->data = $dasta; + } + + public function jsonSerialize() + { + return $this->data; + } +} + +$obj = new MyClass(array('sample', 'data', 'to', 'encode')); + +$encoded = json_encode($obj->jsonSerialize()); +``` + +## Installation via Composer + +Add `"joomla/compat": "~1.0"` to the require block in your composer.json and then run `composer install`. + +```json +{ + "require": { + "joomla/compat": "~1.0" + } +} +``` + +Alternatively, you can simply run the following from the command line: + +```sh +composer require joomla/compat "~1.0" +``` diff --git a/libraries/joomla/compat/composer.json b/libraries/joomla/compat/composer.json new file mode 100644 index 0000000000000..1906ba3713091 --- /dev/null +++ b/libraries/joomla/compat/composer.json @@ -0,0 +1,14 @@ +{ + "name": "joomla/compat", + "type": "joomla-package", + "description": "Joomla Compat Package", + "keywords": ["joomla", "framework", "compat"], + "homepage": "https://github.com/joomla-framework/compat", + "license": "GPL-2.0+", + "require": { + "php": ">=5.3.10" + }, + "autoload": { + "classmap": ["src/JsonSerializable.php"] + } +} diff --git a/libraries/joomla/compat/src/JsonSerializable.php b/libraries/joomla/compat/src/JsonSerializable.php new file mode 100644 index 0000000000000..425c4ef641d9f --- /dev/null +++ b/libraries/joomla/compat/src/JsonSerializable.php @@ -0,0 +1,26 @@ + + Copyright (C) + + 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 2 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, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/libraries/joomla/di/README.md b/libraries/joomla/di/README.md new file mode 100644 index 0000000000000..d7dbe5d22c3b7 --- /dev/null +++ b/libraries/joomla/di/README.md @@ -0,0 +1,431 @@ +# The DI Package [![Build Status](https://travis-ci.org/joomla-framework/di.png?branch=master)](https://travis-ci.org/joomla-framework/di) + +The Dependency Injection package for Joomla provides a simple IoC Container for your application. +Dependency Injection allows you the developer to control the construction and lifecycle of your objects, +rather than leaving that control to the classes themselves. Instead of hard coding a class's dependencies +within the class `__construct()` method, you instead provide to a class the dependencies it requires as +arguments to its constructor. This helps to decrease hard dependencies and to create loosely coupled code. + +Read more about [why you should be using dependency injection](docs/why-dependency-injection.md). + +An Inversion of Control (IoC) Container helps you to manage these dependencies in a controlled fashion. + +## Using the Container + +### Creating a Container + +Creating a container usually happens very early in the application lifecycle. For a Joomla MVC app, this +typically happens in the application's `doExecute` method. This allows your application access to the DI +Container, which you can then use within the app class to build your controllers and their dependencies. + +```php +namespace My\App; + +use Joomla\DI\Container; +use Joomla\Application\AbstractWebApplication; + +class WebApp extends AbstractWebApplication +{ + protected $container; + + // ...snip + + protected function doExecute() + { + $this->container = new Container; + + // ...snip + } +} +``` + +Another feature of the container is the ability to create a child container with a different resolution +scope. This allows you to easily override an interface binding for a specific controller, without +destroying the resolution scope for the rest of the classes using the container. A child container will +search recursively through it's parent containers to resolve all the required dependencies. + +```php +use Joomla\DI\Container; + +$container->set('Some\Interface\I\NeedInterface', new My\App\InterfaceImplementation); +// Application executes... Come to a class that needs a different implementation. +$child = $container->createChild(); +$child->set('Some\Interface\I\NeedInterface', new My\Other\InterfaceImplementation); +``` + +### Setting an Item + +Setting an item within the container is very straightforward. You pass the `set` method a string `$key` +and a `$value`, which can be pretty much anything. If the `$value` is an anonymous function or a `Closure`, +or a callable value, +that value will be set as the resolving callback for the `$key`. If it is anything else (an instantiated +object, array, integer, serialized controller, etc) it will be wrapped in a closure and that closure will +be set as the resolving callback for the `$key`. + +> If the `$value` you are setting is a closure or a callable, it will receive a single function argument, +> the calling container. This allows access to the container within your resolving callback. + +```php +// Assume a created $container +$container->set('foo', 'bar'); + +$container->set('something', new Something); + +$container->set('callMe', array($this, 'callMe'); +// etc +``` + +In the case of a callable, the called method must take a `Container` object as its first and only argument. + +When setting items in the container, you are allowed to specify whether the item is supposed to be a +shared or protected item. A shared item means that when you get an item from the container, the resolving +callback will be fired once, and the value will be stored and used on every subsequent request for that +item. The other option, protected, is a special status that you can use to prevent others from overwriting +the item down the line. A good example for this would be a global config that you don't want to be +overwritten. The third option is that you can both share AND protect an item. A good use case for this would +be a database connection that you only want one of, and you don't want it to be overwritten. + +```php +// Assume a created $container +$container->share( + 'foo', + function () + { + // some expensive $stuff; + + return $stuff; + } +); + +$container->protect( + 'bar', + function (Container $c) + { + // Don't overwrite my db connection. + $config = $c->get('config'); + + $databaseConfig = (array) $config->get('database'); + + return new DatabaseDriver($databaseConfig); + } +); +``` + +> Both the `protect` and `share` methods take an optional third parameter. If set to `true`, it will +> tell the container to both protect _and_ share the item. (Or share _and_ protect, depending on +> the origin method you call. Essentially it's the same thing.) + +The most powerful feature of setting an item in the container is the ability to bind an implementation +to an interface. This is useful when using the container to build your app objects. You can typehint +against an interface, and when the object gets built, the container will pass your implementation. + +@TODO +- Interface binding usage example + +### Item Aliases + +Any item set in the container can be aliased. This allows you to create an object that is a named +dependency for object resolution, but also have a "shortcut" access to the item from the container. + +```php +// Assume a created $container +$container->set( + 'Really\Long\ConfigClassName', + function () + { + // ...snip + } +); + +$container->alias('config', 'Really\Long\ConfigClassName'); + +$container->get('config'); // Returns the value set on the aliased key. +``` + +### Getting an Item + +At its most basic level, the DI Container is a registry that holds keys and values. When you set +an item on the container, you can retrieve it by passing the same `$key` to the `get` method that +you did when you set the method in the container. + +> If you've aliased a set item, you can also retrieve it using the alias key. + +```php +// Assume a created $container +$container->set('foo', 'bar'); + +$foo = $container->get('foo'); +``` + +Normally, the value you'll be passing will be a closure. When you fetch the item from the container, +the closure is executed, and the result is returned. + +```php +// Assume a created $container +$container->set( + 'foo', + function () + { + // Create an instance of \Joomla\Github\Github; + + return $github; + } +); + +$github = $container->get('foo'); + +var_dump($github instanceof \Joomla\Github\Github); // prints bool(true) +``` + +If you get the item again, the closure is executed again and the result is returned. + +```php +// Picking up from the previous codeblock +$github2 = $container->get('foo'); + +print($github2 === $github); // prints bool(false) +``` + +However, if you specify that the object as shared when setting it in the container, the closure will +only be executed once (the first time it is requested), the value will be stored and then returned +on every subsequent request. +```php +// Assume a created $container +$container->share( + 'twitter', + function () + { + // Create an instance of \Joomla\Twitter\Twitter; + + return $twitter; + } +); + +$twitter = $container->get('twitter'); +$twitter2 = $container->get('twitter'); + +var_dump($twitter === $twitter2); // prints bool(true) +``` + +If you've specified an item as shared, but you really need a new instance of it for some reason, you +can force the creation of a new instance by passing true as the second argument, or using the `getNewInstance` +convenience method. + +> When you force create a new instance on a shared object, that new instance replaces the instance +> that is stored in the container and will be used on subsequent requests. + +```php +// Picking up from the previous codeblock +$twitter3 = $container->getNewInstance('twitter'); + +var_dump($twitter === $twitter3); // prints bool(false) + +$twitter4 = $container->get('twitter'); +var_dump($twitter3 === $twitter4); // prints bool(true) +``` + +> If you've created a child container, you can use the `get` and `getNewInstance` methods on it to +> fetch items from the parent container that have not yet been overwritten in the child container. + + +### Instantiate an object from the Container + +The most useful function of the container is it's ability to build complete objects, instantiating +any needed dependencies along the way. When you use the container in this way, it looks at a classes +constructor declared dependencies and then automatically passes them into the object. + +> Classes will only receive dependencies that have been properly typehinted or given a default value. + +Since the container allows you to bind an implementation to an interface, this gives you great flexibility +to build your classes within the container. If your model class requires a user repository, you can typehint +against a `UserRepositoryInterface` and then bind an implementation to that interface to be passed into +the model when it's created. + +```php +class User implements UserRepositoryInterface +{ + // ...snip +} + +class UserProfile +{ + protected $user; + + public function __construct(UserRepositoryInterface $user) + { + $this->user = $user; + } +} + +// Assume a created $container +$container->set( + 'UserRepositoryInterface', + function () + { + retur new User; + } +); + +$userProfile = $container->buildObject('UserProfile'); + +// Use reflection to get the $user property from $userProfile +var_dump($user instanceof User); // prints bool(true) +var_dump($user instanceof UserRepositoryInterface); // prints bool(true) +``` + +When you build an object, the information required to actually build it (dependencies, etc) are +stored in a callable and set in the container with the class name as the key. You can then fetch +the item from the container by name later on. Alias support applies here as well. + +You can also specify to build a shared object by using the function `buildSharedObject($key)`. This +works exactly as you would expect. The information required to build it is discovered, stored in a +callable, then the callable is executed and the result returned. The result is stored as an instance +within the container and is returned on subsequent requests. + + +### Extending an Item + +The Container also allows you to extend items. Extending an item can be thought of as a way to +implement the decorator pattern, although it's not really in the strict sense. When you extend an +item, you must pass the key for the item you want to extend, and then a closure as the second +argument. The closure will receive 2 arguments. The first is result of the callable for the given key, +and the second will be the container itself. When extending an item, the new extended version overwrites +the existing item in the container. If you try to extend an item that does not exist, an `\InvalidArgumentException` +will be thrown. + +> When extending an item, normal rules apply. A protected object cannot be overwritten, so you also can not extend them. + +```php +// Assume a created $container +$container->set('foo', 'bar'); + +var_dump($container->get('foo')); // prints string(3) "bar" + +$container->extend( + 'foo', + function ($originalResult, Container $c) + { + return $originalResult .= 'baz'; + } +); + +var_dump($container->get('foo')); // prints string(6) "barbaz" +``` + + +### Service Providers + +Another strong feature of the Container is the ability register a _service provider_ to the container. +Service providers are useful in that they are a simple way to encapsulate setup logic for your objects. +In order to use create a service provider, you must implement the `Joomla\DI\ServiceProviderInterface`. +The `ServiceProviderInterface` tells the container that your object has a `register` method that takes +the container as it's only argument. + +> Registering service providers is typically done very early in the application lifecycle. Usually +> right after the container is created. + +```php +// Assume a created $container +use Joomla\DI\Container; +use Joomla\DI\ServiceProviderInterface; +use Joomla\Database\DatabaseDriver; + +class DatabaseServiceProvider implements ServiceProviderInterface +{ + public function register(Container $container) + { + $container->share( + 'Joomla\Database\DatabaseDriver', + function () use ($container) + { + $databaseConfig = (array) $container->get('config')->get('database'); + + return new DatabaseDriver($databaseConfig); + }, + true + ); + + $container->alias('db', 'Joomla\Database\DatabaseDriver'); + } +} + +$container->registerServiceProvider(new DatabaseServiceProvider); +``` + +Here is an alternative using a callable. + +```php +// Assume a created $container +use Joomla\DI\Container; +use Joomla\DI\ServiceProviderInterface; + +class CallableServiceProvider implements ServiceProviderInterface +{ + public function getCallable(Container $c) + { + return 'something'; + } + + public function register(Container $container) + { + $container->set('callable', array($this, 'getCallable'); + } +} + +$container->registerServiceProvider(new CallableServiceProvider); +``` + +The advantage here is that it is easier to write unit tests for the callable method (closures can be awkward to isolate +and test). + +### Container Aware Objects + +You are able to make objects _ContainerAware_ by implementing the `Joomla\DI\ContainerAwareInterface` within your +class. This can be useful when used within the construction level of your application. The construction +level is considered to be anything that is responsible for the creation of other objects. When using +the MVC pattern as recommended by Joomla, this can be at the application or controller level. Controllers +in Joomla are responsible for creating Models and Views, and linking them together. In this case, it would +be reasonable for the controllers to have access to the container in order to build these objects. + +> __NOTE:__ The business layer of your app (eg: Models) should _never_ be container aware. Doing so will +> make your code harder to test, and is a far cry from best practices. + +### Container Aware Trait + +Since PHP 5.4 traits are [available](http://www.php.net/traits), so you can use `ContainerAwareTrait`. + +Usage: + +```php +use Joomla\DI\ContainerAwareInterface, + Joomla\DI\ContainerAwareTrait, + Joomla\Controller\AbstractController; + +class MyConroller extends AbstractController implements ContainerAwareInterface +{ + use ContainerAwareTrait; + + public function execute() + { + $container = $this->getContainer(); + } +} +``` + +## Installation via Composer + +Add `"joomla/di": "~1.0"` to the require block in your composer.json and then run `composer install`. + +```json +{ + "require": { + "joomla/di": "~1.0" + } +} +``` + +Alternatively, you can simply run the following from the command line: + +```sh +composer require joomla/di "~1.0" +``` diff --git a/libraries/joomla/di/Tests/ContainerTest.php b/libraries/joomla/di/Tests/ContainerTest.php new file mode 100644 index 0000000000000..7a6db851570c8 --- /dev/null +++ b/libraries/joomla/di/Tests/ContainerTest.php @@ -0,0 +1,949 @@ +fixture = new Container; + } + + /** + * Tear down the tests. + * + * @return void + * + * @since 1.0 + */ + public function tearDown() + { + $this->fixture = null; + } + + /** + * Tests the constructor. + * + * @return void + * + * @since 1.0 + */ + public function testConstructor() + { + $this->assertAttributeEquals( + null, + 'parent', + $this->fixture, + 'A default new object should have a null $parent.' + ); + } + + /** + * Tests the constructor. + * + * @return void + * + * @since 1.0 + */ + public function testConstructorWithParent() + { + $container = new Container($this->fixture); + + $this->assertAttributeInstanceOf( + 'Joomla\\DI\\Container', + 'parent', + $container, + 'A default new object should have a null $parent.' + ); + } + + /** + * Test the alias method. + * + * @return void + * + * @since 1.0 + */ + public function testAlias() + { + $this->fixture->alias('foo', 'bar'); + + $aliases = $this->readAttribute($this->fixture, 'aliases'); + + $this->assertEquals( + array('foo' => 'bar'), + $aliases, + 'When setting an alias, it should be set in the $aliases Container property.' + ); + } + + /** + * Test resolving an alias that has been set. + * + * @return void + * + * @since 1.0 + */ + public function testResolveAliasSet() + { + $reflection = new \ReflectionClass($this->fixture); + $refProp = $reflection->getProperty('aliases'); + $refProp->setAccessible(true); + $refProp->setValue($this->fixture, array('foo' => 'bar')); + + $refMethod = $reflection->getMethod('resolveAlias'); + $refMethod->setAccessible(true); + + $alias = $refMethod->invoke($this->fixture, 'foo'); + + $this->assertEquals( + 'bar', + $alias, + 'When resolving an alias that has been set, the aliased key should be returned.' + ); + } + + /** + * Test resolving an alias that has not been set. + * + * @return void + * + * @since 1.0 + */ + public function testResolveAliasNotSet() + { + $refMethod = new \ReflectionMethod($this->fixture, 'resolveAlias'); + $refMethod->setAccessible(true); + + $alias = $refMethod->invoke($this->fixture, 'foo'); + + $this->assertEquals( + 'foo', + $alias, + 'When resolving an alias that has not been set, the requested key should be returned.' + ); + } + + /** + * Tests the buildObject with no dependencies. + * + * @return void + * + * @since 1.0 + */ + public function testBuildObjectNoDependencies() + { + $object = $this->fixture->buildObject('Joomla\\DI\\Tests\\Stub1'); + + $this->assertInstanceOf( + 'Joomla\\DI\\Tests\\Stub1', + $object, + 'When building an object, an instance of the requested class should be returned.' + ); + } + + /** + * Tests the buildObject, getting dependency from the container. + * + * @return void + * + * @since 1.0 + */ + public function testBuildObjectGetDependencyFromContainer() + { + $this->fixture->set('Joomla\\DI\\Tests\\StubInterface', function () { + return new Stub1; + } + ); + + $object = $this->fixture->buildObject('Joomla\\DI\\Tests\\Stub2'); + + $this->assertAttributeInstanceOf( + 'Joomla\\DI\\Tests\\Stub1', + 'stub', + $object, + 'When building an object, the dependencies should resolve from the container.' + ); + } + + /** + * Tests attempting to build a non-class. + * + * @return void + * + * @since 1.0 + */ + public function testBuildObjectNonClass() + { + $this->assertFalse( + $this->fixture->buildObject('asdf'), + 'Attempting to build a non-class should return false.' + ); + } + + /** + * Tests the buildSharedObject. + * + * @return void + * + * @since 1.0 + */ + public function testBuildSharedObject() + { + $object = $this->fixture->buildSharedObject('Joomla\\DI\\Tests\\Stub1'); + + $this->assertSame( + $object, + $this->fixture->get('Joomla\\DI\\Tests\\Stub1'), + 'Building a shared object should return the same object whenever requested.' + ); + } + + /** + * Tests the creation of a child Container. + * + * @return void + */ + public function testCreateChild() + { + $child = $this->fixture->createChild(); + + $this->assertAttributeInstanceOf( + 'Joomla\\DI\\Container', + 'parent', + $child, + 'When creating a child container, the $parent property should be an instance of Joomla\\DI\\Container.' + ); + + $this->assertAttributeSame( + $this->fixture, + 'parent', + $child, + 'When creating a child container, the $parent property should be the same as the creating Container.' + ); + } + + /** + * Testing the `extend` method. + * + * @return void + * + * @since 1.0 + */ + public function testExtend() + { + $this->fixture->share( + 'foo', + function () + { + return new \stdClass; + } + ); + + $value = 42; + + $this->fixture->extend( + 'foo', + function ($shared) use ($value) + { + $shared->value = $value; + + return $shared; + } + ); + + $one = $this->fixture->get('foo'); + $this->assertInstanceOf('stdClass', $one); + $this->assertEquals($value, $one->value); + + $two = $this->fixture->get('foo'); + $this->assertInstanceOf('stdClass', $two); + $this->assertEquals($value, $two->value); + + $this->assertSame($one, $two); + } + + /** + * Testing the extend method to ensure that a valid key is present to extend. + * + * @return void + * + * @since 1.0 + * + * @expectedException \InvalidArgumentException + */ + public function testExtendValidatesKeyIsPresent() + { + $this->fixture->extend( + 'foo', + function () + { + // Noop. + } + ); + } + + /** + * Test getting method args + * + * @return void + * + * @since 1.0 + */ + public function testGetMethodArgsFromContainer() + { + $this->fixture->set( + 'Joomla\\DI\\Tests\\StubInterface', + function () + { + return new Stub1; + } + ); + + $reflectionMethod = new \ReflectionMethod($this->fixture, 'getMethodArgs'); + $reflectionMethod->setAccessible(true); + + $reflectionClass = new \ReflectionClass('Joomla\\DI\\Tests\\Stub2'); + $constructor = $reflectionClass->getConstructor(); + + $args = $reflectionMethod->invoke($this->fixture, $constructor); + + $this->assertInstanceOf( + 'Joomla\\DI\\Tests\\Stub1', + $args[0], + 'When getting method args, it should resolve dependencies from the container if set.' + ); + } + + /** + * Test getting method args as concrete class + * + * @return void + * + * @since 1.0 + */ + public function testGetMethodArgsConcreteClass() + { + $reflectionMethod = new \ReflectionMethod($this->fixture, 'getMethodArgs'); + $reflectionMethod->setAccessible(true); + + $reflectionClass = new \ReflectionClass('Joomla\\DI\\Tests\\Stub5'); + $constructor = $reflectionClass->getConstructor(); + + $args = $reflectionMethod->invoke($this->fixture, $constructor); + + $this->assertInstanceOf( + 'Joomla\\DI\\Tests\\Stub4', + $args[0], + 'When getting method args, it should create any concrete dependencies.' + ); + } + + /** + * Test getting method args as default values + * + * @return void + * + * @since 1.0 + */ + public function testGetMethodArgsDefaultValues() + { + $reflectionMethod = new \ReflectionMethod($this->fixture, 'getMethodArgs'); + $reflectionMethod->setAccessible(true); + + $reflectionClass = new \ReflectionClass('Joomla\\DI\\Tests\\Stub6'); + $constructor = $reflectionClass->getConstructor(); + + $args = $reflectionMethod->invoke($this->fixture, $constructor); + + $this->assertEquals( + 'foo', + $args[0], + 'When getting method args, it should resolve dependencies from their default values.' + ); + } + + /** + * Test getting method args that can't resolve. + * + * @return void + * + * @since 1.0 + * + * @expectedException \Joomla\DI\Exception\DependencyResolutionException + */ + public function testGetMethodArgsCantResolve() + { + $reflectionMethod = new \ReflectionMethod($this->fixture, 'getMethodArgs'); + $reflectionMethod->setAccessible(true); + + $reflectionClass = new \ReflectionClass('Joomla\\DI\\Tests\\Stub7'); + $constructor = $reflectionClass->getConstructor(); + + $reflectionMethod->invoke($this->fixture, $constructor); + } + + /** + * Test getting method args that can't resolve. + * + * @return void + * + * @since 1.0 + * + * @expectedException \Joomla\DI\Exception\DependencyResolutionException + */ + public function testGetMethodArgsResolvedIsNotInstanceOfHintedDependency() + { + $this->fixture->set( + 'Joomla\\DI\\Tests\\StubInterface', + function () + { + return new Stub9; + } + ); + + $reflectionMethod = new \ReflectionMethod($this->fixture, 'getMethodArgs'); + $reflectionMethod->setAccessible(true); + + $reflectionClass = new \ReflectionClass('Joomla\\DI\\Tests\\Stub2'); + $constructor = $reflectionClass->getConstructor(); + + $reflectionMethod->invoke($this->fixture, $constructor); + } + + /** + * Tests the set method a callable value. + * + * @return void + * + * @since 1.0 + */ + public function testSetCallable() + { + $this->fixture->set('foo', array($this, 'callMe')); + $this->assertEquals('called', $this->fixture->get('foo')); + } + + /** + * Tests the set method with bad callback. + * + * @return void + * + * @since 1.0 + */ + public function testSetNotCallable() + { + $this->fixture->set('foo', 'bar'); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertInstanceOf( + 'Closure', + $dataStore['foo']['callback'], + 'Passing a non-closure to set will wrap the item in a closure for easy resolution and extension.' + ); + + $this->assertEquals( + 'bar', + $dataStore['foo']['callback']($this->fixture), + 'Resolving a non-closure should return the set value.' + ); + } + + /** + * Tests the set method with already set protected key. + * + * @return void + * + * @since 1.0 + * + * @expectedException \OutOfBoundsException + */ + public function testSetAlreadySetProtected() + { + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + }, + false, + true + ); + + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + }, + false, + true + ); + } + + /** + * Tests the set method with already set not protected key. + * + * @return void + * + * @since 1.0 + */ + public function testSetAlreadySetNotProtected() + { + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + } + ); + + $this->fixture->set( + 'foo', + function () + { + return 'bar'; + } + ); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertSame( + $dataStore['foo']['callback']($this->fixture), + 'bar', + 'Overwriting a non-protected key should be allowed.' + ); + } + + /** + * Tests the set method as default shared. + * + * @return void + * + * @since 1.0 + */ + public function testSetShared() + { + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + }, + true + ); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertTrue($dataStore['foo']['shared']); + } + + /** + * Tests the set method not shared. + * + * @return void + * + * @since 1.0 + */ + public function testSetNotShared() + { + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + }, + false + ); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertFalse($dataStore['foo']['shared']); + } + + /** + * Tests the protected method. + * + * @return void + * + * @since 1.0 + */ + public function testProtect() + { + $this->fixture->protect( + 'foo', + function () + { + return new \stdClass; + } + ); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertTrue( + $dataStore['foo']['protected'], + 'The protect convenience method sets items as protected.' + ); + + $this->assertFalse( + $dataStore['foo']['shared'], + 'The protected method does not set shared by default.' + ); + } + + /** + * Tests the protected method when passing the shared arg.. + * + * @return void + * + * @since 1.0 + */ + public function testProtectShared() + { + $this->fixture->protect( + 'foo', + function () + { + return new \stdClass; + }, + true + ); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertTrue( + $dataStore['foo']['protected'], + 'The protect convenience method sets items as protected.' + ); + + $this->assertTrue( + $dataStore['foo']['shared'], + 'The protected method does set shared when passed true as third arg.' + ); + } + + /** + * Tests the share method. + * + * @return void + * + * @since 1.0 + */ + public function testShare() + { + $this->fixture->share( + 'foo', + function () + { + return new \stdClass; + } + ); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertTrue( + $dataStore['foo']['shared'], + 'The share convenience method sets items as shared.' + ); + + $this->assertFalse( + $dataStore['foo']['protected'], + 'The protected method does not set protected by default.' + ); + } + + /** + * Tests the protected method when passing the shared arg.. + * + * @return void + * + * @since 1.0 + */ + public function testShareProtected() + { + $this->fixture->share( + 'foo', + function () + { + return new \stdClass; + }, + true + ); + + $dataStore = $this->readAttribute($this->fixture, 'dataStore'); + + $this->assertTrue( + $dataStore['foo']['protected'], + 'The shared method does set protected when passed true as third arg.' + ); + + $this->assertTrue( + $dataStore['foo']['shared'], + 'The share convenience method sets items as shared.' + ); + } + + /** + * Tests the get method shared. + * + * @return void + * + * @since 1.0 + */ + public function testGetShared() + { + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + }, + true + ); + $this->assertSame($this->fixture->get('foo'), $this->fixture->get('foo')); + } + + /** + * Tests the get method not shared. + * + * @return void + * + * @since 1.0 + */ + public function testGetNotShared() + { + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + }, + false + ); + $this->assertNotSame($this->fixture->get('foo'), $this->fixture->get('foo')); + } + + /** + * Tests the get method on a non-existent offset. + * + * @return void + * + * @since 1.0 + * + * @expectedException \InvalidArgumentException + */ + public function testGetNotExists() + { + $this->fixture->get('foo'); + } + + /** + * Tests the get method for passing the + * Joomla\DI\Container instance to the callback. + * + * @return void + * + * @since 1.0 + */ + public function testGetPassesContainerInstanceShared() + { + $this->fixture->set( + 'foo', + function ($c) + { + return $c; + } + ); + + $this->assertSame($this->fixture, $this->fixture->get('foo')); + } + + /** + * Tests the get method for passing the + * Joomla\DI\Container instance to the callback. + * + * @return void + * + * @since 1.0 + */ + public function testGetPassesContainerInstanceNotShared() + { + $this->fixture->set( + 'foo', + function ($c) + { + return $c; + }, + false + ); + + $this->assertSame($this->fixture, $this->fixture->get('foo')); + } + + /** + * Test exists + * + * @return void + * + * @since 1.0 + */ + public function testExists() + { + $reflection = new \ReflectionProperty($this->fixture, 'dataStore'); + $reflection->setAccessible(true); + $reflection->setValue($this->fixture, array('foo' => 'bar')); + + $this->assertTrue( + $this->fixture->exists('foo'), + 'When calling exists on an item that has been set in the container, it should return true.' + ); + + $this->assertFalse( + $this->fixture->exists('baz'), + 'When calling exists on an item that has not been set in the container, it should return false.' + ); + } + + + /** + * Test getRaw + * + * @return void + * + * @since 1.0 + */ + public function testGetRaw() + { + $reflectionMethod = new \ReflectionMethod($this->fixture, 'getRaw'); + $reflectionMethod->setAccessible(true); + + $function = function () + { + return 'foo'; + }; + + $this->fixture->set('foo', $function); + + $raw = $reflectionMethod->invoke($this->fixture, 'foo'); + + $this->assertSame( + $function, + $raw['callback'], + 'getRaw should return the raw object uncalled' + ); + } + + /** + * Test getRaw + * + * @return void + * + * @since 1.0 + */ + public function testGetRawFromParent() + { + $reflectionMethod = new \ReflectionMethod($this->fixture, 'getRaw'); + $reflectionMethod->setAccessible(true); + + $function = function () + { + return 'foo'; + }; + + $this->fixture->set('foo', $function); + + $child = new Container($this->fixture); + + $raw = $reflectionMethod->invoke($child, 'foo'); + + $this->assertSame( + $function, + $raw['callback'], + 'getRaw should return the raw object uncalled' + ); + } + + /** + * Tests the getNew method which will always return a + * new instance, even if the $key was set to be shared. + * + * @return void + * + * @since 1.0 + */ + public function testGetNewInstance() + { + $this->fixture->set( + 'foo', + function () + { + return new \stdClass; + } + ); + + $this->assertNotSame($this->fixture->getNewInstance('foo'), $this->fixture->getNewInstance('foo')); + } + + /** + * Test registering a service provider. Make sure register get's called. + * + * @return void + * + * @since 1.0 + */ + public function testRegisterServiceProvider() + { + $mock = $this->getMock('Joomla\\DI\\ServiceProviderInterface'); + + $mock->expects($this->once()) + ->method('register'); + + $returned = $this->fixture->registerServiceProvider($mock); + + $this->assertSame( + $returned, + $this->fixture, + 'When registering a service provider, the container instance should be returned.' + ); + } +} diff --git a/libraries/joomla/di/Tests/Stubs/stubs.php b/libraries/joomla/di/Tests/Stubs/stubs.php new file mode 100644 index 0000000000000..e75b291f8c950 --- /dev/null +++ b/libraries/joomla/di/Tests/Stubs/stubs.php @@ -0,0 +1,81 @@ +stub = $stub; + } +} + +class Stub3 +{ + protected $stub; + protected $stub2; + + public function __construct(StubInterface $stub, StubInterface $stub2) + { + $this->stub = $stub; + $this->stub2 = $stub2; + } +} + +class Stub4 implements StubInterface {} + +class Stub5 +{ + protected $stub; + + public function __construct(Stub4 $stub) + { + $this->stub = $stub; + } +} + +class Stub6 +{ + protected $stub; + + public function __construct($stub = 'foo') + { + $this->stub = $stub; + } +} + +class Stub7 +{ + protected $stub; + + public function __construct($stub) + { + $this->stub = $stub; + } +} + +class Stub8 +{ + protected $stub; + + public function __construct(DoesntExist $stub) + { + $this->stub = $stub; + } +} + +class Stub9 +{ +} diff --git a/libraries/joomla/di/composer.json b/libraries/joomla/di/composer.json new file mode 100644 index 0000000000000..fd5486154478d --- /dev/null +++ b/libraries/joomla/di/composer.json @@ -0,0 +1,17 @@ +{ + "name": "joomla/di", + "type": "joomla-package", + "description": "Joomla DI Package", + "keywords": ["joomla", "framework", "dependency injection", "di", "ioc", "container"], + "homepage": "https://github.com/joomla-framework/di", + "license": "GPL-2.0+", + "require": { + "php": ">=5.3.10" + }, + "autoload": { + "psr-4": { + "Joomla\\DI\\": "src/", + "Joomla\\DI\\Tests\\": "Tests/" + } + } +} diff --git a/libraries/joomla/di/docs/why-dependency-injection.md b/libraries/joomla/di/docs/why-dependency-injection.md new file mode 100644 index 0000000000000..2e2e9eacfa69f --- /dev/null +++ b/libraries/joomla/di/docs/why-dependency-injection.md @@ -0,0 +1,175 @@ +# Why Dependency Injection + +Dependency Injection (DI) can be a somewhat complicated concept to those who aren't familiar with it. Once you see it and get used to it the benefits become clear, so let's go over an example: + +```php +class Samurai +{ + private $sword; + private $shuriken; + + public function __construct() + { + $this->sword = new Sword; + $this->shuriken = new Shuriken; + } + + public function attack($useSword = true) + { + if ($useSword) + { + $this->sword->hit(); + } + else + { + $this->shuriken->hit(); + } + } +} +``` +```php +class Sword +{ + public function hit($target) + { + echo 'Hit the ' . $target; + } +} +``` +```php +class Shuriken +{ + public function hit($target) + { + echo 'Throw shuriken at ' . $target; + } +} +``` +```php +$warrior = new Samurai; + +// preparations.... + +$warrior->attack(); +``` + +### The Situation + +In the last code block above, imagine yourself as the commander of a samurai army. You are aware of the battle and what needs to be done to win, and as such, you are preparing your attack. So, you tell one of your warriors to prepare themselves for battle. As he's preparing, he has to stop and locate his weapons before he is ready to attack. Then, he stands idle waiting for your command, which you issue. He runs out sword drawn, but then you realize it would be better to use a bow and arrow instead. But your warrior didn't know to bring his bow with him. The battle is lost because of poor preparation. + +### The Problem + +Since your told your warrior to prepare himself for battle, he took the items he was familiar with and prepared the best he could. There's no way he could carry every possible weapon you might request of him. Instead of letting the samurai dictate what weapons to use, it would obviously be better for you to provide the weapons for him. + +### The Solution + +The best way to solve this is to provide the weapon for him as he's preparing. There is one major task you need to do in order to train the samurai on how to use any weapon you might throw at him, but it's worth the effort. + +#### Create an Interface + +An interface is a contract between the implementing class and the calling class that certain criteria will be met by each class that implements the interface. We currently have 2 weapons, let's make a contract for them, and then implement that contract in the classes so the samurai is properly trained. + +```php +interface WeaponInterface +{ + public function hit($target); +} + +class Sword implements WeaponInterface +{ + public function hit($target) + { + echo 'Hit ' . $target; + } +} + +class Shuriken implements WeaponInterface +{ + public function hit($target) + { + echo 'Throw shuriken at ' . $target; + } +} +``` + +Now that we know our weapons will have a hit method, and since they signed the contract by implementing the interface, we can easily modify our samurai to receive one of these weapons while he's preparing. + +```php +class Samurai +{ + protected $weapon; + + public function __construct(WeaponInterface $weapon) + { + $this->weapon = $weapon; + } + + public function setWeapon(WeaponInterface $weapon) + { + $this->weapon = $weapon; + } + + public function attack($target) + { + $this->weapon->hit($target); + } +} +``` + +As you can see, we've greatly reduced the amount of preparation work he needs to do. + +```php +$warrior = new Samurai(new Sword); + +$warrior->attack('the enemy'); +``` + +That's the basics of DI. Passing the requirements for a class to the class via it's constructor or via a `setProperty` method, where "property" would typically match the name of the property you are setting, as in the second version of the Samurai class with the `setWeapon` method. Here's an example using the setter for DI. + +```php +$warrior = new Samurai; + +$warrior->setWeapon(new Sword); + +$warrior->attack(); +``` + +## How A Can Container Help + +An Inversion of Control (IoC) Container can help you to manage all the parts of the application. Instead of re-building a new warrior each time, it would be much easier for the app to remember how to prepare a warrior and be able to create one on demand. In our example, since the Samurai doesn't have a lot of dependencies, the benefits of a container might be hard to see. But consider that each time you want to create a warrior you need to remember to pass in the dependencies. With a container, you can set up a template, so to speak, and let the app handle the creation. It REALLY comes in handy when the dependencies you are injecting have dependencies within their dependencies. It can get very complicated very fast. + +```php +$warrior = new Samurai(new Sword); +$warrior->attack(); + +$warrior = new Samurai(new Sword); +$warrior->attack(); + +$warrior = new Samurai(new Sword); +$warrior->attack(); + +$warrior = new Samurai(new Sword); +$warrior->attack(); + +// vs + +$ioc['warrior']->attack(); +$ioc['warrior']->attack(); +$ioc['warrior']->attack(); +$ioc['warrior']->attack(); + +/** + * This would be in your app bootstrap + * or somewhere out of the way. + */ +$ioc = new Joomla\DI\Container; + +$ioc->set('warrior', function () +{ + return new Samurai(new Sword); +}, false); +``` + +``` +Note: The samurai concept came from a DI/IoC video about using Ninject in .NET. I've expanded upon the concept here. +``` \ No newline at end of file diff --git a/libraries/joomla/di/phpunit.xml.dist b/libraries/joomla/di/phpunit.xml.dist new file mode 100644 index 0000000000000..2278bfbac86a6 --- /dev/null +++ b/libraries/joomla/di/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + Tests + + + diff --git a/libraries/joomla/di/src/Container.php b/libraries/joomla/di/src/Container.php new file mode 100644 index 0000000000000..3fbf06909f6e8 --- /dev/null +++ b/libraries/joomla/di/src/Container.php @@ -0,0 +1,428 @@ +parent = $parent; + } + + /** + * Create an alias for a given key for easy access. + * + * @param string $alias The alias name + * @param string $key The key to alias + * + * @return Container This object for chaining. + * + * @since 1.0 + */ + public function alias($alias, $key) + { + $this->aliases[$alias] = $key; + + return $this; + } + + /** + * Search the aliases property for a matching alias key. + * + * @param string $key The key to search for. + * + * @return string + * + * @since 1.0 + */ + protected function resolveAlias($key) + { + if (isset($this->aliases[$key])) + { + return $this->aliases[$key]; + } + + return $key; + } + + /** + * Build an object of class $key; + * + * @param string $key The class name to build. + * @param boolean $shared True to create a shared resource. + * + * @return mixed Instance of class specified by $key with all dependencies injected. + * Returns an object if the class exists and false otherwise + * + * @since 1.0 + */ + public function buildObject($key, $shared = false) + { + try + { + $reflection = new \ReflectionClass($key); + } + catch (\ReflectionException $e) + { + return false; + } + + $constructor = $reflection->getConstructor(); + + // If there are no parameters, just return a new object. + if (is_null($constructor)) + { + $callback = function () use ($key) { + return new $key; + }; + } + else + { + $newInstanceArgs = $this->getMethodArgs($constructor); + + // Create a callable for the dataStore + $callback = function () use ($reflection, $newInstanceArgs) { + return $reflection->newInstanceArgs($newInstanceArgs); + }; + } + + return $this->set($key, $callback, $shared)->get($key); + } + + /** + * Convenience method for building a shared object. + * + * @param string $key The class name to build. + * + * @return object Instance of class specified by $key with all dependencies injected. + * + * @since 1.0 + */ + public function buildSharedObject($key) + { + return $this->buildObject($key, true); + } + + /** + * Create a child Container with a new property scope that + * that has the ability to access the parent scope when resolving. + * + * @return Container This object for chaining. + * + * @since 1.0 + */ + public function createChild() + { + return new static($this); + } + + /** + * Extend a defined service Closure by wrapping the existing one with a new Closure. This + * works very similar to a decorator pattern. Note that this only works on service Closures + * that have been defined in the current Provider, not parent providers. + * + * @param string $key The unique identifier for the Closure or property. + * @param \Closure $callable A Closure to wrap the original service Closure. + * + * @return void + * + * @since 1.0 + * @throws \InvalidArgumentException + */ + public function extend($key, \Closure $callable) + { + $raw = $this->getRaw($key); + + if (is_null($raw)) + { + throw new \InvalidArgumentException(sprintf('The requested key %s does not exist to extend.', $key)); + } + + $closure = function ($c) use($callable, $raw) { + return $callable($raw['callback']($c), $c); + }; + + $this->set($key, $closure, $raw['shared']); + } + + /** + * Build an array of constructor parameters. + * + * @param \ReflectionMethod $method Method for which to build the argument array. + * + * @return array Array of arguments to pass to the method. + * + * @since 1.0 + * @throws DependencyResolutionException + */ + protected function getMethodArgs(\ReflectionMethod $method) + { + $methodArgs = array(); + + foreach ($method->getParameters() as $param) + { + $dependency = $param->getClass(); + $dependencyVarName = $param->getName(); + + // If we have a dependency, that means it has been type-hinted. + if (!is_null($dependency)) + { + $dependencyClassName = $dependency->getName(); + + // If the dependency class name is registered with this container or a parent, use it. + if ($this->getRaw($dependencyClassName) !== null) + { + $depObject = $this->get($dependencyClassName); + } + else + { + $depObject = $this->buildObject($dependencyClassName); + } + + if ($depObject instanceof $dependencyClassName) + { + $methodArgs[] = $depObject; + continue; + } + } + + // Finally, if there is a default parameter, use it. + if ($param->isOptional()) + { + $methodArgs[] = $param->getDefaultValue(); + continue; + } + + // Couldn't resolve dependency, and no default was provided. + throw new DependencyResolutionException(sprintf('Could not resolve dependency: %s', $dependencyVarName)); + } + + return $methodArgs; + } + + /** + * Method to set the key and callback to the dataStore array. + * + * @param string $key Name of dataStore key to set. + * @param mixed $value Callable function to run or string to retrive when requesting the specified $key. + * @param boolean $shared True to create and store a shared instance. + * @param boolean $protected True to protect this item from being overwritten. Useful for services. + * + * @return Container This object for chaining. + * + * @throws \OutOfBoundsException Thrown if the provided key is already set and is protected. + * + * @since 1.0 + */ + public function set($key, $value, $shared = false, $protected = false) + { + if (isset($this->dataStore[$key]) && $this->dataStore[$key]['protected'] === true) + { + throw new \OutOfBoundsException(sprintf('Key %s is protected and can\'t be overwritten.', $key)); + } + + // If the provided $value is not a closure, make it one now for easy resolution. + if (!is_callable($value)) + { + $value = function () use ($value) { + return $value; + }; + } + + $this->dataStore[$key] = array( + 'callback' => $value, + 'shared' => $shared, + 'protected' => $protected + ); + + return $this; + } + + /** + * Convenience method for creating protected keys. + * + * @param string $key Name of dataStore key to set. + * @param callable $callback Callable function to run when requesting the specified $key. + * @param bool $shared True to create and store a shared instance. + * + * @return Container This object for chaining. + * + * @since 1.0 + */ + public function protect($key, $callback, $shared = false) + { + return $this->set($key, $callback, $shared, true); + } + + /** + * Convenience method for creating shared keys. + * + * @param string $key Name of dataStore key to set. + * @param callable $callback Callable function to run when requesting the specified $key. + * @param bool $protected True to create and store a shared instance. + * + * @return Container This object for chaining. + * + * @since 1.0 + */ + public function share($key, $callback, $protected = false) + { + return $this->set($key, $callback, true, $protected); + } + + /** + * Method to retrieve the results of running the $callback for the specified $key; + * + * @param string $key Name of the dataStore key to get. + * @param boolean $forceNew True to force creation and return of a new instance. + * + * @return mixed Results of running the $callback for the specified $key. + * + * @since 1.0 + * @throws \InvalidArgumentException + */ + public function get($key, $forceNew = false) + { + $raw = $this->getRaw($key); + + if (is_null($raw)) + { + throw new \InvalidArgumentException(sprintf('Key %s has not been registered with the container.', $key)); + } + + if ($raw['shared']) + { + if (!isset($this->instances[$key]) || $forceNew) + { + $this->instances[$key] = $raw['callback']($this); + } + + return $this->instances[$key]; + } + + return call_user_func($raw['callback'], $this); + } + + /** + * Method to check if specified dataStore key exists. + * + * @param string $key Name of the dataStore key to check. + * + * @return boolean True for success + * + * @since 1.0 + */ + public function exists($key) + { + return (bool) $this->getRaw($key); + } + + /** + * Get the raw data assigned to a key. + * + * @param string $key The key for which to get the stored item. + * + * @return mixed + * + * @since 1.0 + */ + protected function getRaw($key) + { + $key = $this->resolveAlias($key); + + if (isset($this->dataStore[$key])) + { + return $this->dataStore[$key]; + } + elseif ($this->parent instanceof Container) + { + return $this->parent->getRaw($key); + } + + return null; + } + + /** + * Method to force the container to return a new instance + * of the results of the callback for requested $key. + * + * @param string $key Name of the dataStore key to get. + * + * @return mixed Results of running the $callback for the specified $key. + * + * @since 1.0 + */ + public function getNewInstance($key) + { + return $this->get($key, true); + } + + /** + * Register a service provider to the container. + * + * @param ServiceProviderInterface $provider The service provider to register.w + * + * @return Container This object for chaining. + * + * @since 1.0 + */ + public function registerServiceProvider(ServiceProviderInterface $provider) + { + $provider->register($this); + + return $this; + } +} diff --git a/libraries/joomla/di/src/ContainerAwareInterface.php b/libraries/joomla/di/src/ContainerAwareInterface.php new file mode 100644 index 0000000000000..879da36507993 --- /dev/null +++ b/libraries/joomla/di/src/ContainerAwareInterface.php @@ -0,0 +1,39 @@ +container) + { + return $this->container; + } + + throw new \UnexpectedValueException('Container not set in ' . __CLASS__); + } + + /** + * Set the DI container. + * + * @param Container $container The DI container. + * + * @return mixed Returns itself to support chaining. + * + * @since 1.2 + */ + public function setContainer(Container $container) + { + $this->container = $container; + + return $this; + } +} diff --git a/libraries/joomla/di/src/Exception/DependencyResolutionException.php b/libraries/joomla/di/src/Exception/DependencyResolutionException.php new file mode 100644 index 0000000000000..96dd837799066 --- /dev/null +++ b/libraries/joomla/di/src/Exception/DependencyResolutionException.php @@ -0,0 +1,18 @@ + + Copyright (C) + + 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 2 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, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/libraries/joomla/registry/README.md b/libraries/joomla/registry/README.md new file mode 100644 index 0000000000000..7ee6a861d0e2d --- /dev/null +++ b/libraries/joomla/registry/README.md @@ -0,0 +1,279 @@ +# The Registry Package + +``` php +use Joomla\Registry\Registry; + +$registry = new Registry; + +// Set a value in the registry. +$registry->set('foo') = 'bar'; + +// Get a value from the registry; +$value = $registry->get('foo'); + +``` + +## Load config by Registry + +``` php +use Joomla\Registry\Registry; + +$registry = new Registry; + +// Load by string +$registry->loadString('{"foo" : "bar"}'); + +$registry->loadString('', 'xml'); + +// Load by object or array +$registry->loadObject($object); +$registry->loadaArray($array); + +// Load by file +$registry->loadFile($root . '/config/config.json', 'json'); +``` + +## Accessing a Registry by getter & setter + +### Get value + +``` php +$registry->get('foo'); + +// Get a non-exists value and return default +$registry->get('foo', 'default'); + +// OR + +$registry->get('foo') ?: 'default'; +``` + +### Set value + +``` php +// Set value +$registry->set('bar', $value); + +// Sets a default value if not already assigned. +$registry->def('bar', $default); +``` + +### Accessing children value by path + +``` php +$json = '{ + "parent" : { + "child" : "Foo" + } +}'; + +$registry = new Registry($json); + +$registry->get('parent.child'); // return 'Foo' + +$registry->set('parent.child', $value); +``` + +## Accessing a Registry as an Array + +The `Registry` class implements `ArrayAccess` so the properties of the registry can be accessed as an array. Consider the following examples: + +``` php +// Set a value in the registry. +$registry['foo'] = 'bar'; + +// Get a value from the registry; +$value = $registry['foo']; + +// Check if a key in the registry is set. +if (isset($registry['foo'])) +{ + echo 'Say bar.'; +} +``` + +## Merge Registry + +#### Using load* methods to merge two config files. + +``` php +$json1 = '{ + "field" : { + "keyA" : "valueA", + "keyB" : "valueB" + } +}'; + +$json2 = '{ + "field" : { + "keyB" : "a new valueB" + } +}'; + +$registry->loadString($json1); +$registry->loadString($json2); +``` + +Output + +``` +Array( + field => Array( + keyA => valueA + keyB => a new valueB + ) +) +``` + +#### Merge another Registry + +``` php +$object1 = '{ + "foo" : "foo value", + "bar" : { + "bar1" : "bar value 1", + "bar2" : "bar value 2" + } +}'; + +$object2 = '{ + "foo" : "foo value", + "bar" : { + "bar2" : "new bar value 2" + } +}'; + +$registry1 = new Registry(json_decode($object1)); +$registry2 = new Registry(json_decode($object2)); + +$registry1->merge($registry2); +``` + +If you just want to merge first level, do not hope recursive: + +``` php +$registry1->merge($registry2, false); // Set param 2 to false that Registry will only merge first level +``` + +## Dump to file. + +``` php +$registry->toString(); + +$registry->toString('xml'); + +$registry->toString('ini'); +``` + +## Using YAML + +Add Symfony YAML component in `composer.json` + +``` json +{ + "require-dev": { + "symfony/yaml": "~2.0" + } +} +``` + +Using `yaml` format + +``` php +$registry->loadFile($yamlFile, 'yaml'); + +$registry->loadString('foo: bar', 'yaml'); + +// Convert to string +$registry->toString('yaml'); +``` + +## Using XML + +Keep in mind that due to XML complexity, special format must be kept when loading into Registry. +By default, the parent XML element should be named "registry" and all child elements should be named "node". +The nodes should include a "name" attribute, for the name of the value. The nodes can be optionally filtered with a "type" +attribute. Valid types are: + +* array +* boolean +* double +* integer +* object (default) +* string + +**Loading input** + +``` xml + + + bar + 1 + 42 + 3.1415 + + value + + + value + + +``` + +with `Registry` + +``` php +$registry = new Registry; + +// Load file or string +$registry->loadFile($xmlFile, 'xml'); +$registry->loadString($xmlString, 'xml'); +``` + +Outputs + +``` +Array( + foo_1 => bar + foo_2 => 1 + foo_3 => 42 + foo_4 => 3.1415 + foo_5 => Array( + foo_5_a => value + ) + foo_6 => Array( + foo_6_a => value + ) +) +``` + +The names of the XML import nodes can be customised using options. For example: + +``` php +$registry = new Registry(array( + 'name' => 'data', + 'nodeName' => 'value' +)); + +$registry->loadString('bar, 'xml'); +``` + +## Installation via Composer + +Add `"joomla/registry": "dev-master"` to the require block in your composer.json, make sure you have `"minimum-stability": "dev"` and then run `composer install`. + +```json +{ + "require": { + "joomla/registry": "dev-master" + }, + "minimum-stability": "dev" +} +``` + +Alternatively, you can simply run the following from the command line: + +```sh +composer init --stability="dev" +composer require joomla/registry "dev-master" +``` diff --git a/libraries/joomla/registry/Tests/FormatTest.php b/libraries/joomla/registry/Tests/FormatTest.php new file mode 100644 index 0000000000000..228c31bd229d2 --- /dev/null +++ b/libraries/joomla/registry/Tests/FormatTest.php @@ -0,0 +1,69 @@ +assertThat( + $object instanceof $class, + $this->isTrue() + ); + } + + /** + * Test getInstance with a non-existent format. + * + * @return void + * + * @expectedException \InvalidArgumentException + * @since 1.0 + */ + public function testGetInstanceNonExistent() + { + AbstractRegistryFormat::getInstance('SQL'); + } +} diff --git a/libraries/joomla/registry/Tests/RegistryTest.php b/libraries/joomla/registry/Tests/RegistryTest.php new file mode 100644 index 0000000000000..9ab383b72f4a9 --- /dev/null +++ b/libraries/joomla/registry/Tests/RegistryTest.php @@ -0,0 +1,749 @@ + '123', 'b' => '456')); + $a->set('foo', 'bar'); + $b = clone $a; + + $this->assertThat( + serialize($a), + $this->equalTo(serialize($b)) + ); + + $this->assertThat( + $a, + $this->logicalNot($this->identicalTo($b)), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::__toString method. + * + * @return void + * + * @covers Joomla\Registry\Registry::__toString + * @since 1.0 + */ + public function test__toString() + { + $object = new \stdClass; + $a = new Registry($object); + $a->set('foo', 'bar'); + + // __toString only allows for a JSON value. + $this->assertThat( + (string) $a, + $this->equalTo('{"foo":"bar"}'), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::jsonSerialize method. + * + * @return void + * + * @covers Joomla\Registry\Registry::jsonSerialize + * @since 1.0 + */ + public function testJsonSerialize() + { + if (version_compare(PHP_VERSION, '5.4.0', '<')) + { + $this->markTestSkipped('This test requires PHP 5.4 or newer.'); + } + + $object = new \stdClass; + $a = new Registry($object); + $a->set('foo', 'bar'); + + // __toString only allows for a JSON value. + $this->assertThat( + json_encode($a), + $this->equalTo('{"foo":"bar"}'), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Tests serializing Registry objects. + * + * @return void + * + * @since 1.0 + */ + public function testSerialize() + { + $a = new Registry; + $a->set('foo', 'bar'); + + $serialized = serialize($a); + $b = unserialize($serialized); + + // __toString only allows for a JSON value. + $this->assertThat( + $b, + $this->equalTo($a), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::def method. + * + * @return void + * + * @covers Joomla\Registry\Registry::def + * @since 1.0 + */ + public function testDef() + { + $a = new Registry; + + $this->assertThat( + $a->def('foo', 'bar'), + $this->equalTo('bar'), + 'Line: ' . __LINE__ . '. def should return default value' + ); + + $this->assertThat( + $a->get('foo'), + $this->equalTo('bar'), + 'Line: ' . __LINE__ . '. default should now be the current value' + ); + } + + /** + * Tet the Joomla\Registry\Registry::bindData method. + * + * @return void + * + * @covers Joomla\Registry\Registry::bindData + * @since 1.0 + */ + public function testBindData() + { + $a = new Registry; + $parent = new \stdClass; + + TestHelper::invoke($a, 'bindData', $parent, 'foo'); + $this->assertThat( + $parent->{0}, + $this->equalTo('foo'), + 'Line: ' . __LINE__ . ' The input value should exist in the parent object.' + ); + + TestHelper::invoke($a, 'bindData', $parent, array('foo' => 'bar')); + $this->assertThat( + $parent->{'foo'}, + $this->equalTo('bar'), + 'Line: ' . __LINE__ . ' The input value should exist in the parent object.' + ); + + TestHelper::invoke($a, 'bindData', $parent, array('level1' => array('level2' => 'value2'))); + $this->assertThat( + $parent->{'level1'}->{'level2'}, + $this->equalTo('value2'), + 'Line: ' . __LINE__ . ' The input value should exist in the parent object.' + ); + + TestHelper::invoke($a, 'bindData', $parent, array('intarray' => array(0, 1, 2))); + $this->assertThat( + $parent->{'intarray'}, + $this->equalTo(array(0, 1, 2)), + 'Line: ' . __LINE__ . ' The un-associative array should bind natively.' + ); + } + + /** + * Test the Joomla\Registry\Registry::exists method. + * + * @return void + * + * @covers Joomla\Registry\Registry::exists + * @since 1.0 + */ + public function testExists() + { + $a = new Registry; + $a->set('foo', 'bar1'); + $a->set('config.foo', 'bar2'); + $a->set('deep.level.foo', 'bar3'); + + $this->assertThat( + $a->exists('foo'), + $this->isTrue(), + 'Line: ' . __LINE__ . ' The path should exist, returning true.' + ); + + $this->assertThat( + $a->exists('config.foo'), + $this->isTrue(), + 'Line: ' . __LINE__ . ' The path should exist, returning true.' + ); + + $this->assertThat( + $a->exists('deep.level.foo'), + $this->isTrue(), + 'Line: ' . __LINE__ . ' The path should exist, returning true.' + ); + + $this->assertThat( + $a->exists('deep.level.bar'), + $this->isFalse(), + 'Line: ' . __LINE__ . ' The path should not exist, returning false.' + ); + + $this->assertThat( + $a->exists('bar.foo'), + $this->isFalse(), + 'Line: ' . __LINE__ . ' The path should not exist, returning false.' + ); + } + + /** + * Test the Joomla\Registry\Registry::get method + * + * @return void + * + * @covers Joomla\Registry\Registry::get + * @since 1.0 + */ + public function testGet() + { + $a = new Registry; + $a->set('foo', 'bar'); + $this->assertEquals('bar', $a->get('foo'), 'Line: ' . __LINE__ . ' get method should work.'); + $this->assertNull($a->get('xxx.yyy'), 'Line: ' . __LINE__ . ' get should return null when not found.'); + } + + /** + * Test the Joomla\Registry\Registry::getInstance method. + * + * @return void + * + * @covers Joomla\Registry\Registry::getInstance + * @since 1.0 + */ + public function testGetInstance() + { + // Test INI format. + $a = Registry::getInstance('a'); + $b = Registry::getInstance('a'); + $c = Registry::getInstance('c'); + + // Check the object type. + $this->assertInstanceOf( + '\\Joomla\\Registry\\Registry', + $a, + 'Line ' . __LINE__ . ' - Object $a should be an instance of Registry.' + ); + + // Check cache handling for same registry id. + $this->assertThat( + $a, + $this->identicalTo($b), + 'Line: ' . __LINE__ . '.' + ); + + // Check cache handling for different registry id. + $this->assertThat( + $a, + $this->logicalNot($this->identicalTo($c)), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::loadArray method. + * + * @return void + * + * @covers Joomla\Registry\Registry::loadArray + * @since 1.0 + */ + public function testLoadArray() + { + $array = array( + 'foo' => 'bar' + ); + $registry = new Registry; + $result = $registry->loadArray($array); + + // Checking result is self that we can chaining + $this->assertEquals($result, $registry, '$result should be $registry self that support chaining'); + + // Test getting a known value. + $this->assertThat( + $registry->get('foo'), + $this->equalTo('bar'), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::loadFile method. + * + * @return void + * + * @covers Joomla\Registry\Registry::loadFile + * @since 1.0 + */ + public function testLoadFile() + { + $registry = new Registry; + + // Result is always true, no error checking in method. + + // JSON. + $result = $registry->loadFile(__DIR__ . '/Stubs/jregistry.json'); + + // Test getting a known value. + $this->assertThat( + $registry->get('foo'), + $this->equalTo('bar'), + 'Line: ' . __LINE__ . '.' + ); + + // INI. + $result = $registry->loadFile(__DIR__ . '/Stubs/jregistry.ini', 'ini'); + + // Test getting a known value. + $this->assertThat( + $registry->get('foo'), + $this->equalTo('bar'), + 'Line: ' . __LINE__ . '.' + ); + + // INI + section. + $result = $registry->loadFile(__DIR__ . '/Stubs/jregistry.ini', 'ini', array('processSections' => true)); + + // Checking result is self that we can chaining + $this->assertEquals($result, $registry, '$result should be $registry self that support chaining'); + + // Test getting a known value. + $this->assertThat( + $registry->get('section.foo'), + $this->equalTo('bar'), + 'Line: ' . __LINE__ . '.' + ); + + // XML and PHP versions do not support stringToObject. + } + + /** + * Test the Joomla\Registry\Registry::loadString() method. + * + * @return void + * + * @covers Joomla\Registry\Registry::loadString + * @since 1.0 + */ + public function testLoadString() + { + $registry = new Registry; + $result = $registry->loadString('foo="testloadini1"', 'INI'); + + // Test getting a known value. + $this->assertThat( + $registry->get('foo'), + $this->equalTo('testloadini1'), + 'Line: ' . __LINE__ . '.' + ); + + $result = $registry->loadString("[section]\nfoo=\"testloadini2\"", 'INI'); + + // Test getting a known value. + $this->assertThat( + $registry->get('foo'), + $this->equalTo('testloadini2'), + 'Line: ' . __LINE__ . '.' + ); + + $result = $registry->loadString("[section]\nfoo=\"testloadini3\"", 'INI', array('processSections' => true)); + + // Test getting a known value after processing sections. + $this->assertThat( + $registry->get('section.foo'), + $this->equalTo('testloadini3'), + 'Line: ' . __LINE__ . '.' + ); + + $string = '{"foo":"testloadjson"}'; + + $registry = new Registry; + $result = $registry->loadString($string); + + // Checking result is self that we can chaining + $this->assertEquals($result, $registry, '$result should be $registry self that support chaining'); + + // Test getting a known value. + $this->assertThat( + $registry->get('foo'), + $this->equalTo('testloadjson'), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::loadObject method. + * + * @return void + * + * @covers Joomla\Registry\Registry::loadObject + * @since 1.0 + */ + public function testLoadObject() + { + $object = new \stdClass; + $object->foo = 'testloadobject'; + + $registry = new Registry; + $result = $registry->loadObject($object); + + // Checking result is self that we can chaining + $this->assertEquals($result, $registry, '$result should be $registry self that support chaining'); + + // Test getting a known value. + $this->assertThat( + $registry->get('foo'), + $this->equalTo('testloadobject'), + 'Line: ' . __LINE__ . '.' + ); + + // Test that loadObject will auto recursive merge + $registry = new Registry; + + $object1 = '{ + "foo" : "foo value", + "bar" : { + "bar1" : "bar value 1", + "bar2" : "bar value 2" + } + }'; + + $object2 = '{ + "foo" : "foo value", + "bar" : { + "bar2" : "new bar value 2" + } + }'; + + $registry->loadObject(json_decode($object1)); + $registry->loadObject(json_decode($object2)); + + $this->assertEquals($registry->get('bar.bar2'), 'new bar value 2', 'Line: ' . __LINE__ . '. bar.bar2 shuould be override.'); + $this->assertEquals($registry->get('bar.bar1'), 'bar value 1', 'Line: ' . __LINE__ . '. bar.bar1 should not be overrided.'); + } + + /** + * Test the Joomla\Registry\Registry::merge method. + * + * @return void + * + * @covers Joomla\Registry\Registry::merge + * @since 1.0 + */ + public function testMerge() + { + $array1 = array( + 'foo' => 'bar', + 'hoo' => 'hum', + 'dum' => array( + 'dee' => 'dum' + ) + ); + + $array2 = array( + 'foo' => 'soap', + 'dum' => 'huh' + ); + $registry1 = new Registry; + $registry1->loadArray($array1); + + $registry2 = new Registry; + $registry2->loadArray($array2); + + $registry1->merge($registry2); + + // Test getting a known value. + $this->assertThat( + $registry1->get('foo'), + $this->equalTo('soap'), + 'Line: ' . __LINE__ . '.' + ); + + $this->assertThat( + $registry1->get('dum'), + $this->equalTo('huh'), + 'Line: ' . __LINE__ . '.' + ); + + // Test merge with zero and blank value + $json1 = '{ + "param1":1, + "param2":"value2" + }'; + $json2 = '{ + "param1":2, + "param2":"", + "param3":0, + "param4":-1, + "param5":1 + }'; + $a = new Registry($json1); + $b = new Registry; + $b->loadString($json2, 'JSON'); + $result = $a->merge($b); + + // New param with zero value should show in merged registry + $this->assertEquals(2, $a->get('param1'), '$b value should override $a value'); + $this->assertEquals('value2', $a->get('param2'), '$a value should override blank $b value'); + $this->assertEquals(0, $a->get('param3'), '$b value of 0 should override $a value'); + $this->assertEquals(-1, $a->get('param4'), '$b value of -1 should override $a value'); + $this->assertEquals(1, $a->get('param5'), '$b value of 1 should override $a value'); + + // Test recursive merge + $registry = new Registry; + + $object1 = '{ + "foo" : "foo value", + "bar" : { + "bar1" : "bar value 1", + "bar2" : "bar value 2" + } + }'; + + $object2 = '{ + "foo" : "foo value", + "bar" : { + "bar2" : "new bar value 2" + } + }'; + + $registry1 = new Registry(json_decode($object1)); + $registry2 = new Registry(json_decode($object2)); + + $registry1->merge($registry2, true); + + $this->assertEquals($registry1->get('bar.bar2'), 'new bar value 2', 'Line: ' . __LINE__ . '. bar.bar2 shuould be override.'); + $this->assertEquals($registry1->get('bar.bar1'), 'bar value 1', 'Line: ' . __LINE__ . '. bar.bar1 should not be overrided.'); + + // Chicking we merge a non Registry object will return error. + $a = new Registry; + $b = new Registry; + + try + { + $a->merge($b); + } + catch (Exception $e) + { + $this->assertInstanceOf('PHPUnit_Framework_Error', $e, 'Line: ' . __LINE__ . '. Attempt to merge non Registry should return Error'); + } + } + + /** + * Test the Joomla\Registry\Registry::offsetExists method. + * + * @return void + * + * @covers Joomla\Registry\Registry::offsetExists + * @since 1.0 + */ + public function testOffsetExists() + { + $instance = new Registry; + + $this->assertTrue(empty($instance['foo.bar'])); + + $instance->set('foo.bar', 'value'); + + $this->assertTrue(isset($instance['foo.bar']), 'Checks a known offset by isset.'); + $this->assertFalse(isset($instance['goo.car']), 'Checks an uknown offset.'); + } + + /** + * Test the Joomla\Registry\Registry::offsetGet method. + * + * @return void + * + * @covers Joomla\Registry\Registry::offsetGet + * @since 1.0 + */ + public function testOffsetGet() + { + $instance = new Registry; + $instance->set('foo.bar', 'value'); + + $this->assertEquals('value', $instance['foo.bar'], 'Checks a known offset.'); + $this->assertNull($instance['goo.car'], 'Checks a unknown offset.'); + } + + /** + * Test the Joomla\Registry\Registry::offsetSet method. + * + * @return void + * + * @covers Joomla\Registry\Registry::offsetSet + * @since 1.0 + */ + public function testOffsetSet() + { + $instance = new Registry; + + $instance['foo.bar'] = 'value'; + $this->assertEquals('value', $instance->get('foo.bar'), 'Checks the set.'); + } + + /** + * Test the Joomla\Registry\Registry::offsetUnset method. + * + * @return void + * + * @covers Joomla\Registry\Registry::offsetUnset + * @since 1.0 + */ + public function testOffsetUnset() + { + $instance = new Registry; + $instance->set('foo.bar', 'value'); + + unset($instance['foo.bar']); + $this->assertFalse(isset($instance['foo.bar'])); + } + + /** + * Test the Joomla\Registry\Registry::set method. + * + * @return void + * + * @covers Joomla\Registry\Registry::set + * @since 1.0 + */ + public function testSet() + { + $a = new Registry; + $a->set('foo', 'testsetvalue1'); + + $this->assertThat( + $a->set('foo', 'testsetvalue2'), + $this->equalTo('testsetvalue2'), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::toArray method. + * + * @return void + * + * @covers Joomla\Registry\Registry::toArray + * @since 1.0 + */ + public function testToArray() + { + $a = new Registry; + $a->set('foo1', 'testtoarray1'); + $a->set('foo2', 'testtoarray2'); + $a->set('config.foo3', 'testtoarray3'); + + $expected = array( + 'foo1' => 'testtoarray1', + 'foo2' => 'testtoarray2', + 'config' => array('foo3' => 'testtoarray3') + ); + + $this->assertThat( + $a->toArray(), + $this->equalTo($expected), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::toObject method. + * + * @return void + * + * @covers Joomla\Registry\Registry::toObject + * @since 1.0 + */ + public function testToObject() + { + $a = new Registry; + $a->set('foo1', 'testtoobject1'); + $a->set('foo2', 'testtoobject2'); + $a->set('config.foo3', 'testtoobject3'); + + $expected = new \stdClass; + $expected->foo1 = 'testtoobject1'; + $expected->foo2 = 'testtoobject2'; + $expected->config = new \stdClass; + $expected->config->foo3 = 'testtoobject3'; + + $this->assertThat( + $a->toObject(), + $this->equalTo($expected), + 'Line: ' . __LINE__ . '.' + ); + } + + /** + * Test the Joomla\Registry\Registry::toString method. + * + * @return void + * + * @covers Joomla\Registry\Registry::toString + * @since 1.0 + */ + public function testToString() + { + $a = new Registry; + $a->set('foo1', 'testtostring1'); + $a->set('foo2', 'testtostring2'); + $a->set('config.foo3', 'testtostring3'); + + $this->assertThat( + trim($a->toString('JSON')), + $this->equalTo( + '{"foo1":"testtostring1","foo2":"testtostring2","config":{"foo3":"testtostring3"}}' + ), + 'Line: ' . __LINE__ . '.' + ); + + $this->assertThat( + trim($a->toString('INI')), + $this->equalTo( + "foo1=\"testtostring1\"\nfoo2=\"testtostring2\"\n\n[config]\nfoo3=\"testtostring3\"" + ), + 'Line: ' . __LINE__ . '.' + ); + } +} diff --git a/libraries/joomla/registry/Tests/Stubs/jregistry.ini b/libraries/joomla/registry/Tests/Stubs/jregistry.ini new file mode 100644 index 0000000000000..fe5baa8c999ad --- /dev/null +++ b/libraries/joomla/registry/Tests/Stubs/jregistry.ini @@ -0,0 +1,2 @@ +[section] +foo="bar" \ No newline at end of file diff --git a/libraries/joomla/registry/Tests/Stubs/jregistry.json b/libraries/joomla/registry/Tests/Stubs/jregistry.json new file mode 100644 index 0000000000000..76a64820e7062 --- /dev/null +++ b/libraries/joomla/registry/Tests/Stubs/jregistry.json @@ -0,0 +1,3 @@ +{ + "foo":"bar" +} diff --git a/libraries/joomla/registry/Tests/format/FormatIniTest.php b/libraries/joomla/registry/Tests/format/FormatIniTest.php new file mode 100644 index 0000000000000..46aa315b12efd --- /dev/null +++ b/libraries/joomla/registry/Tests/format/FormatIniTest.php @@ -0,0 +1,112 @@ +foo = 'bar'; + $object->booleantrue = true; + $object->booleanfalse = false; + $object->numericint = 42; + $object->numericfloat = 3.1415; + $object->section = new \stdClass; + $object->section->key = 'value'; + + // Test basic object to string. + $string = $class->objectToString($object, $options); + $this->assertThat( + trim($string), + $this->equalTo("foo=\"bar\"\nbooleantrue=true\nbooleanfalse=false\nnumericint=42\nnumericfloat=3.1415\n\n[section]\nkey=\"value\"") + ); + } + + /** + * Test the Ini::stringToObject method. + * + * @return void + * + * @since 1.0 + */ + public function testStringToObject() + { + $class = AbstractRegistryFormat::getInstance('INI'); + + $string2 = "[section]\nfoo=bar"; + + $object1 = new \stdClass; + $object1->foo = 'bar'; + + $object2 = new \stdClass; + $object2->section = $object1; + + // Test INI format string without sections. + $object = $class->stringToObject($string2, array('processSections' => false)); + $this->assertThat( + $object, + $this->equalTo($object1) + ); + + // Test INI format string with sections. + $object = $class->stringToObject($string2, array('processSections' => true)); + $this->assertThat( + $object, + $this->equalTo($object2) + ); + + // Test empty string + $this->assertThat( + $class->stringToObject(null), + $this->equalTo(new \stdClass) + ); + + $string3 = "[section]\nfoo=bar\n;Testcomment\nkey=value\n\n/brokenkey=)brokenvalue"; + $object2->section->key = 'value'; + + $this->assertThat( + $class->stringToObject($string3, array('processSections' => true)), + $this->equalTo($object2) + ); + + $string4 = "boolfalse=false\nbooltrue=true\nkeywithoutvalue\nnumericfloat=3.1415\nnumericint=42\nkey=\"value\""; + $object3 = new \stdClass; + $object3->boolfalse = false; + $object3->booltrue = true; + $object3->numericfloat = 3.1415; + $object3->numericint = 42; + $object3->key = 'value'; + + $this->assertThat( + $class->stringToObject($string4), + $this->equalTo($object3) + ); + + // Trigger the cache - Doing this only to achieve 100% code coverage. ;-) + $this->assertThat( + $class->stringToObject($string4), + $this->equalTo($object3) + ); + } +} diff --git a/libraries/joomla/registry/Tests/format/FormatJsonTest.php b/libraries/joomla/registry/Tests/format/FormatJsonTest.php new file mode 100644 index 0000000000000..1235fc070e572 --- /dev/null +++ b/libraries/joomla/registry/Tests/format/FormatJsonTest.php @@ -0,0 +1,121 @@ +foo = 'bar'; + $object->quoted = '"stringwithquotes"'; + $object->booleantrue = true; + $object->booleanfalse = false; + $object->numericint = 42; + $object->numericfloat = 3.1415; + + // The PHP registry format does not support nested objects + $object->section = new \stdClass; + $object->section->key = 'value'; + $object->array = array('nestedarray' => array('test1' => 'value1')); + + $string = '{"foo":"bar","quoted":"\"stringwithquotes\"",' . + '"booleantrue":true,"booleanfalse":false,' . + '"numericint":42,"numericfloat":3.1415,' . + '"section":{"key":"value"},' . + '"array":{"nestedarray":{"test1":"value1"}}' . + '}'; + + // Test basic object to string. + $this->assertThat( + $class->objectToString($object, $options), + $this->equalTo($string) + ); + } + + /** + * Test the Json::stringToObject method. + * + * @return void + * + * @since 1.0 + */ + public function testStringToObject() + { + $class = AbstractRegistryFormat::getInstance('JSON'); + + $string1 = '{"title":"Joomla Framework","author":"Me","params":{"show_title":1,"show_abstract":0,"show_author":1,"categories":[1,2]}}'; + $string2 = "[section]\nfoo=bar"; + + $object1 = new \stdClass; + $object1->title = 'Joomla Framework'; + $object1->author = 'Me'; + $object1->params = new \stdClass; + $object1->params->show_title = 1; + $object1->params->show_abstract = 0; + $object1->params->show_author = 1; + $object1->params->categories = array(1, 2); + + $object2 = new \stdClass; + $object2->section = new \stdClass; + $object2->section->foo = 'bar'; + + $object3 = new \stdClass; + $object3->foo = 'bar'; + + // Test basic JSON string to object. + $object = $class->stringToObject($string1, array('processSections' => false)); + $this->assertThat( + $object, + $this->equalTo($object1), + 'Line:' . __LINE__ . ' The complex JSON string should convert into the appropriate object.' + ); + + // Test INI format string without sections. + $object = $class->stringToObject($string2, array('processSections' => false)); + $this->assertThat( + $object, + $this->equalTo($object3), + 'Line:' . __LINE__ . ' The INI string should convert into an object without sections.' + ); + + // Test INI format string with sections. + $object = $class->stringToObject($string2, array('processSections' => true)); + $this->assertThat( + $object, + $this->equalTo($object2), + 'Line:' . __LINE__ . ' The INI string should covert into an object with sections.' + ); + + /** + * Test for bad input + * Everything that is not starting with { is handled by + * Format\Ini, which we test seperately + */ + $this->assertThat( + $class->stringToObject('{key:\'value\''), + $this->equalTo(false) + ); + } +} diff --git a/libraries/joomla/registry/Tests/format/FormatPhpTest.php b/libraries/joomla/registry/Tests/format/FormatPhpTest.php new file mode 100644 index 0000000000000..24de634f347e9 --- /dev/null +++ b/libraries/joomla/registry/Tests/format/FormatPhpTest.php @@ -0,0 +1,73 @@ + 'myClass'); + $object = new \stdClass; + $object->foo = 'bar'; + $object->quoted = '"stringwithquotes"'; + $object->booleantrue = true; + $object->booleanfalse = false; + $object->numericint = 42; + $object->numericfloat = 3.1415; + + // The PHP registry format does not support nested objects + $object->section = new \stdClass; + $object->section->key = 'value'; + $object->array = array('nestedarray' => array('test1' => 'value1')); + + $string = " \"value\");\n" . + "\tpublic \$array = array(\"nestedarray\" => array(\"test1\" => \"value1\"));\n" . + "}\n?>"; + $this->assertThat( + $class->objectToString($object, $options), + $this->equalTo($string) + ); + } + + /** + * Test the Php::stringToObject method. + * + * @return void + * + * @since 1.0 + */ + public function testStringToObject() + { + $class = AbstractRegistryFormat::getInstance('PHP'); + + // This method is not implemented in the class. The test is to achieve 100% code coverage + $this->assertTrue($class->stringToObject('')); + } +} diff --git a/libraries/joomla/registry/Tests/format/FormatXmlTest.php b/libraries/joomla/registry/Tests/format/FormatXmlTest.php new file mode 100644 index 0000000000000..12464659edc35 --- /dev/null +++ b/libraries/joomla/registry/Tests/format/FormatXmlTest.php @@ -0,0 +1,111 @@ +foo = 'bar'; + $object->quoted = '"stringwithquotes"'; + $object->booleantrue = true; + $object->booleanfalse = false; + $object->numericint = 42; + $object->numericfloat = 3.1415; + $object->section = new \stdClass; + $object->section->key = 'value'; + $object->array = array('nestedarray' => array('test1' => 'value1')); + + // Check for different PHP behavior of displaying boolean false in XML. + $checkFalse = '' == simplexml_load_string('')->addChild('check', false)->asXML() + ? '/>' + : '>'; + + $string = "\n" . + "bar" . + "\"stringwithquotes\"" . + "1" . + "42" . + "3.1415" . + "" . + "value" . + "" . + "" . + "" . + "value1" . + "" . + "" . + "\n"; + + // Test basic object to string. + $this->assertXmlStringEqualsXmlString( + $class->objectToString($object, $options), + $string + ); + } + + /** + * Test the Xml::stringToObject method. + * + * @return void + * + * @since 1.0 + */ + public function testStringToObject() + { + $class = AbstractRegistryFormat::getInstance('XML'); + $object = new \stdClass; + $object->foo = 'bar'; + $object->booleantrue = true; + $object->booleanfalse1 = false; + $object->booleanfalse2 = false; + $object->numericint = 42; + $object->numericfloat = 3.1415; + $object->section = new \stdClass; + $object->section->key = 'value'; + $object->array = array('test1' => 'value1'); + + $string = "\n" . + "bar" . + "1" . + "" . + "" . + "42" . + "3.1415" . + "" . + "value" . + "" . + "" . + "value1" . + "" . + "\n"; + + // Test basic object to string. + $this->assertThat( + $class->stringToObject($string), + $this->equalTo($object) + ); + } +} diff --git a/libraries/joomla/registry/Tests/format/FormatYamlTest.php b/libraries/joomla/registry/Tests/format/FormatYamlTest.php new file mode 100644 index 0000000000000..c7161a3c7976a --- /dev/null +++ b/libraries/joomla/registry/Tests/format/FormatYamlTest.php @@ -0,0 +1,161 @@ +fixture = AbstractRegistryFormat::getInstance('Yaml'); + } + + /** + * Test the __construct method + * + * @return void + * + * @since 1.0 + */ + public function testConstruct() + { + $this->assertAttributeInstanceOf('Symfony\Component\Yaml\Parser', 'parser', $this->fixture); + $this->assertAttributeInstanceOf('Symfony\Component\Yaml\Dumper', 'dumper', $this->fixture); + } + + /** + * Test the objectToString method with an object as input. + * + * @return void + * + * @since 1.0 + */ + public function testObjectToStringWithObject() + { + $object = (object) array( + 'foo' => 'bar', + 'quoted' => '"stringwithquotes"', + 'booleantrue' => true, + 'booleanfalse' => false, + 'numericint' => 42, + 'numericfloat' => 3.1415, + 'section' => (object) array('key' => 'value'), + 'array' => (object) array('nestedarray' => (object) array('test1' => 'value1')) + ); + + $yaml = 'foo: bar +quoted: \'"stringwithquotes"\' +booleantrue: true +booleanfalse: false +numericint: 42 +numericfloat: 3.1415 +section: + key: value +array: + nestedarray: { test1: value1 } +'; + + $this->assertEquals( + str_replace(array("\n", "\r"), '', trim($this->fixture->objectToString($object))), + str_replace(array("\n", "\r"), '', trim($yaml)) + ); + } + + /** + * Test the objectToString method with an array as input. + * + * @return void + * + * @since 1.0 + */ + public function testObjectToStringWithArray() + { + $object = array( + 'foo' => 'bar', + 'quoted' => '"stringwithquotes"', + 'booleantrue' => true, + 'booleanfalse' => false, + 'numericint' => 42, + 'numericfloat' => 3.1415, + 'section' => array('key' => 'value'), + 'array' => array('nestedarray' => array('test1' => 'value1')) + ); + + $yaml = 'foo: bar +quoted: \'"stringwithquotes"\' +booleantrue: true +booleanfalse: false +numericint: 42 +numericfloat: 3.1415 +section: + key: value +array: + nestedarray: { test1: value1 } +'; + + $this->assertEquals( + str_replace(array("\n", "\r"), '', trim($this->fixture->objectToString($object))), + str_replace(array("\n", "\r"), '', trim($yaml)) + ); + } + + /** + * Test the stringToObject method. + * + * @return void + * + * @since 1.0 + */ + public function testStringToObject() + { + $object = (object) array( + 'foo' => 'bar', + 'quoted' => '"stringwithquotes"', + 'booleantrue' => true, + 'booleanfalse' => false, + 'numericint' => 42, + 'numericfloat' => 3.1415, + 'section' => (object) array('key' => 'value'), + 'array' => (object) array('nestedarray' => (object) array('test1' => 'value1')) + ); + + $yaml = 'foo: bar +quoted: \'"stringwithquotes"\' +booleantrue: true +booleanfalse: false +numericint: 42 +numericfloat: 3.1415 +section: + key: value +array: + nestedarray: { test1: value1 } +'; + $this->assertEquals($object, $this->fixture->stringToObject($yaml)); + } +} diff --git a/libraries/joomla/registry/composer.json b/libraries/joomla/registry/composer.json new file mode 100644 index 0000000000000..c05c9f553681d --- /dev/null +++ b/libraries/joomla/registry/composer.json @@ -0,0 +1,26 @@ +{ + "name": "joomla/registry", + "type": "joomla-package", + "description": "Joomla Registry Package", + "keywords": ["joomla", "framework", "registry"], + "homepage": "https://github.com/joomla-framework/registry", + "license": "GPL-2.0+", + "require": { + "php": ">=5.3.10", + "joomla/compat": "~1.0", + "joomla/utilities": "~1.0" + }, + "require-dev": { + "symfony/yaml": "~2.0", + "joomla/test": "~1.0" + }, + "suggest": { + "symfony/yaml": "Install 2.* if you require YAML support." + }, + "autoload": { + "psr-4": { + "Joomla\\Registry\\": "src/", + "Joomla\\Registry\\Tests\\": "Tests/" + } + } +} diff --git a/libraries/joomla/registry/phpunit.xml.dist b/libraries/joomla/registry/phpunit.xml.dist new file mode 100644 index 0000000000000..2278bfbac86a6 --- /dev/null +++ b/libraries/joomla/registry/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + Tests + + + diff --git a/libraries/joomla/registry/src/AbstractRegistryFormat.php b/libraries/joomla/registry/src/AbstractRegistryFormat.php new file mode 100644 index 0000000000000..db01eecbea86e --- /dev/null +++ b/libraries/joomla/registry/src/AbstractRegistryFormat.php @@ -0,0 +1,79 @@ + $value) + { + // If the value is an object then we need to put it in a local section. + if (is_object($value)) + { + // Add the section line. + $local[] = ''; + $local[] = '[' . $key . ']'; + + // Add the properties for this section. + foreach (get_object_vars($value) as $k => $v) + { + $local[] = $k . '=' . $this->getValueAsINI($v); + } + } + else + { + // Not in a section so add the property to the global array. + $global[] = $key . '=' . $this->getValueAsINI($value); + } + } + + return implode("\n", array_merge($global, $local)); + } + + /** + * Parse an INI formatted string and convert it into an object. + * + * @param string $data INI formatted string to convert. + * @param array $options An array of options used by the formatter, or a boolean setting to process sections. + * + * @return object Data object. + * + * @since 1.0 + */ + public function stringToObject($data, array $options = array()) + { + $sections = (isset($options['processSections'])) ? $options['processSections'] : false; + + // Check the memory cache for already processed strings. + $hash = md5($data . ':' . (int) $sections); + + if (isset(self::$cache[$hash])) + { + return self::$cache[$hash]; + } + + // If no lines present just return the object. + if (empty($data)) + { + return new stdClass; + } + + $obj = new stdClass; + $section = false; + $lines = explode("\n", $data); + + // Process the lines. + foreach ($lines as $line) + { + // Trim any unnecessary whitespace. + $line = trim($line); + + // Ignore empty lines and comments. + if (empty($line) || ($line{0} == ';')) + { + continue; + } + + if ($sections) + { + $length = strlen($line); + + // If we are processing sections and the line is a section add the object and continue. + if (($line[0] == '[') && ($line[$length - 1] == ']')) + { + $section = substr($line, 1, $length - 2); + $obj->$section = new stdClass; + continue; + } + } + elseif ($line{0} == '[') + { + continue; + } + + // Check that an equal sign exists and is not the first character of the line. + if (!strpos($line, '=')) + { + // Maybe throw exception? + continue; + } + + // Get the key and value for the line. + list ($key, $value) = explode('=', $line, 2); + + // Validate the key. + if (preg_match('/[^A-Z0-9_]/i', $key)) + { + // Maybe throw exception? + continue; + } + + // If the value is quoted then we assume it is a string. + $length = strlen($value); + + if ($length && ($value[0] == '"') && ($value[$length - 1] == '"')) + { + // Strip the quotes and Convert the new line characters. + $value = stripcslashes(substr($value, 1, ($length - 2))); + $value = str_replace('\n', "\n", $value); + } + else + { + // If the value is not quoted, we assume it is not a string. + + // If the value is 'false' assume boolean false. + if ($value == 'false') + { + $value = false; + } + elseif ($value == 'true') + // If the value is 'true' assume boolean true. + { + $value = true; + } + elseif (is_numeric($value)) + // If the value is numeric than it is either a float or int. + { + // If there is a period then we assume a float. + if (strpos($value, '.') !== false) + { + $value = (float) $value; + } + else + { + $value = (int) $value; + } + } + } + + // If a section is set add the key/value to the section, otherwise top level. + if ($section) + { + $obj->$section->$key = $value; + } + else + { + $obj->$key = $value; + } + } + + // Cache the string to save cpu cycles -- thus the world :) + self::$cache[$hash] = clone ($obj); + + return $obj; + } + + /** + * Method to get a value in an INI format. + * + * @param mixed $value The value to convert to INI format. + * + * @return string The value in INI format. + * + * @since 1.0 + */ + protected function getValueAsINI($value) + { + $string = ''; + + switch (gettype($value)) + { + case 'integer': + case 'double': + $string = $value; + break; + + case 'boolean': + $string = $value ? 'true' : 'false'; + break; + + case 'string': + // Sanitize any CRLF characters.. + $string = '"' . str_replace(array("\r\n", "\n"), '\\n', $value) . '"'; + break; + } + + return $string; + } +} diff --git a/libraries/joomla/registry/src/Format/Json.php b/libraries/joomla/registry/src/Format/Json.php new file mode 100644 index 0000000000000..bd449423dcf94 --- /dev/null +++ b/libraries/joomla/registry/src/Format/Json.php @@ -0,0 +1,63 @@ + false)) + { + $data = trim($data); + + if ((substr($data, 0, 1) != '{') && (substr($data, -1, 1) != '}')) + { + $ini = AbstractRegistryFormat::getInstance('Ini'); + $obj = $ini->stringToObject($data, $options); + } + else + { + $obj = json_decode($data); + } + + return $obj; + } +} diff --git a/libraries/joomla/registry/src/Format/Php.php b/libraries/joomla/registry/src/Format/Php.php new file mode 100644 index 0000000000000..5fe01eb149741 --- /dev/null +++ b/libraries/joomla/registry/src/Format/Php.php @@ -0,0 +1,111 @@ + $v) + { + if (is_scalar($v)) + { + $vars .= "\tpublic $" . $k . " = '" . addcslashes($v, '\\\'') . "';\n"; + } + elseif (is_array($v) || is_object($v)) + { + $vars .= "\tpublic $" . $k . " = " . $this->getArrayString((array) $v) . ";\n"; + } + } + + $str = ""; + } + + return $str; + } + + /** + * Parse a PHP class formatted string and convert it into an object. + * + * @param string $data PHP Class formatted string to convert. + * @param array $options Options used by the formatter. + * + * @return object Data object. + * + * @since 1.0 + */ + public function stringToObject($data, array $options = array()) + { + return true; + } + + /** + * Method to get an array as an exported string. + * + * @param array $a The array to get as a string. + * + * @return array + * + * @since 1.0 + */ + protected function getArrayString($a) + { + $s = 'array('; + $i = 0; + + foreach ($a as $k => $v) + { + $s .= ($i) ? ', ' : ''; + $s .= '"' . $k . '" => '; + + if (is_array($v) || is_object($v)) + { + $s .= $this->getArrayString((array) $v); + } + else + { + $s .= '"' . addslashes($v) . '"'; + } + + $i++; + } + + $s .= ')'; + + return $s; + } +} diff --git a/libraries/joomla/registry/src/Format/Xml.php b/libraries/joomla/registry/src/Format/Xml.php new file mode 100644 index 0000000000000..0b12ced2139a7 --- /dev/null +++ b/libraries/joomla/registry/src/Format/Xml.php @@ -0,0 +1,164 @@ +'); + + // Iterate over the object members. + $this->getXmlChildren($root, $object, $nodeName); + + return $root->asXML(); + } + + /** + * Parse a XML formatted string and convert it into an object. + * + * @param string $data XML formatted string to convert. + * @param array $options Options used by the formatter. + * + * @return object Data object. + * + * @since 1.0 + */ + public function stringToObject($data, array $options = array()) + { + $obj = new stdClass; + + // Parse the XML string. + $xml = simplexml_load_string($data); + + foreach ($xml->children() as $node) + { + $obj->$node['name'] = $this->getValueFromNode($node); + } + + return $obj; + } + + /** + * Method to get a PHP native value for a SimpleXMLElement object. -- called recursively + * + * @param object $node SimpleXMLElement object for which to get the native value. + * + * @return mixed Native value of the SimpleXMLElement object. + * + * @since 1.0 + */ + protected function getValueFromNode($node) + { + switch ($node['type']) + { + case 'integer': + $value = (string) $node; + + return (int) $value; + break; + + case 'string': + return (string) $node; + break; + + case 'boolean': + $value = (string) $node; + + return (bool) $value; + break; + + case 'double': + $value = (string) $node; + + return (float) $value; + break; + + case 'array': + $value = array(); + + foreach ($node->children() as $child) + { + $value[(string) $child['name']] = $this->getValueFromNode($child); + } + + break; + + default: + $value = new stdClass; + + foreach ($node->children() as $child) + { + $value->$child['name'] = $this->getValueFromNode($child); + } + + break; + } + + return $value; + } + + /** + * Method to build a level of the XML string -- called recursively + * + * @param SimpleXMLElement $node SimpleXMLElement object to attach children. + * @param object $var Object that represents a node of the XML document. + * @param string $nodeName The name to use for node elements. + * + * @return void + * + * @since 1.0 + */ + protected function getXmlChildren(SimpleXMLElement $node, $var, $nodeName) + { + // Iterate over the object members. + foreach ((array) $var as $k => $v) + { + if (is_scalar($v)) + { + $n = $node->addChild($nodeName, $v); + $n->addAttribute('name', $k); + $n->addAttribute('type', gettype($v)); + } + else + { + $n = $node->addChild($nodeName); + $n->addAttribute('name', $k); + $n->addAttribute('type', gettype($v)); + + $this->getXmlChildren($n, $v, $nodeName); + } + } + } +} diff --git a/libraries/joomla/registry/src/Format/Yaml.php b/libraries/joomla/registry/src/Format/Yaml.php new file mode 100644 index 0000000000000..6c9eff19a615c --- /dev/null +++ b/libraries/joomla/registry/src/Format/Yaml.php @@ -0,0 +1,86 @@ +parser = new SymfonyYamlParser; + $this->dumper = new SymfonyYamlDumper; + } + + /** + * Converts an object into a YAML formatted string. + * We use json_* to convert the passed object to an array. + * + * @param object $object Data source object. + * @param array $options Options used by the formatter. + * + * @return string YAML formatted string. + * + * @since 1.0 + */ + public function objectToString($object, $options = array()) + { + $array = json_decode(json_encode($object), true); + + return $this->dumper->dump($array, 2, 0); + } + + /** + * Parse a YAML formatted string and convert it into an object. + * We use the json_* methods to convert the parsed YAML array to an object. + * + * @param string $data YAML formatted string to convert. + * @param array $options Options used by the formatter. + * + * @return object Data object. + * + * @since 1.0 + */ + public function stringToObject($data, array $options = array()) + { + $array = $this->parser->parse(trim($data)); + + return json_decode(json_encode($array)); + } +} diff --git a/libraries/joomla/registry/src/Registry.php b/libraries/joomla/registry/src/Registry.php new file mode 100644 index 0000000000000..ffa49809746d1 --- /dev/null +++ b/libraries/joomla/registry/src/Registry.php @@ -0,0 +1,538 @@ +data = new \stdClass; + + // Optionally load supplied data. + if (is_array($data) || is_object($data)) + { + $this->bindData($this->data, $data); + } + elseif (!empty($data) && is_string($data)) + { + $this->loadString($data); + } + } + + /** + * Magic function to clone the registry object. + * + * @return Registry + * + * @since 1.0 + */ + public function __clone() + { + $this->data = unserialize(serialize($this->data)); + } + + /** + * Magic function to render this object as a string using default args of toString method. + * + * @return string + * + * @since 1.0 + */ + public function __toString() + { + return $this->toString(); + } + + /** + * Implementation for the JsonSerializable interface. + * Allows us to pass Registry objects to json_encode. + * + * @return object + * + * @since 1.0 + * @note The interface is only present in PHP 5.4 and up. + */ + public function jsonSerialize() + { + return $this->data; + } + + /** + * Sets a default value if not already assigned. + * + * @param string $key The name of the parameter. + * @param mixed $default An optional value for the parameter. + * + * @return mixed The value set, or the default if the value was not previously set (or null). + * + * @since 1.0 + */ + public function def($key, $default = '') + { + $value = $this->get($key, $default); + $this->set($key, $value); + + return $value; + } + + /** + * Check if a registry path exists. + * + * @param string $path Registry path (e.g. joomla.content.showauthor) + * + * @return boolean + * + * @since 1.0 + */ + public function exists($path) + { + // Explode the registry path into an array + $nodes = explode('.', $path); + + if ($nodes) + { + // Initialize the current node to be the registry root. + $node = $this->data; + + // Traverse the registry to find the correct node for the result. + for ($i = 0, $n = count($nodes); $i < $n; $i++) + { + if (isset($node->$nodes[$i])) + { + $node = $node->$nodes[$i]; + } + else + { + break; + } + + if ($i + 1 == $n) + { + return true; + } + } + } + + return false; + } + + /** + * Get a registry value. + * + * @param string $path Registry path (e.g. joomla.content.showauthor) + * @param mixed $default Optional default value, returned if the internal value is null. + * + * @return mixed Value of entry or null + * + * @since 1.0 + */ + public function get($path, $default = null) + { + $result = $default; + + if (!strpos($path, '.')) + { + return (isset($this->data->$path) && $this->data->$path !== null && $this->data->$path !== '') ? $this->data->$path : $default; + } + + // Explode the registry path into an array + $nodes = explode('.', $path); + + // Initialize the current node to be the registry root. + $node = $this->data; + $found = false; + + // Traverse the registry to find the correct node for the result. + foreach ($nodes as $n) + { + if (isset($node->$n)) + { + $node = $node->$n; + $found = true; + } + else + { + $found = false; + break; + } + } + + if ($found && $node !== null && $node !== '') + { + $result = $node; + } + + return $result; + } + + /** + * Returns a reference to a global Registry object, only creating it + * if it doesn't already exist. + * + * This method must be invoked as: + *
$registry = Registry::getInstance($id);
+ * + * @param string $id An ID for the registry instance + * + * @return Registry The Registry object. + * + * @since 1.0 + */ + public static function getInstance($id) + { + if (empty(self::$instances[$id])) + { + self::$instances[$id] = new self; + } + + return self::$instances[$id]; + } + + /** + * Load a associative array of values into the default namespace + * + * @param array $array Associative array of value to load + * + * @return Registry Return this object to support chaining. + * + * @since 1.0 + */ + public function loadArray($array) + { + $this->bindData($this->data, $array); + + return $this; + } + + /** + * Load the public variables of the object into the default namespace. + * + * @param object $object The object holding the publics to load + * + * @return Registry Return this object to support chaining. + * + * @since 1.0 + */ + public function loadObject($object) + { + $this->bindData($this->data, $object); + + return $this; + } + + /** + * Load the contents of a file into the registry + * + * @param string $file Path to file to load + * @param string $format Format of the file [optional: defaults to JSON] + * @param array $options Options used by the formatter + * + * @return Registry Return this object to support chaining. + * + * @since 1.0 + */ + public function loadFile($file, $format = 'JSON', $options = array()) + { + $data = file_get_contents($file); + + return $this->loadString($data, $format, $options); + } + + /** + * Load a string into the registry + * + * @param string $data String to load into the registry + * @param string $format Format of the string + * @param array $options Options used by the formatter + * + * @return Registry Return this object to support chaining. + * + * @since 1.0 + */ + public function loadString($data, $format = 'JSON', $options = array()) + { + // Load a string into the given namespace [or default namespace if not given] + $handler = AbstractRegistryFormat::getInstance($format); + + $obj = $handler->stringToObject($data, $options); + $this->loadObject($obj); + + return $this; + } + + /** + * Merge a Registry object into this one + * + * @param Registry $source Source Registry object to merge. + * @param boolean $recursive True to support recursive merge the children values. + * + * @return Registry Return this object to support chaining. + * + * @since 1.0 + */ + public function merge(Registry $source, $recursive = false) + { + $this->bindData($this->data, $source->toArray(), $recursive); + + return $this; + } + + /** + * Checks whether an offset exists in the iterator. + * + * @param mixed $offset The array offset. + * + * @return boolean True if the offset exists, false otherwise. + * + * @since 1.0 + */ + public function offsetExists($offset) + { + return (boolean) ($this->get($offset) !== null); + } + + /** + * Gets an offset in the iterator. + * + * @param mixed $offset The array offset. + * + * @return mixed The array value if it exists, null otherwise. + * + * @since 1.0 + */ + public function offsetGet($offset) + { + return $this->get($offset); + } + + /** + * Sets an offset in the iterator. + * + * @param mixed $offset The array offset. + * @param mixed $value The array value. + * + * @return void + * + * @since 1.0 + */ + public function offsetSet($offset, $value) + { + $this->set($offset, $value); + } + + /** + * Unsets an offset in the iterator. + * + * @param mixed $offset The array offset. + * + * @return void + * + * @since 1.0 + */ + public function offsetUnset($offset) + { + $this->set($offset, null); + } + + /** + * Set a registry value. + * + * @param string $path Registry Path (e.g. joomla.content.showauthor) + * @param mixed $value Value of entry + * + * @return mixed The value of the that has been set. + * + * @since 1.0 + */ + public function set($path, $value) + { + $result = null; + + /** + * Explode the registry path into an array and remove empty + * nodes that occur as a result of a double dot. ex: joomla..test + * Finally, re-key the array so they are sequential. + */ + $nodes = array_values(array_filter(explode('.', $path), 'strlen')); + + if ($nodes) + { + // Initialize the current node to be the registry root. + $node = $this->data; + + // Traverse the registry to find the correct node for the result. + for ($i = 0, $n = count($nodes) - 1; $i < $n; $i++) + { + if (!isset($node->$nodes[$i]) && ($i != $n)) + { + $node->$nodes[$i] = new \stdClass; + } + + $node = $node->$nodes[$i]; + } + + // Get the old value if exists so we can return it + $result = $node->$nodes[$i] = $value; + } + + return $result; + } + + /** + * Transforms a namespace to an array + * + * @return array An associative array holding the namespace data + * + * @since 1.0 + */ + public function toArray() + { + return (array) $this->asArray($this->data); + } + + /** + * Transforms a namespace to an object + * + * @return object An an object holding the namespace data + * + * @since 1.0 + */ + public function toObject() + { + return $this->data; + } + + /** + * Get a namespace in a given string format + * + * @param string $format Format to return the string in + * @param mixed $options Parameters used by the formatter, see formatters for more info + * + * @return string Namespace in string format + * + * @since 1.0 + */ + public function toString($format = 'JSON', $options = array()) + { + // Return a namespace in a given format + $handler = AbstractRegistryFormat::getInstance($format); + + return $handler->objectToString($this->data, $options); + } + + /** + * Method to recursively bind data to a parent object. + * + * @param object $parent The parent object on which to attach the data values. + * @param mixed $data An array or object of data to bind to the parent object. + * @param boolean $recursive True to support recursive bindData. + * + * @return void + * + * @since 1.0 + */ + protected function bindData($parent, $data, $recursive = true) + { + // Ensure the input data is an array. + if (is_object($data)) + { + $data = get_object_vars($data); + } + else + { + $data = (array) $data; + } + + foreach ($data as $k => $v) + { + if ($v === '' || $v === null) + { + continue; + } + + if ((is_array($v) && ArrayHelper::isAssociative($v)) || is_object($v) && $recursive) + { + if (!isset($parent->$k)) + { + $parent->$k = new \stdClass; + } + + $this->bindData($parent->$k, $v); + } + else + { + $parent->$k = $v; + } + } + } + + /** + * Method to recursively convert an object of data to an array. + * + * @param object $data An object of data to return as an array. + * + * @return array Array representation of the input object. + * + * @since 1.0 + */ + protected function asArray($data) + { + $array = array(); + + if (is_object($data)) + { + $data = get_object_vars($data); + } + + foreach ($data as $k => $v) + { + if (is_object($v) || is_array($v)) + { + $array[$k] = $this->asArray($v); + } + else + { + $array[$k] = $v; + } + } + + return $array; + } +} diff --git a/libraries/joomla/string/LICENSE b/libraries/joomla/string/LICENSE new file mode 100644 index 0000000000000..df50810b85774 --- /dev/null +++ b/libraries/joomla/string/LICENSE @@ -0,0 +1,340 @@ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 2 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, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/libraries/joomla/string/README.md b/libraries/joomla/string/README.md new file mode 100644 index 0000000000000..03762582c4a76 --- /dev/null +++ b/libraries/joomla/string/README.md @@ -0,0 +1,22 @@ +# The String Package + + +## Installation via Composer + +Add `"joomla/string": "dev-master"` to the require block in your composer.json, make sure you have `"minimum-stability": "dev"` and then run `composer install`. + +```json +{ + "require": { + "joomla/string": "dev-master" + }, + "minimum-stability": "dev" +} +``` + +Alternatively, you can simply run the following from the command line: + +```sh +composer init --stability="dev" +composer require joomla/string "dev-master" +``` diff --git a/libraries/joomla/string/Tests/InflectorTest.php b/libraries/joomla/string/Tests/InflectorTest.php new file mode 100644 index 0000000000000..6072c5247dfae --- /dev/null +++ b/libraries/joomla/string/Tests/InflectorTest.php @@ -0,0 +1,513 @@ +inflector = Inflector::getInstance(true); + } + + /** + * Method to test Inflector::addRule(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::addRule + */ + public function testAddRule() + { + // Case 1 + TestHelper::invoke($this->inflector, 'addRule', '/foo/', 'singular'); + + $rules = TestHelper::getValue($this->inflector, 'rules'); + + $this->assertThat( + in_array('/foo/', $rules['singular']), + $this->isTrue(), + 'Checks if the singular rule was added correctly.' + ); + + // Case 2 + TestHelper::invoke($this->inflector, 'addRule', '/bar/', 'plural'); + + $rules = TestHelper::getValue($this->inflector, 'rules'); + + $this->assertThat( + in_array('/bar/', $rules['plural']), + $this->isTrue(), + 'Checks if the plural rule was added correctly.' + ); + + // Case 3 + TestHelper::invoke($this->inflector, 'addRule', array('/goo/', '/car/'), 'singular'); + + $rules = TestHelper::getValue($this->inflector, 'rules'); + + $this->assertThat( + in_array('/goo/', $rules['singular']), + $this->isTrue(), + 'Checks if an array of rules was added correctly (1).' + ); + + $this->assertThat( + in_array('/car/', $rules['singular']), + $this->isTrue(), + 'Checks if an array of rules was added correctly (2).' + ); + } + + /** + * Method to test Inflector::addRule(). + * + * @return void + * + * @since 1.0 + * @expectedException InvalidArgumentException + * @covers Joomla\String\Inflector::addRule + */ + public function testAddRuleException() + { + TestHelper::invoke($this->inflector, 'addRule', new \stdClass, 'singular'); + } + + /** + * Method to test Inflector::getCachedPlural(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::getCachedPlural + */ + public function testGetCachedPlural() + { + // Reset the cache. + TestHelper::setValue($this->inflector, 'cache', array('foo' => 'bar')); + + $this->assertThat( + TestHelper::invoke($this->inflector, 'getCachedPlural', 'bar'), + $this->isFalse(), + 'Checks for an uncached plural.' + ); + + $this->assertThat( + TestHelper::invoke($this->inflector, 'getCachedPlural', 'foo'), + $this->equalTo('bar'), + 'Checks for a cached plural word.' + ); + } + + /** + * Method to test Inflector::getCachedSingular(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::getCachedSingular + */ + public function testGetCachedSingular() + { + // Reset the cache. + TestHelper::setValue($this->inflector, 'cache', array('foo' => 'bar')); + + $this->assertThat( + TestHelper::invoke($this->inflector, 'getCachedSingular', 'foo'), + $this->isFalse(), + 'Checks for an uncached singular.' + ); + + $this->assertThat( + TestHelper::invoke($this->inflector, 'getCachedSingular', 'bar'), + $this->equalTo('foo'), + 'Checks for a cached singular word.' + ); + } + + /** + * Method to test Inflector::matchRegexRule(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::matchRegexRule + */ + public function testMatchRegexRule() + { + $this->assertThat( + TestHelper::invoke($this->inflector, 'matchRegexRule', 'xyz', 'plural'), + $this->equalTo('xyzs'), + 'Checks pluralising against the basic regex.' + ); + + $this->assertThat( + TestHelper::invoke($this->inflector, 'matchRegexRule', 'xyzs', 'singular'), + $this->equalTo('xyz'), + 'Checks singularising against the basic regex.' + ); + + $this->assertThat( + TestHelper::invoke($this->inflector, 'matchRegexRule', 'xyz', 'singular'), + $this->isFalse(), + 'Checks singularising against an unmatched regex.' + ); + } + + /** + * Method to test Inflector::setCache(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::setCache + */ + public function testSetCache() + { + TestHelper::invoke($this->inflector, 'setCache', 'foo', 'bar'); + + $cache = TestHelper::getValue($this->inflector, 'cache'); + + $this->assertThat( + $cache['foo'], + $this->equalTo('bar'), + 'Checks the cache was set.' + ); + + TestHelper::invoke($this->inflector, 'setCache', 'foo', 'car'); + + $cache = TestHelper::getValue($this->inflector, 'cache'); + + $this->assertThat( + $cache['foo'], + $this->equalTo('car'), + 'Checks an existing value in the cache was reset.' + ); + } + + /** + * Method to test Inflector::addCountableRule(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::addCountableRule + */ + public function testAddCountableRule() + { + // Add string. + $this->inflector->addCountableRule('foo'); + + $rules = TestHelper::getValue($this->inflector, 'rules'); + + $this->assertThat( + in_array('foo', $rules['countable']), + $this->isTrue(), + 'Checks a countable rule was added.' + ); + + // Add array. + $this->inflector->addCountableRule(array('goo', 'car')); + + $rules = TestHelper::getValue($this->inflector, 'rules'); + + $this->assertThat( + in_array('car', $rules['countable']), + $this->isTrue(), + 'Checks a countable rule was added by array.' + ); + } + + /** + * Method to test Inflector::addPluraliseRule(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::addPluraliseRule + */ + public function testAddPluraliseRule() + { + $chain = $this->inflector->addPluraliseRule(array('/foo/', '/bar/')); + + $this->assertThat( + $chain, + $this->identicalTo($this->inflector), + 'Checks chaining.' + ); + + $rules = TestHelper::getValue($this->inflector, 'rules'); + + $this->assertThat( + in_array('/bar/', $rules['plural']), + $this->isTrue(), + 'Checks a pluralisation rule was added.' + ); + } + + /** + * Method to test Inflector::addSingulariseRule(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::addSingulariseRule + */ + public function testAddSingulariseRule() + { + $chain = $this->inflector->addSingulariseRule(array('/foo/', '/bar/')); + + $this->assertThat( + $chain, + $this->identicalTo($this->inflector), + 'Checks chaining.' + ); + + $rules = TestHelper::getValue($this->inflector, 'rules'); + + $this->assertThat( + in_array('/bar/', $rules['singular']), + $this->isTrue(), + 'Checks a singularisation rule was added.' + ); + } + + /** + * Method to test Inflector::getInstance(). + * + * @return void + * + * @since 1.0 + * @covers Joomla\String\Inflector::getInstance + */ + public function testGetInstance() + { + $this->assertInstanceOf( + 'Joomla\\String\\Inflector', + Inflector::getInstance(), + 'Check getInstance returns the right class.' + ); + + // Inject an instance an test. + TestHelper::setValue($this->inflector, 'instance', new \stdClass); + + $this->assertThat( + Inflector::getInstance(), + $this->equalTo(new \stdClass), + 'Checks singleton instance is returned.' + ); + + $this->assertInstanceOf( + 'Joomla\\String\\Inflector', + Inflector::getInstance(true), + 'Check getInstance a fresh object with true argument even though the instance is set to something else.' + ); + } + + /** + * Method to test Inflector::isCountable(). + * + * @param string $input A string. + * @param boolean $expected The expected result of the function call. + * + * @return void + * + * @dataProvider seedIsCountable + * @since 1.0 + * @covers Joomla\String\Inflector::isCountable + */ + public function testIsCountable($input, $expected) + { + $this->assertThat( + $this->inflector->isCountable($input), + $this->equalTo($expected) + ); + } + + /** + * Method to test Inflector::isPlural(). + * + * @param string $singular The singular form of a word. + * @param string $plural The plural form of a word. + * + * @return void + * + * @dataProvider seedSinglePlural + * @since 1.0 + * @covers Joomla\String\Inflector::isPlural + */ + public function testIsPlural($singular, $plural) + { + $this->assertThat( + $this->inflector->isPlural($plural), + $this->isTrue(), + 'Checks the plural is a plural.' + ); + + if ($singular != $plural) + { + $this->assertThat( + $this->inflector->isPlural($singular), + $this->isFalse(), + 'Checks the singular is not plural.' + ); + } + } + + /** + * Method to test Inflector::isSingular(). + * + * @param string $singular The singular form of a word. + * @param string $plural The plural form of a word. + * + * @return void + * + * @dataProvider seedSinglePlural + * @since 1.0 + * @covers Joomla\String\Inflector::isSingular + */ + public function testIsSingular($singular, $plural) + { + $this->assertThat( + $this->inflector->isSingular($singular), + $this->isTrue(), + 'Checks the singular is a singular.' + ); + + if ($singular != $plural) + { + $this->assertThat( + $this->inflector->isSingular($plural), + $this->isFalse(), + 'Checks the plural is not singular.' + ); + } + } + + /** + * Method to test Inflector::toPlural(). + * + * @param string $singular The singular form of a word. + * @param string $plural The plural form of a word. + * + * @return void + * + * @dataProvider seedSinglePlural + * @since 1.0 + * @covers Joomla\String\Inflector::toPlural + */ + public function testToPlural($singular, $plural) + { + $this->assertThat( + $this->inflector->toPlural($singular), + $this->equalTo($plural) + ); + } + + /** + * Method to test Inflector::toPlural(). + * + * @param string $singular The singular form of a word. + * @param string $plural The plural form of a word. + * + * @return void + * + * @dataProvider seedSinglePlural + * @since 1.0 + * @covers Joomla\String\Inflector::toSingular + */ + public function testToSingular($singular, $plural) + { + $this->assertThat( + $this->inflector->toSingular($plural), + $this->equalTo($singular) + ); + } +} diff --git a/libraries/joomla/string/Tests/NormaliseTest.php b/libraries/joomla/string/Tests/NormaliseTest.php new file mode 100644 index 0000000000000..8f412f117398f --- /dev/null +++ b/libraries/joomla/string/Tests/NormaliseTest.php @@ -0,0 +1,314 @@ +assertEquals($expected, Normalise::fromCamelcase($input)); + } + + /** + * Method to test Normalise::fromCamelCase(string, true). + * + * @param string $input The input value for the method. + * @param string $expected The expected value from the method. + * + * @return void + * + * @dataProvider seedTestFromCamelCase + * @since 1.0 + * @covers Joomla\String\Normalise::fromCamelcase + */ + public function testFromCamelCase_grouped($input, $expected) + { + $this->assertEquals($expected, Normalise::fromCamelcase($input, true)); + } + + /** + * Method to test Normalise::toCamelCase(). + * + * @param string $expected The expected value from the method. + * @param string $input The input value for the method. + * + * @return void + * + * @dataProvider seedTestToCamelCase + * @since 1.0 + * @covers Joomla\String\Normalise::toCamelcase + */ + public function testToCamelCase($expected, $input) + { + $this->assertEquals($expected, Normalise::toCamelcase($input)); + } + + /** + * Method to test Normalise::toDashSeparated(). + * + * @param string $expected The expected value from the method. + * @param string $input The input value for the method. + * + * @return void + * + * @dataProvider seedTestToDashSeparated + * @since 1.0 + * @covers Joomla\String\Normalise::toDashSeparated + */ + public function testToDashSeparated($expected, $input) + { + $this->assertEquals($expected, Normalise::toDashSeparated($input)); + } + + /** + * Method to test Normalise::toSpaceSeparated(). + * + * @param string $expected The expected value from the method. + * @param string $input The input value for the method. + * + * @return void + * + * @dataProvider seedTestToSpaceSeparated + * @since 1.0 + * @covers Joomla\String\Normalise::toSpaceSeparated + */ + public function testToSpaceSeparated($expected, $input) + { + $this->assertEquals($expected, Normalise::toSpaceSeparated($input)); + } + + /** + * Method to test Normalise::toUnderscoreSeparated(). + * + * @param string $expected The expected value from the method. + * @param string $input The input value for the method. + * + * @return void + * + * @dataProvider seedTestToUnderscoreSeparated + * @since 1.0 + * @covers Joomla\String\Normalise::toUnderscoreSeparated + */ + public function testToUnderscoreSeparated($expected, $input) + { + $this->assertEquals($expected, Normalise::toUnderscoreSeparated($input)); + } + + /** + * Method to test Normalise::toVariable(). + * + * @param string $expected The expected value from the method. + * @param string $input The input value for the method. + * + * @return void + * + * @dataProvider seedTestToVariable + * @since 1.0 + * @covers Joomla\String\Normalise::toVariable + */ + public function testToVariable($expected, $input) + { + $this->assertEquals($expected, Normalise::toVariable($input)); + } + + /** + * Method to test Normalise::toKey(). + * + * @param string $expected The expected value from the method. + * @param string $input The input value for the method. + * + * @return void + * + * @dataProvider seedTestToKey + * @since 1.0 + * @covers Joomla\String\Normalise::toKey + */ + public function testToKey($expected, $input) + { + $this->assertEquals($expected, Normalise::toKey($input)); + } +} diff --git a/libraries/joomla/string/Tests/StringTest.php b/libraries/joomla/string/Tests/StringTest.php new file mode 100644 index 0000000000000..b1c907563f005 --- /dev/null +++ b/libraries/joomla/string/Tests/StringTest.php @@ -0,0 +1,1000 @@ + array('title', null, 0, 'title (2)'), + 'Second default increment' => array('title(2)', null, 0, 'title(3)'), + 'First dash increment' => array('title', 'dash', 0, 'title-2'), + 'Second dash increment' => array('title-2', 'dash', 0, 'title-3'), + 'Set default increment' => array('title', null, 4, 'title (4)'), + 'Unknown style fallback to default' => array('title', 'foo', 0, 'title (2)'), + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrpos() + { + return array( + array('missing', 'sing', 0, 3), + array('missing', 'sting', 0, false), + array('missing', 'ing', 0, 4), + array(' объектов на карте с', 'на карте', 0, 10), + array('на карте с', 'на карте', 0, 0), + array('на карте с', 'на каррте', 0, false), + array('на карте с', 'на карте', 2, false), + array('missing', 'sing', false, 3) + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestGetStrrpos() + { + return array( + array('missing', 'sing', 0, 3), + array('missing', 'sting', 0, false), + array('missing', 'ing', 0, 4), + array(' объектов на карте с', 'на карте', 0, 10), + array('на карте с', 'на карте', 0, 0), + array('на карте с', 'на каррте', 0, false), + array('на карте с', 'карт', 2, 3) + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestSubstr() + { + return array( + array('Mississauga', 4, false, 'issauga'), + array(' объектов на карте с', 10, false, 'на карте с'), + array(' объектов на карте с', 10, 5, 'на ка'), + array(' объектов на карте с', -4, false, 'те с'), + array(' объектов на карте с', 99, false, false) + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrtolower() + { + return array( + array('Joomla! Rocks', 'joomla! rocks') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrtoupper() + { + return array( + array('Joomla! Rocks', 'JOOMLA! ROCKS') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrlen() + { + return array( + array('Joomla! Rocks', 13) + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStr_ireplace() + { + return array( + array('Pig', 'cow', 'the pig jumped', false, 'the cow jumped'), + array('Pig', 'cow', 'the pig jumped', true, 'the cow jumped'), + array('Pig', 'cow', 'the pig jumped over the cow', true, 'the cow jumped over the cow'), + array(array('PIG', 'JUMPED'), array('cow', 'hopped'), 'the pig jumped over the pig', true, 'the cow hopped over the cow'), + array('шил', 'биш', 'Би шил идэй чадна', true, 'Би биш идэй чадна'), + array('/', ':', '/test/slashes/', true, ':test:slashes:'), + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStr_split() + { + return array( + array('string', 1, array('s', 't', 'r', 'i', 'n', 'g')), + array('string', 2, array('st', 'ri', 'ng')), + array('волн', 3, array('вол', 'н')), + array('волн', 1, array('в', 'о', 'л', 'н')) + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrcasecmp() + { + return array( + array('THIS IS STRING1', 'this is string1', false, 0), + array('this is string1', 'this is string2', false, -1), + array('this is string2', 'this is string1', false, 1), + array('бгдпт', 'бгдпт', false, 0), + array('àbc', 'abc', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), 1), + array('àbc', 'bcd', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + array('é', 'è', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + array('É', 'é', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), 0), + array('œ', 'p', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + array('œ', 'n', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), 1), + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrcmp() + { + return array( + array('THIS IS STRING1', 'this is string1', false, -1), + array('this is string1', 'this is string2', false, -1), + array('this is string2', 'this is string1', false, 1), + array('a', 'B', false, 1), + array('A', 'b', false, -1), + array('Àbc', 'abc', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), 1), + array('Àbc', 'bcd', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + array('É', 'è', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + array('é', 'È', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + array('Œ', 'p', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + array('Œ', 'n', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), 1), + array('œ', 'N', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), 1), + array('œ', 'P', array('fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR'), -1), + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrcspn() + { + return array( + array('subject string ', '<>', false, false, 8), + array('Би шил {123} идэй {456} чадна', '}{', null, false, 7), + array('Би шил {123} идэй {456} чадна', '}{', 13, 10, 5) + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStristr() + { + return array( + array('haystack', 'needle', false), + array('before match, after match', 'match', 'match, after match'), + array('Би шил идэй чадна', 'шил', 'шил идэй чадна') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrrev() + { + return array( + array('abc def', 'fed cba'), + array('Би шил', 'лиш иБ') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestStrspn() + { + return array( + array('A321 Main Street', '0123456789', 1, 2, 2), + array('321 Main Street', '0123456789', null, 2, 2), + array('A321 Main Street', '0123456789', null, 10, 0), + array('321 Main Street', '0123456789', null, null, 3), + array('Main Street 321', '0123456789', null, -3, 0), + array('321 Main Street', '0123456789', null, -13, 2), + array('321 Main Street', '0123456789', null, -12, 3), + array('A321 Main Street', '0123456789', 0, null, 0), + array('A321 Main Street', '0123456789', 1, 10, 3), + array('A321 Main Street', '0123456789', 1, null, 3), + array('Би шил идэй чадна', 'Би', null, null, 2), + array('чадна Би шил идэй чадна', 'Би', null, null, 0) + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestSubstr_replace() + { + return array( + array('321 Main Street', 'Broadway Avenue', 4, false, '321 Broadway Avenue'), + array('321 Main Street', 'Broadway', 4, 4, '321 Broadway Street'), + array('чадна Би шил идэй чадна', '我能吞', 6, false, 'чадна 我能吞'), + array('чадна Би шил идэй чадна', '我能吞', 6, 2, 'чадна 我能吞 шил идэй чадна') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestLtrim() + { + return array( + array(' abc def', null, 'abc def'), + array(' abc def', '', ' abc def'), + array(' Би шил', null, 'Би шил'), + array("\t\n\r\x0BБи шил", null, 'Би шил'), + array("\x0B\t\n\rБи шил", "\t\n\x0B", "\rБи шил"), + array("\x09Би шил\x0A", "\x09\x0A", "Би шил\x0A"), + array('1234abc', '0123456789', 'abc') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestRtrim() + { + return array( + array('abc def ', null, 'abc def'), + array('abc def ', '', 'abc def '), + array('Би шил ', null, 'Би шил'), + array("Би шил\t\n\r\x0B", null, 'Би шил'), + array("Би шил\r\x0B\t\n", "\t\n\x0B", "Би шил\r"), + array("\x09Би шил\x0A", "\x09\x0A", "\x09Би шил"), + array('1234abc', 'abc', '01234') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestTrim() + { + return array( + array(' abc def ', null, 'abc def'), + array(' abc def ', '', ' abc def '), + array(' Би шил ', null, 'Би шил'), + array("\t\n\r\x0BБи шил\t\n\r\x0B", null, 'Би шил'), + array("\x0B\t\n\rБи шил\r\x0B\t\n", "\t\n\x0B", "\rБи шил\r"), + array("\x09Би шил\x0A", "\x09\x0A", "Би шил"), + array('1234abc56789', '0123456789', 'abc') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestUcfirst() + { + return array( + array('george', null, null, 'George'), + array('мога', null, null, 'Мога'), + array('ψυχοφθόρα', null, null, 'Ψυχοφθόρα'), + array('dr jekill and mister hyde', ' ', null, 'Dr Jekill And Mister Hyde'), + array('dr jekill and mister hyde', ' ', '_', 'Dr_Jekill_And_Mister_Hyde'), + array('dr jekill and mister hyde', ' ', '', 'DrJekillAndMisterHyde'), + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestUcwords() + { + return array( + array('george washington', 'George Washington'), + array("george\r\nwashington", "George\r\nWashington"), + array('мога', 'Мога'), + array('αβγ δεζ', 'Αβγ Δεζ'), + array('åbc öde', 'Åbc Öde') + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestTranscode() + { + return array( + array('Åbc Öde €100', 'UTF-8', 'ISO-8859-1', "\xc5bc \xd6de EUR100"), + array(array('Åbc Öde €100'), 'UTF-8', 'ISO-8859-1', null), + ); + } + + /** + * Test... + * + * @return array + * + * @since 1.0 + */ + public function seedTestValid() + { + return array( + array('george Мога Ž Ψυχοφθόρα ฉันกินกระจกได้ 我能吞下玻璃而不伤身体 ', true), + array("\xFF ABC", false), + array("0xfffd ABC", true), + array('', true) + ); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $style @todo + * @param string $number @todo + * @param string $expected @todo + * + * @return void + * + * @dataProvider seedTestIncrement + * @since 1.0 + * @covers Joomla\String\String::increment + */ + public function testIncrement($string, $style, $number, $expected) + { + $this->assertThat( + String::increment($string, $style, $number), + $this->equalTo($expected) + ); + } + + // @codingStandardsIgnoreStart + // @todo Arguments with default values must be at the end of the argument list + + /** + * Test... + * + * @param string $haystack @todo + * @param string $needle @todo + * @param integer $offset @todo + * @param string $expect @todo + * + * @return void + * + * @dataProvider seedTestStrpos + * @since 1.0 + * @covers Joomla\String\String::strpos + */ + public function testStrpos($haystack, $needle, $offset = 0, $expect) + { + $actual = String::strpos($haystack, $needle, $offset); + $this->assertEquals($expect, $actual); + } + + // @codingStandardsIgnoreEnd + + // @codingStandardsIgnoreStart + // @todo Arguments with default values must be at the end of the argument list + + /** + * Test... + * + * @param string $haystack @todo + * @param string $needle @todo + * @param integer $offset @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestGetStrrpos + * @since 1.0 + * @covers Joomla\String\String::strrpos + */ + public function testStrrpos($haystack, $needle, $offset = 0, $expect) + { + $actual = String::strrpos($haystack, $needle, $offset); + $this->assertEquals($expect, $actual); + } + + // @codingStandardsIgnoreEnd + + // @codingStandardsIgnoreStart + // @todo Arguments with default values must be at the end of the argument list + + /** + * Test... + * + * @param string $string @todo + * @param string $start @todo + * @param bool|int $length @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestSubstr + * @since 1.0 + * @covers Joomla\String\String::substr + */ + public function testSubstr($string, $start, $length = false, $expect) + { + $actual = String::substr($string, $start, $length); + $this->assertEquals($expect, $actual); + } + + // @codingStandardsIgnoreEnd + + /** + * Test... + * + * @param string $string @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrtolower + * @since 1.0 + * @covers Joomla\String\String::strtolower + */ + public function testStrtolower($string, $expect) + { + $actual = String::strtolower($string); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrtoupper + * @since 1.0 + * @covers Joomla\String\String::strtoupper + */ + public function testStrtoupper($string, $expect) + { + $actual = String::strtoupper($string); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrlen + * @since 1.0 + * @covers Joomla\String\String::strlen + */ + public function testStrlen($string, $expect) + { + $actual = String::strlen($string); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $search @todo + * @param string $replace @todo + * @param string $subject @todo + * @param integer $count @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStr_ireplace + * @since 1.0 + * @covers Joomla\String\String::str_ireplace + */ + public function testStr_ireplace($search, $replace, $subject, $count, $expect) + { + $actual = String::str_ireplace($search, $replace, $subject, $count); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $split_length @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStr_split + * @since 1.0 + * @covers Joomla\String\String::str_split + */ + public function testStr_split($string, $split_length, $expect) + { + $actual = String::str_split($string, $split_length); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string1 @todo + * @param string $string2 @todo + * @param string $locale @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrcasecmp + * @since 1.0 + * @covers Joomla\String\String::strcasecmp + */ + public function testStrcasecmp($string1, $string2, $locale, $expect) + { + // Convert the $locale param to a string if it is an array + if (is_array($locale)) + { + $locale = "'" . implode("', '", $locale) . "'"; + } + + if (substr(php_uname(), 0, 6) == 'Darwin' && $locale != false) + { + $this->markTestSkipped('Darwin bug prevents foreign conversion from working properly'); + } + elseif ($locale != false && !setlocale(LC_COLLATE, $locale)) + { + $this->markTestSkipped("Locale {$locale} is not available."); + } + else + { + $actual = String::strcasecmp($string1, $string2, $locale); + + if ($actual != 0) + { + $actual = $actual / abs($actual); + } + + $this->assertEquals($expect, $actual); + } + } + + /** + * Test... + * + * @param string $string1 @todo + * @param string $string2 @todo + * @param string $locale @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrcmp + * @since 1.0 + * @covers Joomla\String\String::strcmp + */ + public function testStrcmp($string1, $string2, $locale, $expect) + { + // Convert the $locale param to a string if it is an array + if (is_array($locale)) + { + $locale = "'" . implode("', '", $locale) . "'"; + } + + if (substr(php_uname(), 0, 6) == 'Darwin' && $locale != false) + { + $this->markTestSkipped('Darwin bug prevents foreign conversion from working properly'); + } + elseif ($locale != false && !setlocale(LC_COLLATE, $locale)) + { + // If the locale is not available, we can't have to transcode the string and can't reliably compare it. + $this->markTestSkipped("Locale {$locale} is not available."); + } + else + { + $actual = String::strcmp($string1, $string2, $locale); + + if ($actual != 0) + { + $actual = $actual / abs($actual); + } + + $this->assertEquals($expect, $actual); + } + } + + /** + * Test... + * + * @param string $haystack @todo + * @param string $needles @todo + * @param integer $start @todo + * @param integer $len @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrcspn + * @since 1.0 + * @covers Joomla\String\String::strcspn + */ + public function testStrcspn($haystack, $needles, $start, $len, $expect) + { + $actual = String::strcspn($haystack, $needles, $start, $len); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $haystack @todo + * @param string $needle @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStristr + * @since 1.0 + * @covers Joomla\String\String::stristr + */ + public function testStristr($haystack, $needle, $expect) + { + $actual = String::stristr($haystack, $needle); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrrev + * @since 1.0 + * @covers Joomla\String\String::strrev + */ + public function testStrrev($string, $expect) + { + $actual = String::strrev($string); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $subject @todo + * @param string $mask @todo + * @param integer $start @todo + * @param integer $length @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestStrspn + * @since 1.0 + * @covers Joomla\String\String::strspn + */ + public function testStrspn($subject, $mask, $start, $length, $expect) + { + $actual = String::strspn($subject, $mask, $start, $length); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $replacement @todo + * @param integer $start @todo + * @param integer $length @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestSubstr_replace + * @since 1.0 + * @covers Joomla\String\String::substr_replace + */ + public function testSubstr_replace($string, $replacement, $start, $length, $expect) + { + $actual = String::substr_replace($string, $replacement, $start, $length); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $charlist @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestLtrim + * @since 1.0 + * @covers Joomla\String\String::ltrim + */ + public function testLtrim($string, $charlist, $expect) + { + if ($charlist === null) + { + $actual = String::ltrim($string); + } + else + { + $actual = String::ltrim($string, $charlist); + } + + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $charlist @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestRtrim + * @since 1.0 + * @covers Joomla\String\String::rtrim + */ + public function testRtrim($string, $charlist, $expect) + { + if ($charlist === null) + { + $actual = String::rtrim($string); + } + else + { + $actual = String::rtrim($string, $charlist); + } + + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $charlist @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestTrim + * @since 1.0 + * @covers Joomla\String\String::trim + */ + public function testTrim($string, $charlist, $expect) + { + if ($charlist === null) + { + $actual = String::trim($string); + } + else + { + $actual = String::trim($string, $charlist); + } + + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $delimiter @todo + * @param string $newDelimiter @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestUcfirst + * @since 1.0 + * @covers Joomla\String\String::ucfirst + */ + public function testUcfirst($string, $delimiter, $newDelimiter, $expect) + { + $actual = String::ucfirst($string, $delimiter, $newDelimiter); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestUcwords + * @since 1.0 + * @covers Joomla\String\String::ucwords + */ + public function testUcwords($string, $expect) + { + $actual = String::ucwords($string); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $source @todo + * @param string $from_encoding @todo + * @param string $to_encoding @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestTranscode + * @since 1.0 + * @covers Joomla\String\String::transcode + */ + public function testTranscode($source, $from_encoding, $to_encoding, $expect) + { + $actual = String::transcode($source, $from_encoding, $to_encoding); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestValid + * @since 1.0 + * @covers Joomla\String\String::valid + */ + public function testValid($string, $expect) + { + $actual = String::valid($string); + $this->assertEquals($expect, $actual); + } + + /** + * Test... + * + * @param string $string @todo + * @param string $expect @todo + * + * @return array + * + * @dataProvider seedTestValid + * @since 1.0 + * @covers Joomla\String\String::compliant + */ + public function testCompliant($string, $expect) + { + $actual = String::compliant($string); + $this->assertEquals($expect, $actual); + } +} diff --git a/libraries/joomla/string/composer.json b/libraries/joomla/string/composer.json new file mode 100644 index 0000000000000..ad5d3e33891ce --- /dev/null +++ b/libraries/joomla/string/composer.json @@ -0,0 +1,20 @@ +{ + "name": "joomla/string", + "type": "joomla-package", + "description": "Joomla String Package", + "keywords": ["joomla", "framework", "string"], + "homepage": "https://github.com/joomla-framework/string", + "license": "GPL-2.0+", + "require": { + "php": ">=5.3.10" + }, + "require-dev": { + "joomla/test": "~1.0" + }, + "autoload": { + "psr-4": { + "Joomla\\String\\": "src/", + "Joomla\\String\\Tests\\": "Tests/" + } + } +} diff --git a/libraries/joomla/string/phpunit.xml.dist b/libraries/joomla/string/phpunit.xml.dist new file mode 100644 index 0000000000000..2278bfbac86a6 --- /dev/null +++ b/libraries/joomla/string/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + Tests + + + diff --git a/libraries/joomla/string/src/Inflector.php b/libraries/joomla/string/src/Inflector.php new file mode 100644 index 0000000000000..ce7d0d20c421b --- /dev/null +++ b/libraries/joomla/string/src/Inflector.php @@ -0,0 +1,468 @@ + array( + '/(matr)ices$/i' => '\1ix', + '/(vert|ind)ices$/i' => '\1ex', + '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|viri?)i$/i' => '\1us', + '/([ftw]ax)es/i' => '\1', + '/(cris|ax|test)es$/i' => '\1is', + '/(shoe|slave)s$/i' => '\1', + '/(o)es$/i' => '\1', + '/([^aeiouy]|qu)ies$/i' => '\1y', + '/$1ses$/i' => '\s', + '/ses$/i' => '\s', + '/eaus$/' => 'eau', + '/^(.*us)$/' => '\\1', + '/s$/i' => '', + ), + 'plural' => array( + '/([m|l])ouse$/i' => '\1ice', + '/(matr|vert|ind)(ix|ex)$/i' => '\1ices', + '/(x|ch|ss|sh)$/i' => '\1es', + '/([^aeiouy]|qu)y$/i' => '\1ies', + '/([^aeiouy]|qu)ies$/i' => '\1y', + '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves', + '/sis$/i' => 'ses', + '/([ti])um$/i' => '\1a', + '/(buffal|tomat)o$/i' => '\1\2oes', + '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$/i' => '\1i', + '/us$/i' => 'uses', + '/(ax|cris|test)is$/i' => '\1es', + '/s$/i' => 's', + '/$/' => 's', + ), + 'countable' => array( + 'id', + 'hits', + 'clicks', + ), + ); + + /** + * Cached inflections. + * + * The array is in the form [singular => plural] + * + * @var array + * @since 1.0 + */ + private $cache = array(); + + /** + * Protected constructor. + * + * @since 1.0 + */ + protected function __construct() + { + // Pre=populate the irregual singular/plural. + $this + ->addWord('deer') + ->addWord('moose') + ->addWord('sheep') + ->addWord('bison') + ->addWord('salmon') + ->addWord('pike') + ->addWord('trout') + ->addWord('fish') + ->addWord('swine') + + ->addWord('alias', 'aliases') + ->addWord('bus', 'buses') + ->addWord('foot', 'feet') + ->addWord('goose', 'geese') + ->addWord('hive', 'hives') + ->addWord('louse', 'lice') + ->addWord('man', 'men') + ->addWord('mouse', 'mice') + ->addWord('ox', 'oxen') + ->addWord('quiz', 'quizes') + ->addWord('status', 'statuses') + ->addWord('tooth', 'teeth') + ->addWord('woman', 'women'); + } + + /** + * Adds inflection regex rules to the inflector. + * + * @param mixed $data A string or an array of strings or regex rules to add. + * @param string $ruleType The rule type: singular | plural | countable + * + * @return void + * + * @since 1.0 + * @throws InvalidArgumentException + */ + private function addRule($data, $ruleType) + { + if (is_string($data)) + { + $data = array($data); + } + elseif (!is_array($data)) + { + // Do not translate. + throw new InvalidArgumentException('Invalid inflector rule data.'); + } + + foreach ($data as $rule) + { + // Ensure a string is pushed. + array_push($this->rules[$ruleType], (string) $rule); + } + } + + /** + * Gets an inflected word from the cache where the singular form is supplied. + * + * @param string $singular A singular form of a word. + * + * @return mixed The cached inflection or false if none found. + * + * @since 1.0 + */ + private function getCachedPlural($singular) + { + $singular = String::strtolower($singular); + + // Check if the word is in cache. + if (isset($this->cache[$singular])) + { + return $this->cache[$singular]; + } + + return false; + } + + /** + * Gets an inflected word from the cache where the plural form is supplied. + * + * @param string $plural A plural form of a word. + * + * @return mixed The cached inflection or false if none found. + * + * @since 1.0 + */ + private function getCachedSingular($plural) + { + $plural = String::strtolower($plural); + + return array_search($plural, $this->cache); + } + + /** + * Execute a regex from rules. + * + * The 'plural' rule type expects a singular word. + * The 'singular' rule type expects a plural word. + * + * @param string $word The string input. + * @param string $ruleType String (eg, singular|plural) + * + * @return mixed An inflected string, or false if no rule could be applied. + * + * @since 1.0 + */ + private function matchRegexRule($word, $ruleType) + { + // Cycle through the regex rules. + foreach ($this->rules[$ruleType] as $regex => $replacement) + { + $matches = 0; + $matchedWord = preg_replace($regex, $replacement, $word, -1, $matches); + + if ($matches > 0) + { + return $matchedWord; + } + } + + return false; + } + + /** + * Sets an inflected word in the cache. + * + * @param string $singular The singular form of the word. + * @param string $plural The plural form of the word. If omitted, it is assumed the singular and plural are identical. + * + * @return void + * + * @since 1.0 + */ + private function setCache($singular, $plural = null) + { + $singular = String::strtolower($singular); + + if ($plural === null) + { + $plural = $singular; + } + else + { + $plural = String::strtolower($plural); + } + + $this->cache[$singular] = $plural; + } + + /** + * Adds a countable word. + * + * @param mixed $data A string or an array of strings to add. + * + * @return Inflector Returns this object to support chaining. + * + * @since 1.0 + */ + public function addCountableRule($data) + { + $this->addRule($data, 'countable'); + + return $this; + } + + /** + * Adds a specific singular-plural pair for a word. + * + * @param string $singular The singular form of the word. + * @param string $plural The plural form of the word. If omitted, it is assumed the singular and plural are identical. + * + * @return Inflector Returns this object to support chaining. + * + * @since 1.0 + */ + public function addWord($singular, $plural =null) + { + $this->setCache($singular, $plural); + + return $this; + } + + /** + * Adds a pluralisation rule. + * + * @param mixed $data A string or an array of regex rules to add. + * + * @return Inflector Returns this object to support chaining. + * + * @since 1.0 + */ + public function addPluraliseRule($data) + { + $this->addRule($data, 'plural'); + + return $this; + } + + /** + * Adds a singularisation rule. + * + * @param mixed $data A string or an array of regex rules to add. + * + * @return Inflector Returns this object to support chaining. + * + * @since 1.0 + */ + public function addSingulariseRule($data) + { + $this->addRule($data, 'singular'); + + return $this; + } + + /** + * Gets an instance of the JStringInflector singleton. + * + * @param boolean $new If true (default is false), returns a new instance regardless if one exists. + * This argument is mainly used for testing. + * + * @return Inflector + * + * @since 1.0 + */ + public static function getInstance($new = false) + { + if ($new) + { + return new static; + } + elseif (!is_object(self::$instance)) + { + self::$instance = new static; + } + + return self::$instance; + } + + /** + * Checks if a word is countable. + * + * @param string $word The string input. + * + * @return boolean True if word is countable, false otherwise. + * + * @since 1.0 + */ + public function isCountable($word) + { + return (boolean) in_array($word, $this->rules['countable']); + } + + /** + * Checks if a word is in a plural form. + * + * @param string $word The string input. + * + * @return boolean True if word is plural, false if not. + * + * @since 1.0 + */ + public function isPlural($word) + { + // Try the cache for an known inflection. + $inflection = $this->getCachedSingular($word); + + if ($inflection !== false) + { + return true; + } + + // Compute the inflection to cache the values, and compare. + return $this->toPlural($this->toSingular($word)) == $word; + } + + /** + * Checks if a word is in a singular form. + * + * @param string $word The string input. + * + * @return boolean True if word is singular, false if not. + * + * @since 1.0 + */ + public function isSingular($word) + { + // Try the cache for an known inflection. + $inflection = $this->getCachedPlural($word); + + if ($inflection !== false) + { + return true; + } + + // Compute the inflection to cache the values, and compare. + return $this->toSingular($this->toPlural($word)) == $word; + } + + /** + * Converts a word into its plural form. + * + * @param string $word The singular word to pluralise. + * + * @return mixed An inflected string, or false if no rule could be applied. + * + * @since 1.0 + */ + public function toPlural($word) + { + // Try to get the cached plural form from the singular. + $cache = $this->getCachedPlural($word); + + if ($cache !== false) + { + return $cache; + } + + // Check if the word is a known singular. + if ($this->getCachedSingular($word)) + { + return false; + } + + // Compute the inflection. + $inflected = $this->matchRegexRule($word, 'plural'); + + if ($inflected !== false) + { + $this->setCache($word, $inflected); + + return $inflected; + } + + return false; + } + + /** + * Converts a word into its singular form. + * + * @param string $word The plural word to singularise. + * + * @return mixed An inflected string, or false if no rule could be applied. + * + * @since 1.0 + */ + public function toSingular($word) + { + // Try to get the cached singular form from the plural. + $cache = $this->getCachedSingular($word); + + if ($cache !== false) + { + return $cache; + } + + // Check if the word is a known plural. + if ($this->getCachedPlural($word)) + { + return false; + } + + // Compute the inflection. + $inflected = $this->matchRegexRule($word, 'singular'); + + if ($inflected !== false) + { + $this->setCache($inflected, $word); + + return $inflected; + } + + return false; + } +} diff --git a/libraries/joomla/string/src/Normalise.php b/libraries/joomla/string/src/Normalise.php new file mode 100644 index 0000000000000..e11437666a058 --- /dev/null +++ b/libraries/joomla/string/src/Normalise.php @@ -0,0 +1,162 @@ + array( + '#-(\d+)$#', + '-%d' + ), + 'default' => array( + array('#\((\d+)\)$#', '#\(\d+\)$#'), + array(' (%d)', '(%d)'), + ), + ); + + /** + * Increments a trailing number in a string. + * + * Used to easily create distinct labels when copying objects. The method has the following styles: + * + * default: "Label" becomes "Label (2)" + * dash: "Label" becomes "Label-2" + * + * @param string $string The source string. + * @param string $style The the style (default|dash). + * @param integer $n If supplied, this number is used for the copy, otherwise it is the 'next' number. + * + * @return string The incremented string. + * + * @since 1.0 + */ + public static function increment($string, $style = 'default', $n = 0) + { + $styleSpec = isset(self::$incrementStyles[$style]) ? self::$incrementStyles[$style] : self::$incrementStyles['default']; + + // Regular expression search and replace patterns. + if (is_array($styleSpec[0])) + { + $rxSearch = $styleSpec[0][0]; + $rxReplace = $styleSpec[0][1]; + } + else + { + $rxSearch = $rxReplace = $styleSpec[0]; + } + + // New and old (existing) sprintf formats. + if (is_array($styleSpec[1])) + { + $newFormat = $styleSpec[1][0]; + $oldFormat = $styleSpec[1][1]; + } + else + { + $newFormat = $oldFormat = $styleSpec[1]; + } + + // Check if we are incrementing an existing pattern, or appending a new one. + if (preg_match($rxSearch, $string, $matches)) + { + $n = empty($n) ? ($matches[1] + 1) : $n; + $string = preg_replace($rxReplace, sprintf($oldFormat, $n), $string); + } + else + { + $n = empty($n) ? 2 : $n; + $string .= sprintf($newFormat, $n); + } + + return $string; + } + + /** + * Tests whether a string contains only 7bit ASCII bytes. + * You might use this to conditionally check whether a string + * needs handling as UTF-8 or not, potentially offering performance + * benefits by using the native PHP equivalent if it's just ASCII e.g.; + * + * + * if (String::is_ascii($someString)) + * { + * // It's just ASCII - use the native PHP version + * $someString = strtolower($someString); + * } + * else + * { + * $someString = String::strtolower($someString); + * } + * + * + * @param string $str The string to test. + * + * @return boolean True if the string is all ASCII + * + * @since 1.0 + */ + public static function is_ascii($str) + { + // Search for any bytes which are outside the ASCII range... + return (preg_match('/(?:[^\x00-\x7F])/', $str) !== 1); + } + + /** + * UTF-8 aware alternative to strpos. + * + * Find position of first occurrence of a string. + * + * @param string $str String being examined + * @param string $search String being searched for + * @param integer $offset Optional, specifies the position from which the search should be performed + * + * @return mixed Number of characters before the first match or FALSE on failure + * + * @see http://www.php.net/strpos + * @since 1.0 + */ + public static function strpos($str, $search, $offset = false) + { + if ($offset === false) + { + return utf8_strpos($str, $search); + } + else + { + return utf8_strpos($str, $search, $offset); + } + } + + /** + * UTF-8 aware alternative to strrpos + * Finds position of last occurrence of a string + * + * @param string $str String being examined. + * @param string $search String being searched for. + * @param integer $offset Offset from the left of the string. + * + * @return mixed Number of characters before the last match or false on failure + * + * @see http://www.php.net/strrpos + * @since 1.0 + */ + public static function strrpos($str, $search, $offset = 0) + { + return utf8_strrpos($str, $search, $offset); + } + + /** + * UTF-8 aware alternative to substr + * Return part of a string given character offset (and optionally length) + * + * @param string $str String being processed + * @param integer $offset Number of UTF-8 characters offset (from left) + * @param integer $length Optional length in UTF-8 characters from offset + * + * @return mixed string or FALSE if failure + * + * @see http://www.php.net/substr + * @since 1.0 + */ + public static function substr($str, $offset, $length = false) + { + if ($length === false) + { + return utf8_substr($str, $offset); + } + else + { + return utf8_substr($str, $offset, $length); + } + } + + /** + * UTF-8 aware alternative to strtlower + * + * Make a string lowercase + * Note: The concept of a characters "case" only exists is some alphabets + * such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does + * not exist in the Chinese alphabet, for example. See Unicode Standard + * Annex #21: Case Mappings + * + * @param string $str String being processed + * + * @return mixed Either string in lowercase or FALSE is UTF-8 invalid + * + * @see http://www.php.net/strtolower + * @since 1.0 + */ + public static function strtolower($str) + { + return utf8_strtolower($str); + } + + /** + * UTF-8 aware alternative to strtoupper + * Make a string uppercase + * Note: The concept of a characters "case" only exists is some alphabets + * such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does + * not exist in the Chinese alphabet, for example. See Unicode Standard + * Annex #21: Case Mappings + * + * @param string $str String being processed + * + * @return mixed Either string in uppercase or FALSE is UTF-8 invalid + * + * @see http://www.php.net/strtoupper + * @since 1.0 + */ + public static function strtoupper($str) + { + return utf8_strtoupper($str); + } + + /** + * UTF-8 aware alternative to strlen. + * + * Returns the number of characters in the string (NOT THE NUMBER OF BYTES), + * + * @param string $str UTF-8 string. + * + * @return integer Number of UTF-8 characters in string. + * + * @see http://www.php.net/strlen + * @since 1.0 + */ + public static function strlen($str) + { + return utf8_strlen($str); + } + + /** + * UTF-8 aware alternative to str_ireplace + * Case-insensitive version of str_replace + * + * @param string $search String to search + * @param string $replace Existing string to replace + * @param string $str New string to replace with + * @param integer $count Optional count value to be passed by referene + * + * @return string UTF-8 String + * + * @see http://www.php.net/str_ireplace + * @since 1.0 + */ + public static function str_ireplace($search, $replace, $str, $count = null) + { + require_once __DIR__ . '/phputf8/str_ireplace.php'; + + if ($count === false) + { + return utf8_ireplace($search, $replace, $str); + } + else + { + return utf8_ireplace($search, $replace, $str, $count); + } + } + + /** + * UTF-8 aware alternative to str_split + * Convert a string to an array + * + * @param string $str UTF-8 encoded string to process + * @param integer $split_len Number to characters to split string by + * + * @return array + * + * @see http://www.php.net/str_split + * @since 1.0 + */ + public static function str_split($str, $split_len = 1) + { + require_once __DIR__ . '/phputf8/str_split.php'; + + return utf8_str_split($str, $split_len); + } + + /** + * UTF-8/LOCALE aware alternative to strcasecmp + * A case insensitive string comparison + * + * @param string $str1 string 1 to compare + * @param string $str2 string 2 to compare + * @param mixed $locale The locale used by strcoll or false to use classical comparison + * + * @return integer < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. + * + * @see http://www.php.net/strcasecmp + * @see http://www.php.net/strcoll + * @see http://www.php.net/setlocale + * @since 1.0 + */ + public static function strcasecmp($str1, $str2, $locale = false) + { + if ($locale) + { + // Get current locale + $locale0 = setlocale(LC_COLLATE, 0); + + if (!$locale = setlocale(LC_COLLATE, $locale)) + { + $locale = $locale0; + } + + // See if we have successfully set locale to UTF-8 + if (!stristr($locale, 'UTF-8') && stristr($locale, '_') && preg_match('~\.(\d+)$~', $locale, $m)) + { + $encoding = 'CP' . $m[1]; + } + elseif (stristr($locale, 'UTF-8') || stristr($locale, 'utf8')) + { + $encoding = 'UTF-8'; + } + else + { + $encoding = 'nonrecodable'; + } + + // If we successfully set encoding it to utf-8 or encoding is sth weird don't recode + if ($encoding == 'UTF-8' || $encoding == 'nonrecodable') + { + return strcoll(utf8_strtolower($str1), utf8_strtolower($str2)); + } + else + { + return strcoll( + self::transcode(utf8_strtolower($str1), 'UTF-8', $encoding), + self::transcode(utf8_strtolower($str2), 'UTF-8', $encoding) + ); + } + } + else + { + return utf8_strcasecmp($str1, $str2); + } + } + + /** + * UTF-8/LOCALE aware alternative to strcmp + * A case sensitive string comparison + * + * @param string $str1 string 1 to compare + * @param string $str2 string 2 to compare + * @param mixed $locale The locale used by strcoll or false to use classical comparison + * + * @return integer < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. + * + * @see http://www.php.net/strcmp + * @see http://www.php.net/strcoll + * @see http://www.php.net/setlocale + * @since 1.0 + */ + public static function strcmp($str1, $str2, $locale = false) + { + if ($locale) + { + // Get current locale + $locale0 = setlocale(LC_COLLATE, 0); + + if (!$locale = setlocale(LC_COLLATE, $locale)) + { + $locale = $locale0; + } + + // See if we have successfully set locale to UTF-8 + if (!stristr($locale, 'UTF-8') && stristr($locale, '_') && preg_match('~\.(\d+)$~', $locale, $m)) + { + $encoding = 'CP' . $m[1]; + } + elseif (stristr($locale, 'UTF-8') || stristr($locale, 'utf8')) + { + $encoding = 'UTF-8'; + } + else + { + $encoding = 'nonrecodable'; + } + + // If we successfully set encoding it to utf-8 or encoding is sth weird don't recode + if ($encoding == 'UTF-8' || $encoding == 'nonrecodable') + { + return strcoll($str1, $str2); + } + else + { + return strcoll(self::transcode($str1, 'UTF-8', $encoding), self::transcode($str2, 'UTF-8', $encoding)); + } + } + else + { + return strcmp($str1, $str2); + } + } + + /** + * UTF-8 aware alternative to strcspn + * Find length of initial segment not matching mask + * + * @param string $str The string to process + * @param string $mask The mask + * @param integer $start Optional starting character position (in characters) + * @param integer $length Optional length + * + * @return integer The length of the initial segment of str1 which does not contain any of the characters in str2 + * + * @see http://www.php.net/strcspn + * @since 1.0 + */ + public static function strcspn($str, $mask, $start = null, $length = null) + { + require_once __DIR__ . '/phputf8/strcspn.php'; + + if ($start === false && $length === false) + { + return utf8_strcspn($str, $mask); + } + elseif ($length === false) + { + return utf8_strcspn($str, $mask, $start); + } + else + { + return utf8_strcspn($str, $mask, $start, $length); + } + } + + /** + * UTF-8 aware alternative to stristr + * Returns all of haystack from the first occurrence of needle to the end. + * needle and haystack are examined in a case-insensitive manner + * Find first occurrence of a string using case insensitive comparison + * + * @param string $str The haystack + * @param string $search The needle + * + * @return string the sub string + * + * @see http://www.php.net/stristr + * @since 1.0 + */ + public static function stristr($str, $search) + { + require_once __DIR__ . '/phputf8/stristr.php'; + + return utf8_stristr($str, $search); + } + + /** + * UTF-8 aware alternative to strrev + * Reverse a string + * + * @param string $str String to be reversed + * + * @return string The string in reverse character order + * + * @see http://www.php.net/strrev + * @since 1.0 + */ + public static function strrev($str) + { + require_once __DIR__ . '/phputf8/strrev.php'; + + return utf8_strrev($str); + } + + /** + * UTF-8 aware alternative to strspn + * Find length of initial segment matching mask + * + * @param string $str The haystack + * @param string $mask The mask + * @param integer $start Start optional + * @param integer $length Length optional + * + * @return integer + * + * @see http://www.php.net/strspn + * @since 1.0 + */ + public static function strspn($str, $mask, $start = null, $length = null) + { + require_once __DIR__ . '/phputf8/strspn.php'; + + if ($start === null && $length === null) + { + return utf8_strspn($str, $mask); + } + elseif ($length === null) + { + return utf8_strspn($str, $mask, $start); + } + else + { + return utf8_strspn($str, $mask, $start, $length); + } + } + + /** + * UTF-8 aware substr_replace + * Replace text within a portion of a string + * + * @param string $str The haystack + * @param string $repl The replacement string + * @param integer $start Start + * @param integer $length Length (optional) + * + * @return string + * + * @see http://www.php.net/substr_replace + * @since 1.0 + */ + public static function substr_replace($str, $repl, $start, $length = null) + { + // Loaded by library loader + if ($length === false) + { + return utf8_substr_replace($str, $repl, $start); + } + else + { + return utf8_substr_replace($str, $repl, $start, $length); + } + } + + /** + * UTF-8 aware replacement for ltrim() + * + * Strip whitespace (or other characters) from the beginning of a string + * You only need to use this if you are supplying the charlist + * optional arg and it contains UTF-8 characters. Otherwise ltrim will + * work normally on a UTF-8 string + * + * @param string $str The string to be trimmed + * @param string $charlist The optional charlist of additional characters to trim + * + * @return string The trimmed string + * + * @see http://www.php.net/ltrim + * @since 1.0 + */ + public static function ltrim($str, $charlist = false) + { + if (empty($charlist) && $charlist !== false) + { + return $str; + } + + require_once __DIR__ . '/phputf8/trim.php'; + + if ($charlist === false) + { + return utf8_ltrim($str); + } + else + { + return utf8_ltrim($str, $charlist); + } + } + + /** + * UTF-8 aware replacement for rtrim() + * Strip whitespace (or other characters) from the end of a string + * You only need to use this if you are supplying the charlist + * optional arg and it contains UTF-8 characters. Otherwise rtrim will + * work normally on a UTF-8 string + * + * @param string $str The string to be trimmed + * @param string $charlist The optional charlist of additional characters to trim + * + * @return string The trimmed string + * + * @see http://www.php.net/rtrim + * @since 1.0 + */ + public static function rtrim($str, $charlist = false) + { + if (empty($charlist) && $charlist !== false) + { + return $str; + } + + require_once __DIR__ . '/phputf8/trim.php'; + + if ($charlist === false) + { + return utf8_rtrim($str); + } + else + { + return utf8_rtrim($str, $charlist); + } + } + + /** + * UTF-8 aware replacement for trim() + * Strip whitespace (or other characters) from the beginning and end of a string + * Note: you only need to use this if you are supplying the charlist + * optional arg and it contains UTF-8 characters. Otherwise trim will + * work normally on a UTF-8 string + * + * @param string $str The string to be trimmed + * @param string $charlist The optional charlist of additional characters to trim + * + * @return string The trimmed string + * + * @see http://www.php.net/trim + * @since 1.0 + */ + public static function trim($str, $charlist = false) + { + if (empty($charlist) && $charlist !== false) + { + return $str; + } + + require_once __DIR__ . '/phputf8/trim.php'; + + if ($charlist === false) + { + return utf8_trim($str); + } + else + { + return utf8_trim($str, $charlist); + } + } + + /** + * UTF-8 aware alternative to ucfirst + * Make a string's first character uppercase or all words' first character uppercase + * + * @param string $str String to be processed + * @param string $delimiter The words delimiter (null means do not split the string) + * @param string $newDelimiter The new words delimiter (null means equal to $delimiter) + * + * @return string If $delimiter is null, return the string with first character as upper case (if applicable) + * else consider the string of words separated by the delimiter, apply the ucfirst to each words + * and return the string with the new delimiter + * + * @see http://www.php.net/ucfirst + * @since 1.0 + */ + public static function ucfirst($str, $delimiter = null, $newDelimiter = null) + { + require_once __DIR__ . '/phputf8/ucfirst.php'; + + if ($delimiter === null) + { + return utf8_ucfirst($str); + } + else + { + if ($newDelimiter === null) + { + $newDelimiter = $delimiter; + } + + return implode($newDelimiter, array_map('utf8_ucfirst', explode($delimiter, $str))); + } + } + + /** + * UTF-8 aware alternative to ucwords + * Uppercase the first character of each word in a string + * + * @param string $str String to be processed + * + * @return string String with first char of each word uppercase + * + * @see http://www.php.net/ucwords + * @since 1.0 + */ + public static function ucwords($str) + { + require_once __DIR__ . '/phputf8/ucwords.php'; + + return utf8_ucwords($str); + } + + /** + * Transcode a string. + * + * @param string $source The string to transcode. + * @param string $from_encoding The source encoding. + * @param string $to_encoding The target encoding. + * + * @return mixed The transcoded string, or null if the source was not a string. + * + * @link https://bugs.php.net/bug.php?id=48147 + * + * @since 1.0 + */ + public static function transcode($source, $from_encoding, $to_encoding) + { + if (is_string($source)) + { + switch (ICONV_IMPL) + { + case 'glibc': + return @iconv($from_encoding, $to_encoding . '//TRANSLIT,IGNORE', $source); + + case 'libiconv': + default: + return iconv($from_encoding, $to_encoding . '//IGNORE//TRANSLIT', $source); + } + } + + return null; + } + + /** + * Tests a string as to whether it's valid UTF-8 and supported by the Unicode standard. + * + * Note: this function has been modified to simple return true or false. + * + * @param string $str UTF-8 encoded string. + * + * @return boolean true if valid + * + * @author + * @see http://hsivonen.iki.fi/php-utf8/ + * @see compliant + * @since 1.0 + */ + public static function valid($str) + { + // Cached expected number of octets after the current octet + // until the beginning of the next UTF8 character sequence + $mState = 0; + + // Cached Unicode character + $mUcs4 = 0; + + // Cached expected number of octets in the current sequence + $mBytes = 1; + + $len = strlen($str); + + for ($i = 0; $i < $len; $i++) + { + $in = ord($str{$i}); + + if ($mState == 0) + { + // When mState is zero we expect either a US-ASCII character or a + // multi-octet sequence. + if (0 == (0x80 & ($in))) + { + // US-ASCII, pass straight through. + $mBytes = 1; + } + elseif (0xC0 == (0xE0 & ($in))) + { + // First octet of 2 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x1F) << 6; + $mState = 1; + $mBytes = 2; + } + elseif (0xE0 == (0xF0 & ($in))) + { + // First octet of 3 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x0F) << 12; + $mState = 2; + $mBytes = 3; + } + elseif (0xF0 == (0xF8 & ($in))) + { + // First octet of 4 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x07) << 18; + $mState = 3; + $mBytes = 4; + } + elseif (0xF8 == (0xFC & ($in))) + { + /* First octet of 5 octet sequence. + * + * This is illegal because the encoded codepoint must be either + * (a) not the shortest form or + * (b) outside the Unicode range of 0-0x10FFFF. + * Rather than trying to resynchronize, we will carry on until the end + * of the sequence and let the later error handling code catch it. + */ + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x03) << 24; + $mState = 4; + $mBytes = 5; + } + elseif (0xFC == (0xFE & ($in))) + { + // First octet of 6 octet sequence, see comments for 5 octet sequence. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 1) << 30; + $mState = 5; + $mBytes = 6; + } + else + { + /* + * Current octet is neither in the US-ASCII range nor a legal first + * octet of a multi-octet sequence. + */ + return false; + } + } + else + { + // When mState is non-zero, we expect a continuation of the multi-octet + // sequence + if (0x80 == (0xC0 & ($in))) + { + // Legal continuation. + $shift = ($mState - 1) * 6; + $tmp = $in; + $tmp = ($tmp & 0x0000003F) << $shift; + $mUcs4 |= $tmp; + + /** + * End of the multi-octet sequence. mUcs4 now contains the final + * Unicode codepoint to be output + */ + if (0 == --$mState) + { + /* + * Check for illegal sequences and codepoints. + */ + // From Unicode 3.1, non-shortest form is illegal + if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || ((3 == $mBytes) && ($mUcs4 < 0x0800)) || ((4 == $mBytes) && ($mUcs4 < 0x10000)) + || (4 < $mBytes) + || (($mUcs4 & 0xFFFFF800) == 0xD800) // From Unicode 3.2, surrogate characters are illegal + || ($mUcs4 > 0x10FFFF)) // Codepoints outside the Unicode range are illegal + { + return false; + } + + // Initialize UTF8 cache. + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + } + } + else + { + /** + *((0xC0 & (*in) != 0x80) && (mState != 0)) + * Incomplete multi-octet sequence. + */ + return false; + } + } + } + + return true; + } + + /** + * Tests whether a string complies as UTF-8. This will be much + * faster than utf8_is_valid but will pass five and six octet + * UTF-8 sequences, which are not supported by Unicode and + * so cannot be displayed correctly in a browser. In other words + * it is not as strict as utf8_is_valid but it's faster. If you use + * it to validate user input, you place yourself at the risk that + * attackers will be able to inject 5 and 6 byte sequences (which + * may or may not be a significant risk, depending on what you are + * are doing) + * + * @param string $str UTF-8 string to check + * + * @return boolean TRUE if string is valid UTF-8 + * + * @see valid + * @see http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php#54805 + * @since 1.0 + */ + public static function compliant($str) + { + if (strlen($str) == 0) + { + return true; + } + + /* + * If even just the first character can be matched, when the /u + * modifier is used, then it's valid UTF-8. If the UTF-8 is somehow + * invalid, nothing at all will match, even if the string contains + * some valid sequences + */ + return (preg_match('/^.{1}/us', $str, $ar) == 1); + } +} diff --git a/libraries/joomla/string/src/phputf8/LICENSE b/libraries/joomla/string/src/phputf8/LICENSE new file mode 100644 index 0000000000000..28f1889698245 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/LICENSE @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/libraries/joomla/string/src/phputf8/README b/libraries/joomla/string/src/phputf8/README new file mode 100644 index 0000000000000..6c30905418608 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/README @@ -0,0 +1,82 @@ +++PHP UTF-8++ + +Version 0.5 + +++DOCUMENTATION++ + +Documentation in progress in ./docs dir + +http://www.phpwact.org/php/i18n/charsets +http://www.phpwact.org/php/i18n/utf-8 + +Important Note: DO NOT use these functions without understanding WHY +you are using them. In particular, do not blindly replace all use of PHP's +string functions which functions found here - most of the time you will +not need to, and you will be introducing a significant performance +overhead to your application. You can get a good idea of when to use what +from reading: http://www.phpwact.org/php/i18n/utf-8 + +Important Note: For sake of performance most of the functions here are +not "defensive" (e.g. there is not extensive parameter checking, well +formed UTF-8 is assumed). This is particularily relevant when is comes to +catching badly formed UTF-8 - you should screen input on the "outer +perimeter" with help from functions in the utf8_validation.php and +utf8_bad.php files. + +Important Note: this library treats ALL ASCII characters as valid, including ASCII control characters. But if you use some ASCII control characters in XML, it will render the XML ill-formed. Don't be a bozo: http://hsivonen.iki.fi/producing-xml/#controlchar + +++BUGS / SUPPORT / FEATURE REQUESTS ++ + +Please report bugs to: +http://sourceforge.net/tracker/?group_id=142846&atid=753842 +- if you are able, please submit a failing unit test +(http://www.lastcraft.com/simple_test.php) with your bug report. + +For feature requests / faster implementation of functions found here, +please drop them in via the RFE tracker: http://sourceforge.net/tracker/?group_id=142846&atid=753845 +Particularily interested in faster implementations! + +For general support / help, use: +http://sourceforge.net/tracker/?group_id=142846&atid=753843 + +In the VERY WORST case, you can email me: hfuecks gmail com - I tend to be slow to respond though so be warned. + +Important Note: when reporting bugs, please provide the following +information; + +PHP version, whether the iconv extension is loaded (in PHP5 it's +there by default), whether the mbstring extension is loaded. The +following PHP script can be used to determine this information; + +"; +if ( extension_loaded('mbstring') ) { + print "mbstring available
"; +} else { + print "mbstring not available
"; +} +if ( extension_loaded('iconv') ) { + print "iconv available
"; +} else { + print "iconv not available
"; +} +?> + +++LICENSING++ + +Parts of the code in this library come from other places, under different +licenses. +The authors involved have been contacted (see below). Attribution for +which code came from elsewhere can be found in the source code itself. + ++Andreas Gohr / Chris Smith - Dokuwiki +There is a fair degree of collaboration / exchange of ideas and code +beteen Dokuwiki's UTF-8 library; +http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php +and phputf8. Although Dokuwiki is released under GPL, its UTF-8 +library is released under LGPL, hence no conflict with phputf8 + ++Henri Sivonen (http://hsivonen.iki.fi/php-utf8/ / +http://hsivonen.iki.fi/php-utf8/) has also given permission for his +code to be released under the terms of the LGPL. He ported a Unicode / UTF-8 +converter from the Mozilla codebase to PHP, which is re-used in phputf8 diff --git a/libraries/joomla/string/src/phputf8/mbstring/core.php b/libraries/joomla/string/src/phputf8/mbstring/core.php new file mode 100644 index 0000000000000..6cb5501d7b8ce --- /dev/null +++ b/libraries/joomla/string/src/phputf8/mbstring/core.php @@ -0,0 +1,132 @@ + +* @link http://www.php.net/manual/en/function.strlen.php +* @link http://www.php.net/manual/en/function.utf8-decode.php +* @param string UTF-8 string +* @return int number of UTF-8 characters in string +* @package utf8 +*/ +function utf8_strlen($str){ + return strlen(utf8_decode($str)); +} + + +//-------------------------------------------------------------------- +/** +* UTF-8 aware alternative to strpos +* Find position of first occurrence of a string +* Note: This will get alot slower if offset is used +* Note: requires utf8_strlen amd utf8_substr to be loaded +* @param string haystack +* @param string needle (you should validate this with utf8_is_valid) +* @param integer offset in characters (from left) +* @return mixed integer position or FALSE on failure +* @see http://www.php.net/strpos +* @see utf8_strlen +* @see utf8_substr +* @package utf8 +*/ +function utf8_strpos($str, $needle, $offset = NULL) { + + if ( is_null($offset) ) { + + $ar = explode($needle, $str, 2); + if ( count($ar) > 1 ) { + return utf8_strlen($ar[0]); + } + return FALSE; + + } else { + + if ( !is_int($offset) ) { + trigger_error('utf8_strpos: Offset must be an integer',E_USER_ERROR); + return FALSE; + } + + $str = utf8_substr($str, $offset); + + if ( FALSE !== ( $pos = utf8_strpos($str, $needle) ) ) { + return $pos + $offset; + } + + return FALSE; + } + +} + +//-------------------------------------------------------------------- +/** +* UTF-8 aware alternative to strrpos +* Find position of last occurrence of a char in a string +* Note: This will get alot slower if offset is used +* Note: requires utf8_substr and utf8_strlen to be loaded +* @param string haystack +* @param string needle (you should validate this with utf8_is_valid) +* @param integer (optional) offset (from left) +* @return mixed integer position or FALSE on failure +* @see http://www.php.net/strrpos +* @see utf8_substr +* @see utf8_strlen +* @package utf8 +*/ +function utf8_strrpos($str, $needle, $offset = NULL) { + + if ( is_null($offset) ) { + + $ar = explode($needle, $str); + + if ( count($ar) > 1 ) { + // Pop off the end of the string where the last match was made + array_pop($ar); + $str = join($needle,$ar); + return utf8_strlen($str); + } + return FALSE; + + } else { + + if ( !is_int($offset) ) { + trigger_error('utf8_strrpos expects parameter 3 to be long',E_USER_WARNING); + return FALSE; + } + + $str = utf8_substr($str, $offset); + + if ( FALSE !== ( $pos = utf8_strrpos($str, $needle) ) ) { + return $pos + $offset; + } + + return FALSE; + } + +} + +//-------------------------------------------------------------------- +/** +* UTF-8 aware alternative to substr +* Return part of a string given character offset (and optionally length) +* +* Note arguments: comparied to substr - if offset or length are +* not integers, this version will not complain but rather massages them +* into an integer. +* +* Note on returned values: substr documentation states false can be +* returned in some cases (e.g. offset > string length) +* mb_substr never returns false, it will return an empty string instead. +* This adopts the mb_substr approach +* +* Note on implementation: PCRE only supports repetitions of less than +* 65536, in order to accept up to MAXINT values for offset and length, +* we'll repeat a group of 65535 characters when needed. +* +* Note on implementation: calculating the number of characters in the +* string is a relatively expensive operation, so we only carry it out when +* necessary. It isn't necessary for +ve offsets and no specified length +* +* @author Chris Smith +* @param string +* @param integer number of UTF-8 characters offset (from left) +* @param integer (optional) length in UTF-8 characters from offset +* @return mixed string or FALSE if failure +* @package utf8 +*/ +function utf8_substr($str, $offset, $length = NULL) { + + // generates E_NOTICE + // for PHP4 objects, but not PHP5 objects + $str = (string)$str; + $offset = (int)$offset; + if (!is_null($length)) $length = (int)$length; + + // handle trivial cases + if ($length === 0) return ''; + if ($offset < 0 && $length < 0 && $length < $offset) + return ''; + + // normalise negative offsets (we could use a tail + // anchored pattern, but they are horribly slow!) + if ($offset < 0) { + + // see notes + $strlen = strlen(utf8_decode($str)); + $offset = $strlen + $offset; + if ($offset < 0) $offset = 0; + + } + + $Op = ''; + $Lp = ''; + + // establish a pattern for offset, a + // non-captured group equal in length to offset + if ($offset > 0) { + + $Ox = (int)($offset/65535); + $Oy = $offset%65535; + + if ($Ox) { + $Op = '(?:.{65535}){'.$Ox.'}'; + } + + $Op = '^(?:'.$Op.'.{'.$Oy.'})'; + + } else { + + // offset == 0; just anchor the pattern + $Op = '^'; + + } + + // establish a pattern for length + if (is_null($length)) { + + // the rest of the string + $Lp = '(.*)$'; + + } else { + + if (!isset($strlen)) { + // see notes + $strlen = strlen(utf8_decode($str)); + } + + // another trivial case + if ($offset > $strlen) return ''; + + if ($length > 0) { + + // reduce any length that would + // go passed the end of the string + $length = min($strlen-$offset, $length); + + $Lx = (int)( $length / 65535 ); + $Ly = $length % 65535; + + // negative length requires a captured group + // of length characters + if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}'; + $Lp = '('.$Lp.'.{'.$Ly.'})'; + + } else if ($length < 0) { + + if ( $length < ($offset - $strlen) ) { + return ''; + } + + $Lx = (int)((-$length)/65535); + $Ly = (-$length)%65535; + + // negative length requires ... capture everything + // except a group of -length characters + // anchored at the tail-end of the string + if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}'; + $Lp = '(.*)(?:'.$Lp.'.{'.$Ly.'})$'; + + } + + } + + if (!preg_match( '#'.$Op.$Lp.'#us',$str, $match )) { + return ''; + } + + return $match[1]; + +} + +//--------------------------------------------------------------- +/** +* UTF-8 aware alternative to strtolower +* Make a string lowercase +* Note: The concept of a characters "case" only exists is some alphabets +* such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does +* not exist in the Chinese alphabet, for example. See Unicode Standard +* Annex #21: Case Mappings +* Note: requires utf8_to_unicode and utf8_from_unicode +* @author Andreas Gohr +* @param string +* @return mixed either string in lowercase or FALSE is UTF-8 invalid +* @see http://www.php.net/strtolower +* @see utf8_to_unicode +* @see utf8_from_unicode +* @see http://www.unicode.org/reports/tr21/tr21-5.html +* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php +* @package utf8 +*/ +function utf8_strtolower($string){ + + static $UTF8_UPPER_TO_LOWER = NULL; + + if ( is_null($UTF8_UPPER_TO_LOWER) ) { + $UTF8_UPPER_TO_LOWER = array( + 0x0041=>0x0061, 0x03A6=>0x03C6, 0x0162=>0x0163, 0x00C5=>0x00E5, 0x0042=>0x0062, + 0x0139=>0x013A, 0x00C1=>0x00E1, 0x0141=>0x0142, 0x038E=>0x03CD, 0x0100=>0x0101, + 0x0490=>0x0491, 0x0394=>0x03B4, 0x015A=>0x015B, 0x0044=>0x0064, 0x0393=>0x03B3, + 0x00D4=>0x00F4, 0x042A=>0x044A, 0x0419=>0x0439, 0x0112=>0x0113, 0x041C=>0x043C, + 0x015E=>0x015F, 0x0143=>0x0144, 0x00CE=>0x00EE, 0x040E=>0x045E, 0x042F=>0x044F, + 0x039A=>0x03BA, 0x0154=>0x0155, 0x0049=>0x0069, 0x0053=>0x0073, 0x1E1E=>0x1E1F, + 0x0134=>0x0135, 0x0427=>0x0447, 0x03A0=>0x03C0, 0x0418=>0x0438, 0x00D3=>0x00F3, + 0x0420=>0x0440, 0x0404=>0x0454, 0x0415=>0x0435, 0x0429=>0x0449, 0x014A=>0x014B, + 0x0411=>0x0431, 0x0409=>0x0459, 0x1E02=>0x1E03, 0x00D6=>0x00F6, 0x00D9=>0x00F9, + 0x004E=>0x006E, 0x0401=>0x0451, 0x03A4=>0x03C4, 0x0423=>0x0443, 0x015C=>0x015D, + 0x0403=>0x0453, 0x03A8=>0x03C8, 0x0158=>0x0159, 0x0047=>0x0067, 0x00C4=>0x00E4, + 0x0386=>0x03AC, 0x0389=>0x03AE, 0x0166=>0x0167, 0x039E=>0x03BE, 0x0164=>0x0165, + 0x0116=>0x0117, 0x0108=>0x0109, 0x0056=>0x0076, 0x00DE=>0x00FE, 0x0156=>0x0157, + 0x00DA=>0x00FA, 0x1E60=>0x1E61, 0x1E82=>0x1E83, 0x00C2=>0x00E2, 0x0118=>0x0119, + 0x0145=>0x0146, 0x0050=>0x0070, 0x0150=>0x0151, 0x042E=>0x044E, 0x0128=>0x0129, + 0x03A7=>0x03C7, 0x013D=>0x013E, 0x0422=>0x0442, 0x005A=>0x007A, 0x0428=>0x0448, + 0x03A1=>0x03C1, 0x1E80=>0x1E81, 0x016C=>0x016D, 0x00D5=>0x00F5, 0x0055=>0x0075, + 0x0176=>0x0177, 0x00DC=>0x00FC, 0x1E56=>0x1E57, 0x03A3=>0x03C3, 0x041A=>0x043A, + 0x004D=>0x006D, 0x016A=>0x016B, 0x0170=>0x0171, 0x0424=>0x0444, 0x00CC=>0x00EC, + 0x0168=>0x0169, 0x039F=>0x03BF, 0x004B=>0x006B, 0x00D2=>0x00F2, 0x00C0=>0x00E0, + 0x0414=>0x0434, 0x03A9=>0x03C9, 0x1E6A=>0x1E6B, 0x00C3=>0x00E3, 0x042D=>0x044D, + 0x0416=>0x0436, 0x01A0=>0x01A1, 0x010C=>0x010D, 0x011C=>0x011D, 0x00D0=>0x00F0, + 0x013B=>0x013C, 0x040F=>0x045F, 0x040A=>0x045A, 0x00C8=>0x00E8, 0x03A5=>0x03C5, + 0x0046=>0x0066, 0x00DD=>0x00FD, 0x0043=>0x0063, 0x021A=>0x021B, 0x00CA=>0x00EA, + 0x0399=>0x03B9, 0x0179=>0x017A, 0x00CF=>0x00EF, 0x01AF=>0x01B0, 0x0045=>0x0065, + 0x039B=>0x03BB, 0x0398=>0x03B8, 0x039C=>0x03BC, 0x040C=>0x045C, 0x041F=>0x043F, + 0x042C=>0x044C, 0x00DE=>0x00FE, 0x00D0=>0x00F0, 0x1EF2=>0x1EF3, 0x0048=>0x0068, + 0x00CB=>0x00EB, 0x0110=>0x0111, 0x0413=>0x0433, 0x012E=>0x012F, 0x00C6=>0x00E6, + 0x0058=>0x0078, 0x0160=>0x0161, 0x016E=>0x016F, 0x0391=>0x03B1, 0x0407=>0x0457, + 0x0172=>0x0173, 0x0178=>0x00FF, 0x004F=>0x006F, 0x041B=>0x043B, 0x0395=>0x03B5, + 0x0425=>0x0445, 0x0120=>0x0121, 0x017D=>0x017E, 0x017B=>0x017C, 0x0396=>0x03B6, + 0x0392=>0x03B2, 0x0388=>0x03AD, 0x1E84=>0x1E85, 0x0174=>0x0175, 0x0051=>0x0071, + 0x0417=>0x0437, 0x1E0A=>0x1E0B, 0x0147=>0x0148, 0x0104=>0x0105, 0x0408=>0x0458, + 0x014C=>0x014D, 0x00CD=>0x00ED, 0x0059=>0x0079, 0x010A=>0x010B, 0x038F=>0x03CE, + 0x0052=>0x0072, 0x0410=>0x0430, 0x0405=>0x0455, 0x0402=>0x0452, 0x0126=>0x0127, + 0x0136=>0x0137, 0x012A=>0x012B, 0x038A=>0x03AF, 0x042B=>0x044B, 0x004C=>0x006C, + 0x0397=>0x03B7, 0x0124=>0x0125, 0x0218=>0x0219, 0x00DB=>0x00FB, 0x011E=>0x011F, + 0x041E=>0x043E, 0x1E40=>0x1E41, 0x039D=>0x03BD, 0x0106=>0x0107, 0x03AB=>0x03CB, + 0x0426=>0x0446, 0x00DE=>0x00FE, 0x00C7=>0x00E7, 0x03AA=>0x03CA, 0x0421=>0x0441, + 0x0412=>0x0432, 0x010E=>0x010F, 0x00D8=>0x00F8, 0x0057=>0x0077, 0x011A=>0x011B, + 0x0054=>0x0074, 0x004A=>0x006A, 0x040B=>0x045B, 0x0406=>0x0456, 0x0102=>0x0103, + 0x039B=>0x03BB, 0x00D1=>0x00F1, 0x041D=>0x043D, 0x038C=>0x03CC, 0x00C9=>0x00E9, + 0x00D0=>0x00F0, 0x0407=>0x0457, 0x0122=>0x0123, + ); + } + + $uni = utf8_to_unicode($string); + + if ( !$uni ) { + return FALSE; + } + + $cnt = count($uni); + for ($i=0; $i < $cnt; $i++){ + if ( isset($UTF8_UPPER_TO_LOWER[$uni[$i]]) ) { + $uni[$i] = $UTF8_UPPER_TO_LOWER[$uni[$i]]; + } + } + + return utf8_from_unicode($uni); +} + +//--------------------------------------------------------------- +/** +* UTF-8 aware alternative to strtoupper +* Make a string uppercase +* Note: The concept of a characters "case" only exists is some alphabets +* such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does +* not exist in the Chinese alphabet, for example. See Unicode Standard +* Annex #21: Case Mappings +* Note: requires utf8_to_unicode and utf8_from_unicode +* @author Andreas Gohr +* @param string +* @return mixed either string in lowercase or FALSE is UTF-8 invalid +* @see http://www.php.net/strtoupper +* @see utf8_to_unicode +* @see utf8_from_unicode +* @see http://www.unicode.org/reports/tr21/tr21-5.html +* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php +* @package utf8 +*/ +function utf8_strtoupper($string){ + + static $UTF8_LOWER_TO_UPPER = NULL; + + if ( is_null($UTF8_LOWER_TO_UPPER) ) { + $UTF8_LOWER_TO_UPPER = array( + 0x0061=>0x0041, 0x03C6=>0x03A6, 0x0163=>0x0162, 0x00E5=>0x00C5, 0x0062=>0x0042, + 0x013A=>0x0139, 0x00E1=>0x00C1, 0x0142=>0x0141, 0x03CD=>0x038E, 0x0101=>0x0100, + 0x0491=>0x0490, 0x03B4=>0x0394, 0x015B=>0x015A, 0x0064=>0x0044, 0x03B3=>0x0393, + 0x00F4=>0x00D4, 0x044A=>0x042A, 0x0439=>0x0419, 0x0113=>0x0112, 0x043C=>0x041C, + 0x015F=>0x015E, 0x0144=>0x0143, 0x00EE=>0x00CE, 0x045E=>0x040E, 0x044F=>0x042F, + 0x03BA=>0x039A, 0x0155=>0x0154, 0x0069=>0x0049, 0x0073=>0x0053, 0x1E1F=>0x1E1E, + 0x0135=>0x0134, 0x0447=>0x0427, 0x03C0=>0x03A0, 0x0438=>0x0418, 0x00F3=>0x00D3, + 0x0440=>0x0420, 0x0454=>0x0404, 0x0435=>0x0415, 0x0449=>0x0429, 0x014B=>0x014A, + 0x0431=>0x0411, 0x0459=>0x0409, 0x1E03=>0x1E02, 0x00F6=>0x00D6, 0x00F9=>0x00D9, + 0x006E=>0x004E, 0x0451=>0x0401, 0x03C4=>0x03A4, 0x0443=>0x0423, 0x015D=>0x015C, + 0x0453=>0x0403, 0x03C8=>0x03A8, 0x0159=>0x0158, 0x0067=>0x0047, 0x00E4=>0x00C4, + 0x03AC=>0x0386, 0x03AE=>0x0389, 0x0167=>0x0166, 0x03BE=>0x039E, 0x0165=>0x0164, + 0x0117=>0x0116, 0x0109=>0x0108, 0x0076=>0x0056, 0x00FE=>0x00DE, 0x0157=>0x0156, + 0x00FA=>0x00DA, 0x1E61=>0x1E60, 0x1E83=>0x1E82, 0x00E2=>0x00C2, 0x0119=>0x0118, + 0x0146=>0x0145, 0x0070=>0x0050, 0x0151=>0x0150, 0x044E=>0x042E, 0x0129=>0x0128, + 0x03C7=>0x03A7, 0x013E=>0x013D, 0x0442=>0x0422, 0x007A=>0x005A, 0x0448=>0x0428, + 0x03C1=>0x03A1, 0x1E81=>0x1E80, 0x016D=>0x016C, 0x00F5=>0x00D5, 0x0075=>0x0055, + 0x0177=>0x0176, 0x00FC=>0x00DC, 0x1E57=>0x1E56, 0x03C3=>0x03A3, 0x043A=>0x041A, + 0x006D=>0x004D, 0x016B=>0x016A, 0x0171=>0x0170, 0x0444=>0x0424, 0x00EC=>0x00CC, + 0x0169=>0x0168, 0x03BF=>0x039F, 0x006B=>0x004B, 0x00F2=>0x00D2, 0x00E0=>0x00C0, + 0x0434=>0x0414, 0x03C9=>0x03A9, 0x1E6B=>0x1E6A, 0x00E3=>0x00C3, 0x044D=>0x042D, + 0x0436=>0x0416, 0x01A1=>0x01A0, 0x010D=>0x010C, 0x011D=>0x011C, 0x00F0=>0x00D0, + 0x013C=>0x013B, 0x045F=>0x040F, 0x045A=>0x040A, 0x00E8=>0x00C8, 0x03C5=>0x03A5, + 0x0066=>0x0046, 0x00FD=>0x00DD, 0x0063=>0x0043, 0x021B=>0x021A, 0x00EA=>0x00CA, + 0x03B9=>0x0399, 0x017A=>0x0179, 0x00EF=>0x00CF, 0x01B0=>0x01AF, 0x0065=>0x0045, + 0x03BB=>0x039B, 0x03B8=>0x0398, 0x03BC=>0x039C, 0x045C=>0x040C, 0x043F=>0x041F, + 0x044C=>0x042C, 0x00FE=>0x00DE, 0x00F0=>0x00D0, 0x1EF3=>0x1EF2, 0x0068=>0x0048, + 0x00EB=>0x00CB, 0x0111=>0x0110, 0x0433=>0x0413, 0x012F=>0x012E, 0x00E6=>0x00C6, + 0x0078=>0x0058, 0x0161=>0x0160, 0x016F=>0x016E, 0x03B1=>0x0391, 0x0457=>0x0407, + 0x0173=>0x0172, 0x00FF=>0x0178, 0x006F=>0x004F, 0x043B=>0x041B, 0x03B5=>0x0395, + 0x0445=>0x0425, 0x0121=>0x0120, 0x017E=>0x017D, 0x017C=>0x017B, 0x03B6=>0x0396, + 0x03B2=>0x0392, 0x03AD=>0x0388, 0x1E85=>0x1E84, 0x0175=>0x0174, 0x0071=>0x0051, + 0x0437=>0x0417, 0x1E0B=>0x1E0A, 0x0148=>0x0147, 0x0105=>0x0104, 0x0458=>0x0408, + 0x014D=>0x014C, 0x00ED=>0x00CD, 0x0079=>0x0059, 0x010B=>0x010A, 0x03CE=>0x038F, + 0x0072=>0x0052, 0x0430=>0x0410, 0x0455=>0x0405, 0x0452=>0x0402, 0x0127=>0x0126, + 0x0137=>0x0136, 0x012B=>0x012A, 0x03AF=>0x038A, 0x044B=>0x042B, 0x006C=>0x004C, + 0x03B7=>0x0397, 0x0125=>0x0124, 0x0219=>0x0218, 0x00FB=>0x00DB, 0x011F=>0x011E, + 0x043E=>0x041E, 0x1E41=>0x1E40, 0x03BD=>0x039D, 0x0107=>0x0106, 0x03CB=>0x03AB, + 0x0446=>0x0426, 0x00FE=>0x00DE, 0x00E7=>0x00C7, 0x03CA=>0x03AA, 0x0441=>0x0421, + 0x0432=>0x0412, 0x010F=>0x010E, 0x00F8=>0x00D8, 0x0077=>0x0057, 0x011B=>0x011A, + 0x0074=>0x0054, 0x006A=>0x004A, 0x045B=>0x040B, 0x0456=>0x0406, 0x0103=>0x0102, + 0x03BB=>0x039B, 0x00F1=>0x00D1, 0x043D=>0x041D, 0x03CC=>0x038C, 0x00E9=>0x00C9, + 0x00F0=>0x00D0, 0x0457=>0x0407, 0x0123=>0x0122, + ); + } + + $uni = utf8_to_unicode($string); + + if ( !$uni ) { + return FALSE; + } + + $cnt = count($uni); + for ($i=0; $i < $cnt; $i++){ + if( isset($UTF8_LOWER_TO_UPPER[$uni[$i]]) ) { + $uni[$i] = $UTF8_LOWER_TO_UPPER[$uni[$i]]; + } + } + + return utf8_from_unicode($uni); +} diff --git a/libraries/joomla/string/src/phputf8/ord.php b/libraries/joomla/string/src/phputf8/ord.php new file mode 100644 index 0000000000000..449fe313fcf03 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/ord.php @@ -0,0 +1,90 @@ += 0 && $ord0 <= 127 ) { + return $ord0; + } + + if ( !isset($chr{1}) ) { + trigger_error('Short sequence - at least 2 bytes expected, only 1 seen'); + return FALSE; + } + + $ord1 = ord($chr{1}); + if ( $ord0 >= 192 && $ord0 <= 223 ) { + return ( $ord0 - 192 ) * 64 + + ( $ord1 - 128 ); + } + + if ( !isset($chr{2}) ) { + trigger_error('Short sequence - at least 3 bytes expected, only 2 seen'); + return FALSE; + } + $ord2 = ord($chr{2}); + if ( $ord0 >= 224 && $ord0 <= 239 ) { + return ($ord0-224)*4096 + + ($ord1-128)*64 + + ($ord2-128); + } + + if ( !isset($chr{3}) ) { + trigger_error('Short sequence - at least 4 bytes expected, only 3 seen'); + return FALSE; + } + $ord3 = ord($chr{3}); + if ($ord0>=240 && $ord0<=247) { + return ($ord0-240)*262144 + + ($ord1-128)*4096 + + ($ord2-128)*64 + + ($ord3-128); + + } + + if ( !isset($chr{4}) ) { + trigger_error('Short sequence - at least 5 bytes expected, only 4 seen'); + return FALSE; + } + $ord4 = ord($chr{4}); + if ($ord0>=248 && $ord0<=251) { + return ($ord0-248)*16777216 + + ($ord1-128)*262144 + + ($ord2-128)*4096 + + ($ord3-128)*64 + + ($ord4-128); + } + + if ( !isset($chr{5}) ) { + trigger_error('Short sequence - at least 6 bytes expected, only 5 seen'); + return FALSE; + } + if ($ord0>=252 && $ord0<=253) { + return ($ord0-252) * 1073741824 + + ($ord1-128)*16777216 + + ($ord2-128)*262144 + + ($ord3-128)*4096 + + ($ord4-128)*64 + + (ord($chr{5})-128); + } + + if ( $ord0 >= 254 && $ord0 <= 255 ) { + trigger_error('Invalid UTF-8 with surrogate ordinal '.$ord0); + return FALSE; + } + +} + diff --git a/libraries/joomla/string/src/phputf8/str_ireplace.php b/libraries/joomla/string/src/phputf8/str_ireplace.php new file mode 100644 index 0000000000000..c4b4df8d67e90 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/str_ireplace.php @@ -0,0 +1,77 @@ + +* @param string $input +* @param int $length +* @param string $padStr +* @param int $type ( same constants as str_pad ) +* @return string +* @see http://www.php.net/str_pad +* @see utf8_substr +* @package utf8 +*/ +function utf8_str_pad($input, $length, $padStr = ' ', $type = STR_PAD_RIGHT) { + + $inputLen = utf8_strlen($input); + if ($length <= $inputLen) { + return $input; + } + + $padStrLen = utf8_strlen($padStr); + $padLen = $length - $inputLen; + + if ($type == STR_PAD_RIGHT) { + $repeatTimes = ceil($padLen / $padStrLen); + return utf8_substr($input . str_repeat($padStr, $repeatTimes), 0, $length); + } + + if ($type == STR_PAD_LEFT) { + $repeatTimes = ceil($padLen / $padStrLen); + return utf8_substr(str_repeat($padStr, $repeatTimes), 0, floor($padLen)) . $input; + } + + if ($type == STR_PAD_BOTH) { + + $padLen/= 2; + $padAmountLeft = floor($padLen); + $padAmountRight = ceil($padLen); + $repeatTimesLeft = ceil($padAmountLeft / $padStrLen); + $repeatTimesRight = ceil($padAmountRight / $padStrLen); + + $paddingLeft = utf8_substr(str_repeat($padStr, $repeatTimesLeft), 0, $padAmountLeft); + $paddingRight = utf8_substr(str_repeat($padStr, $repeatTimesRight), 0, $padAmountLeft); + return $paddingLeft . $input . $paddingRight; + } + + trigger_error('utf8_str_pad: Unknown padding type (' . $type . ')',E_USER_ERROR); +} diff --git a/libraries/joomla/string/src/phputf8/str_split.php b/libraries/joomla/string/src/phputf8/str_split.php new file mode 100644 index 0000000000000..13b93d517b96e --- /dev/null +++ b/libraries/joomla/string/src/phputf8/str_split.php @@ -0,0 +1,32 @@ + +* @see http://www.php.net/ltrim +* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php +* @return string +* @package utf8 +*/ +function utf8_ltrim( $str, $charlist = FALSE ) { + if($charlist === FALSE) return ltrim($str); + + //quote charlist for use in a characterclass + $charlist = preg_replace('!([\\\\\\-\\]\\[/^])!','\\\${1}',$charlist); + + return preg_replace('/^['.$charlist.']+/u','',$str); +} + +//--------------------------------------------------------------- +/** +* UTF-8 aware replacement for rtrim() +* Note: you only need to use this if you are supplying the charlist +* optional arg and it contains UTF-8 characters. Otherwise rtrim will +* work normally on a UTF-8 string +* @author Andreas Gohr +* @see http://www.php.net/rtrim +* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php +* @return string +* @package utf8 +*/ +function utf8_rtrim( $str, $charlist = FALSE ) { + if($charlist === FALSE) return rtrim($str); + + //quote charlist for use in a characterclass + $charlist = preg_replace('!([\\\\\\-\\]\\[/^])!','\\\${1}',$charlist); + + return preg_replace('/['.$charlist.']+$/u','',$str); +} + +//--------------------------------------------------------------- +/** +* UTF-8 aware replacement for trim() +* Note: you only need to use this if you are supplying the charlist +* optional arg and it contains UTF-8 characters. Otherwise trim will +* work normally on a UTF-8 string +* @author Andreas Gohr +* @see http://www.php.net/trim +* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php +* @return string +* @package utf8 +*/ +function utf8_trim( $str, $charlist = FALSE ) { + if($charlist === FALSE) return trim($str); + return utf8_ltrim(utf8_rtrim($str, $charlist), $charlist); +} diff --git a/libraries/joomla/string/src/phputf8/ucfirst.php b/libraries/joomla/string/src/phputf8/ucfirst.php new file mode 100644 index 0000000000000..7f7ae9ecab9e5 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/ucfirst.php @@ -0,0 +1,31 @@ + +* if ( utf8_is_ascii($someString) ) { +* // It's just ASCII - use the native PHP version +* $someString = strtolower($someString); +* } else { +* $someString = utf8_strtolower($someString); +* } +* +* +* @param string +* @return boolean TRUE if it's all ASCII +* @package utf8 +* @see utf8_is_ascii_ctrl +*/ +function utf8_is_ascii($str) { + // Search for any bytes which are outside the ASCII range... + return (preg_match('/(?:[^\x00-\x7F])/',$str) !== 1); +} + +//-------------------------------------------------------------------- +/** +* Tests whether a string contains only 7bit ASCII bytes with device +* control codes omitted. The device control codes can be found on the +* second table here: http://www.w3schools.com/tags/ref_ascii.asp +* +* @param string +* @return boolean TRUE if it's all ASCII without device control codes +* @package utf8 +* @see utf8_is_ascii +*/ +function utf8_is_ascii_ctrl($str) { + if ( strlen($str) > 0 ) { + // Search for any bytes which are outside the ASCII range, + // or are device control codes + return (preg_match('/[^\x09\x0A\x0D\x20-\x7E]/',$str) !== 1); + } + return FALSE; +} + +//-------------------------------------------------------------------- +/** +* Strip out all non-7bit ASCII bytes +* If you need to transmit a string to system which you know can only +* support 7bit ASCII, you could use this function. +* @param string +* @return string with non ASCII bytes removed +* @package utf8 +* @see utf8_strip_non_ascii_ctrl +*/ +function utf8_strip_non_ascii($str) { + ob_start(); + while ( preg_match( + '/^([\x00-\x7F]+)|([^\x00-\x7F]+)/S', + $str, $matches) ) { + if ( !isset($matches[2]) ) { + echo $matches[0]; + } + $str = substr($str, strlen($matches[0])); + } + $result = ob_get_contents(); + ob_end_clean(); + return $result; +} + +//-------------------------------------------------------------------- +/** +* Strip out device control codes in the ASCII range +* which are not permitted in XML. Note that this leaves +* multi-byte characters untouched - it only removes device +* control codes +* @see http://hsivonen.iki.fi/producing-xml/#controlchar +* @param string +* @return string control codes removed +*/ +function utf8_strip_ascii_ctrl($str) { + ob_start(); + while ( preg_match( + '/^([^\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+)|([\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+)/S', + $str, $matches) ) { + if ( !isset($matches[2]) ) { + echo $matches[0]; + } + $str = substr($str, strlen($matches[0])); + } + $result = ob_get_contents(); + ob_end_clean(); + return $result; +} + +//-------------------------------------------------------------------- +/** +* Strip out all non 7bit ASCII bytes and ASCII device control codes. +* For a list of ASCII device control codes see the 2nd table here: +* http://www.w3schools.com/tags/ref_ascii.asp +* +* @param string +* @return boolean TRUE if it's all ASCII +* @package utf8 +*/ +function utf8_strip_non_ascii_ctrl($str) { + ob_start(); + while ( preg_match( + '/^([\x09\x0A\x0D\x20-\x7E]+)|([^\x09\x0A\x0D\x20-\x7E]+)/S', + $str, $matches) ) { + if ( !isset($matches[2]) ) { + echo $matches[0]; + } + $str = substr($str, strlen($matches[0])); + } + $result = ob_get_contents(); + ob_end_clean(); + return $result; +} + +//--------------------------------------------------------------- +/** +* Replace accented UTF-8 characters by unaccented ASCII-7 "equivalents". +* The purpose of this function is to replace characters commonly found in Latin +* alphabets with something more or less equivalent from the ASCII range. This can +* be useful for converting a UTF-8 to something ready for a filename, for example. +* Following the use of this function, you would probably also pass the string +* through utf8_strip_non_ascii to clean out any other non-ASCII chars +* Use the optional parameter to just deaccent lower ($case = -1) or upper ($case = 1) +* letters. Default is to deaccent both cases ($case = 0) +* +* For a more complete implementation of transliteration, see the utf8_to_ascii package +* available from the phputf8 project downloads: +* http://prdownloads.sourceforge.net/phputf8 +* +* @param string UTF-8 string +* @param int (optional) -1 lowercase only, +1 uppercase only, 1 both cases +* @param string UTF-8 with accented characters replaced by ASCII chars +* @return string accented chars replaced with ascii equivalents +* @author Andreas Gohr +* @package utf8 +*/ +function utf8_accents_to_ascii( $str, $case=0 ){ + + static $UTF8_LOWER_ACCENTS = NULL; + static $UTF8_UPPER_ACCENTS = NULL; + + if($case <= 0){ + + if ( is_null($UTF8_LOWER_ACCENTS) ) { + $UTF8_LOWER_ACCENTS = array( + 'à' => 'a', 'ô' => 'o', 'ď' => 'd', 'ḟ' => 'f', 'ë' => 'e', 'š' => 's', 'ơ' => 'o', + 'ß' => 'ss', 'ă' => 'a', 'ř' => 'r', 'ț' => 't', 'ň' => 'n', 'ā' => 'a', 'ķ' => 'k', + 'ŝ' => 's', 'ỳ' => 'y', 'ņ' => 'n', 'ĺ' => 'l', 'ħ' => 'h', 'ṗ' => 'p', 'ó' => 'o', + 'ú' => 'u', 'ě' => 'e', 'é' => 'e', 'ç' => 'c', 'ẁ' => 'w', 'ċ' => 'c', 'õ' => 'o', + 'ṡ' => 's', 'ø' => 'o', 'ģ' => 'g', 'ŧ' => 't', 'ș' => 's', 'ė' => 'e', 'ĉ' => 'c', + 'ś' => 's', 'î' => 'i', 'ű' => 'u', 'ć' => 'c', 'ę' => 'e', 'ŵ' => 'w', 'ṫ' => 't', + 'ū' => 'u', 'č' => 'c', 'ö' => 'oe', 'è' => 'e', 'ŷ' => 'y', 'ą' => 'a', 'ł' => 'l', + 'ų' => 'u', 'ů' => 'u', 'ş' => 's', 'ğ' => 'g', 'ļ' => 'l', 'ƒ' => 'f', 'ž' => 'z', + 'ẃ' => 'w', 'ḃ' => 'b', 'å' => 'a', 'ì' => 'i', 'ï' => 'i', 'ḋ' => 'd', 'ť' => 't', + 'ŗ' => 'r', 'ä' => 'ae', 'í' => 'i', 'ŕ' => 'r', 'ê' => 'e', 'ü' => 'ue', 'ò' => 'o', + 'ē' => 'e', 'ñ' => 'n', 'ń' => 'n', 'ĥ' => 'h', 'ĝ' => 'g', 'đ' => 'd', 'ĵ' => 'j', + 'ÿ' => 'y', 'ũ' => 'u', 'ŭ' => 'u', 'ư' => 'u', 'ţ' => 't', 'ý' => 'y', 'ő' => 'o', + 'â' => 'a', 'ľ' => 'l', 'ẅ' => 'w', 'ż' => 'z', 'ī' => 'i', 'ã' => 'a', 'ġ' => 'g', + 'ṁ' => 'm', 'ō' => 'o', 'ĩ' => 'i', 'ù' => 'u', 'į' => 'i', 'ź' => 'z', 'á' => 'a', + 'û' => 'u', 'þ' => 'th', 'ð' => 'dh', 'æ' => 'ae', 'µ' => 'u', 'ĕ' => 'e', + ); + } + + $str = str_replace( + array_keys($UTF8_LOWER_ACCENTS), + array_values($UTF8_LOWER_ACCENTS), + $str + ); + } + + if($case >= 0){ + if ( is_null($UTF8_UPPER_ACCENTS) ) { + $UTF8_UPPER_ACCENTS = array( + 'À' => 'A', 'Ô' => 'O', 'Ď' => 'D', 'Ḟ' => 'F', 'Ë' => 'E', 'Š' => 'S', 'Ơ' => 'O', + 'Ă' => 'A', 'Ř' => 'R', 'Ț' => 'T', 'Ň' => 'N', 'Ā' => 'A', 'Ķ' => 'K', + 'Ŝ' => 'S', 'Ỳ' => 'Y', 'Ņ' => 'N', 'Ĺ' => 'L', 'Ħ' => 'H', 'Ṗ' => 'P', 'Ó' => 'O', + 'Ú' => 'U', 'Ě' => 'E', 'É' => 'E', 'Ç' => 'C', 'Ẁ' => 'W', 'Ċ' => 'C', 'Õ' => 'O', + 'Ṡ' => 'S', 'Ø' => 'O', 'Ģ' => 'G', 'Ŧ' => 'T', 'Ș' => 'S', 'Ė' => 'E', 'Ĉ' => 'C', + 'Ś' => 'S', 'Î' => 'I', 'Ű' => 'U', 'Ć' => 'C', 'Ę' => 'E', 'Ŵ' => 'W', 'Ṫ' => 'T', + 'Ū' => 'U', 'Č' => 'C', 'Ö' => 'Oe', 'È' => 'E', 'Ŷ' => 'Y', 'Ą' => 'A', 'Ł' => 'L', + 'Ų' => 'U', 'Ů' => 'U', 'Ş' => 'S', 'Ğ' => 'G', 'Ļ' => 'L', 'Ƒ' => 'F', 'Ž' => 'Z', + 'Ẃ' => 'W', 'Ḃ' => 'B', 'Å' => 'A', 'Ì' => 'I', 'Ï' => 'I', 'Ḋ' => 'D', 'Ť' => 'T', + 'Ŗ' => 'R', 'Ä' => 'Ae', 'Í' => 'I', 'Ŕ' => 'R', 'Ê' => 'E', 'Ü' => 'Ue', 'Ò' => 'O', + 'Ē' => 'E', 'Ñ' => 'N', 'Ń' => 'N', 'Ĥ' => 'H', 'Ĝ' => 'G', 'Đ' => 'D', 'Ĵ' => 'J', + 'Ÿ' => 'Y', 'Ũ' => 'U', 'Ŭ' => 'U', 'Ư' => 'U', 'Ţ' => 'T', 'Ý' => 'Y', 'Ő' => 'O', + 'Â' => 'A', 'Ľ' => 'L', 'Ẅ' => 'W', 'Ż' => 'Z', 'Ī' => 'I', 'Ã' => 'A', 'Ġ' => 'G', + 'Ṁ' => 'M', 'Ō' => 'O', 'Ĩ' => 'I', 'Ù' => 'U', 'Į' => 'I', 'Ź' => 'Z', 'Á' => 'A', + 'Û' => 'U', 'Þ' => 'Th', 'Ð' => 'Dh', 'Æ' => 'Ae', 'Ĕ' => 'E', + ); + } + $str = str_replace( + array_keys($UTF8_UPPER_ACCENTS), + array_values($UTF8_UPPER_ACCENTS), + $str + ); + } + + return $str; + +} diff --git a/libraries/joomla/string/src/phputf8/utils/bad.php b/libraries/joomla/string/src/phputf8/utils/bad.php new file mode 100644 index 0000000000000..e8b8f117758e0 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/utils/bad.php @@ -0,0 +1,406 @@ + 0 ) { + return $badList; + } + return FALSE; +} + +//-------------------------------------------------------------------- +/** +* Strips out any bad bytes from a UTF-8 string and returns the rest +* PCRE Pattern to locate bad bytes in a UTF-8 string +* Comes from W3 FAQ: Multilingual Forms +* Note: modified to include full ASCII range including control chars +* @see http://www.w3.org/International/questions/qa-forms-utf-8 +* @param string +* @return string +* @package utf8 +*/ +function utf8_bad_strip($str) { + $UTF8_BAD = + '([\x00-\x7F]'. # ASCII (including control chars) + '|[\xC2-\xDF][\x80-\xBF]'. # non-overlong 2-byte + '|\xE0[\xA0-\xBF][\x80-\xBF]'. # excluding overlongs + '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'. # straight 3-byte + '|\xED[\x80-\x9F][\x80-\xBF]'. # excluding surrogates + '|\xF0[\x90-\xBF][\x80-\xBF]{2}'. # planes 1-3 + '|[\xF1-\xF3][\x80-\xBF]{3}'. # planes 4-15 + '|\xF4[\x80-\x8F][\x80-\xBF]{2}'. # plane 16 + '|(.{1}))'; # invalid byte + ob_start(); + while (preg_match('/'.$UTF8_BAD.'/S', $str, $matches)) { + if ( !isset($matches[2])) { + echo $matches[0]; + } + $str = substr($str,strlen($matches[0])); + } + $result = ob_get_contents(); + ob_end_clean(); + return $result; +} + +//-------------------------------------------------------------------- +/** +* Replace bad bytes with an alternative character - ASCII character +* recommended is replacement char +* PCRE Pattern to locate bad bytes in a UTF-8 string +* Comes from W3 FAQ: Multilingual Forms +* Note: modified to include full ASCII range including control chars +* @see http://www.w3.org/International/questions/qa-forms-utf-8 +* @param string to search +* @param string to replace bad bytes with (defaults to '?') - use ASCII +* @return string +* @package utf8 +*/ +function utf8_bad_replace($str, $replace = '?') { + $UTF8_BAD = + '([\x00-\x7F]'. # ASCII (including control chars) + '|[\xC2-\xDF][\x80-\xBF]'. # non-overlong 2-byte + '|\xE0[\xA0-\xBF][\x80-\xBF]'. # excluding overlongs + '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'. # straight 3-byte + '|\xED[\x80-\x9F][\x80-\xBF]'. # excluding surrogates + '|\xF0[\x90-\xBF][\x80-\xBF]{2}'. # planes 1-3 + '|[\xF1-\xF3][\x80-\xBF]{3}'. # planes 4-15 + '|\xF4[\x80-\x8F][\x80-\xBF]{2}'. # plane 16 + '|(.{1}))'; # invalid byte + ob_start(); + while (preg_match('/'.$UTF8_BAD.'/S', $str, $matches)) { + if ( !isset($matches[2])) { + echo $matches[0]; + } else { + echo $replace; + } + $str = substr($str,strlen($matches[0])); + } + $result = ob_get_contents(); + ob_end_clean(); + return $result; +} + +//-------------------------------------------------------------------- +/** +* Return code from utf8_bad_identify() when a five octet sequence is detected. +* Note: 5 octets sequences are valid UTF-8 but are not supported by Unicode so +* do not represent a useful character +* @see utf8_bad_identify +* @package utf8 +*/ +define('UTF8_BAD_5OCTET',1); + +/** +* Return code from utf8_bad_identify() when a six octet sequence is detected. +* Note: 6 octets sequences are valid UTF-8 but are not supported by Unicode so +* do not represent a useful character +* @see utf8_bad_identify +* @package utf8 +*/ +define('UTF8_BAD_6OCTET',2); + +/** +* Return code from utf8_bad_identify(). +* Invalid octet for use as start of multi-byte UTF-8 sequence +* @see utf8_bad_identify +* @package utf8 +*/ +define('UTF8_BAD_SEQID',3); + +/** +* Return code from utf8_bad_identify(). +* From Unicode 3.1, non-shortest form is illegal +* @see utf8_bad_identify +* @package utf8 +*/ +define('UTF8_BAD_NONSHORT',4); + +/** +* Return code from utf8_bad_identify(). +* From Unicode 3.2, surrogate characters are illegal +* @see utf8_bad_identify +* @package utf8 +*/ +define('UTF8_BAD_SURROGATE',5); + +/** +* Return code from utf8_bad_identify(). +* Codepoints outside the Unicode range are illegal +* @see utf8_bad_identify +* @package utf8 +*/ +define('UTF8_BAD_UNIOUTRANGE',6); + +/** +* Return code from utf8_bad_identify(). +* Incomplete multi-octet sequence +* Note: this is kind of a "catch-all" +* @see utf8_bad_identify +* @package utf8 +*/ +define('UTF8_BAD_SEQINCOMPLETE',7); + +//-------------------------------------------------------------------- +/** +* Reports on the type of bad byte found in a UTF-8 string. Returns a +* status code on the first bad byte found +* @author +* @param string UTF-8 encoded string +* @return mixed integer constant describing problem or FALSE if valid UTF-8 +* @see utf8_bad_explain +* @see http://hsivonen.iki.fi/php-utf8/ +* @package utf8 +*/ +function utf8_bad_identify($str, &$i) { + + $mState = 0; // cached expected number of octets after the current octet + // until the beginning of the next UTF8 character sequence + $mUcs4 = 0; // cached Unicode character + $mBytes = 1; // cached expected number of octets in the current sequence + + $len = strlen($str); + + for($i = 0; $i < $len; $i++) { + + $in = ord($str{$i}); + + if ( $mState == 0) { + + // When mState is zero we expect either a US-ASCII character or a + // multi-octet sequence. + if (0 == (0x80 & ($in))) { + // US-ASCII, pass straight through. + $mBytes = 1; + + } else if (0xC0 == (0xE0 & ($in))) { + // First octet of 2 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x1F) << 6; + $mState = 1; + $mBytes = 2; + + } else if (0xE0 == (0xF0 & ($in))) { + // First octet of 3 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x0F) << 12; + $mState = 2; + $mBytes = 3; + + } else if (0xF0 == (0xF8 & ($in))) { + // First octet of 4 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x07) << 18; + $mState = 3; + $mBytes = 4; + + } else if (0xF8 == (0xFC & ($in))) { + + /* First octet of 5 octet sequence. + * + * This is illegal because the encoded codepoint must be either + * (a) not the shortest form or + * (b) outside the Unicode range of 0-0x10FFFF. + */ + + return UTF8_BAD_5OCTET; + + } else if (0xFC == (0xFE & ($in))) { + + // First octet of 6 octet sequence, see comments for 5 octet sequence. + return UTF8_BAD_6OCTET; + + } else { + // Current octet is neither in the US-ASCII range nor a legal first + // octet of a multi-octet sequence. + return UTF8_BAD_SEQID; + + } + + } else { + + // When mState is non-zero, we expect a continuation of the multi-octet + // sequence + if (0x80 == (0xC0 & ($in))) { + + // Legal continuation. + $shift = ($mState - 1) * 6; + $tmp = $in; + $tmp = ($tmp & 0x0000003F) << $shift; + $mUcs4 |= $tmp; + + /** + * End of the multi-octet sequence. mUcs4 now contains the final + * Unicode codepoint to be output + */ + if (0 == --$mState) { + + // From Unicode 3.1, non-shortest form is illegal + if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || + ((3 == $mBytes) && ($mUcs4 < 0x0800)) || + ((4 == $mBytes) && ($mUcs4 < 0x10000)) ) { + return UTF8_BAD_NONSHORT; + + // From Unicode 3.2, surrogate characters are illegal + } else if (($mUcs4 & 0xFFFFF800) == 0xD800) { + return UTF8_BAD_SURROGATE; + + // Codepoints outside the Unicode range are illegal + } else if ($mUcs4 > 0x10FFFF) { + return UTF8_BAD_UNIOUTRANGE; + } + + //initialize UTF8 cache + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + } + + } else { + // ((0xC0 & (*in) != 0x80) && (mState != 0)) + // Incomplete multi-octet sequence. + $i--; + return UTF8_BAD_SEQINCOMPLETE; + } + } + } + + if ( $mState != 0 ) { + // Incomplete multi-octet sequence. + $i--; + return UTF8_BAD_SEQINCOMPLETE; + } + + // No bad octets found + $i = NULL; + return FALSE; +} + +//-------------------------------------------------------------------- +/** +* Takes a return code from utf8_bad_identify() are returns a message +* (in English) explaining what the problem is. +* @param int return code from utf8_bad_identify +* @return mixed string message or FALSE if return code unknown +* @see utf8_bad_identify +* @package utf8 +*/ +function utf8_bad_explain($code) { + + switch ($code) { + + case UTF8_BAD_5OCTET: + return 'Five octet sequences are valid UTF-8 but are not supported by Unicode'; + break; + + case UTF8_BAD_6OCTET: + return 'Six octet sequences are valid UTF-8 but are not supported by Unicode'; + break; + + case UTF8_BAD_SEQID: + return 'Invalid octet for use as start of multi-byte UTF-8 sequence'; + break; + + case UTF8_BAD_NONSHORT: + return 'From Unicode 3.1, non-shortest form is illegal'; + break; + + case UTF8_BAD_SURROGATE: + return 'From Unicode 3.2, surrogate characters are illegal'; + break; + + case UTF8_BAD_UNIOUTRANGE: + return 'Codepoints outside the Unicode range are illegal'; + break; + + case UTF8_BAD_SEQINCOMPLETE: + return 'Incomplete multi-octet sequence'; + break; + + } + + trigger_error('Unknown error code: '.$code,E_USER_WARNING); + return FALSE; + +} diff --git a/libraries/joomla/string/src/phputf8/utils/patterns.php b/libraries/joomla/string/src/phputf8/utils/patterns.php new file mode 100644 index 0000000000000..0ed8346337795 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/utils/patterns.php @@ -0,0 +1,64 @@ + +* @param string string to locate index in +* @param int (n times) +* @return mixed - int if only one input int, array if more +* @return boolean TRUE if it's all ASCII +* @package utf8 +*/ +function utf8_byte_position() { + + $args = func_get_args(); + $str =& array_shift($args); + if (!is_string($str)) return false; + + $result = array(); + + // trivial byte index, character offset pair + $prev = array(0,0); + + // use a short piece of str to estimate bytes per character + // $i (& $j) -> byte indexes into $str + $i = utf8_locate_next_chr($str, 300); + + // $c -> character offset into $str + $c = strlen(utf8_decode(substr($str,0,$i))); + + // deal with arguments from lowest to highest + sort($args); + + foreach ($args as $offset) { + // sanity checks FIXME + + // 0 is an easy check + if ($offset == 0) { $result[] = 0; continue; } + + // ensure no endless looping + $safety_valve = 50; + + do { + + if ( ($c - $prev[1]) == 0 ) { + // Hack: gone past end of string + $error = 0; + $i = strlen($str); + break; + } + + $j = $i + (int)(($offset-$c) * ($i - $prev[0]) / ($c - $prev[1])); + + // correct to utf8 character boundary + $j = utf8_locate_next_chr($str, $j); + + // save the index, offset for use next iteration + $prev = array($i,$c); + + if ($j > $i) { + // determine new character offset + $c += strlen(utf8_decode(substr($str,$i,$j-$i))); + } else { + // ditto + $c -= strlen(utf8_decode(substr($str,$j,$i-$j))); + } + + $error = abs($c-$offset); + + // ready for next time around + $i = $j; + + // from 7 it is faster to iterate over the string + } while ( ($error > 7) && --$safety_valve) ; + + if ($error && $error <= 7) { + + if ($c < $offset) { + // move up + while ($error--) { $i = utf8_locate_next_chr($str,++$i); } + } else { + // move down + while ($error--) { $i = utf8_locate_current_chr($str,--$i); } + } + + // ready for next arg + $c = $offset; + } + $result[] = $i; + } + + if ( count($result) == 1 ) { + return $result[0]; + } + + return $result; +} + +//-------------------------------------------------------------------- +/** +* Given a string and any byte index, returns the byte index +* of the start of the current UTF-8 character, relative to supplied +* position. If the current character begins at the same place as the +* supplied byte index, that byte index will be returned. Otherwise +* this function will step backwards, looking for the index where +* curent UTF-8 character begins +* @author Chris Smith +* @param string +* @param int byte index in the string +* @return int byte index of start of next UTF-8 character +* @package utf8 +*/ +function utf8_locate_current_chr( &$str, $idx ) { + + if ($idx <= 0) return 0; + + $limit = strlen($str); + if ($idx >= $limit) return $limit; + + // Binary value for any byte after the first in a multi-byte UTF-8 character + // will be like 10xxxxxx so & 0xC0 can be used to detect this kind + // of byte - assuming well formed UTF-8 + while ($idx && ((ord($str[$idx]) & 0xC0) == 0x80)) $idx--; + + return $idx; +} + +//-------------------------------------------------------------------- +/** +* Given a string and any byte index, returns the byte index +* of the start of the next UTF-8 character, relative to supplied +* position. If the next character begins at the same place as the +* supplied byte index, that byte index will be returned. +* @author Chris Smith +* @param string +* @param int byte index in the string +* @return int byte index of start of next UTF-8 character +* @package utf8 +*/ +function utf8_locate_next_chr( &$str, $idx ) { + + if ($idx <= 0) return 0; + + $limit = strlen($str); + if ($idx >= $limit) return $limit; + + // Binary value for any byte after the first in a multi-byte UTF-8 character + // will be like 10xxxxxx so & 0xC0 can be used to detect this kind + // of byte - assuming well formed UTF-8 + while (($idx < $limit) && ((ord($str[$idx]) & 0xC0) == 0x80)) $idx++; + + return $idx; +} + diff --git a/libraries/joomla/string/src/phputf8/utils/specials.php b/libraries/joomla/string/src/phputf8/utils/specials.php new file mode 100644 index 0000000000000..a53e2745e2b87 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/utils/specials.php @@ -0,0 +1,126 @@ + +* @param string $string The UTF8 string to strip of special chars +* @param string (optional) $repl Replace special with this string +* @return string with common non-alphanumeric characters removed +* @see utf8_specials_pattern +*/ +function utf8_strip_specials($string, $repl=''){ + return preg_replace(utf8_specials_pattern(), $repl, $string); +} + + diff --git a/libraries/joomla/string/src/phputf8/utils/unicode.php b/libraries/joomla/string/src/phputf8/utils/unicode.php new file mode 100644 index 0000000000000..2d561f3c2c451 --- /dev/null +++ b/libraries/joomla/string/src/phputf8/utils/unicode.php @@ -0,0 +1,265 @@ + 0xFFFF. Occurrances of the BOM are ignored. Surrogates +* are not allowed. +* Returns false if the input string isn't a valid UTF-8 octet sequence +* and raises a PHP error at level E_USER_WARNING +* Note: this function has been modified slightly in this library to +* trigger errors on encountering bad bytes +* @author +* @param string UTF-8 encoded string +* @return mixed array of unicode code points or FALSE if UTF-8 invalid +* @see utf8_from_unicode +* @see http://hsivonen.iki.fi/php-utf8/ +* @package utf8 +*/ +function utf8_to_unicode($str) { + $mState = 0; // cached expected number of octets after the current octet + // until the beginning of the next UTF8 character sequence + $mUcs4 = 0; // cached Unicode character + $mBytes = 1; // cached expected number of octets in the current sequence + + $out = array(); + + $len = strlen($str); + + for($i = 0; $i < $len; $i++) { + + $in = ord($str{$i}); + + if ( $mState == 0) { + + // When mState is zero we expect either a US-ASCII character or a + // multi-octet sequence. + if (0 == (0x80 & ($in))) { + // US-ASCII, pass straight through. + $out[] = $in; + $mBytes = 1; + + } else if (0xC0 == (0xE0 & ($in))) { + // First octet of 2 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x1F) << 6; + $mState = 1; + $mBytes = 2; + + } else if (0xE0 == (0xF0 & ($in))) { + // First octet of 3 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x0F) << 12; + $mState = 2; + $mBytes = 3; + + } else if (0xF0 == (0xF8 & ($in))) { + // First octet of 4 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x07) << 18; + $mState = 3; + $mBytes = 4; + + } else if (0xF8 == (0xFC & ($in))) { + /* First octet of 5 octet sequence. + * + * This is illegal because the encoded codepoint must be either + * (a) not the shortest form or + * (b) outside the Unicode range of 0-0x10FFFF. + * Rather than trying to resynchronize, we will carry on until the end + * of the sequence and let the later error handling code catch it. + */ + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x03) << 24; + $mState = 4; + $mBytes = 5; + + } else if (0xFC == (0xFE & ($in))) { + // First octet of 6 octet sequence, see comments for 5 octet sequence. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 1) << 30; + $mState = 5; + $mBytes = 6; + + } else { + /* Current octet is neither in the US-ASCII range nor a legal first + * octet of a multi-octet sequence. + */ + trigger_error( + 'utf8_to_unicode: Illegal sequence identifier '. + 'in UTF-8 at byte '.$i, + E_USER_WARNING + ); + return FALSE; + + } + + } else { + + // When mState is non-zero, we expect a continuation of the multi-octet + // sequence + if (0x80 == (0xC0 & ($in))) { + + // Legal continuation. + $shift = ($mState - 1) * 6; + $tmp = $in; + $tmp = ($tmp & 0x0000003F) << $shift; + $mUcs4 |= $tmp; + + /** + * End of the multi-octet sequence. mUcs4 now contains the final + * Unicode codepoint to be output + */ + if (0 == --$mState) { + + /* + * Check for illegal sequences and codepoints. + */ + // From Unicode 3.1, non-shortest form is illegal + if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || + ((3 == $mBytes) && ($mUcs4 < 0x0800)) || + ((4 == $mBytes) && ($mUcs4 < 0x10000)) || + (4 < $mBytes) || + // From Unicode 3.2, surrogate characters are illegal + (($mUcs4 & 0xFFFFF800) == 0xD800) || + // Codepoints outside the Unicode range are illegal + ($mUcs4 > 0x10FFFF)) { + + trigger_error( + 'utf8_to_unicode: Illegal sequence or codepoint '. + 'in UTF-8 at byte '.$i, + E_USER_WARNING + ); + + return FALSE; + + } + + if (0xFEFF != $mUcs4) { + // BOM is legal but we don't want to output it + $out[] = $mUcs4; + } + + //initialize UTF8 cache + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + } + + } else { + /** + *((0xC0 & (*in) != 0x80) && (mState != 0)) + * Incomplete multi-octet sequence. + */ + trigger_error( + 'utf8_to_unicode: Incomplete multi-octet '. + ' sequence in UTF-8 at byte '.$i, + E_USER_WARNING + ); + + return FALSE; + } + } + } + return $out; +} + +//-------------------------------------------------------------------- +/** +* Takes an array of ints representing the Unicode characters and returns +* a UTF-8 string. Astral planes are supported ie. the ints in the +* input can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates +* are not allowed. +* Returns false if the input array contains ints that represent +* surrogates or are outside the Unicode range +* and raises a PHP error at level E_USER_WARNING +* Note: this function has been modified slightly in this library to use +* output buffering to concatenate the UTF-8 string (faster) as well as +* reference the array by it's keys +* @param array of unicode code points representing a string +* @return mixed UTF-8 string or FALSE if array contains invalid code points +* @author +* @see utf8_to_unicode +* @see http://hsivonen.iki.fi/php-utf8/ +* @package utf8 +*/ +function utf8_from_unicode($arr) { + ob_start(); + + foreach (array_keys($arr) as $k) { + + # ASCII range (including control chars) + if ( ($arr[$k] >= 0) && ($arr[$k] <= 0x007f) ) { + + echo chr($arr[$k]); + + # 2 byte sequence + } else if ($arr[$k] <= 0x07ff) { + + echo chr(0xc0 | ($arr[$k] >> 6)); + echo chr(0x80 | ($arr[$k] & 0x003f)); + + # Byte order mark (skip) + } else if($arr[$k] == 0xFEFF) { + + // nop -- zap the BOM + + # Test for illegal surrogates + } else if ($arr[$k] >= 0xD800 && $arr[$k] <= 0xDFFF) { + + // found a surrogate + trigger_error( + 'utf8_from_unicode: Illegal surrogate '. + 'at index: '.$k.', value: '.$arr[$k], + E_USER_WARNING + ); + + return FALSE; + + # 3 byte sequence + } else if ($arr[$k] <= 0xffff) { + + echo chr(0xe0 | ($arr[$k] >> 12)); + echo chr(0x80 | (($arr[$k] >> 6) & 0x003f)); + echo chr(0x80 | ($arr[$k] & 0x003f)); + + # 4 byte sequence + } else if ($arr[$k] <= 0x10ffff) { + + echo chr(0xf0 | ($arr[$k] >> 18)); + echo chr(0x80 | (($arr[$k] >> 12) & 0x3f)); + echo chr(0x80 | (($arr[$k] >> 6) & 0x3f)); + echo chr(0x80 | ($arr[$k] & 0x3f)); + + } else { + + trigger_error( + 'utf8_from_unicode: Codepoint out of Unicode range '. + 'at index: '.$k.', value: '.$arr[$k], + E_USER_WARNING + ); + + // out of range + return FALSE; + } + } + + $result = ob_get_contents(); + ob_end_clean(); + return $result; +} diff --git a/libraries/joomla/string/src/phputf8/utils/validation.php b/libraries/joomla/string/src/phputf8/utils/validation.php new file mode 100644 index 0000000000000..13e180610b22d --- /dev/null +++ b/libraries/joomla/string/src/phputf8/utils/validation.php @@ -0,0 +1,181 @@ + +* @param string UTF-8 encoded string +* @return boolean true if valid +* @see http://hsivonen.iki.fi/php-utf8/ +* @see utf8_compliant +* @package utf8 +*/ +function utf8_is_valid($str) { + + $mState = 0; // cached expected number of octets after the current octet + // until the beginning of the next UTF8 character sequence + $mUcs4 = 0; // cached Unicode character + $mBytes = 1; // cached expected number of octets in the current sequence + + $len = strlen($str); + + for($i = 0; $i < $len; $i++) { + + $in = ord($str{$i}); + + if ( $mState == 0) { + + // When mState is zero we expect either a US-ASCII character or a + // multi-octet sequence. + if (0 == (0x80 & ($in))) { + // US-ASCII, pass straight through. + $mBytes = 1; + + } else if (0xC0 == (0xE0 & ($in))) { + // First octet of 2 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x1F) << 6; + $mState = 1; + $mBytes = 2; + + } else if (0xE0 == (0xF0 & ($in))) { + // First octet of 3 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x0F) << 12; + $mState = 2; + $mBytes = 3; + + } else if (0xF0 == (0xF8 & ($in))) { + // First octet of 4 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x07) << 18; + $mState = 3; + $mBytes = 4; + + } else if (0xF8 == (0xFC & ($in))) { + /* First octet of 5 octet sequence. + * + * This is illegal because the encoded codepoint must be either + * (a) not the shortest form or + * (b) outside the Unicode range of 0-0x10FFFF. + * Rather than trying to resynchronize, we will carry on until the end + * of the sequence and let the later error handling code catch it. + */ + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x03) << 24; + $mState = 4; + $mBytes = 5; + + } else if (0xFC == (0xFE & ($in))) { + // First octet of 6 octet sequence, see comments for 5 octet sequence. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 1) << 30; + $mState = 5; + $mBytes = 6; + + } else { + /* Current octet is neither in the US-ASCII range nor a legal first + * octet of a multi-octet sequence. + */ + return FALSE; + + } + + } else { + + // When mState is non-zero, we expect a continuation of the multi-octet + // sequence + if (0x80 == (0xC0 & ($in))) { + + // Legal continuation. + $shift = ($mState - 1) * 6; + $tmp = $in; + $tmp = ($tmp & 0x0000003F) << $shift; + $mUcs4 |= $tmp; + + /** + * End of the multi-octet sequence. mUcs4 now contains the final + * Unicode codepoint to be output + */ + if (0 == --$mState) { + + /* + * Check for illegal sequences and codepoints. + */ + // From Unicode 3.1, non-shortest form is illegal + if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || + ((3 == $mBytes) && ($mUcs4 < 0x0800)) || + ((4 == $mBytes) && ($mUcs4 < 0x10000)) || + (4 < $mBytes) || + // From Unicode 3.2, surrogate characters are illegal + (($mUcs4 & 0xFFFFF800) == 0xD800) || + // Codepoints outside the Unicode range are illegal + ($mUcs4 > 0x10FFFF)) { + + return FALSE; + + } + + //initialize UTF8 cache + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + } + + } else { + /** + *((0xC0 & (*in) != 0x80) && (mState != 0)) + * Incomplete multi-octet sequence. + */ + + return FALSE; + } + } + } + return TRUE; +} + +//-------------------------------------------------------------------- +/** +* Tests whether a string complies as UTF-8. This will be much +* faster than utf8_is_valid but will pass five and six octet +* UTF-8 sequences, which are not supported by Unicode and +* so cannot be displayed correctly in a browser. In other words +* it is not as strict as utf8_is_valid but it's faster. If you use +* is to validate user input, you place yourself at the risk that +* attackers will be able to inject 5 and 6 byte sequences (which +* may or may not be a significant risk, depending on what you are +* are doing) +* @see utf8_is_valid +* @see http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php#54805 +* @param string UTF-8 string to check +* @return boolean TRUE if string is valid UTF-8 +* @package utf8 +*/ +function utf8_compliant($str) { + if ( strlen($str) == 0 ) { + return TRUE; + } + // If even just the first character can be matched, when the /u + // modifier is used, then it's valid UTF-8. If the UTF-8 is somehow + // invalid, nothing at all will match, even if the string contains + // some valid sequences + return (preg_match('/^.{1}/us',$str,$ar) == 1); +} + diff --git a/libraries/joomla/utilities/LICENSE b/libraries/joomla/utilities/LICENSE new file mode 100644 index 0000000000000..df50810b85774 --- /dev/null +++ b/libraries/joomla/utilities/LICENSE @@ -0,0 +1,340 @@ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 2 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, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/libraries/joomla/utilities/README.md b/libraries/joomla/utilities/README.md new file mode 100644 index 0000000000000..8de6a2e2152f6 --- /dev/null +++ b/libraries/joomla/utilities/README.md @@ -0,0 +1,381 @@ +# The Utilities Package + +## Using ArrayHelper + +### toInteger + +```php +use Joomla\Utilities\ArrayHelper; + +$input = array( + "width" => "100", + "height" => "200xxx", + "length" => "10.3" +); +$result = ArrayHelper::toInteger($input); +var_dump($result); +``` +Result: +``` +array(3) { + 'width' => + int(100) + 'height' => + int(200) + 'length' => + int(10) +} +``` + +### toObject + +```php +use Joomla\Utilities\ArrayHelper; + +class Book { + public $name; + public $author; + public $genre; + public $rating; +} +class Author { + public $name; + public $born; +} +$input = array( + "name" => "The Hitchhiker's Guide to the Galaxy", + "author" => array( + "name" => "Douglas Adams", + "born" => 1952, + "died" => 2001), + "genre" => "comic science fiction", + "rating" => 10 +); +$book = ArrayHelper::toObject($input, 'Book'); +var_dump($book); +``` +Result: +``` +class Book#1 (4) { + public $name => + string(36) "The Hitchhiker's Guide to the Galaxy" + public $author => + class Book#2 (6) { + public $name => + string(13) "Douglas Adams" + public $author => + NULL + public $genre => + NULL + public $rating => + NULL + public $born => + int(1952) + public $died => + int(2001) + } + public $genre => + string(21) "comic science fiction" + public $rating => + int(10) +} +``` + +### toString + +```php +use Joomla\Utilities\ArrayHelper; + +$input = array( + "fruit" => "apple", + "pi" => 3.14 +); +echo ArrayHelper::toString($input); +``` +Result: +``` +fruit="apple" pi="3.14" +``` + +### fromObject + +```php +use Joomla\Utilities\ArrayHelper; + +class Book { + public $name; + public $author; + public $genre; + public $rating; +} +class Author { + public $name; + public $born; +} + +$book = new Book(); +$book->name = "Harry Potter and the Philosopher's Stone"; +$book->author = new Author(); +$book->author->name = "J.K. Rowling"; +$book->author->born = 1965; +$book->genre = "fantasy"; +$book->rating = 10; + +$array = ArrayHelper::fromObject($book); +var_dump($array); +``` +Result: +``` +array(4) { + 'name' => + string(40) "Harry Potter and the Philosopher's Stone" + 'author' => + array(2) { + 'name' => + string(12) "J.K. Rowling" + 'born' => + int(1965) + } + 'genre' => + string(7) "fantasy" + 'rating' => + int(10) +} +``` + +### getColumn + +```php +use Joomla\Utilities\ArrayHelper; + +$rows = array( + array("name" => "John", "age" => 20), + array("name" => "Alex", "age" => 35), + array("name" => "Sarah", "age" => 27) +); +$names = ArrayHelper::getColumn($rows, 'name'); +var_dump($names); +``` +Result: +``` +array(3) { + [0] => + string(4) "John" + [1] => + string(4) "Alex" + [2] => + string(5) "Sarah" +} +``` + +### getValue +```php +use Joomla\Utilities\ArrayHelper; + +$city = array( + "name" => "Oslo", + "country" => "Norway" +); + +// Prints 'Oslo' +echo ArrayHelper::getValue($city, 'name'); + +// Prints 'unknown mayor' (no 'mayor' key is found in the array) +echo ArrayHelper::getValue($city, 'mayor', 'unknown mayor'); +``` + +### invert + +```php +use Joomla\Utilities\ArrayHelper; + +$input = array( + 'New' => array('1000', '1500', '1750'), + 'Used' => array('3000', '4000', '5000', '6000') +); +$output = ArrayHelper::invert($input); +var_dump($output); +``` +Result: +``` +array(7) { + [1000] => + string(3) "New" + [1500] => + string(3) "New" + [1750] => + string(3) "New" + [3000] => + string(4) "Used" + [4000] => + string(4) "Used" + [5000] => + string(4) "Used" + [6000] => + string(4) "Used" +} +``` + + +### isAssociative + +```php +use Joomla\Utilities\ArrayHelper; + +$user = array("id" => 46, "name" => "John"); +echo ArrayHelper::isAssociative($user) ? 'true' : 'false'; // true + +$letters = array("a", "b", "c"); +echo ArrayHelper::isAssociative($letters) ? 'true' : 'false'; // false +``` + +### pivot + +```php +use Joomla\Utilities\ArrayHelper; + +$movies = array( + array('year' => 1972, 'title' => 'The Godfather'), + array('year' => 2000, 'title' => 'Gladiator'), + array('year' => 2000, 'title' => 'Memento'), + array('year' => 1964, 'title' => 'Dr. Strangelove') +); +$pivoted = ArrayHelper::pivot($movies, 'year'); +var_dump($pivoted); +``` +Result: +``` +array(3) { + [1972] => + array(2) { + 'year' => + int(1972) + 'title' => + string(13) "The Godfather" + } + [2000] => + array(2) { + [0] => + array(2) { + 'year' => + int(2000) + 'title' => + string(9) "Gladiator" + } + [1] => + array(2) { + 'year' => + int(2000) + 'title' => + string(7) "Memento" + } + } + [1964] => + array(2) { + 'year' => + int(1964) + 'title' => + string(15) "Dr. Strangelove" + } +} +``` + +### sortObjects + +```php +use Joomla\Utilities\ArrayHelper; + +$members = array( + (object) array('first_name' => 'Carl', 'last_name' => 'Hopkins'), + (object) array('first_name' => 'Lisa', 'last_name' => 'Smith'), + (object) array('first_name' => 'Julia', 'last_name' => 'Adams') +); +$sorted = ArrayHelper::sortObjects($members, 'last_name', 1); +var_dump($sorted); +``` +Result: +``` +array(3) { + [0] => + class stdClass#3 (2) { + public $first_name => + string(5) "Julia" + public $last_name => + string(5) "Adams" + } + [1] => + class stdClass#1 (2) { + public $first_name => + string(4) "Carl" + public $last_name => + string(7) "Hopkins" + } + [2] => + class stdClass#2 (2) { + public $first_name => + string(4) "Lisa" + public $last_name => + string(5) "Smith" + } +} +``` + +### arrayUnique +```php +use Joomla\Utilities\ArrayHelper; + +$names = array( + array("first_name" => "John", "last_name" => "Adams"), + array("first_name" => "John", "last_name" => "Adams"), + array("first_name" => "John", "last_name" => "Smith"), + array("first_name" => "Sam", "last_name" => "Smith") +); +$unique = ArrayHelper::arrayUnique($names); +var_dump($unique); +``` +Result: +``` +array(3) { + [0] => + array(2) { + 'first_name' => + string(4) "John" + 'last_name' => + string(5) "Adams" + } + [2] => + array(2) { + 'first_name' => + string(4) "John" + 'last_name' => + string(5) "Smith" + } + [3] => + array(2) { + 'first_name' => + string(3) "Sam" + 'last_name' => + string(5) "Smith" + } +} +``` + +## Installation via Composer + +Add `"joomla/utilities": "dev-master"` to the require block in your composer.json, make sure you have `"minimum-stability": "dev"` and then run `composer install`. + +```json +{ + "require": { + "joomla/utilities": "dev-master" + }, + "minimum-stability": "dev" +} +``` + +Alternatively, you can simply run the following from the command line: + +```sh +composer init --stability="dev" +composer require joomla/utilities "dev-master" +``` diff --git a/libraries/joomla/utilities/Tests/ArrayHelperTest.php b/libraries/joomla/utilities/Tests/ArrayHelperTest.php new file mode 100644 index 0000000000000..0321c8dae9183 --- /dev/null +++ b/libraries/joomla/utilities/Tests/ArrayHelperTest.php @@ -0,0 +1,1686 @@ + array( + // Input + array( + array(1, 2, 3, array(4)), + array(2, 2, 3, array(4)), + array(3, 2, 3, array(4)), + array(2, 2, 3, array(4)), + array(3, 2, 3, array(4)), + ), + // Expected + array( + array(1, 2, 3, array(4)), + array(2, 2, 3, array(4)), + array(3, 2, 3, array(4)), + ), + ) + ); + } + + /** + * Data provider for from object inputs + * + * @return array + * + * @since 1.0 + */ + public function seedTestFromObject() + { + // Define a common array. + $common = array('integer' => 12, 'float' => 1.29999, 'string' => 'A Test String'); + + return array( + 'Invalid input' => array( + // Array The array being input + null, + // Boolean Recurse through multiple dimensions + null, + // String Regex to select only some attributes + null, + // String The expected return value + null, + // Boolean Use function defaults (true) or full argument list + true + ), + 'To single dimension array' => array( + (object) $common, + null, + null, + $common, + true + ), + 'Object with nested arrays and object.' => array( + (object) array( + 'foo' => $common, + 'bar' => (object) array( + 'goo' => $common, + ), + ), + null, + null, + array( + 'foo' => $common, + 'bar' => array( + 'goo' => $common, + ), + ), + true + ), + 'To single dimension array with recursion' => array( + (object) $common, + true, + null, + $common, + false + ), + 'To single dimension array using regex on keys' => array( + (object) $common, + true, + // Only get the 'integer' and 'float' keys. + '/^(integer|float)/', + array( + 'integer' => 12, 'float' => 1.29999 + ), + false + ), + 'Nested objects to single dimension array' => array( + (object) array( + 'first' => (object) $common, + 'second' => (object) $common, + 'third' => (object) $common, + ), + null, + null, + array( + 'first' => (object) $common, + 'second' => (object) $common, + 'third' => (object) $common, + ), + false + ), + 'Nested objects into multiple dimension array' => array( + (object) array( + 'first' => (object) $common, + 'second' => (object) $common, + 'third' => (object) $common, + ), + null, + null, + array( + 'first' => $common, + 'second' => $common, + 'third' => $common, + ), + true + ), + 'Nested objects into multiple dimension array 2' => array( + (object) array( + 'first' => (object) $common, + 'second' => (object) $common, + 'third' => (object) $common, + ), + true, + null, + array( + 'first' => $common, + 'second' => $common, + 'third' => $common, + ), + true + ), + 'Nested objects into multiple dimension array 3' => array( + (object) array( + 'first' => (object) $common, + 'second' => (object) $common, + 'third' => (object) $common, + ), + false, + null, + array( + 'first' => (object) $common, + 'second' => (object) $common, + 'third' => (object) $common, + ), + false + ), + 'multiple 4' => array( + (object) array( + 'first' => 'Me', + 'second' => (object) $common, + 'third' => (object) $common, + ), + false, + null, + array( + 'first' => 'Me', + 'second' => (object) $common, + 'third' => (object) $common, + ), + false + ), + 'Nested objects into multiple dimension array of int and string' => array( + (object) array( + 'first' => (object) $common, + 'second' => (object) $common, + 'third' => (object) $common, + ), + true, + '/(first|second|integer|string)/', + array( + 'first' => array( + 'integer' => 12, 'string' => 'A Test String' + ), 'second' => array( + 'integer' => 12, 'string' => 'A Test String' + ), + ), + false + ), + 'multiple 6' => array( + (object) array( + 'first' => array( + 'integer' => 12, + 'float' => 1.29999, + 'string' => 'A Test String', + 'third' => (object) $common, + ), + 'second' => $common, + ), + null, + null, + array( + 'first' => array( + 'integer' => 12, + 'float' => 1.29999, + 'string' => 'A Test String', + 'third' => $common, + ), + 'second' => $common, + ), + true + ), + ); + } + + /** + * Data provider for get column + * + * @return array + * + * @since 1.0 + */ + public function seedTestGetColumn() + { + return array( + 'generic array' => array( + array( + array( + 1, 2, 3, 4, 5 + ), array( + 6, 7, 8, 9, 10 + ), array( + 11, 12, 13, 14, 15 + ), array( + 16, 17, 18, 19, 20 + ) + ), + 2, + array( + 3, 8, 13, 18 + ), + 'Should get column #2' + ), + 'associative array' => array( + array( + array( + 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5 + ), + array( + 'one' => 6, 'two' => 7, 'three' => 8, 'four' => 9, 'five' => 10 + ), + array( + 'one' => 11, 'two' => 12, 'three' => 13, 'four' => 14, 'five' => 15 + ), + array( + 'one' => 16, 'two' => 17, 'three' => 18, 'four' => 19, 'five' => 20 + ) + ), + 'four', + array( + 4, 9, 14, 19 + ), + 'Should get column \'four\'' + ), + 'object array' => array( + array( + (object) array( + 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5 + ), + (object) array( + 'one' => 6, 'two' => 7, 'three' => 8, 'four' => 9, 'five' => 10 + ), + (object) array( + 'one' => 11, 'two' => 12, 'three' => 13, 'four' => 14, 'five' => 15 + ), + (object) array( + 'one' => 16, 'two' => 17, 'three' => 18, 'four' => 19, 'five' => 20 + ) + ), + 'four', + array( + 4, 9, 14, 19 + ), + 'Should get column \'four\'' + ), + ); + } + + /** + * Data provider for get value + * + * @return array + * + * @since 1.0 + */ + public function seedTestGetValue() + { + $input = array( + 'one' => 1, + 'two' => 2, + 'three' => 3, + 'four' => 4, + 'five' => 5, + 'six' => 6, + 'seven' => 7, + 'eight' => 8, + 'nine' => 'It\'s nine', + 'ten' => 10, + 'eleven' => 11, + 'twelve' => 12, + 'thirteen' => 13, + 'fourteen' => 14, + 'fifteen' => 15, + 'sixteen' => 16, + 'seventeen' => 17, + 'eightteen' => 'eighteen ninety-five', + 'nineteen' => 19, + 'twenty' => 20 + ); + + return array( + 'defaults' => array( + $input, 'five', null, null, 5, 'Should get 5', true + ), + 'get non-value' => array( + $input, 'fiveio', 198, null, 198, 'Should get the default value', false + ), + 'get int 5' => array( + $input, 'five', 198, 'int', (int) 5, 'Should get an int', false + ), + 'get float six' => array( + $input, 'six', 198, 'float', (float) 6, 'Should get a float', false + ), + 'get get boolean seven' => array( + $input, 'seven', 198, 'bool', (bool) 7, 'Should get a boolean', false + ), + 'get array eight' => array( + $input, 'eight', 198, 'array', array( + 8 + ), 'Should get an array', false + ), + 'get string nine' => array( + $input, 'nine', 198, 'string', 'It\'s nine', 'Should get string', false + ), + 'get word' => array( + $input, 'eightteen', 198, 'word', 'eighteenninetyfive', 'Should get it as a single word', false + ), + ); + } + + /** + * Data provider for invert + * + * @return array + * + * @since 1.0 + */ + public function seedTestInvert() + { + return array( + 'Case 1' => array( + // Input + array( + 'New' => array('1000', '1500', '1750'), + 'Used' => array('3000', '4000', '5000', '6000') + ), + // Expected + array( + '1000' => 'New', + '1500' => 'New', + '1750' => 'New', + '3000' => 'Used', + '4000' => 'Used', + '5000' => 'Used', + '6000' => 'Used' + ) + ), + 'Case 2' => array( + // Input + array( + 'New' => array(1000, 1500, 1750), + 'Used' => array(2750, 3000, 4000, 5000, 6000), + 'Refurbished' => array(2000, 2500), + 'Unspecified' => array() + ), + // Expected + array( + '1000' => 'New', + '1500' => 'New', + '1750' => 'New', + '2750' => 'Used', + '3000' => 'Used', + '4000' => 'Used', + '5000' => 'Used', + '6000' => 'Used', + '2000' => 'Refurbished', + '2500' => 'Refurbished' + ) + ) + ); + } + + /** + * Data provider for testPivot + * + * @return array + * + * @since 1.0 + */ + public function seedTestPivot() + { + return array( + 'A scalar array' => array( + // Source + array( + 1 => 'a', + 2 => 'b', + 3 => 'b', + 4 => 'c', + 5 => 'a', + 6 => 'a', + ), + // Key + null, + // Expected + array( + 'a' => array( + 1, 5, 6 + ), + 'b' => array( + 2, 3 + ), + 'c' => 4, + ) + ), + 'An array of associative arrays' => array( + // Source + array( + 1 => array('id' => 41, 'title' => 'boo'), + 2 => array('id' => 42, 'title' => 'boo'), + 3 => array('title' => 'boo'), + 4 => array('id' => 42, 'title' => 'boo'), + 5 => array('id' => 43, 'title' => 'boo'), + ), + // Key + 'id', + // Expected + array( + 41 => array('id' => 41, 'title' => 'boo'), + 42 => array( + array('id' => 42, 'title' => 'boo'), + array('id' => 42, 'title' => 'boo'), + ), + 43 => array('id' => 43, 'title' => 'boo'), + ) + ), + 'An array of objects' => array( + // Source + array( + 1 => (object) array('id' => 41, 'title' => 'boo'), + 2 => (object) array('id' => 42, 'title' => 'boo'), + 3 => (object) array('title' => 'boo'), + 4 => (object) array('id' => 42, 'title' => 'boo'), + 5 => (object) array('id' => 43, 'title' => 'boo'), + ), + // Key + 'id', + // Expected + array( + 41 => (object) array('id' => 41, 'title' => 'boo'), + 42 => array( + (object) array('id' => 42, 'title' => 'boo'), + (object) array('id' => 42, 'title' => 'boo'), + ), + 43 => (object) array('id' => 43, 'title' => 'boo'), + ) + ), + ); + } + + /** + * Data provider for sorting objects + * + * @return array + * + * @since 1.0 + */ + public function seedTestSortObject() + { + $input1 = array( + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 'T Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'G Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + ); + $input2 = array( + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 't Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'g Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + ); + + if (substr(php_uname(), 0, 6) != 'Darwin') + { + $input3 = array( + (object) array( + 'string' => 'A Test String', 'integer' => 1, + ), + (object) array( + 'string' => 'é Test String', 'integer' => 2, + ), + (object) array( + 'string' => 'è Test String', 'integer' => 3, + ), + (object) array( + 'string' => 'É Test String', 'integer' => 4, + ), + (object) array( + 'string' => 'È Test String', 'integer' => 5, + ), + (object) array( + 'string' => 'Œ Test String', 'integer' => 6, + ), + (object) array( + 'string' => 'œ Test String', 'integer' => 7, + ), + (object) array( + 'string' => 'L Test String', 'integer' => 8, + ), + (object) array( + 'string' => 'P Test String', 'integer' => 9, + ), + (object) array( + 'string' => 'p Test String', 'integer' => 10, + ), + ); + } + else + { + $input3 = array(); + } + + return array( + 'by int defaults' => array( + $input1, + 'integer', + null, + false, + false, + array( + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 'T Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'G Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + ), + 'Should be sorted by the integer field in ascending order', + true + ), + 'by int ascending' => array( + $input1, + 'integer', + 1, + false, + false, + array( + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 'T Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'G Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + ), + 'Should be sorted by the integer field in ascending order full argument list', + false + ), + 'by int descending' => array( + $input1, + 'integer', + -1, + false, + false, + array( + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'G Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 'T Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + ), + 'Should be sorted by the integer field in descending order', + false + ), + 'by string ascending' => array( + $input1, + 'string', + 1, + false, + false, + array( + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'G Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 'T Test String' + ), + ), + 'Should be sorted by the string field in ascending order full argument list', + false, + array(1, 2) + ), + 'by string descending' => array( + $input1, + 'string', + -1, + false, + false, + array( + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 'T Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'G Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + 'Should be sorted by the string field in descending order', + false, + array(5, 6) + ), + 'by casesensitive string ascending' => array( + $input2, + 'string', + 1, + true, + false, + array( + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'g Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 't Test String' + ), + ), + 'Should be sorted by the string field in ascending order with casesensitive comparisons', + false, + array(1, 2) + ), + 'by casesensitive string descending' => array( + $input2, + 'string', + -1, + true, + false, + array( + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 't Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'g Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + 'Should be sorted by the string field in descending order with casesensitive comparisons', + false, + array(5, 6) + ), + 'by casesensitive string,integer ascending' => array( + $input2, + array( + 'string', 'integer' + ), + 1, + true, + false, + array( + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'g Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 't Test String' + ), + ), + 'Should be sorted by the string,integer field in descending order with casesensitive comparisons', + false + ), + 'by casesensitive string,integer descending' => array( + $input2, + array( + 'string', 'integer' + ), + -1, + true, + false, + array( + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 't Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'g Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + 'Should be sorted by the string,integer field in descending order with casesensitive comparisons', + false + ), + 'by casesensitive string,integer ascending,descending' => array( + $input2, + array( + 'string', 'integer' + ), + array( + 1, -1 + ), + true, + false, + array( + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'g Test String' + ), + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 't Test String' + ), + ), + 'Should be sorted by the string,integer field in ascending,descending order with casesensitive comparisons', + false + ), + 'by casesensitive string,integer descending,ascending' => array( + $input2, + array( + 'string', 'integer' + ), + array( + -1, 1 + ), + true, + false, + array( + (object) array( + 'integer' => 5, 'float' => 1.29999, 'string' => 't Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'g Test String' + ), + (object) array( + 'integer' => 1, 'float' => 1.29999, 'string' => 'N Test String' + ), + (object) array( + 'integer' => 6, 'float' => 1.29999, 'string' => 'L Test String' + ), + (object) array( + 'integer' => 22, 'float' => 1.29999, 'string' => 'E Test String' + ), + (object) array( + 'integer' => 15, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 35, 'float' => 1.29999, 'string' => 'C Test String' + ), + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + 'Should be sorted by the string,integer field in descending,ascending order with casesensitive comparisons', + false + ), + 'by casesensitive string ascending' => array( + $input3, + 'string', + 1, + true, + array( + 'fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR' + ), + array( + (object) array( + 'string' => 'A Test String', 'integer' => 1, + ), + (object) array( + 'string' => 'é Test String', 'integer' => 2, + ), + (object) array( + 'string' => 'É Test String', 'integer' => 4, + ), + (object) array( + 'string' => 'è Test String', 'integer' => 3, + ), + (object) array( + 'string' => 'È Test String', 'integer' => 5, + ), + (object) array( + 'string' => 'L Test String', 'integer' => 8, + ), + (object) array( + 'string' => 'œ Test String', 'integer' => 7, + ), + (object) array( + 'string' => 'Œ Test String', 'integer' => 6, + ), + (object) array( + 'string' => 'p Test String', 'integer' => 10, + ), + (object) array( + 'string' => 'P Test String', 'integer' => 9, + ), + ), + 'Should be sorted by the string field in ascending order with casesensitive comparisons and fr_FR locale', + false + ), + 'by caseinsensitive string, integer ascending' => array( + $input3, + array( + 'string', 'integer' + ), + 1, + false, + array( + 'fr_FR.utf8', 'fr_FR.UTF-8', 'fr_FR.UTF-8@euro', 'French_Standard', 'french', 'fr_FR', 'fre_FR' + ), + array( + (object) array( + 'string' => 'A Test String', 'integer' => 1, + ), + (object) array( + 'string' => 'é Test String', 'integer' => 2, + ), + (object) array( + 'string' => 'É Test String', 'integer' => 4, + ), + (object) array( + 'string' => 'è Test String', 'integer' => 3, + ), + (object) array( + 'string' => 'È Test String', 'integer' => 5, + ), + (object) array( + 'string' => 'L Test String', 'integer' => 8, + ), + (object) array( + 'string' => 'Œ Test String', 'integer' => 6, + ), + (object) array( + 'string' => 'œ Test String', 'integer' => 7, + ), + (object) array( + 'string' => 'P Test String', 'integer' => 9, + ), + (object) array( + 'string' => 'p Test String', 'integer' => 10, + ), + ), + 'Should be sorted by the string,integer field in ascending order with caseinsensitive comparisons and fr_FR locale', + false + ), + ); + } + + /** + * Data provider for numeric inputs + * + * @return array + * + * @since 1.0 + */ + public function seedTestToInteger() + { + return array( + 'floating with single argument' => array( + array( + 0.9, 3.2, 4.9999999, 7.5 + ), null, array( + 0, 3, 4, 7 + ), 'Should truncate numbers in array' + ), + 'floating with default array' => array( + array( + 0.9, 3.2, 4.9999999, 7.5 + ), array( + 1, 2, 3 + ), array( + 0, 3, 4, 7 + ), 'Supplied default should not be used' + ), + 'non-array with single argument' => array( + 12, null, array(), 'Should replace non-array input with empty array' + ), + 'non-array with default array' => array( + 12, array( + 1.5, 2.6, 3 + ), array( + 1, 2, 3 + ), 'Should replace non-array input with array of truncated numbers' + ), + 'non-array with default single' => array( + 12, 3.5, array( + 3 + ), 'Should replace non-array with single-element array of truncated number' + ), + ); + } + + /** + * Data provider for object inputs + * + * @return array + * + * @since 1.0 + */ + public function seedTestToObject() + { + return array( + 'single object' => array( + array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + null, + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'Should turn array into single object' + ), + 'multiple objects' => array( + array( + 'first' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + null, + (object) array( + 'first' => (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + 'Should turn multiple dimension array into nested objects' + ), + 'single object with class' => array( + array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'stdClass', + (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'Should turn array into single object' + ), + 'multiple objects with class' => array( + array( + 'first' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + 'stdClass', + (object) array( + 'first' => (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => (object) array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + 'Should turn multiple dimension array into nested objects' + ), + ); + } + + /** + * Data provider for string inputs + * + * @return array + * + * @since 1.0 + */ + public function seedTestToString() + { + return array( + 'single dimension 1' => array( + array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + null, + null, + false, + 'integer="12" float="1.29999" string="A Test String"', + 'Should turn array into single string with defaults', + true + ), + 'single dimension 2' => array( + array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + " = ", + null, + true, + 'integer = "12"float = "1.29999"string = "A Test String"', + 'Should turn array into single string with " = " and no spaces', + false + ), + 'single dimension 3' => array( + array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ' = ', + ' then ', + true, + 'integer = "12" then float = "1.29999" then string = "A Test String"', + 'Should turn array into single string with " = " and then between elements', + false + ), + 'multiple dimensions 1' => array( + array( + 'first' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + null, + null, + false, + 'integer="12" float="1.29999" string="A Test String" ' . 'integer="12" float="1.29999" string="A Test String" ' + . 'integer="12" float="1.29999" string="A Test String"', + 'Should turn multiple dimension array into single string', + true + ), + 'multiple dimensions 2' => array( + array( + 'first' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + ' = ', + null, + false, + 'integer = "12"float = "1.29999"string = "A Test String"' . 'integer = "12"float = "1.29999"string = "A Test String"' + . 'integer = "12"float = "1.29999"string = "A Test String"', + 'Should turn multiple dimension array into single string with " = " and no spaces', + false + ), + 'multiple dimensions 3' => array( + array( + 'first' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + ' = ', + ' ', + false, + 'integer = "12" float = "1.29999" string = "A Test String" ' . 'integer = "12" float = "1.29999" string = "A Test String" ' + . 'integer = "12" float = "1.29999" string = "A Test String"', + 'Should turn multiple dimension array into single string with " = " and a space', + false + ), + 'multiple dimensions 4' => array( + array( + 'first' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'second' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + 'third' => array( + 'integer' => 12, 'float' => 1.29999, 'string' => 'A Test String' + ), + ), + ' = ', + null, + true, + 'firstinteger = "12"float = "1.29999"string = "A Test String"' . 'secondinteger = "12"float = "1.29999"string = "A Test String"' + . 'thirdinteger = "12"float = "1.29999"string = "A Test String"', + 'Should turn multiple dimension array into single string with " = " and no spaces with outer key', + false + ), + ); + } + + /** + * Tests the ArrayHelper::arrayUnique method. + * + * @param array $input The array being input. + * @param string $expected The expected return value. + * + * @return void + * + * @dataProvider seedTestArrayUnique + * @covers Joomla\Utilities\ArrayHelper::arrayUnique + * @since 1.0 + */ + public function testArrayUnique($input, $expected) + { + $this->assertThat( + ArrayHelper::arrayUnique($input), + $this->equalTo($expected) + ); + } + + /** + * Tests conversion of object to string. + * + * @param array $input The array being input + * @param boolean $recurse Recurse through multiple dimensions? + * @param string $regex Regex to select only some attributes + * @param string $expect The expected return value + * @param boolean $defaults Use function defaults (true) or full argument list + * + * @return void + * + * @dataProvider seedTestFromObject + * @covers Joomla\Utilities\ArrayHelper::fromObject + * @covers Joomla\Utilities\ArrayHelper::arrayFromObject + * @since 1.0 + */ + public function testFromObject($input, $recurse, $regex, $expect, $defaults) + { + if ($defaults) + { + $output = ArrayHelper::fromObject($input); + } + else + { + $output = ArrayHelper::fromObject($input, $recurse, $regex); + } + + $this->assertEquals($expect, $output); + } + + /** + * Test pulling data from a single column (by index or association). + * + * @param array $input Input array + * @param mixed $index Column to pull, either by association or number + * @param array $expect The expected results + * @param string $message The failure message + * + * @return void + * + * @dataProvider seedTestGetColumn + * @covers Joomla\Utilities\ArrayHelper::getColumn + * @since 1.0 + */ + public function testGetColumn($input, $index, $expect, $message) + { + $this->assertEquals($expect, ArrayHelper::getColumn($input, $index), $message); + } + + /** + * Test get value from an array. + * + * @param array $input Input array + * @param mixed $index Element to pull, either by association or number + * @param mixed $default The defualt value, if element not present + * @param string $type The type of value returned + * @param array $expect The expected results + * @param string $message The failure message + * @param bool $defaults Use the defaults (true) or full argument list + * + * @return void + * + * @dataProvider seedTestGetValue + * @covers Joomla\Utilities\ArrayHelper::getValue + * @since 1.0 + */ + public function testGetValue($input, $index, $default, $type, $expect, $message, $defaults) + { + if ($defaults) + { + $output = ArrayHelper::getValue($input, $index); + } + else + { + $output = ArrayHelper::getValue($input, $index, $default, $type); + } + + $this->assertEquals($expect, $output, $message); + } + + /** + * Tests the ArrayHelper::invert method. + * + * @param array $input The array being input. + * @param string $expected The expected return value. + * + * @return void + * + * @dataProvider seedTestInvert + * @since 1.0 + */ + public function testInvert($input, $expected) + { + $this->assertThat( + ArrayHelper::invert($input), + $this->equalTo($expected) + ); + } + + /** + * Test the ArrayHelper::isAssociate method. + * + * @return void + * + * @since 1.0 + * @sovers ArrayHelper::isAssociative + */ + public function testIsAssociative() + { + $this->assertThat( + ArrayHelper::isAssociative( + array( + 1, 2, 3 + ) + ), + $this->isFalse(), + 'Line: ' . __LINE__ . ' This array should not be associative.' + ); + + $this->assertThat( + ArrayHelper::isAssociative( + array( + 'a' => 1, 'b' => 2, 'c' => 3 + ) + ), + $this->isTrue(), + 'Line: ' . __LINE__ . ' This array should be associative.' + ); + + $this->assertThat( + ArrayHelper::isAssociative( + array( + 'a' => 1, 2, 'c' => 3 + ) + ), + $this->isTrue(), + 'Line: ' . __LINE__ . ' This array should be associative.' + ); + } + + /** + * Tests the ArrayHelper::pivot method. + * + * @param array $source The source array. + * @param string $key Where the elements of the source array are objects or arrays, the key to pivot on. + * @param array $expected The expected result. + * + * @return void + * + * @dataProvider seedTestPivot + * @covers Joomla\Utilities\ArrayHelper::pivot + * @since 1.0 + */ + public function testPivot($source, $key, $expected) + { + $this->assertThat( + ArrayHelper::pivot($source, $key), + $this->equalTo($expected) + ); + } + + /** + * Test sorting an array of objects. + * + * @param array $input Input array of objects + * @param mixed $key Key to sort on + * @param mixed $direction Ascending (1) or Descending(-1) + * @param string $casesensitive @todo + * @param string $locale @todo + * @param array $expect The expected results + * @param string $message The failure message + * @param boolean $defaults Use the defaults (true) or full argument list + * + * @return void + * + * @dataProvider seedTestSortObject + * @covers Joomla\Utilities\ArrayHelper::sortObjects + * @since 1.0 + */ + public function testSortObjects($input, $key, $direction, $casesensitive, $locale, $expect, $message, $defaults, $swappable_keys = array()) + { + // Convert the $locale param to a string if it is an array + if (is_array($locale)) + { + $locale = "'" . implode("', '", $locale) . "'"; + } + + if (empty($input)) + { + $this->markTestSkipped('Skip for MAC until PHP sort bug is fixed'); + + return; + } + elseif ($locale != false && !setlocale(LC_COLLATE, $locale)) + { + // If the locale is not available, we can't have to transcode the string and can't reliably compare it. + $this->markTestSkipped("Locale {$locale} is not available."); + + return; + } + + if ($defaults) + { + $output = ArrayHelper::sortObjects($input, $key); + } + else + { + $output = ArrayHelper::sortObjects($input, $key, $direction, $casesensitive, $locale); + } + + // The ordering of elements that compare equal according to + // $key is undefined (implementation dependent). + if ($expect != $output && $swappable_keys) { + list($k1, $k2) = $swappable_keys; + $e1 = $output[$k1]; + $e2 = $output[$k2]; + $output[$k1] = $e2; + $output[$k2] = $e1; + } + + $this->assertEquals($expect, $output, $message); + } + + /** + * Test convert an array to all integers. + * + * @param string $input The array being input + * @param string $default The default value + * @param string $expect The expected return value + * @param string $message The failure message + * + * @return void + * + * @dataProvider seedTestToInteger + * @covers Joomla\Utilities\ArrayHelper::toInteger + * @since 1.0 + */ + public function testToInteger($input, $default, $expect, $message) + { + $result = ArrayHelper::toInteger($input, $default); + $this->assertEquals( + $expect, + $result, + $message + ); + } + + /** + * Test convert array to object. + * + * @param string $input The array being input + * @param string $className The class name to build + * @param string $expect The expected return value + * @param string $message The failure message + * + * @return void + * + * @dataProvider seedTestToObject + * @covers Joomla\Utilities\ArrayHelper::toObject + * @since 1.0 + */ + public function testToObject($input, $className, $expect, $message) + { + $this->assertEquals( + $expect, + ArrayHelper::toObject($input), + $message + ); + } + + /** + * Tests converting array to string. + * + * @param array $input The array being input + * @param string $inner The inner glue + * @param string $outer The outer glue + * @param boolean $keepKey Keep the outer key + * @param string $expect The expected return value + * @param string $message The failure message + * @param boolean $defaults Use function defaults (true) or full argument list + * + * @return void + * + * @dataProvider seedTestToString + * @covers Joomla\Utilities\ArrayHelper::toString + * @since 1.0 + */ + public function testToString($input, $inner, $outer, $keepKey, $expect, $message, $defaults) + { + if ($defaults) + { + $output = ArrayHelper::toString($input); + } + else + { + $output = ArrayHelper::toString($input, $inner, $outer, $keepKey); + } + + $this->assertEquals($expect, $output, $message); + } + + /** + * Tests the arraySearch method. + * + * @return void + * + * @covers Joomla\Utilities\ArrayHelper::arraySearch + * @since 1.0 + */ + public function testArraySearch() + { + $array = array( + 'name' => 'Foo', + 'email' => 'foobar@example.com' + ); + + // Search case sensitive. + $this->assertEquals('name', ArrayHelper::arraySearch('Foo', $array)); + + // Search case insenitive. + $this->assertEquals('email', ArrayHelper::arraySearch('FOOBAR', $array, false)); + } +} diff --git a/libraries/joomla/utilities/composer.json b/libraries/joomla/utilities/composer.json new file mode 100644 index 0000000000000..25b0811f0e001 --- /dev/null +++ b/libraries/joomla/utilities/composer.json @@ -0,0 +1,18 @@ +{ + "name": "joomla/utilities", + "type": "joomla-package", + "description": "Joomla Utilities Package", + "keywords": ["joomla", "framework", "utilities"], + "homepage": "https://github.com/joomla-framework/utilities", + "license": "GPL-2.0+", + "require": { + "php": ">=5.3.10", + "joomla/string": "~1.0" + }, + "autoload": { + "psr-4": { + "Joomla\\Utilities\\": "src/", + "Joomla\\Utilities\\Tests\\": "Tests/" + } + } +} diff --git a/libraries/joomla/utilities/phpunit.xml.dist b/libraries/joomla/utilities/phpunit.xml.dist new file mode 100644 index 0000000000000..2278bfbac86a6 --- /dev/null +++ b/libraries/joomla/utilities/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + Tests + + + diff --git a/libraries/joomla/utilities/src/ArrayHelper.php b/libraries/joomla/utilities/src/ArrayHelper.php new file mode 100644 index 0000000000000..e1494e7c0535a --- /dev/null +++ b/libraries/joomla/utilities/src/ArrayHelper.php @@ -0,0 +1,577 @@ + $v) + { + if (is_array($v)) + { + $obj->$k = self::toObject($v, $class); + } + else + { + $obj->$k = $v; + } + } + + return $obj; + } + + /** + * Utility function to map an array to a string. + * + * @param array $array The array to map. + * @param string $inner_glue The glue (optional, defaults to '=') between the key and the value. + * @param string $outer_glue The glue (optional, defaults to ' ') between array elements. + * @param boolean $keepOuterKey True if final key should be kept. + * + * @return string The string mapped from the given array + * + * @since 1.0 + */ + public static function toString(array $array, $inner_glue = '=', $outer_glue = ' ', $keepOuterKey = false) + { + $output = array(); + + foreach ($array as $key => $item) + { + if (is_array($item)) + { + if ($keepOuterKey) + { + $output[] = $key; + } + + // This is value is an array, go and do it again! + $output[] = self::toString($item, $inner_glue, $outer_glue, $keepOuterKey); + } + else + { + $output[] = $key . $inner_glue . '"' . $item . '"'; + } + } + + return implode($outer_glue, $output); + } + + /** + * Utility function to map an object to an array + * + * @param object $p_obj The source object + * @param boolean $recurse True to recurse through multi-level objects + * @param string $regex An optional regular expression to match on field names + * + * @return array The array mapped from the given object + * + * @since 1.0 + */ + public static function fromObject($p_obj, $recurse = true, $regex = null) + { + if (is_object($p_obj)) + { + return self::arrayFromObject($p_obj, $recurse, $regex); + } + else + { + return null; + } + } + + /** + * Utility function to map an object or array to an array + * + * @param mixed $item The source object or array + * @param boolean $recurse True to recurse through multi-level objects + * @param string $regex An optional regular expression to match on field names + * + * @return array The array mapped from the given object + * + * @since 1.0 + */ + private static function arrayFromObject($item, $recurse, $regex) + { + if (is_object($item)) + { + $result = array(); + + foreach (get_object_vars($item) as $k => $v) + { + if (!$regex || preg_match($regex, $k)) + { + if ($recurse) + { + $result[$k] = self::arrayFromObject($v, $recurse, $regex); + } + else + { + $result[$k] = $v; + } + } + } + } + elseif (is_array($item)) + { + $result = array(); + + foreach ($item as $k => $v) + { + $result[$k] = self::arrayFromObject($v, $recurse, $regex); + } + } + else + { + $result = $item; + } + + return $result; + } + + /** + * Extracts a column from an array of arrays or objects + * + * @param array $array The source array + * @param string $index The index of the column or name of object property + * + * @return array Column of values from the source array + * + * @since 1.0 + */ + public static function getColumn(array $array, $index) + { + $result = array(); + + foreach ($array as $item) + { + if (is_array($item) && isset($item[$index])) + { + $result[] = $item[$index]; + } + elseif (is_object($item) && isset($item->$index)) + { + $result[] = $item->$index; + } + } + + return $result; + } + + /** + * Utility function to return a value from a named array or a specified default + * + * @param array $array A named array + * @param string $name The key to search for + * @param mixed $default The default value to give if no key found + * @param string $type Return type for the variable (INT, FLOAT, STRING, WORD, BOOLEAN, ARRAY) + * + * @return mixed The value from the source array + * + * @since 1.0 + */ + public static function getValue(array $array, $name, $default = null, $type = '') + { + $result = null; + + if (isset($array[$name])) + { + $result = $array[$name]; + } + + // Handle the default case + if (is_null($result)) + { + $result = $default; + } + + // Handle the type constraint + switch (strtoupper($type)) + { + case 'INT': + case 'INTEGER': + // Only use the first integer value + @preg_match('/-?[0-9]+/', $result, $matches); + $result = @(int) $matches[0]; + break; + + case 'FLOAT': + case 'DOUBLE': + // Only use the first floating point value + @preg_match('/-?[0-9]+(\.[0-9]+)?/', $result, $matches); + $result = @(float) $matches[0]; + break; + + case 'BOOL': + case 'BOOLEAN': + $result = (bool) $result; + break; + + case 'ARRAY': + if (!is_array($result)) + { + $result = array($result); + } + break; + + case 'STRING': + $result = (string) $result; + break; + + case 'WORD': + $result = (string) preg_replace('#\W#', '', $result); + break; + + case 'NONE': + default: + // No casting necessary + break; + } + + return $result; + } + + /** + * Takes an associative array of arrays and inverts the array keys to values using the array values as keys. + * + * Example: + * $input = array( + * 'New' => array('1000', '1500', '1750'), + * 'Used' => array('3000', '4000', '5000', '6000') + * ); + * $output = ArrayHelper::invert($input); + * + * Output would be equal to: + * $output = array( + * '1000' => 'New', + * '1500' => 'New', + * '1750' => 'New', + * '3000' => 'Used', + * '4000' => 'Used', + * '5000' => 'Used', + * '6000' => 'Used' + * ); + * + * @param array $array The source array. + * + * @return array The inverted array. + * + * @since 1.0 + */ + public static function invert(array $array) + { + $return = array(); + + foreach ($array as $base => $values) + { + if (!is_array($values)) + { + continue; + } + + foreach ($values as $key) + { + // If the key isn't scalar then ignore it. + if (is_scalar($key)) + { + $return[$key] = $base; + } + } + } + + return $return; + } + + /** + * Method to determine if an array is an associative array. + * + * @param array $array An array to test. + * + * @return boolean True if the array is an associative array. + * + * @since 1.0 + */ + public static function isAssociative($array) + { + if (is_array($array)) + { + foreach (array_keys($array) as $k => $v) + { + if ($k !== $v) + { + return true; + } + } + } + + return false; + } + + /** + * Pivots an array to create a reverse lookup of an array of scalars, arrays or objects. + * + * @param array $source The source array. + * @param string $key Where the elements of the source array are objects or arrays, the key to pivot on. + * + * @return array An array of arrays pivoted either on the value of the keys, or an individual key of an object or array. + * + * @since 1.0 + */ + public static function pivot(array $source, $key = null) + { + $result = array(); + $counter = array(); + + foreach ($source as $index => $value) + { + // Determine the name of the pivot key, and its value. + if (is_array($value)) + { + // If the key does not exist, ignore it. + if (!isset($value[$key])) + { + continue; + } + + $resultKey = $value[$key]; + $resultValue = $source[$index]; + } + elseif (is_object($value)) + { + // If the key does not exist, ignore it. + if (!isset($value->$key)) + { + continue; + } + + $resultKey = $value->$key; + $resultValue = $source[$index]; + } + else + { + // Just a scalar value. + $resultKey = $value; + $resultValue = $index; + } + + // The counter tracks how many times a key has been used. + if (empty($counter[$resultKey])) + { + // The first time around we just assign the value to the key. + $result[$resultKey] = $resultValue; + $counter[$resultKey] = 1; + } + elseif ($counter[$resultKey] == 1) + { + // If there is a second time, we convert the value into an array. + $result[$resultKey] = array( + $result[$resultKey], + $resultValue, + ); + $counter[$resultKey]++; + } + else + { + // After the second time, no need to track any more. Just append to the existing array. + $result[$resultKey][] = $resultValue; + } + } + + unset($counter); + + return $result; + } + + /** + * Utility function to sort an array of objects on a given field + * + * @param array $a An array of objects + * @param mixed $k The key (string) or a array of key to sort on + * @param mixed $direction Direction (integer) or an array of direction to sort in [1 = Ascending] [-1 = Descending] + * @param mixed $caseSensitive Boolean or array of booleans to let sort occur case sensitive or insensitive + * @param mixed $locale Boolean or array of booleans to let sort occur using the locale language or not + * + * @return array The sorted array of objects + * + * @since 1.0 + */ + public static function sortObjects(array $a, $k, $direction = 1, $caseSensitive = true, $locale = false) + { + if (!is_array($locale) || !is_array($locale[0])) + { + $locale = array($locale); + } + + $sortCase = (array) $caseSensitive; + $sortDirection = (array) $direction; + $key = (array) $k; + $sortLocale = $locale; + + usort( + $a, function($a, $b) use($sortCase, $sortDirection, $key, $sortLocale) + { + for ($i = 0, $count = count($key); $i < $count; $i++) + { + if (isset($sortDirection[$i])) + { + $direction = $sortDirection[$i]; + } + + if (isset($sortCase[$i])) + { + $caseSensitive = $sortCase[$i]; + } + + if (isset($sortLocale[$i])) + { + $locale = $sortLocale[$i]; + } + + $va = $a->$key[$i]; + $vb = $b->$key[$i]; + + if ((is_bool($va) || is_numeric($va)) && (is_bool($vb) || is_numeric($vb))) + { + $cmp = $va - $vb; + } + elseif ($caseSensitive) + { + $cmp = String::strcmp($va, $vb, $locale); + } + else + { + $cmp = String::strcasecmp($va, $vb, $locale); + } + + if ($cmp > 0) + { + return $direction; + } + + if ($cmp < 0) + { + return -$direction; + } + } + + return 0; + } + ); + + return $a; + } + + /** + * Multidimensional array safe unique test + * + * @param array $array The array to make unique. + * + * @return array + * + * @see http://php.net/manual/en/function.array-unique.php + * @since 1.0 + */ + public static function arrayUnique(array $array) + { + $array = array_map('serialize', $array); + $array = array_unique($array); + $array = array_map('unserialize', $array); + + return $array; + } + + /** + * An improved array_search that allows for partial matching + * of strings values in associative arrays. + * + * @param string $needle The text to search for within the array. + * @param array $haystack Associative array to search in to find $needle. + * @param boolean $caseSensitive True to search case sensitive, false otherwise. + * + * @return mixed Returns the matching array $key if found, otherwise false. + * + * @since 1.0 + */ + public static function arraySearch($needle, array $haystack, $caseSensitive = true) + { + foreach ($haystack as $key => $value) + { + $searchFunc = ($caseSensitive) ? 'strpos' : 'stripos'; + + if ($searchFunc($value, $needle) === 0) + { + return $key; + } + } + + return false; + } +} diff --git a/libraries/phpmailer/phpmailer/.gitignore b/libraries/phpmailer/phpmailer/.gitignore new file mode 100644 index 0000000000000..88d2922477729 --- /dev/null +++ b/libraries/phpmailer/phpmailer/.gitignore @@ -0,0 +1,4 @@ +docs/phpdoc/ +test/message.txt +test/testbootstrap.php +.idea diff --git a/libraries/phpmailer/phpmailer/.travis.yml b/libraries/phpmailer/phpmailer/.travis.yml new file mode 100644 index 0000000000000..28f0099f96ecd --- /dev/null +++ b/libraries/phpmailer/phpmailer/.travis.yml @@ -0,0 +1,20 @@ +language: php +php: + - 5.5 + - 5.4 + - 5.3 +before_install: + - sudo apt-get update -qq + - sudo apt-get install -y -qq postfix +before_script: + - sudo service postfix stop + - smtp-sink -d "%d.%H.%M.%S" localhost:2500 1000 & + - cd test + - cp testbootstrap-dist.php testbootstrap.php + - chmod +x fakesendmail.sh + - sudo mkdir -p /var/qmail/bin + - sudo cp fakesendmail.sh /var/qmail/bin/sendmail + - sudo cp fakesendmail.sh /usr/sbin/sendmail + - echo 'sendmail_path = "/usr/sbin/sendmail -t -i "' | sudo tee "/home/travis/.phpenv/versions/`php -i|grep "PHP Version"|head -n 1|grep -o -P '\d+\.\d+\.\d+.*'`/etc/conf.d/sendmail.ini" +script: + - phpunit phpmailerTest diff --git a/libraries/phpmailer/phpmailer/LICENSE b/libraries/phpmailer/phpmailer/LICENSE new file mode 100644 index 0000000000000..8e0763d1c21e7 --- /dev/null +++ b/libraries/phpmailer/phpmailer/LICENSE @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/libraries/phpmailer/phpmailer/PHPMailerAutoload.php b/libraries/phpmailer/phpmailer/PHPMailerAutoload.php new file mode 100644 index 0000000000000..46db5bd0bef54 --- /dev/null +++ b/libraries/phpmailer/phpmailer/PHPMailerAutoload.php @@ -0,0 +1,33 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +/** + * PHPMailer SPL autoloader. + * @param string $classname The name of the class to load + */ +function PHPMailerAutoload($classname) +{ + //Can't use __DIR__ as it's only in PHP 5.3+ + $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php'; + if (is_readable($filename)) { + require $filename; + } +} + +spl_autoload_register('PHPMailerAutoload'); diff --git a/libraries/phpmailer/phpmailer/README.md b/libraries/phpmailer/phpmailer/README.md new file mode 100644 index 0000000000000..de76a7679bf24 --- /dev/null +++ b/libraries/phpmailer/phpmailer/README.md @@ -0,0 +1,134 @@ +# PHPMailer - A full-featured email creation and transfer class for PHP + +Build status: [![Build Status](https://travis-ci.org/Synchro/PHPMailer.png)](https://travis-ci.org/Synchro/PHPMailer) + +## Class Features + +- Probably the world's most popular code for sending email from PHP! +- Used by many open-source projects: Drupal, SugarCRM, Yii, Joomla! and many more +- Integrated SMTP support - send without a local mail server +- send emails with multiple TOs, CCs, BCCs and REPLY-TOs +- Multipart/alternative emails for mail clients that do not read HTML email +- Support for 8bit, base64, binary, and quoted-printable encoding +- SMTP authentication with LOGIN, PLAIN, NTLM and CRAM-MD5 mechanisms +- Native language support +- Compatible with PHP 5.0 and later +- Much more! + +## Why you might need it + +Many PHP developers utilize email in their code. The only PHP function that supports this is the mail() function. However, it does not provide any assistance for making use of popular features such as HTML-based emails and attachments. + +Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules - the vast majority of code that you'll find online that uses the mail() function directly is just plain wrong! +*Please* don't be tempted to do it yourself - if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own - try SwiftMailer, Zend_Mail, eZcomponents etc. + +The PHP mail() function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD and OS X platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server. + +## License + +This software is licenced under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html). Please read LICENSE for information on the +software availability and distribution. + +## Installation + +PHPMailer is available via [Composer/Packagist](https://packagist.org/packages/phpmailer/phpmailer). Alternatively, just copy the contents of the PHPMailer folder into somewhere that's in your PHP `include_path` setting. If you don't speak git or just want a tarball, click the 'zip' button at the top of the page in GitHub. + + +## A Simple Example + +```php +isSMTP(); // Set mailer to use SMTP +$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server +$mail->SMTPAuth = true; // Enable SMTP authentication +$mail->Username = 'jswan'; // SMTP username +$mail->Password = 'secret'; // SMTP password +$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted + +$mail->From = 'from@example.com'; +$mail->FromName = 'Mailer'; +$mail->addAddress('josh@example.net', 'Josh Adams'); // Add a recipient +$mail->addAddress('ellen@example.com'); // Name is optional +$mail->addReplyTo('info@example.com', 'Information'); +$mail->addCC('cc@example.com'); +$mail->addBCC('bcc@example.com'); + +$mail->WordWrap = 50; // Set word wrap to 50 characters +$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments +$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name +$mail->isHTML(true); // Set email format to HTML + +$mail->Subject = 'Here is the subject'; +$mail->Body = 'This is the HTML message body in bold!'; +$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; + +if(!$mail->send()) { + echo 'Message could not be sent.'; + echo 'Mailer Error: ' . $mail->ErrorInfo; + exit; +} + +echo 'Message has been sent'; +``` + +You'll find plenty more to play with in the `examples` folder. + +That's it. You should now be ready to use PHPMailer! + +## Localization +PHPMailer defaults to English, but in the `languages` folder you'll find numerous translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this: + +```php +// To load the French version +$mail->setLanguage('fr', '/optional/path/to/language/directory/'); +``` + +## Documentation + +You'll find some basic user-level docs in the docs folder, and you can generate complete API-level documentation using the `generatedocs.sh` shell script in the docs folder, though you'll need to install [PHPDocumentor](http://www.phpdoc.org) first. + +## Tests + +You'll find a PHPUnit test script in the `test` folder. + +Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.png)](https://travis-ci.org/PHPMailer/PHPMailer) + +If this isn't passing, is there something you can do to help? + +## Contributing + +Please submit bug reports, suggestions and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues). + +We're particularly interested in fixing edge-cases, expanding test coverage and updating translations. + +With the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone: + +`git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git` + +Please *don't* use the SourceForge or Google Code projects any more. + +## Changelog + +See [changelog](changelog.md). + +## History +- PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](http://sourceforge.net/projects/phpmailer/). +- Marcus Bointon (coolbru on SF) and Andy Prevost (codeworxtech) took over the project in 2004. +- Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski. +- Marcus created his fork on [GitHub](https://github.com/Synchro/PHPMailer). +- Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer. +- PHPMailer moves to the [PHPMailer organisation](https://github.com/PHPMailer) on GitHub. + +### What's changed since moving from SourceForge? +- Official successor to the SourceForge and Google Code projects. +- Test suite. +- Continuous integration with Travis-CI. +- Composer support. +- Rolling releases. +- Additional languages and language strings. +- CRAM-MD5 authentication support. +- Preserves full repo history of authors, commits and branches from the original SourceForge project. diff --git a/libraries/phpmailer/phpmailer/changelog.md b/libraries/phpmailer/phpmailer/changelog.md new file mode 100644 index 0000000000000..4caa7778a587e --- /dev/null +++ b/libraries/phpmailer/phpmailer/changelog.md @@ -0,0 +1,540 @@ +# ChangeLog + +## Version 5.2.7 (September 12th 2013) +* Add Ukranian translation from @Krezalis +* Support for do_verp +* Fix bug in CRAM-MD5 AUTH +* Propagate Debugoutput option to SMTP class (@Reblutus) +* Determine MIME type of attachments automatically +* Add cross-platform, multibyte-safe pathinfo replacement (with tests) and use it +* Add a new 'html' Debugoutput type +* Clean up SMTP debug output, remove embedded HTML +* Some small changes in header formatting to improve IETF msglint test results +* Update test_script to use some recently changed features, rename to code_generator +* Generated code actually works! +* Update SyntaxHighlighter +* Major overhaul and cleanup of example code +* New PHPMailer graphic +* msgHTML now uses RFC2392-compliant content ids +* Add line break normalization function and use it in msgHTML +* Don't set unnecessary reply-to addresses +* Make fakesendmail.sh a bit cleaner and safer +* Set a content-transfer-encoding on multiparts (fixes msglint error) +* Fix cid generation in msgHTML (Thanks to @digitalthought) +* Fix handling of multiple SMTP servers (Thanks to @NanoCaiordo) +* SMTP->connect() now supports stream context options (Thanks to @stanislavdavid) +* Add support for iCal event alternatives (Thanks to @reblutus) +* Update to Polish language file (Thanks to Krzysztof Kowalewski) +* Update to Norwegian language file (Thanks to @datagutten) +* Update to Hungarian language file (Thanks to @dominicus-75) +* Add Persian/Farsi translation from @jaii +* Make SMTPDebug property type match type in SMTP class +* Add unit tests for DKIM +* Major refactor of SMTP class +* Reformat to PSR-2 coding standard +* Introduce autoloader +* Allow overriding of SMTP class +* Overhaul of PHPDocs +* Fix broken Q-encoding +* Czech language update (Thanks to @nemelu) +* Removal of excess blank lines in messages +* Added fake POP server and unit tests for POP-before-SMTP + +## Version 5.2.6 (April 11th 2013) +* Reflect move to PHPMailer GitHub organisation at https://github.com/PHPMailer/PHPMailer +* Fix unbumped version numbers +* Update packagist.org with new location +* Clean up Changelog + +## Version 5.2.5 (April 6th 2013) +* First official release after move from Google Code +* Fixes for qmail when sending via mail() +* Merge in changes from Google code 5.2.4 release +* Minor coding standards cleanup in SMTP class +* Improved unit tests, now tests S/MIME signing +* Travis-CI support on GitHub, runs tests with fake SMTP server + +## Version 5.2.4 (February 19, 2013) +* Fix tag and version bug. +* un-deprecate isSMTP(), isMail(), IsSendmail() and isQmail(). +* Numerous translation updates + +## Version 5.2.3 (February 8, 2013) +* Fix issue with older PCREs and ValidateAddress() (Bugz: 124) +* Add CRAM-MD5 authentication, thanks to Elijah madden, https://github.com/okonomiyaki3000 +* Replacement of obsolete Quoted-Printable encoder with a much better implementation +* Composer package definition +* New language added: Hebrew + +## Version 5.2.2 (December 3, 2012) +* Some fixes and syncs from https://github.com/Synchro/PHPMailer +* Add Slovak translation, thanks to Michal Tinka + +## Version 5.2.2-rc2 (November 6, 2012) +* Fix SMTP server rotation (Bugz: 118) +* Allow override of autogen'ed 'Date' header (for Drupal's + og_mailinglist module) +* No whitespace after '-f' option (Bugz: 116) +* Work around potential warning (Bugz: 114) + +## Version 5.2.2-rc1 (September 28, 2012) +* Header encoding works with long lines (Bugz: 93) +* Turkish language update (Bugz: 94) +* undefined $pattern in EncodeQ bug squashed (Bugz: 98) +* use of mail() in safe_mode now works (Bugz: 96) +* ValidateAddress() now 'public static' so people can override the + default and use their own validation scheme. +* ValidateAddress() no longer uses broken FILTER_VALIDATE_EMAIL +* Added in AUTH PLAIN SMTP authentication + +## Version 5.2.2-beta2 (August 17, 2012) +* Fixed Postfix VERP support (Bugz: 92) +* Allow action_function callbacks to pass/use + the From address (passed as final param) +* Prevent inf look for get_lines() (Bugz: 77) +* New public var ($UseSendmailOptions). Only pass sendmail() + options iff we really are using sendmail or something sendmail + compatible. (Bugz: 75) +* default setting for LE returned to "\n" due to popular demand. + +## Version 5.2.2-beta1 (July 13, 2012) +* Expose PreSend() and PostSend() as public methods to allow + for more control if serializing message sending. +* GetSentMIMEMessage() only constructs the message copy when + needed. Save memory. +* Only pass params to mail() if the underlying MTA is + "sendmail" (as defined as "having the string sendmail + in its pathname") [#69] +* Attachments now work with Amazon SES and others [Bugz#70] +* Debug output now sent to stdout (via echo) or error_log [Bugz#5] +* New var: Debugoutput (for above) [Bugz#5] +* SMTP reads now Timeout aware (new var: Timeout=15) [Bugz#71] +* SMTP reads now can have a Timelimit associated with them + (new var: Timelimit=30)[Bugz#71] +* Fix quoting issue associated with charsets +* default setting for LE is now RFC compliant: "\r\n" +* Return-Path can now be user defined (new var: ReturnPath) + (the default is "" which implies no change from previous + behavior, which was to use either From or Sender) [Bugz#46] +* X-Mailer header can now be disabled (by setting to a + whitespace string, eg " ") [Bugz#66] +* Bugz closed: #68, #60, #42, #43, #59, #55, #66, #48, #49, + #52, #31, #41, #5. #70, #69 + +## Version 5.2.1 (January 16, 2012) +* Closed several bugs#5 +* Performance improvements +* MsgHTML() now returns the message as required. +* New method: GetSentMIMEMessage() (returns full copy of sent message) + +## Version 5.2 (July 19, 2011) +* protected MIME body and header +* better DKIM DNS Resource Record support +* better aly handling +* htmlfilter class added to extras +* moved to Apache Extras + +## Version 5.1 (October 20, 2009) +* fixed filename issue with AddStringAttachment (thanks to Tony) +* fixed "SingleTo" property, now works with Senmail, Qmail, and SMTP in + addition to PHP mail() +* added DKIM digital signing functionality, new properties: + - DKIM_domain (sets the domain name) + - DKIM_private (holds DKIM private key) + - DKIM_passphrase (holds your DKIM passphrase) + - DKIM_selector (holds the DKIM "selector") + - DKIM_identity (holds the identifying email address) +* added callback function support + - callback function parameters include: + result, to, cc, bcc, subject and body + - see the test/test_callback.php file for usage. +* added "auto" identity functionality + - can automatically add: + - Return-path (if Sender not set) + - Reply-To (if ReplyTo not set) + - can be disabled: + - $mail->SetFrom('yourname@yourdomain.com','First Last',false); + - or by adding the $mail->Sender and/or $mail->ReplyTo properties + +Note: "auto" identity added to help with emails ending up in spam or junk boxes because of missing headers + +## Version 5.0.2 (May 24, 2009) +* Fix for missing attachments when inline graphics are present +* Fix for missing Cc in header when using SMTP (mail was sent, + but not displayed in header -- Cc receiver only saw email To: + line and no Cc line, but did get the email (To receiver + saw same) + +## Version 5.0.1 (April 05, 2009) +* Temporary fix for missing attachments + +## Version 5.0.0 (April 02, 2009) +With the release of this version, we are initiating a new version numbering +system to differentiate from the PHP4 version of PHPMailer. +Most notable in this release is fully object oriented code. + +### class.smtp.php: +* Refactored class.smtp.php to support new exception handling +* code size reduced from 29.2 Kb to 25.6 Kb +* Removed unnecessary functions from class.smtp.php: + - public function Expand($name) { + - public function Help($keyword="") { + - public function Noop() { + - public function Send($from) { + - public function SendOrMail($from) { + - public function Verify($name) { + +### class.phpmailer.php: +* Refactored class.phpmailer.php with new exception handling +* Changed processing functionality of Sendmail and Qmail so they cannot be + inadvertently used +* removed getFile() function, just became a simple wrapper for + file_get_contents() +* added check for PHP version (will gracefully exit if not at least PHP 5.0) +* enhanced code to check if an attachment source is the same as an embedded or + inline graphic source to eliminate duplicate attachments + +### New /test_script +We have written a test script you can use to test the script as part of your +installation. Once you press submit, the test script will send a multi-mime +email with either the message you type in or an HTML email with an inline +graphic. Two attachments are included in the email (one of the attachments +is also the inline graphic so you can see that only one copy of the graphic +is sent in the email). The test script will also display the functional +script that you can copy/paste to your editor to duplicate the functionality. + +### New examples +All new examples in both basic and advanced modes. Advanced examples show + Exception handling. + +### PHPDocumentator (phpdocs) documentation for PHPMailer version 5.0.0 +All new documentation + +## Version 2.3 (November 06, 2008) +* added Arabic language (many thanks to Bahjat Al Mostafa) +* removed English language from language files and made it a default within + class.phpmailer.php - if no language is found, it will default to use + the english language translation +* fixed public/private declarations +* corrected line 1728, $basedir to $directory +* added $sign_cert_file to avoid improper duplicate use of $sign_key_file +* corrected $this->Hello on line 612 to $this->Helo +* changed default of $LE to "\r\n" to comply with RFC 2822. Can be set by the user + if default is not acceptable +* removed trim() from return results in EncodeQP +* /test and three files it contained are removed from version 2.3 +* fixed phpunit.php for compliance with PHP5 +* changed $this->AltBody = $textMsg; to $this->AltBody = html_entity_decode($textMsg); +* We have removed the /phpdoc from the downloads. All documentation is now on + the http://phpmailer.codeworxtech.com website. + +## Version 2.2.1 () July 19 2008 +* fixed line 1092 in class.smtp.php (my apologies, error on my part) + +## Version 2.2 () July 15 2008 +* Fixed redirect issue (display of UTF-8 in thank you redirect) +* fixed error in getResponse function declaration (class.pop3.php) +* PHPMailer now PHP6 compliant +* fixed line 1092 in class.smtp.php (endless loop from missing = sign) + +## Version 2.1 (Wed, June 04 2008) +NOTE: WE HAVE A NEW LANGUAGE VARIABLE FOR DIGITALLY SIGNED S/MIME EMAILS. IF YOU CAN HELP WITH LANGUAGES OTHER THAN ENGLISH AND SPANISH, IT WOULD BE APPRECIATED. + +* added S/MIME functionality (ability to digitally sign emails) + BIG THANKS TO "sergiocambra" for posting this patch back in November 2007. + The "Signed Emails" functionality adds the Sign method to pass the private key + filename and the password to read it, and then email will be sent with + content-type multipart/signed and with the digital signature attached. +* fully compatible with E_STRICT error level + - Please note: + In about half the test environments this development version was subjected + to, an error was thrown for the date() functions used (line 1565 and 1569). + This is NOT a PHPMailer error, it is the result of an incorrectly configured + PHP5 installation. The fix is to modify your 'php.ini' file and include the + date.timezone = America/New York + directive, to your own server timezone + - If you do get this error, and are unable to access your php.ini file: + In your PHP script, add + `date_default_timezone_set('America/Toronto');` + - do not try to use + `$myVar = date_default_timezone_get();` + as a test, it will throw an error. +* added ability to define path (mainly for embedded images) + function `MsgHTML($message,$basedir='')` ... where: + `$basedir` is the fully qualified path +* fixed `MsgHTML()` function: + - Embedded Images where images are specified by `://` will not be altered or embedded +* fixed the return value of SMTP exit code ( pclose ) +* addressed issue of multibyte characters in subject line and truncating +* added ability to have user specified Message ID + (default is still that PHPMailer create a unique Message ID) +* corrected unidentified message type to 'application/octet-stream' +* fixed chunk_split() multibyte issue (thanks to Colin Brown, et al). +* added check for added attachments +* enhanced conversion of HTML to text in MsgHTML (thanks to "brunny") + +## Version 2.1.0beta2 (Sun, Dec 02 2007) +* implemented updated EncodeQP (thanks to coolbru, aka Marcus Bointon) +* finished all testing, all known bugs corrected, enhancements tested + +Note: will NOT work with PHP4. + +Please note, this is BETA software **DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS; INTENDED STRICTLY FOR TESTING** + +## Version 2.1.0beta1 +Please note, this is BETA software +** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS + INTENDED STRICTLY FOR TESTING + +## Version 2.0.0 rc2 (Fri, Nov 16 2007), interim release +* implements new property to control VERP in class.smtp.php + example (requires instantiating class.smtp.php): + $mail->do_verp = true; +* POP-before-SMTP functionality included, thanks to Richard Davey + (see class.pop3.php & pop3_before_smtp_test.php for examples) +* included example showing how to use PHPMailer with GMAIL +* fixed the missing Cc in SendMail() and Mail() + +****************** +A note on sending bulk emails: + +If the email you are sending is not personalized, consider using the +"undisclosed-recipient:;" strategy. That is, put all of your recipients +in the Bcc field and set the To field to "undisclosed-recipients:;". +It's a lot faster (only one send) and saves quite a bit on resources. +Contrary to some opinions, this will not get you listed in spam engines - +it's a legitimate way for you to send emails. + +A partial example for use with PHPMailer: + +``` +$mail->AddAddress("undisclosed-recipients:;"); +$mail->AddBCC("email1@anydomain.com,email2@anyotherdomain.com,email3@anyalternatedomain.com"); +``` + +Many email service providers restrict the number of emails that can be sent +in any given time period. Often that is between 50 - 60 emails maximum +per hour or per send session. + +If that's the case, then break up your Bcc lists into chunks that are one +less than your limit, and put a pause in your script. +******************* + +## Version 2.0.0 rc1 (Thu, Nov 08 2007), interim release +* dramatically simplified using inline graphics ... it's fully automated and requires no user input +* added automatic document type detection for attachments and pictures +* added MsgHTML() function to replace Body tag for HTML emails +* fixed the SendMail security issues (input validation vulnerability) +* enhanced the AddAddresses functionality so that the "Name" portion is used in the email address +* removed the need to use the AltBody method (set from the HTML, or default text used) +* set the PHP Mail() function as the default (still support SendMail, SMTP Mail) +* removed the need to set the IsHTML property (set automatically) +* added Estonian language file by Indrek Päri +* added header injection patch +* added "set" method to permit users to create their own pseudo-properties like 'X-Headers', etc. + example of use: + +``` +$mail->set('X-Priority', '3'); +$mail->set('X-MSMail-Priority', 'Normal'); +``` + +* fixed warning message in SMTP get_lines method +* added TLS/SSL SMTP support. Example of use: + +``` +$mail = new PHPMailer(); +$mail->Mailer = "smtp"; +$mail->Host = "smtp.example.com"; +$mail->SMTPSecure = "tls"; // option +//$mail->SMTPSecure = "ssl"; // option +... +$mail->Send(); +``` + +* PHPMailer has been tested with PHP4 (4.4.7) and PHP5 (5.2.7) +* Works with PHP installed as a module or as CGI-PHP +NOTE: will NOT work with PHP5 in E_STRICT error mode + +## Version 1.73 (Sun, Jun 10 2005) +* Fixed denial of service bug: http://www.cybsec.com/vuln/PHPMailer-DOS.pdf +* Now has a total of 20 translations +* Fixed alt attachments bug: http://tinyurl.com/98u9k + +## Version 1.72 (Wed, May 25 2004) +* Added Dutch, Swedish, Czech, Norwegian, and Turkish translations. +* Received: Removed this method because spam filter programs like + SpamAssassin reject this header. +* Fixed error count bug. +* SetLanguage default is now "language/". +* Fixed magic_quotes_runtime bug. + +## Version 1.71 (Tue, Jul 28 2003) +* Made several speed enhancements +* Added German and Italian translation files +* Fixed HELO/AUTH bugs on keep-alive connects +* Now provides an error message if language file does not load +* Fixed attachment EOL bug +* Updated some unclear documentation +* Added additional tests and improved others + +## Version 1.70 (Mon, Jun 20 2003) +* Added SMTP keep-alive support +* Added IsError method for error detection +* Added error message translation support (SetLanguage) +* Refactored many methods to increase library performance +* Hello now sends the newer EHLO message before HELO as per RFC 2821 +* Removed the boundary class and replaced it with GetBoundary +* Removed queue support methods +* New $Hostname variable +* New Message-ID header +* Received header reformat +* Helo variable default changed to $Hostname +* Removed extra spaces in Content-Type definition (#667182) +* Return-Path should be set to Sender when set +* Adds Q or B encoding to headers when necessary +* quoted-encoding should now encode NULs \000 +* Fixed encoding of body/AltBody (#553370) +* Adds "To: undisclosed-recipients:;" when all recipients are hidden (BCC) +* Multiple bug fixes + +## Version 1.65 (Fri, Aug 09 2002) +* Fixed non-visible attachment bug (#585097) for Outlook +* SMTP connections are now closed after each transaction +* Fixed SMTP::Expand return value +* Converted SMTP class documentation to phpDocumentor format + +## Version 1.62 (Wed, Jun 26 2002) +* Fixed multi-attach bug +* Set proper word wrapping +* Reduced memory use with attachments +* Added more debugging +* Changed documentation to phpDocumentor format + +## Version 1.60 (Sat, Mar 30 2002) +* Sendmail pipe and address patch (Christian Holtje) +* Added embedded image and read confirmation support (A. Ognio) +* Added unit tests +* Added SMTP timeout support (*nix only) +* Added possibly temporary PluginDir variable for SMTP class +* Added LE message line ending variable +* Refactored boundary and attachment code +* Eliminated SMTP class warnings +* Added SendToQueue method for future queuing support + +## Version 1.54 (Wed, Dec 19 2001) +* Add some queuing support code +* Fixed a pesky multi/alt bug +* Messages are no longer forced to have "To" addresses + +## Version 1.50 (Thu, Nov 08 2001) +* Fix extra lines when not using SMTP mailer +* Set WordWrap variable to int with a zero default + +## Version 1.47 (Tue, Oct 16 2001) +* Fixed Received header code format +* Fixed AltBody order error +* Fixed alternate port warning + +## Version 1.45 (Tue, Sep 25 2001) +* Added enhanced SMTP debug support +* Added support for multiple ports on SMTP +* Added Received header for tracing +* Fixed AddStringAttachment encoding +* Fixed possible header name quote bug +* Fixed wordwrap() trim bug +* Couple other small bug fixes + +## Version 1.41 (Wed, Aug 22 2001) +* Fixed AltBody bug w/o attachments +* Fixed rfc_date() for certain mail servers + +## Version 1.40 (Sun, Aug 12 2001) +* Added multipart/alternative support (AltBody) +* Documentation update +* Fixed bug in Mercury MTA + +## Version 1.29 (Fri, Aug 03 2001) +* Added AddStringAttachment() method +* Added SMTP authentication support + +## Version 1.28 (Mon, Jul 30 2001) +* Fixed a typo in SMTP class +* Fixed header issue with Imail (win32) SMTP server +* Made fopen() calls for attachments use "rb" to fix win32 error + +## Version 1.25 (Mon, Jul 02 2001) +* Added RFC 822 date fix (Patrice) +* Added improved error handling by adding a $ErrorInfo variable +* Removed MailerDebug variable (obsolete with new error handler) + +## Version 1.20 (Mon, Jun 25 2001) +* Added quoted-printable encoding (Patrice) +* Set Version as public and removed PrintVersion() +* Changed phpdoc to only display public variables and methods + +## Version 1.19 (Thu, Jun 21 2001) +* Fixed MS Mail header bug +* Added fix for Bcc problem with mail(). *Does not work on Win32* + (See PHP bug report: http://www.php.net/bugs.php?id=11616) +* mail() no longer passes a fifth parameter when not needed + +## Version 1.15 (Fri, Jun 15 2001) +Note: these changes contributed by Patrice Fournier +* Changed all remaining \n to \r\n +* Bcc: header no longer writen to message except + when sent directly to sendmail +* Added a small message to non-MIME compliant mail reader +* Added Sender variable to change the Sender email + used in -f for sendmail/mail and in 'MAIL FROM' for smtp mode +* Changed boundary setting to a place it will be set only once +* Removed transfer encoding for whole message when using multipart +* Message body now uses Encoding in multipart messages +* Can set encoding and type to attachments 7bit, 8bit + and binary attachment are sent as is, base64 are encoded +* Can set Encoding to base64 to send 8 bits body + through 7 bits servers + +## Version 1.10 (Tue, Jun 12 2001) +* Fixed win32 mail header bug (printed out headers in message body) + +## Version 1.09 (Fri, Jun 08 2001) +* Changed date header to work with Netscape mail programs +* Altered phpdoc documentation + +## Version 1.08 (Tue, Jun 05 2001) +* Added enhanced error-checking +* Added phpdoc documentation to source + +## Version 1.06 (Fri, Jun 01 2001) +* Added optional name for file attachments + +## Version 1.05 (Tue, May 29 2001) +* Code cleanup +* Eliminated sendmail header warning message +* Fixed possible SMTP error + +## Version 1.03 (Thu, May 24 2001) +* Fixed problem where qmail sends out duplicate messages + +## Version 1.02 (Wed, May 23 2001) +* Added multiple recipient and attachment Clear* methods +* Added Sendmail public variable +* Fixed problem with loading SMTP library multiple times + +## Version 0.98 (Tue, May 22 2001) +* Fixed problem with redundant mail hosts sending out multiple messages +* Added additional error handler code +* Added AddCustomHeader() function +* Added support for Microsoft mail client headers (affects priority) +* Fixed small bug with Mailer variable +* Added PrintVersion() function + +## Version 0.92 (Tue, May 15 2001) +* Changed file names to class.phpmailer.php and class.smtp.php to match + current PHP class trend. +* Fixed problem where body not being printed when a message is attached +* Several small bug fixes + +## Version 0.90 (Tue, April 17 2001) +* Initial public release diff --git a/libraries/phpmailer/phpmailer/class.phpmailer.php b/libraries/phpmailer/phpmailer/class.phpmailer.php new file mode 100644 index 0000000000000..fe37a93bf89e5 --- /dev/null +++ b/libraries/phpmailer/phpmailer/class.phpmailer.php @@ -0,0 +1,3268 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +if (version_compare(PHP_VERSION, '5.0.0', '<')) { + exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n"); +} + +/** + * PHPMailer - PHP email creation and transport class. + * PHP Version 5.0.0 + * @package PHPMailer + * @author Marcus Bointon (coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + */ +class PHPMailer +{ + /** + * The PHPMailer Version number. + * @type string + */ + public $Version = '5.2.7'; + + /** + * Email priority. + * Options: 1 = High, 3 = Normal, 5 = low. + * @type int + */ + public $Priority = 3; + + /** + * The character set of the message. + * @type string + */ + public $CharSet = 'iso-8859-1'; + + /** + * The MIME Content-type of the message. + * @type string + */ + public $ContentType = 'text/plain'; + + /** + * The message encoding. + * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". + * @type string + */ + public $Encoding = '8bit'; + + /** + * Holds the most recent mailer error message. + * @type string + */ + public $ErrorInfo = ''; + + /** + * The From email address for the message. + * @type string + */ + public $From = 'root@localhost'; + + /** + * The From name of the message. + * @type string + */ + public $FromName = 'Root User'; + + /** + * The Sender email (Return-Path) of the message. + * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. + * @type string + */ + public $Sender = ''; + + /** + * The Return-Path of the message. + * If empty, it will be set to either From or Sender. + * @type string + */ + public $ReturnPath = ''; + + /** + * The Subject of the message. + * @type string + */ + public $Subject = ''; + + /** + * An HTML or plain text message body. + * If HTML then call isHTML(true). + * @type string + */ + public $Body = ''; + + /** + * The plain-text message body. + * This body can be read by mail clients that do not have HTML email + * capability such as mutt & Eudora. + * Clients that can read HTML will view the normal Body. + * @type string + */ + public $AltBody = ''; + + /** + * An iCal message part body. + * Only supported in simple alt or alt_inline message types + * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator + * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ + * @link http://kigkonsult.se/iCalcreator/ + * @type string + */ + public $Ical = ''; + + /** + * The complete compiled MIME message body. + * @access protected + * @type string + */ + protected $MIMEBody = ''; + + /** + * The complete compiled MIME message headers. + * @type string + * @access protected + */ + protected $MIMEHeader = ''; + + /** + * Extra headers that createHeader() doesn't fold in. + * @type string + * @access protected + */ + protected $mailHeader = ''; + + /** + * Word-wrap the message body to this number of chars. + * @type int + */ + public $WordWrap = 0; + + /** + * Which method to use to send mail. + * Options: "mail", "sendmail", or "smtp". + * @type string + */ + public $Mailer = 'mail'; + + /** + * The path to the sendmail program. + * @type string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Whether mail() uses a fully sendmail-compatible MTA. + * One which supports sendmail's "-oi -f" options. + * @type bool + */ + public $UseSendmailOptions = true; + + /** + * Path to PHPMailer plugins. + * Useful if the SMTP class is not in the PHP include path. + * @type string + * @deprecated Should not be needed now there is an autoloader. + */ + public $PluginDir = ''; + + /** + * The email address that a reading confirmation should be sent to. + * @type string + */ + public $ConfirmReadingTo = ''; + + /** + * The hostname to use in Message-Id and Received headers + * and as default HELO string. + * If empty, the value returned + * by SERVER_NAME is used or 'localhost.localdomain'. + * @type string + */ + public $Hostname = ''; + + /** + * An ID to be used in the Message-Id header. + * If empty, a unique id will be generated. + * @type string + */ + public $MessageID = ''; + + /** + * The message Date to be used in the Date header. + * If empty, the current date will be added. + * @type string + */ + public $MessageDate = ''; + + /** + * SMTP hosts. + * Either a single hostname or multiple semicolon-delimited hostnames. + * You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * Hosts will be tried in order. + * @type string + */ + public $Host = 'localhost'; + + /** + * The default SMTP server port. + * @type int + * @Todo Why is this needed when the SMTP class takes care of it? + */ + public $Port = 25; + + /** + * The SMTP HELO of the message. + * Default is $Hostname. + * @type string + * @see PHPMailer::$Hostname + */ + public $Helo = ''; + + /** + * The secure connection prefix. + * Options: "", "ssl" or "tls" + * @type string + */ + public $SMTPSecure = ''; + + /** + * Whether to use SMTP authentication. + * Uses the Username and Password properties. + * @type bool + * @see PHPMailer::$Username + * @see PHPMailer::$Password + */ + public $SMTPAuth = false; + + /** + * SMTP username. + * @type string + */ + public $Username = ''; + + /** + * SMTP password. + * @type string + */ + public $Password = ''; + + /** + * SMTP auth type. + * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5 + * @type string + */ + public $AuthType = ''; + + /** + * SMTP realm. + * Used for NTLM auth + * @type string + */ + public $Realm = ''; + + /** + * SMTP workstation. + * Used for NTLM auth + * @type string + */ + public $Workstation = ''; + + /** + * The SMTP server timeout in seconds. + * @type int + */ + public $Timeout = 10; + + /** + * SMTP class debug output mode. + * Options: 0 = off, 1 = commands, 2 = commands and data + * @type int + * @see SMTP::$do_debug + */ + public $SMTPDebug = 0; + + /** + * The function/method to use for debugging output. + * Options: "echo" or "error_log" + * @type string + * @see SMTP::$Debugoutput + */ + public $Debugoutput = "echo"; + + /** + * Whether to keep SMTP connection open after each message. + * If this is set to true then to close the connection + * requires an explicit call to smtpClose(). + * @type bool + */ + public $SMTPKeepAlive = false; + + /** + * Whether to split multiple to addresses into multiple messages + * or send them all in one message. + * @type bool + */ + public $SingleTo = false; + + /** + * Storage for addresses when SingleTo is enabled. + * @type array + * @todo This should really not be public + */ + public $SingleToArray = array(); + + /** + * Whether to generate VERP addresses on send. + * Only applicable when sending via SMTP. + * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path + * @type bool + */ + public $do_verp = false; + + /** + * Whether to allow sending messages with an empty body. + * @type bool + */ + public $AllowEmpty = false; + + /** + * The default line ending. + * @note The default remains "\n". We force CRLF where we know + * it must be used via self::CRLF. + * @type string + */ + public $LE = "\n"; + + /** + * DKIM selector. + * @type string + */ + public $DKIM_selector = ''; + + /** + * DKIM Identity. + * Usually the email address used as the source of the email + * @type string + */ + public $DKIM_identity = ''; + + /** + * DKIM passphrase. + * Used if your key is encrypted. + * @type string + */ + public $DKIM_passphrase = ''; + + /** + * DKIM signing domain name. + * @example 'example.com' + * @type string + */ + public $DKIM_domain = ''; + + /** + * DKIM private key file path. + * @type string + */ + public $DKIM_private = ''; + + /** + * Callback Action function name. + * + * The function that handles the result of the send email action. + * It is called out by send() for each email sent. + * + * Value can be: + * - 'function_name' for function names + * - 'Class::Method' for static method calls + * - array($object, 'Method') for calling methods on $object + * See http://php.net/is_callable manual page for more details. + * + * Parameters: + * bool $result result of the send action + * string $to email address of the recipient + * string $cc cc email addresses + * string $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * string $from email address of sender + * + * @type string + */ + public $action_function = ''; + + /** + * What to use in the X-Mailer header. + * Options: null for default, whitespace for none, or a string to use + * @type string + */ + public $XMailer = ''; + + /** + * An instance of the SMTP sender class. + * @type SMTP + * @access protected + */ + protected $smtp = null; + + /** + * The array of 'to' addresses. + * @type array + * @access protected + */ + protected $to = array(); + + /** + * The array of 'cc' addresses. + * @type array + * @access protected + */ + protected $cc = array(); + + /** + * The array of 'bcc' addresses. + * @type array + * @access protected + */ + protected $bcc = array(); + + /** + * The array of reply-to names and addresses. + * @type array + * @access protected + */ + protected $ReplyTo = array(); + + /** + * An array of all kinds of addresses. + * Includes all of $to, $cc, $bcc, $replyto + * @type array + * @access protected + */ + protected $all_recipients = array(); + + /** + * The array of attachments. + * @type array + * @access protected + */ + protected $attachment = array(); + + /** + * The array of custom headers. + * @type array + * @access protected + */ + protected $CustomHeader = array(); + + /** + * The most recent Message-ID (including angular brackets). + * @type string + * @access protected + */ + protected $lastMessageID = ''; + + /** + * The message's MIME type. + * @type string + * @access protected + */ + protected $message_type = ''; + + /** + * The array of MIME boundary strings. + * @type array + * @access protected + */ + protected $boundary = array(); + + /** + * The array of available languages. + * @type array + * @access protected + */ + protected $language = array(); + + /** + * The number of errors encountered. + * @type integer + * @access protected + */ + protected $error_count = 0; + + /** + * The S/MIME certificate file path. + * @type string + * @access protected + */ + protected $sign_cert_file = ''; + + /** + * The S/MIME key file path. + * @type string + * @access protected + */ + protected $sign_key_file = ''; + + /** + * The S/MIME password for the key. + * Used only if the key is encrypted. + * @type string + * @access protected + */ + protected $sign_key_pass = ''; + + /** + * Whether to throw exceptions for errors. + * @type bool + * @access protected + */ + protected $exceptions = false; + + /** + * Error severity: message only, continue processing + */ + const STOP_MESSAGE = 0; + + /** + * Error severity: message, likely ok to continue processing + */ + const STOP_CONTINUE = 1; + + /** + * Error severity: message, plus full stop, critical error reached + */ + const STOP_CRITICAL = 2; + + /** + * SMTP RFC standard line ending + */ + const CRLF = "\r\n"; + + /** + * Constructor + * @param bool $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = false) + { + $this->exceptions = ($exceptions == true); + //Make sure our autoloader is loaded + if (!in_array('PHPMailerAutoload', spl_autoload_functions())) { + require 'PHPMailerAutoload.php'; + } + } + + /** + * Destructor. + */ + public function __destruct() + { + if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely + $this->smtpClose(); + } + } + + /** + * Call mail() in a safe_mode-aware fashion. + * Also, unless sendmail_path points to sendmail (or something that + * claims to be sendmail), don't pass params (not a perfect fix, + * but it will do) + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string $params Params + * @access private + * @return bool + */ + private function mailPassthru($to, $subject, $body, $header, $params) + { + if (ini_get('safe_mode') || !($this->UseSendmailOptions)) { + $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header); + } else { + $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header, $params); + } + return $rt; + } + + /** + * Output debugging info via user-defined method. + * Only if debug output is enabled. + * @see PHPMailer::$Debugoutput + * @see PHPMailer::$SMTPDebug + * @param string $str + */ + protected function edebug($str) + { + if (!$this->SMTPDebug) { + return; + } + switch ($this->Debugoutput) { + case 'error_log': + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking display that's HTML-safe + echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet) . "
\n"; + break; + case 'echo': + default: + //Just echoes exactly what was received + echo $str; + } + } + + /** + * Sets message type to HTML or plain. + * @param bool $ishtml True for HTML mode. + * @return void + */ + public function isHTML($ishtml = true) + { + if ($ishtml) { + $this->ContentType = 'text/html'; + } else { + $this->ContentType = 'text/plain'; + } + } + + /** + * Send messages using SMTP. + * @return void + */ + public function isSMTP() + { + $this->Mailer = 'smtp'; + } + + /** + * Send messages using PHP's mail() function. + * @return void + */ + public function isMail() + { + $this->Mailer = 'mail'; + } + + /** + * Send messages using $Sendmail. + * @return void + */ + public function isSendmail() + { + if (!stristr(ini_get('sendmail_path'), 'sendmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + /** + * Send messages using qmail. + * @return void + */ + public function isQmail() + { + if (stristr(ini_get('sendmail_path'), 'qmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + /** + * Add a "To" address. + * @param string $address + * @param string $name + * @return bool true on success, false if address already used + */ + public function addAddress($address, $name = '') + { + return $this->addAnAddress('to', $address, $name); + } + + /** + * Add a "CC" address. + * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return bool true on success, false if address already used + */ + public function addCC($address, $name = '') + { + return $this->addAnAddress('cc', $address, $name); + } + + /** + * Add a "BCC" address. + * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return bool true on success, false if address already used + */ + public function addBCC($address, $name = '') + { + return $this->addAnAddress('bcc', $address, $name); + } + + /** + * Add a "Reply-to" address. + * @param string $address + * @param string $name + * @return bool + */ + public function addReplyTo($address, $name = '') + { + return $this->addAnAddress('Reply-To', $address, $name); + } + + /** + * Add an address to one of the recipient arrays. + * Addresses that have been added already return false, but do not throw exceptions + * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' + * @param string $address The email address to send to + * @param string $name + * @throws phpmailerException + * @return bool true on success, false if address already used or invalid in some way + * @access protected + */ + protected function addAnAddress($kind, $address, $name = '') + { + if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { + $this->setError($this->lang('Invalid recipient array') . ': ' . $kind); + if ($this->exceptions) { + throw new phpmailerException('Invalid recipient array: ' . $kind); + } + $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind); + return false; + } + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!$this->validateAddress($address)) { + $this->setError($this->lang('invalid_address') . ': ' . $address); + if ($this->exceptions) { + throw new phpmailerException($this->lang('invalid_address') . ': ' . $address); + } + $this->edebug($this->lang('invalid_address') . ': ' . $address); + return false; + } + if ($kind != 'Reply-To') { + if (!isset($this->all_recipients[strtolower($address)])) { + array_push($this->$kind, array($address, $name)); + $this->all_recipients[strtolower($address)] = true; + return true; + } + } else { + if (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = array($address, $name); + return true; + } + } + return false; + } + + /** + * Set the From and FromName properties. + * @param string $address + * @param string $name + * @param bool $auto Whether to also set the Sender address, defaults to true + * @throws phpmailerException + * @return bool + */ + public function setFrom($address, $name = '', $auto = true) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!$this->validateAddress($address)) { + $this->setError($this->lang('invalid_address') . ': ' . $address); + if ($this->exceptions) { + throw new phpmailerException($this->lang('invalid_address') . ': ' . $address); + } + $this->edebug($this->lang('invalid_address') . ': ' . $address); + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto) { + if (empty($this->Sender)) { + $this->Sender = $address; + } + } + return true; + } + + /** + * Return the Message-ID header of the last email. + * Technically this is the value from the last time the headers were created, + * but it's also the message ID of the last sent message except in + * pathological cases. + * @return string + */ + public function getLastMessageID() + { + return $this->lastMessageID; + } + + /** + * Check that a string looks like an email address. + * @param string $address The email address to check + * @param string $patternselect A selector for the validation pattern to use : + * 'auto' - pick best one automatically; + * 'pcre8' - use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14; + * 'pcre' - use old PCRE implementation; + * 'php' - use PHP built-in FILTER_VALIDATE_EMAIL; faster, less thorough; + * 'noregex' - super fast, really dumb. + * @return bool + * @static + * @access public + */ + public static function validateAddress($address, $patternselect = 'auto') + { + if ($patternselect == 'auto') { + if (defined( + 'PCRE_VERSION' + ) + ) { //Check this instead of extension_loaded so it works when that function is disabled + if (version_compare(PCRE_VERSION, '8.0') >= 0) { + $patternselect = 'pcre8'; + } else { + $patternselect = 'pcre'; + } + } else { + //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension + if (version_compare(PHP_VERSION, '5.2.0') >= 0) { + $patternselect = 'php'; + } else { + $patternselect = 'noregex'; + } + } + } + switch ($patternselect) { + case 'pcre8': + /** + * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is + * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to + * not allow a@b type valid addresses :( + * @link http://squiloople.com/2009/12/20/email-address-validation/ + * @copyright 2009-2010 Michael Rushton + * Feel free to use and redistribute this code. But please keep this copyright notice. + */ + return (bool)preg_match( + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', + $address + ); + break; + case 'pcre': + //An older regex that doesn't need a recent PCRE + return (bool)preg_match( + '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' . + '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' . + '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' . + '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' . + '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' . + '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' . + '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' . + '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' . + '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', + $address + ); + break; + case 'php': + default: + return (bool)filter_var($address, FILTER_VALIDATE_EMAIL); + break; + case 'noregex': + //No PCRE! Do something _very_ approximate! + //Check the address is 3 chars or longer and contains an @ that's not the first or last char + return (strlen($address) >= 3 + and strpos($address, '@') >= 1 + and strpos($address, '@') != strlen($address) - 1); + break; + } + } + + /** + * Create a message and send it. + * Uses the sending method specified by $Mailer. + * Returns false on error - Use the ErrorInfo variable to view description of the error. + * @throws phpmailerException + * @return bool + */ + public function send() + { + try { + if (!$this->preSend()) { + return false; + } + return $this->postSend(); + } catch (phpmailerException $e) { + $this->mailHeader = ''; + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + return false; + } + } + + /** + * Prepare a message for sending. + * @throws phpmailerException + * @return bool + */ + public function preSend() + { + try { + $this->mailHeader = ""; + if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { + throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL); + } + + // Set whether the message is multipart/alternative + if (!empty($this->AltBody)) { + $this->ContentType = 'multipart/alternative'; + } + + $this->error_count = 0; // reset errors + $this->setMessageType(); + // Refuse to send an empty message unless we are specifically allowing it + if (!$this->AllowEmpty and empty($this->Body)) { + throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL); + } + + $this->MIMEHeader = $this->createHeader(); + $this->MIMEBody = $this->createBody(); + + // To capture the complete message when using mail(), create + // an extra header list which createHeader() doesn't fold in + if ($this->Mailer == 'mail') { + if (count($this->to) > 0) { + $this->mailHeader .= $this->addrAppend("To", $this->to); + } else { + $this->mailHeader .= $this->headerLine("To", "undisclosed-recipients:;"); + } + $this->mailHeader .= $this->headerLine( + 'Subject', + $this->encodeHeader($this->secureHeader(trim($this->Subject))) + ); + } + + // Sign with DKIM if enabled + if (!empty($this->DKIM_domain) + && !empty($this->DKIM_private) + && !empty($this->DKIM_selector) + && !empty($this->DKIM_domain) + && file_exists($this->DKIM_private)) { + $header_dkim = $this->DKIM_Add( + $this->MIMEHeader . $this->mailHeader, + $this->encodeHeader($this->secureHeader($this->Subject)), + $this->MIMEBody + ); + $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF . + str_replace("\r\n", "\n", $header_dkim) . self::CRLF; + } + return true; + + } catch (phpmailerException $e) { + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + return false; + } + } + + /** + * Actually send a message. + * Send the email via the selected mechanism + * @throws phpmailerException + * @return bool + */ + public function postSend() + { + try { + // Choose the mailer and send through it + switch ($this->Mailer) { + case 'sendmail': + return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); + case 'mail': + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + default: + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + } + } catch (phpmailerException $e) { + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + $this->edebug($e->getMessage() . "\n"); + } + return false; + } + + /** + * Send mail using the $Sendmail program. + * @param string $header The message headers + * @param string $body The message body + * @see PHPMailer::$Sendmail + * @throws phpmailerException + * @access protected + * @return bool + */ + protected function sendmailSend($header, $body) + { + if ($this->Sender != '') { + $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); + } else { + $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); + } + if ($this->SingleTo === true) { + foreach ($this->SingleToArray as $val) { + if (!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, "To: " . $val . "\n"); + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + if ($result != 0) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + if (!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + if ($result != 0) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + return true; + } + + /** + * Send mail using the PHP mail() function. + * @param string $header The message headers + * @param string $body The message body + * @link http://www.php.net/manual/en/book.mail.php + * @throws phpmailerException + * @access protected + * @return bool + */ + protected function mailSend($header, $body) + { + $toArr = array(); + foreach ($this->to as $t) { + $toArr[] = $this->addrFormat($t); + } + $to = implode(', ', $toArr); + + if (empty($this->Sender)) { + $params = " "; + } else { + $params = sprintf("-f%s", $this->Sender); + } + if ($this->Sender != '' and !ini_get('safe_mode')) { + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + } + $rt = false; + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $val) { + $rt = $this->mailPassthru($val, $this->Subject, $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + } + } else { + $rt = $this->mailPassthru($to, $this->Subject, $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if (!$rt) { + throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL); + } + return true; + } + + /** + * Get an instance to use for SMTP operations. + * Override this function to load your own SMTP implementation + * @return SMTP + */ + public function getSMTPInstance() + { + if (!is_object($this->smtp)) { + $this->smtp = new SMTP; + } + return $this->smtp; + } + + /** + * Send mail via SMTP. + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * Uses the PHPMailerSMTP class by default. + * @see PHPMailer::getSMTPInstance() to use a different class. + * @param string $header The message headers + * @param string $body The message body + * @throws phpmailerException + * @uses SMTP + * @access protected + * @return bool + */ + protected function smtpSend($header, $body) + { + $bad_rcpt = array(); + + if (!$this->smtpConnect()) { + throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; + if (!$this->smtp->mail($smtp_from)) { + $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); + } + + // Attempt to send attach all recipients + foreach ($this->to as $to) { + if (!$this->smtp->recipient($to[0])) { + $bad_rcpt[] = $to[0]; + $isSent = 0; + } else { + $isSent = 1; + } + $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body, $this->From); + } + foreach ($this->cc as $cc) { + if (!$this->smtp->recipient($cc[0])) { + $bad_rcpt[] = $cc[0]; + $isSent = 0; + } else { + $isSent = 1; + } + $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body, $this->From); + } + foreach ($this->bcc as $bcc) { + if (!$this->smtp->recipient($bcc[0])) { + $bad_rcpt[] = $bcc[0]; + $isSent = 0; + } else { + $isSent = 1; + } + $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body, $this->From); + } + + if (count($bad_rcpt) > 0) { //Create error message for any bad addresses + throw new phpmailerException($this->lang('recipients_failed') . implode(', ', $bad_rcpt)); + } + if (!$this->smtp->data($header . $body)) { + throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL); + } + if ($this->SMTPKeepAlive == true) { + $this->smtp->reset(); + } else { + $this->smtp->quit(); + $this->smtp->close(); + } + return true; + } + + /** + * Initiate a connection to an SMTP server. + * Returns false if the operation failed. + * @param array $options An array of options compatible with stream_context_create() + * @uses SMTP + * @access public + * @throws phpmailerException + * @return bool + */ + public function smtpConnect($options = array()) + { + if (is_null($this->smtp)) { + $this->smtp = $this->getSMTPInstance(); + } + + //Already connected? + if ($this->smtp->connected()) { + return true; + } + + $this->smtp->setTimeout($this->Timeout); + $this->smtp->setDebugLevel($this->SMTPDebug); + $this->smtp->setDebugOutput($this->Debugoutput); + $this->smtp->setVerp($this->do_verp); + $tls = ($this->SMTPSecure == 'tls'); + $ssl = ($this->SMTPSecure == 'ssl'); + $hosts = explode(';', $this->Host); + $lastexception = null; + + foreach ($hosts as $hostentry) { + $hostinfo = array(); + $host = $hostentry; + $port = $this->Port; + if (preg_match( + '/^(.+):([0-9]+)$/', + $hostentry, + $hostinfo + ) + ) { //If $hostentry contains 'address:port', override default + $host = $hostinfo[1]; + $port = $hostinfo[2]; + } + if ($this->smtp->connect(($ssl ? 'ssl://' : '') . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); + } + $this->smtp->hello($hello); + + if ($tls) { + if (!$this->smtp->startTLS()) { + throw new phpmailerException($this->lang('connect_host')); + } + //We must resend HELO after tls negotiation + $this->smtp->hello($hello); + } + if ($this->SMTPAuth) { + if (!$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->Realm, + $this->Workstation + ) + ) { + throw new phpmailerException($this->lang('authenticate')); + } + } + return true; + } catch (phpmailerException $e) { + $lastexception = $e; + //We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); + } + } + } + //If we get here, all connection attempts have failed, so close connection hard + $this->smtp->close(); + //As we've caught all exceptions, just report whatever the last one was + if ($this->exceptions and !is_null($lastexception)) { + throw $lastexception; + } + return false; + } + + /** + * Close the active SMTP session if one exists. + * @return void + */ + public function smtpClose() + { + if ($this->smtp !== null) { + if ($this->smtp->connected()) { + $this->smtp->quit(); + $this->smtp->close(); + } + } + } + + /** + * Set the language for error messages. + * Returns false if it cannot load the language file. + * The default language is English. + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * @return bool + * @access public + */ + public function setLanguage($langcode = 'en', $lang_path = 'language/') + { + //Define full set of translatable strings + $PHPMAILER_LANG = array( + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'data_not_accepted' => 'SMTP Error: data not accepted.', + 'empty_message' => 'Message body empty', + 'encoding' => 'Unknown encoding: ', + 'execute' => 'Could not execute: ', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'from_failed' => 'The following From address failed: ', + 'instantiate' => 'Could not instantiate mail function.', + 'invalid_address' => 'Invalid address', + 'mailer_not_supported' => ' mailer is not supported.', + 'provide_address' => 'You must provide at least one recipient email address.', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'signing' => 'Signing Error: ', + 'smtp_connect_failed' => 'SMTP connect() failed.', + 'smtp_error' => 'SMTP server error: ', + 'variable_set' => 'Cannot set or reset variable: ' + ); + //Overwrite language-specific strings. + //This way we'll never have missing translations - no more "language string failed to load"! + $l = true; + if ($langcode != 'en') { //There is no English translation file + $l = @include $lang_path . 'phpmailer.lang-' . $langcode . '.php'; + } + $this->language = $PHPMAILER_LANG; + return ($l == true); //Returns false if language not found + } + + /** + * Get the array of strings for the current language. + * @return array + */ + public function getTranslations() + { + return $this->language; + } + + /** + * Create recipient headers. + * @access public + * @param string $type + * @param array $addr An array of recipient, + * where each recipient is a 2-element indexed array with element 0 containing an address + * and element 1 containing a name, like: + * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User')) + * @return string + */ + public function addrAppend($type, $addr) + { + $addresses = array(); + foreach ($addr as $a) { + $addresses[] = $this->addrFormat($a); + } + return $type . ': ' . implode(', ', $addresses) . $this->LE; + } + + /** + * Format an address for use in a message header. + * @access public + * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name + * like array('joe@example.com', 'Joe User') + * @return string + */ + public function addrFormat($addr) + { + if (empty($addr[1])) { // No name provided + return $this->secureHeader($addr[0]); + } else { + return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . " <" . $this->secureHeader( + $addr[0] + ) . ">"; + } + } + + /** + * Word-wrap message. + * For use with mailers that do not automatically perform wrapping + * and for quoted-printable encoded messages. + * Original written by philippe. + * @param string $message The message to wrap + * @param integer $length The line length to wrap to + * @param bool $qp_mode Whether to run in Quoted-Printable mode + * @access public + * @return string + */ + public function wrapText($message, $length, $qp_mode = false) + { + $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; + // If utf-8 encoding is used, we will need to make sure we don't + // split multibyte characters when we wrap + $is_utf8 = (strtolower($this->CharSet) == "utf-8"); + $lelen = strlen($this->LE); + $crlflen = strlen(self::CRLF); + + $message = $this->fixEOL($message); + if (substr($message, -$lelen) == $this->LE) { + $message = substr($message, 0, -$lelen); + } + + $line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE + $message = ''; + for ($i = 0; $i < count($line); $i++) { + $line_part = explode(' ', $line[$i]); + $buf = ''; + for ($e = 0; $e < count($line_part); $e++) { + $word = $line_part[$e]; + if ($qp_mode and (strlen($word) > $length)) { + $space_left = $length - strlen($buf) - $crlflen; + if ($e != 0) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf("=%s", self::CRLF); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while (strlen($word) > 0) { + if ($length <= 0) { + break; + } + $len = $length; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + + if (strlen($word) > 0) { + $message .= $part . sprintf("=%s", self::CRLF); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + $buf .= ($e == 0) ? $word : (' ' . $word); + + if (strlen($buf) > $length and $buf_o != '') { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + } + $message .= $buf . self::CRLF; + } + + return $message; + } + + /** + * Find the last character boundary prior to $maxLength in a utf-8 + * quoted (printable) encoded string. + * Original written by Colin Brown. + * @access public + * @param string $encodedText utf-8 QP text + * @param int $maxLength find last character boundary prior to this length + * @return int + */ + public function utf8CharBoundary($encodedText, $maxLength) + { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, "="); + if ($encodedCharPos !== false) { + // Found start of encoded character byte within $lookBack block. + // Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { // Single byte character. + // If the encoded char was found at pos 0, it will fit + // otherwise reduce maxLength to start of the encoded char + $maxLength = ($encodedCharPos == 0) ? $maxLength : + $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec >= 192) { // First byte of a multi byte character + // Reduce maxLength to split at start of character + $maxLength = $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + // No encoded character found + $foundSplitPos = true; + } + } + return $maxLength; + } + + + /** + * Set the body wrapping. + * @access public + * @return void + */ + public function setWordWrap() + { + if ($this->WordWrap < 1) { + return; + } + + switch ($this->message_type) { + case 'alt': + case 'alt_inline': + case 'alt_attach': + case 'alt_inline_attach': + $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->wrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assemble message headers. + * @access public + * @return string The assembled headers + */ + public function createHeader() + { + $result = ''; + + // Set the boundaries + $uniq_id = md5(uniqid(time())); + $this->boundary[1] = 'b1_' . $uniq_id; + $this->boundary[2] = 'b2_' . $uniq_id; + $this->boundary[3] = 'b3_' . $uniq_id; + + if ($this->MessageDate == '') { + $result .= $this->headerLine('Date', self::rfcDate()); + } else { + $result .= $this->headerLine('Date', $this->MessageDate); + } + + if ($this->ReturnPath) { + $result .= $this->headerLine('Return-Path', '<' . trim($this->ReturnPath) . '>'); + } elseif ($this->Sender == '') { + $result .= $this->headerLine('Return-Path', '<' . trim($this->From) . '>'); + } else { + $result .= $this->headerLine('Return-Path', '<' . trim($this->Sender) . '>'); + } + + // To be created automatically by mail() + if ($this->Mailer != 'mail') { + if ($this->SingleTo === true) { + foreach ($this->to as $t) { + $this->SingleToArray[] = $this->addrFormat($t); + } + } else { + if (count($this->to) > 0) { + $result .= $this->addrAppend('To', $this->to); + } elseif (count($this->cc) == 0) { + $result .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + } + } + + $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName))); + + // sendmail and mail() extract Cc from the header before sending + if (count($this->cc) > 0) { + $result .= $this->addrAppend('Cc', $this->cc); + } + + // sendmail and mail() extract Bcc from the header before sending + if ((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { + $result .= $this->addrAppend('Bcc', $this->bcc); + } + + if (count($this->ReplyTo) > 0) { + $result .= $this->addrAppend('Reply-To', $this->ReplyTo); + } + + // mail() sets the subject itself + if ($this->Mailer != 'mail') { + $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); + } + + if ($this->MessageID != '') { + $this->lastMessageID = $this->MessageID; + } else { + $this->lastMessageID = sprintf("<%s@%s>", $uniq_id, $this->ServerHostname()); + } + $result .= $this->HeaderLine('Message-ID', $this->lastMessageID); + $result .= $this->headerLine('X-Priority', $this->Priority); + if ($this->XMailer == '') { + $result .= $this->headerLine( + 'X-Mailer', + 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)' + ); + } else { + $myXmailer = trim($this->XMailer); + if ($myXmailer) { + $result .= $this->headerLine('X-Mailer', $myXmailer); + } + } + + if ($this->ConfirmReadingTo != '') { + $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); + } + + // Add custom headers + for ($index = 0; $index < count($this->CustomHeader); $index++) { + $result .= $this->headerLine( + trim($this->CustomHeader[$index][0]), + $this->encodeHeader(trim($this->CustomHeader[$index][1])) + ); + } + if (!$this->sign_key_file) { + $result .= $this->headerLine('MIME-Version', '1.0'); + $result .= $this->getMailMIME(); + } + + return $result; + } + + /** + * Get the message MIME type headers. + * @access public + * @return string + */ + public function getMailMIME() + { + $result = ''; + switch ($this->message_type) { + case 'inline': + $result .= $this->headerLine('Content-Type', 'multipart/related;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'attach': + case 'inline_attach': + case 'alt_attach': + case 'alt_inline_attach': + $result .= $this->headerLine('Content-Type', 'multipart/mixed;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'alt': + case 'alt_inline': + $result .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + default: + // Catches case 'plain': and case '': + $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); + break; + } + //RFC1341 part 5 says 7bit is assumed if not specified + if ($this->Encoding != '7bit') { + $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); + } + + if ($this->Mailer != 'mail') { + $result .= $this->LE; + } + + return $result; + } + + /** + * Returns the whole MIME message. + * Includes complete headers and body. + * Only valid post PreSend(). + * @see PHPMailer::PreSend() + * @access public + * @return string + */ + public function getSentMIMEMessage() + { + return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody; + } + + + /** + * Assemble the message body. + * Returns an empty string on failure. + * @access public + * @throws phpmailerException + * @return string The assembled message body + */ + public function createBody() + { + $body = ''; + + if ($this->sign_key_file) { + $body .= $this->getMailMIME() . $this->LE; + } + + $this->setWordWrap(); + + switch ($this->message_type) { + case 'inline': + $body .= $this->getBoundary($this->boundary[1], '', '', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[1]); + break; + case 'attach': + $body .= $this->getBoundary($this->boundary[1], '', '', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'inline_attach': + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', '', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt': + $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->getBoundary($this->boundary[1], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + if (!empty($this->Ical)) { + $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); + $body .= $this->encodeString($this->Ical, $this->Encoding); + $body .= $this->LE . $this->LE; + } + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_inline': + $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= $this->LE; + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_attach': + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt_inline_attach': + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', ''); + $body .= $this->encodeString($this->AltBody, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->textLine('--' . $this->boundary[2]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[3], '', 'text/html', ''); + $body .= $this->encodeString($this->Body, $this->Encoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[3]); + $body .= $this->LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + default: + // catch case 'plain' and case '' + $body .= $this->encodeString($this->Body, $this->Encoding); + break; + } + + if ($this->isError()) { + $body = ''; + } elseif ($this->sign_key_file) { + try { + if (!defined('PKCS7_TEXT')) { + throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.'); + } + $file = tempnam(sys_get_temp_dir(), 'mail'); + file_put_contents($file, $body); //TODO check this worked + $signed = tempnam(sys_get_temp_dir(), 'signed'); + if (@openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), + null + ) + ) { + @unlink($file); + $body = file_get_contents($signed); + @unlink($signed); + } else { + @unlink($file); + @unlink($signed); + throw new phpmailerException($this->lang('signing') . openssl_error_string()); + } + } catch (phpmailerException $e) { + $body = ''; + if ($this->exceptions) { + throw $e; + } + } + } + return $body; + } + + /** + * Return the start of a message boundary. + * @access protected + * @param string $boundary + * @param string $charSet + * @param string $contentType + * @param string $encoding + * @return string + */ + protected function getBoundary($boundary, $charSet, $contentType, $encoding) + { + $result = ''; + if ($charSet == '') { + $charSet = $this->CharSet; + } + if ($contentType == '') { + $contentType = $this->ContentType; + } + if ($encoding == '') { + $encoding = $this->Encoding; + } + $result .= $this->textLine('--' . $boundary); + $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet); + $result .= $this->LE; + $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); + $result .= $this->LE; + + return $result; + } + + /** + * Return the end of a message boundary. + * @access protected + * @param string $boundary + * @return string + */ + protected function endBoundary($boundary) + { + return $this->LE . '--' . $boundary . '--' . $this->LE; + } + + /** + * Set the message type. + * PHPMailer only supports some preset message types, + * not arbitrary MIME structures. + * @access protected + * @return void + */ + protected function setMessageType() + { + $this->message_type = array(); + if ($this->alternativeExists()) { + $this->message_type[] = "alt"; + } + if ($this->inlineImageExists()) { + $this->message_type[] = "inline"; + } + if ($this->attachmentExists()) { + $this->message_type[] = "attach"; + } + $this->message_type = implode("_", $this->message_type); + if ($this->message_type == "") { + $this->message_type = "plain"; + } + } + + /** + * Format a header line. + * @access public + * @param string $name + * @param string $value + * @return string + */ + public function headerLine($name, $value) + { + return $name . ': ' . $value . $this->LE; + } + + /** + * Return a formatted mail line. + * @access public + * @param string $value + * @return string + */ + public function textLine($value) + { + return $value . $this->LE; + } + + /** + * Add an attachment from a path on the filesystem. + * Returns false if the file could not be found or read. + * @param string $path Path to the attachment. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @param string $disposition Disposition to use + * @throws phpmailerException + * @return bool + */ + public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') + { + try { + if (!@is_file($path)) { + throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE); + } + + //If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($path); + } + + $filename = basename($path); + if ($name == '') { + $name = $filename; + } + + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => 0 + ); + + } catch (phpmailerException $e) { + $this->setError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + $this->edebug($e->getMessage() . "\n"); + return false; + } + return true; + } + + /** + * Return the array of attachments. + * @return array + */ + public function getAttachments() + { + return $this->attachment; + } + + /** + * Attach all file, string, and binary attachments to the message. + * Returns an empty string on failure. + * @access protected + * @param string $disposition_type + * @param string $boundary + * @return string + */ + protected function attachAll($disposition_type, $boundary) + { + // Return text of body + $mime = array(); + $cidUniq = array(); + $incl = array(); + + // Add all attachments + foreach ($this->attachment as $attachment) { + // Check if it is a valid disposition_filter + if ($attachment[6] == $disposition_type) { + // Check for string attachment + $string = ''; + $path = ''; + $bString = $attachment[5]; + if ($bString) { + $string = $attachment[0]; + } else { + $path = $attachment[0]; + } + + $inclhash = md5(serialize($attachment)); + if (in_array($inclhash, $incl)) { + continue; + } + $incl[] = $inclhash; + $name = $attachment[2]; + $encoding = $attachment[3]; + $type = $attachment[4]; + $disposition = $attachment[6]; + $cid = $attachment[7]; + if ($disposition == 'inline' && isset($cidUniq[$cid])) { + continue; + } + $cidUniq[$cid] = true; + + $mime[] = sprintf("--%s%s", $boundary, $this->LE); + $mime[] = sprintf( + "Content-Type: %s; name=\"%s\"%s", + $type, + $this->encodeHeader($this->secureHeader($name)), + $this->LE + ); + $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); + + if ($disposition == 'inline') { + $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); + } + + // If a filename contains any of these chars, it should be quoted, + // but not otherwise: RFC2183 & RFC2045 5.1 + // Fixes a warning in IETF's msglint MIME checker + // Allow for bypassing the Content-Disposition header totally + if (!(empty($disposition))) { + if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) { + $mime[] = sprintf( + "Content-Disposition: %s; filename=\"%s\"%s", + $disposition, + $this->encodeHeader($this->secureHeader($name)), + $this->LE . $this->LE + ); + } else { + $mime[] = sprintf( + "Content-Disposition: %s; filename=%s%s", + $disposition, + $this->encodeHeader($this->secureHeader($name)), + $this->LE . $this->LE + ); + } + } else { + $mime[] = $this->LE; + } + + // Encode as string attachment + if ($bString) { + $mime[] = $this->encodeString($string, $encoding); + if ($this->isError()) { + return ''; + } + $mime[] = $this->LE . $this->LE; + } else { + $mime[] = $this->encodeFile($path, $encoding); + if ($this->isError()) { + return ''; + } + $mime[] = $this->LE . $this->LE; + } + } + } + + $mime[] = sprintf("--%s--%s", $boundary, $this->LE); + + return implode("", $mime); + } + + /** + * Encode a file attachment in requested format. + * Returns an empty string on failure. + * @param string $path The full path to the file + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @throws phpmailerException + * @see EncodeFile(encodeFile + * @access protected + * @return string + */ + protected function encodeFile($path, $encoding = 'base64') + { + try { + if (!is_readable($path)) { + throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE); + } + $magic_quotes = get_magic_quotes_runtime(); + if ($magic_quotes) { + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + set_magic_quotes_runtime(0); + } else { + ini_set('magic_quotes_runtime', 0); + } + } + $file_buffer = file_get_contents($path); + $file_buffer = $this->encodeString($file_buffer, $encoding); + if ($magic_quotes) { + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + set_magic_quotes_runtime($magic_quotes); + } else { + ini_set('magic_quotes_runtime', $magic_quotes); + } + } + return $file_buffer; + } catch (Exception $e) { + $this->setError($e->getMessage()); + return ''; + } + } + + /** + * Encode a string in requested format. + * Returns an empty string on failure. + * @param string $str The text to encode + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @access public + * @return string + */ + public function encodeString($str, $encoding = 'base64') + { + $encoded = ''; + switch (strtolower($encoding)) { + case 'base64': + $encoded = chunk_split(base64_encode($str), 76, $this->LE); + break; + case '7bit': + case '8bit': + $encoded = $this->fixEOL($str); + //Make sure it ends with a line break + if (substr($encoded, -(strlen($this->LE))) != $this->LE) { + $encoded .= $this->LE; + } + break; + case 'binary': + $encoded = $str; + break; + case 'quoted-printable': + $encoded = $this->encodeQP($str); + break; + default: + $this->setError($this->lang('encoding') . $encoding); + break; + } + return $encoded; + } + + /** + * Encode a header string optimally. + * Picks shortest of Q, B, quoted-printable or none. + * @access public + * @param string $str + * @param string $position + * @return string + */ + public function encodeHeader($str, $position = 'text') + { + $x = 0; + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + // Can't use addslashes as we don't know what value has magic_quotes_sybase + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return ($encoded); + } else { + return ("\"$encoded\""); + } + } + $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + /** @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $x = preg_match_all('/[()"]/', $str, $matches); + // Intentional fall-through + case 'text': + default: + $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($x == 0) { //There are no chars that need encoding + return ($str); + } + + $maxlen = 75 - 7 - strlen($this->CharSet); + // Try to select the encoding which should produce the shortest output + if ($x > strlen($str) / 3) { + //More than a third of the content will need encoding, so B encoding will be most efficient + $encoding = 'B'; + if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) { + // Use a custom function which correctly encodes and wraps long + // multibyte strings without breaking lines within a character + $encoded = $this->base64EncodeWrapMB($str, "\n"); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + } else { + $encoding = 'Q'; + $encoded = $this->encodeQ($str, $position); + $encoded = $this->wrapText($encoded, $maxlen, true); + $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded)); + } + + $encoded = preg_replace('/^(.*)$/m', " =?" . $this->CharSet . "?$encoding?\\1?=", $encoded); + $encoded = trim(str_replace("\n", $this->LE, $encoded)); + + return $encoded; + } + + /** + * Check if a string contains multi-byte characters. + * @access public + * @param string $str multi-byte text to wrap encode + * @return bool + */ + public function hasMultiBytes($str) + { + if (function_exists('mb_strlen')) { + return (strlen($str) > mb_strlen($str, $this->CharSet)); + } else { // Assume no multibytes (we can't handle without mbstring functions anyway) + return false; + } + } + + /** + * Encode and wrap long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php + * @access public + * @param string $str multi-byte text to wrap encode + * @param string $lf string to use as linefeed/end-of-line + * @return string + */ + public function base64EncodeWrapMB($str, $lf = null) + { + $start = "=?" . $this->CharSet . "?B?"; + $end = "?="; + $encoded = ""; + if ($lf === null) { + $lf = $this->LE; + } + + $mb_length = mb_strlen($str, $this->CharSet); + // Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + // Average multi-byte ratio + $ratio = $mb_length / strlen($str); + // Base64 has a 4:3 ratio + $avgLength = floor($length * $ratio * .75); + + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + $lookBack++; + } while (strlen($chunk) > $length); + $encoded .= $chunk . $lf; + } + + // Chomp the last linefeed + $encoded = substr($encoded, 0, -strlen($lf)); + return $encoded; + } + + /** + * Encode a string in quoted-printable format. + * According to RFC2045 section 6.7. + * @access public + * @param string $string The text to encode + * @param integer $line_max Number of chars allowed on a line before wrapping + * @return string + * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 + */ + public function encodeQP($string, $line_max = 76) + { + if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) + return quoted_printable_encode($string); + } + //Fall back to a pure PHP implementation + $string = str_replace( + array('%20', '%0D%0A.', '%0D%0A', '%'), + array(' ', "\r\n=2E", "\r\n", '='), + rawurlencode($string) + ); + $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string); + return $string; + } + + /** + * Backward compatibility wrapper for an old QP encoding function that was removed. + * @see PHPMailer::encodeQP() + * @access public + * @param string $string + * @param integer $line_max + * @param bool $space_conv + * @return string + * @deprecated Use encodeQP instead. + */ + public function encodeQPphp( + $string, + $line_max = 76, + /** @noinspection PhpUnusedParameterInspection */ $space_conv = false + ) { + return $this->encodeQP($string, $line_max); + } + + /** + * Encode a string using Q encoding. + * @link http://tools.ietf.org/html/rfc2047 + * @param string $str the text to encode + * @param string $position Where the text is going to be used, see the RFC for what that means + * @access public + * @return string + */ + public function encodeQ($str, $position = 'text') + { + //There should not be any EOL in the string + $pattern = ''; + $encoded = str_replace(array("\r", "\n"), '', $str); + switch (strtolower($position)) { + case 'phrase': + //RFC 2047 section 5.3 + $pattern = '^A-Za-z0-9!*+\/ -'; + break; + /** @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + //RFC 2047 section 5.2 + $pattern = '\(\)"'; + //intentional fall-through + //for this reason we build the $pattern without including delimiters and [] + case 'text': + default: + //RFC 2047 section 5.1 + //Replace every high ascii, control, =, ? and _ characters + $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; + break; + } + $matches = array(); + if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { + //If the string contains an '=', make sure it's the first thing we replace + //so as to avoid double-encoding + $s = array_search('=', $matches[0]); + if ($s !== false) { + unset($matches[0][$s]); + array_unshift($matches[0], '='); + } + foreach (array_unique($matches[0]) as $char) { + $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); + } + } + //Replace every spaces to _ (more readable than =20) + return str_replace(' ', '_', $encoded); + } + + + /** + * Add a string or binary attachment (non-filesystem). + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * @param string $string String attachment data. + * @param string $filename Name of the attachment. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @param string $disposition Disposition to use + * @return void + */ + public function addStringAttachment( + $string, + $filename, + $encoding = 'base64', + $type = '', + $disposition = 'attachment' + ) { + //If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($filename); + } + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $filename, + 2 => basename($filename), + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => 0 + ); + } + + /** + * Add an embedded (inline) attachment from a file. + * This can include images, sounds, and just about any other document type. + * These differ from 'regular' attachmants in that they are intended to be + * displayed inline with the message, not just attached for download. + * This is used in HTML messages that embed the images + * the HTML refers to using the $cid value. + * @param string $path Path to the attachment. + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File MIME type. + * @param string $disposition Disposition to use + * @return bool True on successfully adding an attachment + */ + public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') + { + if (!@is_file($path)) { + $this->setError($this->lang('file_access') . $path); + return false; + } + + //If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($path); + } + + $filename = basename($path); + if ($name == '') { + $name = $filename; + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => $cid + ); + return true; + } + + /** + * Add an embedded stringified attachment. + * This can include images, sounds, and just about any other document type. + * Be sure to set the $type to an image type for images: + * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. + * @param string $string The attachment binary data. + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML. + * @param string $name + * @param string $encoding File encoding (see $Encoding). + * @param string $type MIME type. + * @param string $disposition Disposition to use + * @return bool True on successfully adding an attachment + */ + public function addStringEmbeddedImage( + $string, + $cid, + $name = '', + $encoding = 'base64', + $type = '', + $disposition = 'inline' + ) { + //If a MIME type is not specified, try to work it out from the name + if ($type == '') { + $type = self::filenameToType($name); + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $name, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => $cid + ); + return true; + } + + /** + * Check if an inline attachment is present. + * @access public + * @return bool + */ + public function inlineImageExists() + { + foreach ($this->attachment as $attachment) { + if ($attachment[6] == 'inline') { + return true; + } + } + return false; + } + + /** + * Check if an attachment (non-inline) is present. + * @return bool + */ + public function attachmentExists() + { + foreach ($this->attachment as $attachment) { + if ($attachment[6] == 'attachment') { + return true; + } + } + return false; + } + + /** + * Check if this message has an alternative body set. + * @return bool + */ + public function alternativeExists() + { + return !empty($this->AltBody); + } + + /** + * Clear all To recipients. + * @return void + */ + public function clearAddresses() + { + foreach ($this->to as $to) { + unset($this->all_recipients[strtolower($to[0])]); + } + $this->to = array(); + } + + /** + * Clear all CC recipients. + * @return void + */ + public function clearCCs() + { + foreach ($this->cc as $cc) { + unset($this->all_recipients[strtolower($cc[0])]); + } + $this->cc = array(); + } + + /** + * Clear all BCC recipients. + * @return void + */ + public function clearBCCs() + { + foreach ($this->bcc as $bcc) { + unset($this->all_recipients[strtolower($bcc[0])]); + } + $this->bcc = array(); + } + + /** + * Clear all ReplyTo recipients. + * @return void + */ + public function clearReplyTos() + { + $this->ReplyTo = array(); + } + + /** + * Clear all recipient types. + * @return void + */ + public function clearAllRecipients() + { + $this->to = array(); + $this->cc = array(); + $this->bcc = array(); + $this->all_recipients = array(); + } + + /** + * Clear all filesystem, string, and binary attachments. + * @return void + */ + public function clearAttachments() + { + $this->attachment = array(); + } + + /** + * Clear all custom headers. + * @return void + */ + public function clearCustomHeaders() + { + $this->CustomHeader = array(); + } + + /** + * Add an error message to the error container. + * @access protected + * @param string $msg + * @return void + */ + protected function setError($msg) + { + $this->error_count++; + if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { + $lasterror = $this->smtp->getError(); + if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { + $msg .= '

' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "

\n"; + } + } + $this->ErrorInfo = $msg; + } + + /** + * Return an RFC 822 formatted date. + * @access public + * @return string + * @static + */ + public static function rfcDate() + { + //Set the time zone to whatever the default is to avoid 500 errors + //Will default to UTC if it's not set properly in php.ini + date_default_timezone_set(@date_default_timezone_get()); + return date('D, j M Y H:i:s O'); + } + + /** + * Get the server hostname. + * Returns 'localhost.localdomain' if unknown. + * @access protected + * @return string + */ + protected function serverHostname() + { + if (!empty($this->Hostname)) { + $result = $this->Hostname; + } elseif (isset($_SERVER['SERVER_NAME'])) { + $result = $_SERVER['SERVER_NAME']; + } else { + $result = 'localhost.localdomain'; + } + + return $result; + } + + /** + * Get an error message in the current language. + * @access protected + * @param string $key + * @return string + */ + protected function lang($key) + { + if (count($this->language) < 1) { + $this->setLanguage('en'); // set the default language + } + + if (isset($this->language[$key])) { + return $this->language[$key]; + } else { + return 'Language string failed to load: ' . $key; + } + } + + /** + * Check if an error occurred. + * @access public + * @return bool True if an error did occur. + */ + public function isError() + { + return ($this->error_count > 0); + } + + /** + * Ensure consistent line endings in a string. + * Changes every end of line from CRLF, CR or LF to $this->LE. + * @access public + * @param string $str String to fixEOL + * @return string + */ + public function fixEOL($str) + { + // Normalise to \n + $nstr = str_replace(array("\r\n", "\r"), "\n", $str); + // Now convert LE as needed + if ($this->LE !== "\n") { + $nstr = str_replace("\n", $this->LE, $nstr); + } + return $nstr; + } + + /** + * Add a custom header. + * $name value can be overloaded to contain + * both header name and value (name:value) + * @access public + * @param string $name Custom header name + * @param string $value Header value + * @return void + */ + public function addCustomHeader($name, $value = null) + { + if ($value === null) { + // Value passed in as name:value + $this->CustomHeader[] = explode(':', $name, 2); + } else { + $this->CustomHeader[] = array($name, $value); + } + } + + /** + * Create a message from an HTML string. + * Automatically makes modifications for inline images and backgrounds + * and creates a plain-text version by converting the HTML. + * Overwrites any existing values in $this->Body and $this->AltBody + * @access public + * @param string $message HTML message string + * @param string $basedir baseline directory for path + * @param bool $advanced Whether to use the advanced HTML to text converter + * @return string $message + */ + public function msgHTML($message, $basedir = '', $advanced = false) + { + preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); + if (isset($images[2])) { + foreach ($images[2] as $i => $url) { + // do not change urls for absolute images (thanks to corvuscorax) + if (!preg_match('#^[A-z]+://#', $url)) { + $filename = basename($url); + $directory = dirname($url); + if ($directory == '.') { + $directory = ''; + } + $cid = md5($url) . '@phpmailer.0'; //RFC2392 S 2 + if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { + $basedir .= '/'; + } + if (strlen($directory) > 1 && substr($directory, -1) != '/') { + $directory .= '/'; + } + if ($this->addEmbeddedImage( + $basedir . $directory . $filename, + $cid, + $filename, + 'base64', + self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION)) + ) + ) { + $message = preg_replace( + "/" . $images[1][$i] . "=[\"']" . preg_quote($url, '/') . "[\"']/Ui", + $images[1][$i] . "=\"cid:" . $cid . "\"", + $message + ); + } + } + } + } + $this->isHTML(true); + if (empty($this->AltBody)) { + $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; + } + //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better + $this->Body = $this->normalizeBreaks($message); + $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced)); + return $this->Body; + } + + /** + * Convert an HTML string into plain text. + * @param string $html The HTML text to convert + * @param bool $advanced Should this use the more complex html2text converter or just a simple one? + * @return string + */ + public function html2text($html, $advanced = false) + { + if ($advanced) { + require_once 'extras/class.html2text.php'; + $h = new html2text($html); + return $h->get_text(); + } + return html_entity_decode( + trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), + ENT_QUOTES, + $this->CharSet + ); + } + + /** + * Get the MIME type for a file extension. + * @param string $ext File extension + * @access public + * @return string MIME type of file. + * @static + */ + public static function _mime_types($ext = '') + { + $mimes = array( + 'xl' => 'application/excel', + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'bin' => 'application/macbinary', + 'doc' => 'application/msword', + 'word' => 'application/msword', + 'class' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'psd' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'so' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'js' => 'application/x-javascript', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => 'application/x-tar', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'zip' => 'application/zip', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mpga' => 'audio/mpeg', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'wav' => 'audio/x-wav', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'png' => 'image/png', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'eml' => 'message/rfc822', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'log' => 'text/plain', + 'text' => 'text/plain', + 'txt' => 'text/plain', + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'mpeg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mov' => 'video/quicktime', + 'qt' => 'video/quicktime', + 'rv' => 'video/vnd.rn-realvideo', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie' + ); + return (array_key_exists(strtolower($ext), $mimes) ? $mimes[strtolower($ext)]: 'application/octet-stream'); + } + + /** + * Map a file name to a MIME type. + * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. + * @param string $filename A file name or full path, does not need to exist as a file + * @return string + * @static + */ + public static function filenameToType($filename) + { + //In case the path is a URL, strip any query string before getting extension + $qpos = strpos($filename, '?'); + if ($qpos !== false) { + $filename = substr($filename, 0, $qpos); + } + $pathinfo = self::mb_pathinfo($filename); + return self::_mime_types($pathinfo['extension']); + } + + /** + * Multi-byte-safe pathinfo replacement. + * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. + * Works similarly to the one in PHP >= 5.2.0 + * @link http://www.php.net/manual/en/function.pathinfo.php#107461 + * @param string $path A filename or path, does not need to exist as a file + * @param integer|string $options Either a PATHINFO_* constant, + * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 + * @return string|array + * @static + */ + public static function mb_pathinfo($path, $options = null) + { + $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); + $m = array(); + preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m); + if (array_key_exists(1, $m)) { + $ret['dirname'] = $m[1]; + } + if (array_key_exists(2, $m)) { + $ret['basename'] = $m[2]; + } + if (array_key_exists(5, $m)) { + $ret['extension'] = $m[5]; + } + if (array_key_exists(3, $m)) { + $ret['filename'] = $m[3]; + } + switch ($options) { + case PATHINFO_DIRNAME: + case 'dirname': + return $ret['dirname']; + break; + case PATHINFO_BASENAME: + case 'basename': + return $ret['basename']; + break; + case PATHINFO_EXTENSION: + case 'extension': + return $ret['extension']; + break; + case PATHINFO_FILENAME: + case 'filename': + return $ret['filename']; + break; + default: + return $ret; + } + } + + /** + * Set or reset instance properties. + * + * Usage Example: + * $page->set('X-Priority', '3'); + * + * @access public + * @param string $name + * @param mixed $value + * NOTE: will not work with arrays, there are no arrays to set/reset + * @throws phpmailerException + * @return bool + * @todo Should this not be using __set() magic function? + */ + public function set($name, $value = '') + { + try { + if (isset($this->$name)) { + $this->$name = $value; + } else { + throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL); + } + } catch (Exception $e) { + $this->setError($e->getMessage()); + if ($e->getCode() == self::STOP_CRITICAL) { + return false; + } + } + return true; + } + + /** + * Strip newlines to prevent header injection. + * @access public + * @param string $str + * @return string + */ + public function secureHeader($str) + { + return trim(str_replace(array("\r", "\n"), '', $str)); + } + + /** + * Normalize line breaks in a string. + * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. + * Defaults to CRLF (for message bodies) and preserves consecutive breaks. + * @param string $text + * @param string $breaktype What kind of line break to use, defaults to CRLF + * @return string + * @access public + * @static + */ + public static function normalizeBreaks($text, $breaktype = "\r\n") + { + return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); + } + + + /** + * Set the private key file and password for S/MIME signing. + * @access public + * @param string $cert_filename + * @param string $key_filename + * @param string $key_pass Password for private key + */ + public function sign($cert_filename, $key_filename, $key_pass) + { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + } + + /** + * Quoted-Printable-encode a DKIM header. + * @access public + * @param string $txt + * @return string + */ + public function DKIM_QP($txt) + { + $line = ''; + for ($i = 0; $i < strlen($txt); $i++) { + $ord = ord($txt[$i]); + if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { + $line .= $txt[$i]; + } else { + $line .= "=" . sprintf("%02X", $ord); + } + } + return $line; + } + + /** + * Generate a DKIM signature. + * @access public + * @param string $s Header + * @throws phpmailerException + * @return string + */ + public function DKIM_Sign($s) + { + if (!defined('PKCS7_TEXT')) { + if ($this->exceptions) { + throw new phpmailerException($this->lang("signing") . ' OpenSSL extension missing.'); + } + return ''; + } + $privKeyStr = file_get_contents($this->DKIM_private); + if ($this->DKIM_passphrase != '') { + $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); + } else { + $privKey = $privKeyStr; + } + if (openssl_sign($s, $signature, $privKey)) { + return base64_encode($signature); + } + return ''; + } + + /** + * Generate a DKIM canonicalization header. + * @access public + * @param string $s Header + * @return string + */ + public function DKIM_HeaderC($s) + { + $s = preg_replace("/\r\n\s+/", " ", $s); + $lines = explode("\r\n", $s); + foreach ($lines as $key => $line) { + list($heading, $value) = explode(":", $line, 2); + $heading = strtolower($heading); + $value = preg_replace("/\s+/", " ", $value); // Compress useless spaces + $lines[$key] = $heading . ":" . trim($value); // Don't forget to remove WSP around the value + } + $s = implode("\r\n", $lines); + return $s; + } + + /** + * Generate a DKIM canonicalization body. + * @access public + * @param string $body Message Body + * @return string + */ + public function DKIM_BodyC($body) + { + if ($body == '') { + return "\r\n"; + } + // stabilize line endings + $body = str_replace("\r\n", "\n", $body); + $body = str_replace("\n", "\r\n", $body); + // END stabilize line endings + while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { + $body = substr($body, 0, strlen($body) - 2); + } + return $body; + } + + /** + * Create the DKIM header and body in a new message header. + * @access public + * @param string $headers_line Header lines + * @param string $subject Subject + * @param string $body Body + * @return string + */ + public function DKIM_Add($headers_line, $subject, $body) + { + $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms + $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body + $DKIMquery = 'dns/txt'; // Query method + $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) + $subject_header = "Subject: $subject"; + $headers = explode($this->LE, $headers_line); + $from_header = ''; + $to_header = ''; + $current = ''; + foreach ($headers as $header) { + if (strpos($header, 'From:') === 0) { + $from_header = $header; + $current = 'from_header'; + } elseif (strpos($header, 'To:') === 0) { + $to_header = $header; + $current = 'to_header'; + } else { + if ($current && strpos($header, ' =?') === 0) { + $current .= $header; + } else { + $current = ''; + } + } + } + $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); + $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); + $subject = str_replace( + '|', + '=7C', + $this->DKIM_QP($subject_header) + ); // Copied header fields (dkim-quoted-printable) + $body = $this->DKIM_BodyC($body); + $DKIMlen = strlen($body); // Length of body + $DKIMb64 = base64_encode(pack("H*", sha1($body))); // Base64 of packed binary SHA-1 hash of body + $ident = ($this->DKIM_identity == '') ? '' : " i=" . $this->DKIM_identity . ";"; + $dkimhdrs = "DKIM-Signature: v=1; a=" . + $DKIMsignatureType . "; q=" . + $DKIMquery . "; l=" . + $DKIMlen . "; s=" . + $this->DKIM_selector . + ";\r\n" . + "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n" . + "\th=From:To:Subject;\r\n" . + "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n" . + "\tz=$from\r\n" . + "\t|$to\r\n" . + "\t|$subject;\r\n" . + "\tbh=" . $DKIMb64 . ";\r\n" . + "\tb="; + $toSign = $this->DKIM_HeaderC( + $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs + ); + $signed = $this->DKIM_Sign($toSign); + return $dkimhdrs . $signed . "\r\n"; + } + + /** + * Perform a callback. + * @param bool $isSent + * @param string $to + * @param string $cc + * @param string $bcc + * @param string $subject + * @param string $body + * @param string $from + */ + protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) + { + if (!empty($this->action_function) && is_callable($this->action_function)) { + $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); + call_user_func_array($this->action_function, $params); + } + } +} + +/** + * PHPMailer exception handler + * @package PHPMailer + */ +class phpmailerException extends Exception +{ + /** + * Prettify error message output + * @return string + */ + public function errorMessage() + { + $errorMsg = '' . $this->getMessage() . "
\n"; + return $errorMsg; + } +} diff --git a/libraries/phpmailer/phpmailer/class.pop3.php b/libraries/phpmailer/phpmailer/class.pop3.php new file mode 100644 index 0000000000000..042b93ac3b5c2 --- /dev/null +++ b/libraries/phpmailer/phpmailer/class.pop3.php @@ -0,0 +1,419 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2013 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +/** + * PHPMailer POP-Before-SMTP Authentication Class. + * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. + * Does not support APOP. + * @package PHPMailer + * @author Richard Davey (original author) + * @author Marcus Bointon (coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + */ + +class POP3 +{ + /** + * The POP3 PHPMailer Version number. + * @type string + * @access public + */ + public $Version = '5.2.7'; + + /** + * Default POP3 port number. + * @type int + * @access public + */ + public $POP3_PORT = 110; + + /** + * Default timeout in seconds. + * @type int + * @access public + */ + public $POP3_TIMEOUT = 30; + + /** + * POP3 Carriage Return + Line Feed. + * @type string + * @access public + * @deprecated Use the constant instead + */ + public $CRLF = "\r\n"; + + /** + * Debug display level. + * Options: 0 = no, 1+ = yes + * @type int + * @access public + */ + public $do_debug = 0; + + /** + * POP3 mail server hostname. + * @type string + * @access public + */ + public $host; + + /** + * POP3 port number. + * @type int + * @access public + */ + public $port; + + /** + * POP3 Timeout Value in seconds. + * @type int + * @access public + */ + public $tval; + + /** + * POP3 username + * @type string + * @access public + */ + public $username; + + /** + * POP3 password. + * @type string + * @access public + */ + public $password; + + /** + * Resource handle for the POP3 connection socket. + * @type resource + * @access private + */ + private $pop_conn; + + /** + * Are we connected? + * @type bool + * @access private + */ + private $connected; + + /** + * Error container. + * @type array + * @access private + */ + private $error; + + /** + * Line break constant + */ + const CRLF = "\r\n"; + + /** + * Constructor. + * @access public + */ + public function __construct() + { + $this->pop_conn = 0; + $this->connected = false; + $this->error = null; + } + + /** + * Simple static wrapper for all-in-one POP before SMTP + * @param $host + * @param bool $port + * @param bool $tval + * @param string $username + * @param string $password + * @param int $debug_level + * @return bool + */ + public static function popBeforeSmtp( + $host, + $port = false, + $tval = false, + $username = '', + $password = '', + $debug_level = 0 + ) { + $pop = new POP3; + return $pop->authorise($host, $port, $tval, $username, $password, $debug_level); + } + + /** + * Authenticate with a POP3 server. + * A connect, login, disconnect sequence + * appropriate for POP-before SMTP authorisation. + * @access public + * @param string $host + * @param bool|int $port + * @param bool|int $tval + * @param string $username + * @param string $password + * @param int $debug_level + * @return bool + */ + public function authorise($host, $port = false, $tval = false, $username = '', $password = '', $debug_level = 0) + { + $this->host = $host; + // If no port value provided, use default + if ($port === false) { + $this->port = $this->POP3_PORT; + } else { + $this->port = $port; + } + // If no timeout value provided, use default + if ($tval === false) { + $this->tval = $this->POP3_TIMEOUT; + } else { + $this->tval = $tval; + } + $this->do_debug = $debug_level; + $this->username = $username; + $this->password = $password; + // Refresh the error log + $this->error = null; + // connect + $result = $this->connect($this->host, $this->port, $this->tval); + if ($result) { + $login_result = $this->login($this->username, $this->password); + if ($login_result) { + $this->disconnect(); + return true; + } + } + // We need to disconnect regardless of whether the login succeeded + $this->disconnect(); + return false; + } + + /** + * Connect to a POP3 server. + * @access public + * @param string $host + * @param bool|int $port + * @param integer $tval + * @return boolean + */ + public function connect($host, $port = false, $tval = 30) + { + // Are we already connected? + if ($this->connected) { + return true; + } + + //On Windows this will raise a PHP Warning error if the hostname doesn't exist. + //Rather than suppress it with @fsockopen, capture it cleanly instead + set_error_handler(array($this, 'catchWarning')); + + // connect to the POP3 server + $this->pop_conn = fsockopen( + $host, // POP3 Host + $port, // Port # + $errno, // Error Number + $errstr, // Error Message + $tval + ); // Timeout (seconds) + // Restore the error handler + restore_error_handler(); + // Does the Error Log now contain anything? + if ($this->error && $this->do_debug >= 1) { + $this->displayErrors(); + } + // Did we connect? + if ($this->pop_conn == false) { + // It would appear not... + $this->error = array( + 'error' => "Failed to connect to server $host on port $port", + 'errno' => $errno, + 'errstr' => $errstr + ); + if ($this->do_debug >= 1) { + $this->displayErrors(); + } + return false; + } + + // Increase the stream time-out + // Check for PHP 4.3.0 or later + if (version_compare(phpversion(), '5.0.0', 'ge')) { + stream_set_timeout($this->pop_conn, $tval, 0); + } else { + // Does not work on Windows + if (substr(PHP_OS, 0, 3) !== 'WIN') { + socket_set_timeout($this->pop_conn, $tval, 0); + } + } + + // Get the POP3 server response + $pop3_response = $this->getResponse(); + // Check for the +OK + if ($this->checkResponse($pop3_response)) { + // The connection is established and the POP3 server is talking + $this->connected = true; + return true; + } + return false; + } + + /** + * Log in to the POP3 server. + * Does not support APOP (RFC 2828, 4949). + * @access public + * @param string $username + * @param string $password + * @return boolean + */ + public function login($username = '', $password = '') + { + if ($this->connected == false) { + $this->error = 'Not connected to POP3 server'; + + if ($this->do_debug >= 1) { + $this->displayErrors(); + } + } + if (empty($username)) { + $username = $this->username; + } + if (empty($password)) { + $password = $this->password; + } + + // Send the Username + $this->sendString("USER $username" . self::CRLF); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + // Send the Password + $this->sendString("PASS $password" . self::CRLF); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + return true; + } + } + return false; + } + + /** + * Disconnect from the POP3 server. + * @access public + */ + public function disconnect() + { + $this->sendString('QUIT'); + //The QUIT command may cause the daemon to exit, which will kill our connection + //So ignore errors here + @fclose($this->pop_conn); + } + + /** + * Get a response from the POP3 server. + * $size is the maximum number of bytes to retrieve + * @param integer $size + * @return string + * @access private + */ + private function getResponse($size = 128) + { + $r = fgets($this->pop_conn, $size); + if ($this->do_debug >= 1) { + echo "Server -> Client: $r"; + } + return $r; + } + + /** + * Send raw data to the POP3 server. + * @param string $string + * @return integer + * @access private + */ + private function sendString($string) + { + if ($this->pop_conn) { + if ($this->do_debug >= 2) { //Show client messages when debug >= 2 + echo "Client -> Server: $string"; + } + return fwrite($this->pop_conn, $string, strlen($string)); + } + return 0; + } + + /** + * Checks the POP3 server response. + * Looks for for +OK or -ERR. + * @param string $string + * @return boolean + * @access private + */ + private function checkResponse($string) + { + if (substr($string, 0, 3) !== '+OK') { + $this->error = array( + 'error' => "Server reported an error: $string", + 'errno' => 0, + 'errstr' => '' + ); + if ($this->do_debug >= 1) { + $this->displayErrors(); + } + return false; + } else { + return true; + } + } + + /** + * Display errors if debug is enabled. + * @access private + */ + private function displayErrors() + { + echo '
';
+        foreach ($this->error as $single_error) {
+            print_r($single_error);
+        }
+        echo '
'; + } + + /** + * POP3 connection error handler. + * @param integer $errno + * @param string $errstr + * @param string $errfile + * @param integer $errline + * @access private + */ + private function catchWarning($errno, $errstr, $errfile, $errline) + { + $this->error[] = array( + 'error' => "Connecting to the POP3 server raised a PHP warning: ", + 'errno' => $errno, + 'errstr' => $errstr, + 'errfile' => $errfile, + 'errline' => $errline + ); + } +} diff --git a/libraries/phpmailer/phpmailer/class.smtp.php b/libraries/phpmailer/phpmailer/class.smtp.php new file mode 100644 index 0000000000000..e6b45222d8d46 --- /dev/null +++ b/libraries/phpmailer/phpmailer/class.smtp.php @@ -0,0 +1,943 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @copyright 2013 Marcus Bointon + * @copyright 2004 - 2008 Andy Prevost + * @copyright 2010 - 2012 Jim Jagielski + * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) + */ + +/** + * PHPMailer RFC821 SMTP email transport class. + * + * Implements RFC 821 SMTP commands + * and provides some utility methods for sending mail to an SMTP server. + * + * PHP Version 5.0.0 + * + * @category PHP + * @package PHPMailer + * @link https://github.com/PHPMailer/PHPMailer/blob/master/class.smtp.php + * @author Chris Ryan + * @author Marcus Bointon + * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) + */ + +class SMTP +{ + /** + * The PHPMailer SMTP Version number. + */ + const VERSION = '5.2.7'; + + /** + * SMTP line break constant. + */ + const CRLF = "\r\n"; + + /** + * The SMTP port to use if one is not specified. + */ + const DEFAULT_SMTP_PORT = 25; + + /** + * The PHPMailer SMTP Version number. + * @type string + * @deprecated This should be a constant + * @see SMTP::VERSION + */ + public $Version = '5.2.7'; + + /** + * SMTP server port number. + * @type int + * @deprecated This is only ever ued as default value, so should be a constant + * @see SMTP::DEFAULT_SMTP_PORT + */ + public $SMTP_PORT = 25; + + /** + * SMTP reply line ending + * @type string + * @deprecated Use the class constant instead + * @see SMTP::CRLF + */ + public $CRLF = "\r\n"; + + /** + * Debug output level. + * Options: 0 for no output, 1 for commands, 2 for data and commands + * @type int + */ + public $do_debug = 0; + + /** + * The function/method to use for debugging output. + * Options: 'echo', 'html' or 'error_log' + * @type string + */ + public $Debugoutput = 'echo'; + + /** + * Whether to use VERP. + * @type bool + */ + public $do_verp = false; + + /** + * The SMTP timeout value for reads, in seconds. + * @type int + */ + public $Timeout = 15; + + /** + * The SMTP timelimit value for reads, in seconds. + * @type int + */ + public $Timelimit = 30; + + /** + * The socket for the server connection. + * @type resource + */ + protected $smtp_conn; + + /** + * Error message, if any, for the last call. + * @type string + */ + protected $error = ''; + + /** + * The reply the server sent to us for HELO. + * @type string + */ + protected $helo_rply = ''; + + /** + * The most recent reply received from the server. + * @type string + */ + protected $last_reply = ''; + + /** + * Constructor. + * @access public + */ + public function __construct() + { + $this->smtp_conn = 0; + $this->error = null; + $this->helo_rply = null; + + $this->do_debug = 0; + } + + /** + * Output debugging info via a user-selected method. + * @param string $str Debug string to output + * @return void + */ + protected function edebug($str) + { + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ) + . "
\n"; + break; + case 'echo': + default: + //Just echoes whatever was received + echo $str; + } + } + + /** + * Connect to an SMTP server. + * @param string $host SMTP server IP or host name + * @param int $port The port number to connect to + * @param int $timeout How long to wait for the connection to open + * @param array $options An array of options for stream_context_create() + * @access public + * @return bool + */ + public function connect($host, $port = null, $timeout = 30, $options = array()) + { + // Clear errors to avoid confusion + $this->error = null; + + // Make sure we are __not__ connected + if ($this->connected()) { + // Already connected, generate error + $this->error = array('error' => 'Already connected to a server'); + return false; + } + + if (empty($port)) { + $port = self::DEFAULT_SMTP_PORT; + } + + // Connect to the SMTP server + $errno = 0; + $errstr = ''; + $socket_context = stream_context_create($options); + //Suppress errors; connection failures are handled at a higher level + $this->smtp_conn = @stream_socket_client( + $host . ":" . $port, + $errno, + $errstr, + $timeout, + STREAM_CLIENT_CONNECT, + $socket_context + ); + + // Verify we connected properly + if (empty($this->smtp_conn)) { + $this->error = array( + 'error' => 'Failed to connect to server', + 'errno' => $errno, + 'errstr' => $errstr + ); + if ($this->do_debug >= 1) { + $this->edebug( + 'SMTP -> ERROR: ' . $this->error['error'] + . ": $errstr ($errno)" + ); + } + return false; + } + + // SMTP server can take longer to respond, give longer timeout for first read + // Windows does not have support for this timeout function + if (substr(PHP_OS, 0, 3) != 'WIN') { + $max = ini_get('max_execution_time'); + if ($max != 0 && $timeout > $max) { // Don't bother if unlimited + @set_time_limit($timeout); + } + stream_set_timeout($this->smtp_conn, $timeout, 0); + } + + // Get any announcement + $announce = $this->get_lines(); + + if ($this->do_debug >= 2) { + $this->edebug('SMTP -> FROM SERVER:' . $announce); + } + + return true; + } + + /** + * Initiate a TLS (encrypted) session. + * @access public + * @return bool + */ + public function startTLS() + { + if (!$this->sendCommand("STARTTLS", "STARTTLS", 220)) { + return false; + } + // Begin encrypted connection + if (!stream_socket_enable_crypto( + $this->smtp_conn, + true, + STREAM_CRYPTO_METHOD_TLS_CLIENT + ) + ) { + return false; + } + return true; + } + + /** + * Perform SMTP authentication. + * Must be run after hello(). + * @see hello() + * @param string $username The user name + * @param string $password The password + * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5) + * @param string $realm The auth realm for NTLM + * @param string $workstation The auth workstation for NTLM + * @access public + * @return bool True if successfully authenticated. + */ + public function authenticate( + $username, + $password, + $authtype = 'LOGIN', + $realm = '', + $workstation = '' + ) { + if (empty($authtype)) { + $authtype = 'LOGIN'; + } + + switch ($authtype) { + case 'PLAIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { + return false; + } + // Send encoded username and password + if (!$this->sendCommand( + 'User & Password', + base64_encode("\0" . $username . "\0" . $password), + 235 + ) + ) { + return false; + } + break; + case 'LOGIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { + return false; + } + if (!$this->sendCommand("Username", base64_encode($username), 334)) { + return false; + } + if (!$this->sendCommand("Password", base64_encode($password), 235)) { + return false; + } + break; + case 'NTLM': + /* + * ntlm_sasl_client.php + * Bundled with Permission + * + * How to telnet in windows: + * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx + * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication + */ + require_once 'extras/ntlm_sasl_client.php'; + $temp = new stdClass(); + $ntlm_client = new ntlm_sasl_client_class; + //Check that functions are available + if (!$ntlm_client->Initialize($temp)) { + $this->error = array('error' => $temp->error); + if ($this->do_debug >= 1) { + $this->edebug( + 'You need to enable some modules in your php.ini file: ' + . $this->error['error'] + ); + } + return false; + } + //msg1 + $msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1 + + if (!$this->sendCommand( + 'AUTH NTLM', + 'AUTH NTLM ' . base64_encode($msg1), + 334 + ) + ) { + return false; + } + + //Though 0 based, there is a white space after the 3 digit number + //msg2 + $challenge = substr($this->last_reply, 3); + $challenge = base64_decode($challenge); + $ntlm_res = $ntlm_client->NTLMResponse( + substr($challenge, 24, 8), + $password + ); + //msg3 + $msg3 = $ntlm_client->TypeMsg3( + $ntlm_res, + $username, + $realm, + $workstation + ); + // send encoded username + return $this->sendCommand('Username', base64_encode($msg3), 235); + break; + case 'CRAM-MD5': + // Start authentication + if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { + return false; + } + // Get the challenge + $challenge = base64_decode(substr($this->last_reply, 4)); + + // Build the response + $response = $username . ' ' . $this->hmac($challenge, $password); + + // send encoded credentials + return $this->sendCommand('Username', base64_encode($response), 235); + break; + } + return true; + } + + /** + * Calculate an MD5 HMAC hash. + * Works like hash_hmac('md5', $data, $key) + * in case that function is not available + * @param string $data The data to hash + * @param string $key The key to hash with + * @access protected + * @return string + */ + protected function hmac($data, $key) + { + if (function_exists('hash_hmac')) { + return hash_hmac('md5', $data, $key); + } + + // The following borrowed from + // http://php.net/manual/en/function.mhash.php#27225 + + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing + + $b = 64; // byte length for md5 + if (strlen($key) > $b) { + $key = pack('H*', md5($key)); + } + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } + + /** + * Check connection state. + * @access public + * @return bool True if connected. + */ + public function connected() + { + if (!empty($this->smtp_conn)) { + $sock_status = stream_get_meta_data($this->smtp_conn); + if ($sock_status['eof']) { + // the socket is valid but we are not connected + if ($this->do_debug >= 1) { + $this->edebug( + 'SMTP -> NOTICE: EOF caught while checking if connected' + ); + } + $this->close(); + return false; + } + return true; // everything looks good + } + return false; + } + + /** + * Close the socket and clean up the state of the class. + * Don't use this function without first trying to use QUIT. + * @see quit() + * @access public + * @return void + */ + public function close() + { + $this->error = null; // so there is no confusion + $this->helo_rply = null; + if (!empty($this->smtp_conn)) { + // close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = 0; + } + } + + /** + * Send an SMTP DATA command. + * Issues a data command and sends the msg_data to the server, + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a with the message headers + * and the message body being separated by and additional . + * Implements rfc 821: DATA + * @param string $msg_data Message data to send + * @access public + * @return bool + */ + public function data($msg_data) + { + if (!$this->sendCommand('DATA', 'DATA', 354)) { + return false; + } + + /* The server is ready to accept data! + * according to rfc821 we should not send more than 1000 + * including the CRLF + * characters on a single line so we will break the data up + * into lines by \r and/or \n then if needed we will break + * each of those into smaller lines to fit within the limit. + * in addition we will be looking for lines that start with + * a period '.' and append and additional period '.' to that + * line. NOTE: this does not count towards limit. + */ + + // Normalize the line breaks before exploding + $msg_data = str_replace("\r\n", "\n", $msg_data); + $msg_data = str_replace("\r", "\n", $msg_data); + $lines = explode("\n", $msg_data); + + /* We need to find a good way to determine if headers are + * in the msg_data or if it is a straight msg body + * currently I am assuming rfc822 definitions of msg headers + * and if the first field of the first line (':' separated) + * does not contain a space then it _should_ be a header + * and we can process all lines before a blank "" line as + * headers. + */ + + $field = substr($lines[0], 0, strpos($lines[0], ':')); + $in_headers = false; + if (!empty($field) && !strstr($field, ' ')) { + $in_headers = true; + } + + //RFC 2822 section 2.1.1 limit + $max_line_length = 998; + + foreach ($lines as $line) { + $lines_out = null; + if ($line == '' && $in_headers) { + $in_headers = false; + } + // ok we need to break this line up into several smaller lines + while (strlen($line) > $max_line_length) { + $pos = strrpos(substr($line, 0, $max_line_length), ' '); + + // Patch to fix DOS attack + if (!$pos) { + $pos = $max_line_length - 1; + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos); + } else { + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos + 1); + } + + /* If processing headers add a LWSP-char to the front of new line + * rfc822 on long msg headers + */ + if ($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + // send the lines to the server + while (list(, $line_out) = @each($lines_out)) { + if (strlen($line_out) > 0) { + if (substr($line_out, 0, 1) == '.') { + $line_out = '.' . $line_out; + } + } + $this->client_send($line_out . self::CRLF); + } + } + + // Message data has been sent, complete the command + return $this->sendCommand('DATA END', '.', 250); + } + + /** + * Send an SMTP HELO or EHLO command. + * Used to identify the sending server to the receiving server. + * This makes sure that client and server are in a known state. + * Implements from RFC 821: HELO + * and RFC 2821 EHLO. + * @param string $host The host name or IP to connect to + * @access public + * @return bool + */ + public function hello($host = '') + { + // Try extended hello first (RFC 2821) + if (!$this->sendHello('EHLO', $host)) { + if (!$this->sendHello('HELO', $host)) { + return false; + } + } + + return true; + } + + /** + * Send an SMTP HELO or EHLO command. + * Low-level implementation used by hello() + * @see hello() + * @param string $hello The HELO string + * @param string $host The hostname to say we are + * @access protected + * @return bool + */ + protected function sendHello($hello, $host) + { + $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); + $this->helo_rply = $this->last_reply; + return $noerror; + } + + /** + * Send an SMTP MAIL command. + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. + * Implements rfc 821: MAIL FROM: + * @param string $from Source address of this message + * @access public + * @return bool + */ + public function mail($from) + { + $useVerp = ($this->do_verp ? ' XVERP' : ''); + return $this->sendCommand( + 'MAIL FROM', + 'MAIL FROM:<' . $from . '>' . $useVerp, + 250 + ); + } + + /** + * Send an SMTP QUIT command. + * Closes the socket if there is no error or the $close_on_error argument is true. + * Implements from rfc 821: QUIT + * @param bool $close_on_error Should the connection close if an error occurs? + * @access public + * @return bool + */ + public function quit($close_on_error = true) + { + $noerror = $this->sendCommand('QUIT', 'QUIT', 221); + $e = $this->error; //Save any error + if ($noerror or $close_on_error) { + $this->close(); + $this->error = $e; //Restore any error from the quit command + } + return $noerror; + } + + /** + * Send an SMTP RCPT command. + * Sets the TO argument to $to. + * Returns true if the recipient was accepted false if it was rejected. + * Implements from rfc 821: RCPT TO: + * @param string $to The address the message is being sent to + * @access public + * @return bool + */ + public function recipient($to) + { + return $this->sendCommand( + 'RCPT TO ', + 'RCPT TO:<' . $to . '>', + array(250, 251) + ); + } + + /** + * Send an SMTP RSET command. + * Abort any transaction that is currently in progress. + * Implements rfc 821: RSET + * @access public + * @return bool True on success. + */ + public function reset() + { + return $this->sendCommand('RSET', 'RSET', 250); + } + + /** + * Send a command to an SMTP server and check its return code. + * @param string $command The command name - not sent to the server + * @param string $commandstring The actual command to send + * @param int|array $expect One or more expected integer success codes + * @access protected + * @return bool True on success. + */ + protected function sendCommand($command, $commandstring, $expect) + { + if (!$this->connected()) { + $this->error = array( + "error" => "Called $command without being connected" + ); + return false; + } + $this->client_send($commandstring . self::CRLF); + + $reply = $this->get_lines(); + $code = substr($reply, 0, 3); + + if ($this->do_debug >= 2) { + $this->edebug('SMTP -> FROM SERVER:' . $reply); + } + + if (!in_array($code, (array)$expect)) { + $this->last_reply = null; + $this->error = array( + "error" => "$command command failed", + "smtp_code" => $code, + "detail" => substr($reply, 4) + ); + if ($this->do_debug >= 1) { + $this->edebug( + 'SMTP -> ERROR: ' . $this->error['error'] . ': ' . $reply + ); + } + return false; + } + + $this->last_reply = $reply; + $this->error = null; + return true; + } + + /** + * Send an SMTP SAML command. + * Starts a mail transaction from the email address specified in $from. + * Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * Implements rfc 821: SAML FROM: + * @param string $from The address the message is from + * @access public + * @return bool + */ + public function sendAndMail($from) + { + return $this->sendCommand("SAML", "SAML FROM:$from", 250); + } + + /** + * Send an SMTP VRFY command. + * @param string $name The name to verify + * @access public + * @return bool + */ + public function verify($name) + { + return $this->sendCommand("VRFY", "VRFY $name", array(250, 251)); + } + + /** + * Send an SMTP NOOP command. + * Used to keep keep-alives alive, doesn't actually do anything + * @access public + * @return bool + */ + public function noop() + { + return $this->sendCommand("NOOP", "NOOP", 250); + } + + /** + * Send an SMTP TURN command. + * This is an optional command for SMTP that this class does not support. + * This method is here to make the RFC821 Definition + * complete for this class and __may__ be implemented in future + * Implements from rfc 821: TURN + * @access public + * @return bool + */ + public function turn() + { + $this->error = array( + 'error' => 'The SMTP TURN command is not implemented' + ); + if ($this->do_debug >= 1) { + $this->edebug('SMTP -> NOTICE: ' . $this->error['error']); + } + return false; + } + + /** + * Send raw data to the server. + * @param string $data The data to send + * @access public + * @return int|bool The number of bytes sent to the server or FALSE on error + */ + public function client_send($data) + { + if ($this->do_debug >= 1) { + $this->edebug("CLIENT -> SMTP: $data"); + } + return fwrite($this->smtp_conn, $data); + } + + /** + * Get the latest error. + * @access public + * @return array + */ + public function getError() + { + return $this->error; + } + + /** + * Get the last reply from the server. + * @access public + * @return string + */ + public function getLastReply() + { + return $this->last_reply; + } + + /** + * Read the SMTP server's response. + * Either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access protected + * @return string + */ + protected function get_lines() + { + $data = ''; + $endtime = 0; + // If the connection is bad, give up now + if (!is_resource($this->smtp_conn)) { + return $data; + } + stream_set_timeout($this->smtp_conn, $this->Timeout); + if ($this->Timelimit > 0) { + $endtime = time() + $this->Timelimit; + } + while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { + $str = @fgets($this->smtp_conn, 515); + if ($this->do_debug >= 4) { + $this->edebug("SMTP -> get_lines(): \$data was \"$data\""); + $this->edebug("SMTP -> get_lines(): \$str is \"$str\""); + } + $data .= $str; + if ($this->do_debug >= 4) { + $this->edebug("SMTP -> get_lines(): \$data is \"$data\""); + } + // if 4th character is a space, we are done reading, break the loop + if (substr($str, 3, 1) == ' ') { + break; + } + // Timed-out? Log and break + $info = stream_get_meta_data($this->smtp_conn); + if ($info['timed_out']) { + if ($this->do_debug >= 4) { + $this->edebug( + 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)' + ); + } + break; + } + // Now check if reads took too long + if ($endtime) { + if (time() > $endtime) { + if ($this->do_debug >= 4) { + $this->edebug( + 'SMTP -> get_lines(): timelimit reached (' + . $this->Timelimit . ' sec)' + ); + } + break; + } + } + } + return $data; + } + + /** + * Enable or disable VERP address generation. + * @param bool $enabled + */ + public function setVerp($enabled = false) + { + $this->do_verp = $enabled; + } + + /** + * Get VERP address generation mode. + * @return bool + */ + public function getVerp() + { + return $this->do_verp; + } + + /** + * Set debug output method. + * @param string $method The function/method to use for debugging output. + */ + public function setDebugOutput($method = 'echo') + { + $this->Debugoutput = $method; + } + + /** + * Get debug output method. + * @return string + */ + public function getDebugOutput() + { + return $this->Debugoutput; + } + + /** + * Set debug output level. + * @param int $level + */ + public function setDebugLevel($level = 0) + { + $this->do_debug = $level; + } + + /** + * Get debug output level. + * @return int + */ + public function getDebugLevel() + { + return $this->do_debug; + } + + /** + * Set SMTP timeout. + * @param int $timeout + */ + public function setTimeout($timeout = 0) + { + $this->Timeout = $timeout; + } + + /** + * Get SMTP timeout. + * @return int + */ + public function getTimeout() + { + return $this->Timeout; + } +} diff --git a/libraries/phpmailer/phpmailer/composer.json b/libraries/phpmailer/phpmailer/composer.json new file mode 100644 index 0000000000000..086f38131d74b --- /dev/null +++ b/libraries/phpmailer/phpmailer/composer.json @@ -0,0 +1,33 @@ +{ + "name": "phpmailer/phpmailer", + "type": "library", + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "authors": [ + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "require": { + "php": ">=5.0.0" + }, + "require-dev": { + "phpdocumentor/phpdocumentor": "*", + "phpunit/phpunit": "*" + }, + "autoload": { + "classmap": ["class.phpmailer.php", "class.pop3.php", "class.smtp.php"] + }, + "license": "LGPL-2.1" +} \ No newline at end of file diff --git a/libraries/phpmailer/phpmailer/docs/Callback_function_notes.txt b/libraries/phpmailer/phpmailer/docs/Callback_function_notes.txt new file mode 100644 index 0000000000000..461ea508e9de1 --- /dev/null +++ b/libraries/phpmailer/phpmailer/docs/Callback_function_notes.txt @@ -0,0 +1,17 @@ +NEW CALLBACK FUNCTION: +====================== + +We have had requests for a method to process the results of sending emails +through PHPMailer. In this new release, we have implemented a callback +function that passes the results of each email sent (to, cc, and/or bcc). +We have provided an example that echos the results back to the screen. The +callback function can be used for any purpose. With minor modifications, the +callback function can be used to create CSV logs, post results to databases, +etc. + +Please review the test.php script for the example. + +It's pretty straight forward. + +Enjoy! +Andy diff --git a/libraries/phpmailer/phpmailer/docs/DomainKeys_notes.txt b/libraries/phpmailer/phpmailer/docs/DomainKeys_notes.txt new file mode 100644 index 0000000000000..2ad10f159a33b --- /dev/null +++ b/libraries/phpmailer/phpmailer/docs/DomainKeys_notes.txt @@ -0,0 +1,55 @@ +CREATE DKIM KEYS and DNS Resource Record: +========================================= + +To create DomainKeys Identified Mail keys, visit: +http://dkim.worxware.com/ +... read the information, fill in the form, and download the ZIP file +containing the public key, private key, DNS Resource Record and instructions +to add to your DNS Zone Record, and the PHPMailer code to enable DKIM +digital signing. + +/*** PROTECT YOUR PRIVATE & PUBLIC KEYS ***/ + +You need to protect your DKIM private and public keys from being viewed or +accessed. Add protection to your .htaccess file as in this example: + +# secure htkeyprivate file + + order allow,deny + deny from all + + +# secure htkeypublic file + + order allow,deny + deny from all + + +(the actual .htaccess additions are in the ZIP file sent back to you from +http://dkim.worxware.com/ + +A few notes on using DomainKey Identified Mail (DKIM): + +You do not need to use PHPMailer to DKIM sign emails IF: +- you enable DomainKey support and add the DNS resource record +- you use your outbound mail server + +If you are a third-party emailer that works on behalf of domain owners to +send their emails from your own server: +- you absolutely have to DKIM sign outbound emails +- the domain owner has to add the DNS resource record to match the + private key, public key, selector, identity, and domain that you create +- use caution with the "selector" ... at least one "selector" will already + exist in the DNS Zone Record of the domain at the domain owner's server + you need to ensure that the "selector" you use is unique +Note: since the IP address will not match the domain owner's DNS Zone record +you can be certain that email providers that validate based on DomainKey will +check the domain owner's DNS Zone record for your DNS resource record. Before +sending out emails on behalf of domain owners, ensure they have entered the +DNS resource record you provided them. + +Enjoy! +Andy + +PS. if you need additional information about DKIM, please see: +http://www.dkim.org/info/dkim-faq.html diff --git a/libraries/phpmailer/phpmailer/docs/Note_for_SMTP_debugging.txt b/libraries/phpmailer/phpmailer/docs/Note_for_SMTP_debugging.txt new file mode 100644 index 0000000000000..128b2d9d878ef --- /dev/null +++ b/libraries/phpmailer/phpmailer/docs/Note_for_SMTP_debugging.txt @@ -0,0 +1,17 @@ +If you are having problems connecting or sending emails through your SMTP server, the SMTP class can provide more information about the processing/errors taking place. +Use the debug functionality of the class to see what's going on in your connections. To do that, set the debug level in your script. For example: + +$mail->SMTPDebug = 1; +$mail->isSMTP(); // telling the class to use SMTP +$mail->SMTPAuth = true; // enable SMTP authentication +$mail->Port = 26; // set the SMTP port +$mail->Host = "mail.yourhost.com"; // SMTP server +$mail->Username = "name@yourhost.com"; // SMTP account username +$mail->Password = "your password"; // SMTP account password + +Notes on this: +$mail->SMTPDebug = 0; ... will disable debugging (you can also leave this out completely, 0 is the default) +$mail->SMTPDebug = 1; ... will echo errors and server responses +$mail->SMTPDebug = 2; ... will echo errors, server responses and client messages + +And finally, don't forget to disable debugging before going into production. diff --git a/libraries/phpmailer/phpmailer/docs/extending.html b/libraries/phpmailer/phpmailer/docs/extending.html new file mode 100644 index 0000000000000..e5f16cec4038c --- /dev/null +++ b/libraries/phpmailer/phpmailer/docs/extending.html @@ -0,0 +1,145 @@ + + +Examples using phpmailer + + + + +

Examples using phpmailer

+ +

1. Advanced Example

+

+ +This demonstrates sending out multiple email messages with binary attachments +from a MySQL database with multipart/alternative support.

+ + + + +
+
+require("class.phpmailer.php");
+
+$mail = new phpmailer();
+
+$mail->From     = "list@example.com";
+$mail->FromName = "List manager";
+$mail->Host     = "smtp1.example.com;smtp2.example.com";
+$mail->Mailer   = "smtp";
+
+@MYSQL_CONNECT("localhost","root","password");
+@mysql_select_db("my_company");
+$query� =�"SELECT full_name, email,�photo�FROM employee�WHERE�id=$id";
+$result�=�@MYSQL_QUERY($query);
+
+while ($row = mysql_fetch_array ($result))
+{
+    // HTML body
+    $body  = "Hello <font size=\"4\">" . $row["full_name"] . "</font>, <p>";
+    $body .= "<i>Your</i> personal photograph to this message.<p>";
+    $body .= "Sincerely, <br>";
+    $body .= "phpmailer List manager";
+
+    // Plain text body (for mail clients that cannot read HTML)
+    $text_body  = "Hello " . $row["full_name"] . ", \n\n";
+    $text_body .= "Your personal photograph to this message.\n\n";
+    $text_body .= "Sincerely, \n";
+    $text_body .= "phpmailer List manager";
+
+    $mail->Body    = $body;
+    $mail->AltBody = $text_body;
+    $mail->addAddress($row["email"], $row["full_name"]);
+    $mail->addStringAttachment($row["photo"], "YourPhoto.jpg");
+
+    if(!$mail->send())
+        echo "There has been a mail error sending to " . $row["email"] . "<br>";
+
+    // Clear all addresses and attachments for next loop
+    $mail->clearAddresses();
+    $mail->clearAttachments();
+}
+
+
+

+ +

2. Extending phpmailer

+

+ +Extending classes with inheritance is one of the most +powerful features of object-oriented +programming. It allows you to make changes to the +original class for your +own personal use without hacking the original +classes. Plus, it is very +easy to do. I've provided an example: + +

+Here's a class that extends the phpmailer class and sets the defaults +for the particular site:
+PHP include file: mail.inc.php +

+ + + + + +
+
+require("class.phpmailer.php");
+
+class my_phpmailer extends phpmailer {
+    // Set default variables for all new objects
+    var $From     = "from@example.com";
+    var $FromName = "Mailer";
+    var $Host     = "smtp1.example.com;smtp2.example.com";
+    var $Mailer   = "smtp";                         // Alternative to isSMTP()
+    var $WordWrap = 75;
+
+    // Replace the default error_handler
+    function error_handler($msg) {
+        print("My Site Error");
+        print("Description:");
+        printf("%s", $msg);
+        exit;
+    }
+
+    // Create an additional function
+    function do_something($something) {
+        // Place your new code here
+    }
+}
+
+
+
+ +Now here's a normal PHP page in the site, which will have all the defaults set above:
+Normal PHP file: mail_test.php + + + + + +
+
+require("mail.inc.php");
+
+// Instantiate your new class
+$mail = new my_phpmailer;
+
+// Now you only need to add the necessary stuff
+$mail->addAddress("josh@example.com", "Josh Adams");
+$mail->Subject = "Here is the subject";
+$mail->Body    = "This is the message body";
+$mail->addAttachment("c:/temp/11-10-00.zip", "new_name.zip");  // optional name
+
+if(!$mail->send())
+{
+   echo "There was an error sending the message";
+   exit;
+}
+
+echo "Message was sent successfully";
+
+
+ + diff --git a/libraries/phpmailer/phpmailer/docs/faq.html b/libraries/phpmailer/phpmailer/docs/faq.html new file mode 100644 index 0000000000000..f71c6c8924d1b --- /dev/null +++ b/libraries/phpmailer/phpmailer/docs/faq.html @@ -0,0 +1,67 @@ + + +PHPMailer FAQ + + + +

+
+

PHPMailer FAQ

+
    + +
  • Q: I'm using the SMTP mailer and I keep on getting a timeout message + well before the X seconds I set it for. What gives?
    + A: PHP versions 4.0.4pl1 and earlier have a bug in which sockets timeout + early. You can fix this by re-compiling PHP 4.0.4pl1 with this fix: +
    timeoutfix.diff. Otherwise you can wait for the new PHP release.

  • + +
  • Q: I am concerned that using include files will take up too much + processing time on my computer. How can I make it run faster?
    + A: PHP by itself is very fast. Much faster than ASP or JSP running on + the same type of server. This is because it has very little overhead compared + to its competitors and it pre-compiles all of + its code before it runs each script (in PHP4). However, all of + this compiling and re-compiling can take up a lot of valuable + computer resources. However, there are programs out there that compile + PHP code and store it in memory (or on mmaped files) to reduce the + processing immensely. Two of these: APC + (Alternative PHP Cache) and Afterburner + (Win32 download) + are excellent free tools that do just this. If you have the money + you might also try Zend Cache, it is + even faster than the open source varieties. All of these tools make your + scripts run faster while also reducing the load on your server. I have tried + them myself and they are quite stable too.

  • + +
  • Q: What mailer gives me the best performance?
    + A: On a single machine the sendmail (or Qmail) is fastest overall. + Next fastest is mail() to give you the best performance. Both do not have the overhead of SMTP. + If you have you have your mail server on a another machine then + SMTP is your only option, but you do get the benefit of redundant mail servers.
    + If you are running a mailing list with thousands of names, the fastest mailers in order are: SMTP, sendmail (or Qmail), mail().

  • + +
  • Q: When I try to attach a file with on my server I get a + "Could not find {file} on filesystem error". Why is this?
    + A: If you are using a Unix machine this is probably because the user + running your web server does not have read access to the directory in question. If you are using Windows, + then the problem probably is that you have used single backslashes to denote directories (\). + A single backslash has a special meaning to PHP so these are not + valid. Instead use double backslashes ("\\") or a single forward + slash ("/").

  • + +
+ +
+
+ + + diff --git a/libraries/phpmailer/phpmailer/docs/generatedocs.sh b/libraries/phpmailer/phpmailer/docs/generatedocs.sh new file mode 100644 index 0000000000000..f4d065f37fc4e --- /dev/null +++ b/libraries/phpmailer/phpmailer/docs/generatedocs.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# Regenerate PHPMailer documentation +# Run from within the docs folder +rm -rf phpdocs/* +phpdoc --directory .. --target ./phpdoc --ignore test/,examples/,extras/,test_script/ --sourcecode --force --title PHPMailer diff --git a/libraries/phpmailer/phpmailer/docs/pop3_article.txt b/libraries/phpmailer/phpmailer/docs/pop3_article.txt new file mode 100644 index 0000000000000..fb90b9c76763a --- /dev/null +++ b/libraries/phpmailer/phpmailer/docs/pop3_article.txt @@ -0,0 +1,50 @@ +This is built for PHP Mailer 1.72 and was not tested with any previous version. It was developed under PHP 4.3.11 (E_ALL). It works under PHP 5 and 5.1 with E_ALL, but not in Strict mode due to var deprecation (but then neither does PHP Mailer either!). It follows the RFC 1939 standard explicitly and is fully commented. + +With that noted, here is how to implement it: + +I didn't want to modify the PHP Mailer classes at all, so you will have to include/require this class along with the base one. It can sit quite happily in the phpmailer directory. + +When you need it, create your POP3 object + +Right before I invoke PHP Mailer I activate the POP3 authorisation. POP3 before SMTP is a process whereby you login to your web hosts POP3 mail server BEFORE sending out any emails via SMTP. The POP3 logon 'verifies' your ability to send email by SMTP, which typically otherwise blocks you. On my web host (Pair Networks) a single POP3 logon is enough to 'verify' you for 90 minutes. Here is some sample PHP code that activates the POP3 logon and then sends an email via PHP Mailer: + +authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1); +$mail = new PHPMailer(); $mail->SMTPDebug = 2; $mail->isSMTP(); +$mail->isHTML(false); $mail->Host = 'relay.example.com'; +$mail->From = 'mailer@example.com'; +$mail->FromName = 'Example Mailer'; +$mail->Subject = 'My subject'; +$mail->Body = 'Hello world'; +$mail->addAddress('rich@corephp.co.uk', 'Richard Davey'); +if (!$mail->send()) { + echo $mail->ErrorInfo; +} +?> + +The PHP Mailer parts of this code should be obvious to anyone who has used PHP Mailer before. One thing to note - you almost certainly will not need to use SMTP Authentication *and* POP3 before SMTP together. The Authorisation method is a proxy method to all of the others within that class. There are connect, Logon and disconnect methods available, but I wrapped them in the single Authorisation one to make things easier. +The Parameters + +The authorise parameters are as follows: + +$pop->authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1); + + 1. pop3.example.com - The POP3 Mail Server Name (hostname or IP address) + 2. 110 - The POP3 Port on which to connect (default is usually 110, but check with your host) + 3. 30 - A connection time-out value (in seconds) + 4. mailer - The POP3 Username required to logon + 5. password - The POP3 Password required to logon + 6. 1 - The class debug level (0 = off, 1+ = debug output is echoed to the browser) + +Final Comments + the Download + +1) This class does not support APOP connections. This is only because I did not have an APOP server to test with, but if you'd like to see that added just contact me. + +2) Opening and closing lots of POP3 connections can be quite a resource/network drain. If you need to send a whole batch of emails then just perform the authentication once at the start, and then loop through your mail sending script. Providing this process doesn't take longer than the verification period lasts on your POP3 server, you should be fine. With my host that period is 90 minutes, i.e. plenty of time. + +3) If you have heavy requirements for this script (i.e. send a LOT of email on a frequent basis) then I would advise seeking out an alternative sending method (direct SMTP ideally). If this isn't possible then you could modify this class so the 'last authorised' date is recorded somewhere (MySQL, Flat file, etc) meaning you only open a new connection if the old one has expired, saving you precious overhead. + +4) There are lots of other POP3 classes for PHP available. However most of them implement the full POP3 command set, where-as this one is purely for authentication, and much lighter as a result. However using any of the other POP3 classes to just logon to your server would have the same net result. At the end of the day, use whatever method you feel most comfortable with. +Download + +My thanks to Chris Ryan for the inspiration (even if indirectly, via his SMTP class) diff --git a/libraries/phpmailer/phpmailer/examples/LGPLv3.txt b/libraries/phpmailer/phpmailer/examples/LGPLv3.txt new file mode 100644 index 0000000000000..3f9959fc56675 --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/LGPLv3.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/libraries/phpmailer/phpmailer/examples/code_generator.phps b/libraries/phpmailer/phpmailer/examples/code_generator.phps new file mode 100644 index 0000000000000..4af07b3aebb2a --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/code_generator.phps @@ -0,0 +1,596 @@ +CharSet = 'utf-8'; +$mail->Debugoutput = $CFG['smtp_debugoutput']; +$example_code .= "\n\n\$mail = new PHPMailer(true);"; +$example_code .= "\n\$mail->CharSet = 'utf-8';"; + +class phpmailerAppException extends phpmailerException +{ +} + +$example_code .= "\n\nclass phpmailerAppException extends phpmailerException {}"; +$example_code .= "\n\ntry {"; + +try { + if (isset($_POST["submit"]) && $_POST['submit'] == "Submit") { + $to = $_POST['To_Email']; + if (!PHPMailer::validateAddress($to)) { + throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!"); + } + + $example_code .= "\n\$to = '{$_POST['To_Email']}';"; + $example_code .= "\nif(!PHPMailer::validateAddress(\$to)) {"; + $example_code .= "\n throw new phpmailerAppException(\"Email address \" . " . + "\$to . \" is invalid -- aborting!\");"; + $example_code .= "\n}"; + + switch ($_POST['test_type']) { + case 'smtp': + $mail->isSMTP(); // telling the class to use SMTP + $mail->SMTPDebug = (integer)$_POST['smtp_debug']; + $mail->Host = $_POST['smtp_server']; // SMTP server + $mail->Port = (integer)$_POST['smtp_port']; // set the SMTP port + if ($_POST['smtp_secure']) { + $mail->SMTPSecure = strtolower($_POST['smtp_secure']); + } + $mail->SMTPAuth = array_key_exists('smtp_authenticate', $_POST); // enable SMTP authentication? + if (array_key_exists('smtp_authenticate', $_POST)) { + $mail->Username = $_POST['authenticate_username']; // SMTP account username + $mail->Password = $_POST['authenticate_password']; // SMTP account password + } + + $example_code .= "\n\$mail->isSMTP();"; + $example_code .= "\n\$mail->SMTPDebug = " . $_POST['smtp_debug'] . ";"; + $example_code .= "\n\$mail->Host = \"" . $_POST['smtp_server'] . "\";"; + $example_code .= "\n\$mail->Port = \"" . $_POST['smtp_port'] . "\";"; + $example_code .= "\n\$mail->SMTPSecure = \"" . strtolower($_POST['smtp_secure']) . "\";"; + $example_code .= "\n\$mail->SMTPAuth = " . (array_key_exists( + 'smtp_authenticate', + $_POST + ) ? 'true' : 'false') . ";"; + if (array_key_exists('smtp_authenticate', $_POST)) { + $example_code .= "\n\$mail->Username = \"" . $_POST['authenticate_username'] . "\";"; + $example_code .= "\n\$mail->Password = \"" . $_POST['authenticate_password'] . "\";"; + } + break; + case 'mail': + $mail->isMail(); // telling the class to use PHP's mail() + $example_code .= "\n\$mail->isMail();"; + break; + case 'sendmail': + $mail->isSendmail(); // telling the class to use Sendmail + $example_code .= "\n\$mail->isSendmail();"; + break; + case 'qmail': + $mail->isQmail(); // telling the class to use Qmail + $example_code .= "\n\$mail->isQmail();"; + break; + default: + throw new phpmailerAppException('Invalid test_type provided'); + } + + try { + if ($_POST['From_Name'] != '') { + $mail->addReplyTo($_POST['From_Email'], $_POST['From_Name']); + $mail->From = $_POST['From_Email']; + $mail->FromName = $_POST['From_Name']; + + $example_code .= "\n\$mail->addReplyTo(\"" . + $_POST['From_Email'] . "\", \"" . $_POST['From_Name'] . "\");"; + $example_code .= "\n\$mail->From = \"" . $_POST['From_Email'] . "\";"; + $example_code .= "\n\$mail->FromName = \"" . $_POST['From_Name'] . "\";"; + } else { + $mail->addReplyTo($_POST['From_Email']); + $mail->From = $_POST['From_Email']; + $mail->FromName = $_POST['From_Email']; + + $example_code .= "\n\$mail->addReplyTo(\"" . $_POST['From_Email'] . "\");"; + $example_code .= "\n\$mail->From = \"" . $_POST['From_Email'] . "\";"; + $example_code .= "\n\$mail->FromName = \"" . $_POST['From_Email'] . "\";"; + } + + if ($_POST['To_Name'] != '') { + $mail->addAddress($to, $_POST['To_Name']); + $example_code .= "\n\$mail->addAddress(\"$to\", \"" . $_POST['To_Name'] . "\");"; + } else { + $mail->addAddress($to); + $example_code .= "\n\$mail->addAddress(\"$to\");"; + } + + if ($_POST['bcc_Email'] != '') { + $indiBCC = explode(" ", $_POST['bcc_Email']); + foreach ($indiBCC as $key => $value) { + $mail->addBCC($value); + $example_code .= "\n\$mail->addBCC(\"$value\");"; + } + } + + if ($_POST['cc_Email'] != '') { + $indiCC = explode(" ", $_POST['cc_Email']); + foreach ($indiCC as $key => $value) { + $mail->addCC($value); + $example_code .= "\n\$mail->addCC(\"$value\");"; + } + } + } catch (phpmailerException $e) { //Catch all kinds of bad addressing + throw new phpmailerAppException($e->getMessage()); + } + $mail->Subject = $_POST['Subject'] . ' (PHPMailer test using ' . strtoupper($_POST['test_type']) . ')'; + $example_code .= "\n\$mail->Subject = \"" . $_POST['Subject'] . + '(PHPMailer test using ' . strtoupper($_POST['test_type']) . ')";'; + + if ($_POST['Message'] == '') { + $body = file_get_contents('contents.html'); + } else { + $body = $_POST['Message']; + } + + $example_code .= "\n\$body = <<<'EOT'\n" . htmlentities($body) . "\nEOT;"; + + $mail->WordWrap = 80; // set word wrap + $mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images + + $example_code .= "\n\$mail->WordWrap = 80;"; + $example_code .= "\n\$mail->msgHTML(\$body, dirname(__FILE__), true); //Create message bodies and embed images"; + + $mail->addAttachment('images/phpmailer_mini.gif', 'phpmailer_mini.gif'); // optional name + $mail->addAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name + $example_code .= "\n\$mail->addAttachment('images/phpmailer_mini.gif'," . + "'phpmailer_mini.gif'); // optional name"; + $example_code .= "\n\$mail->addAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name"; + + try { + $mail->send(); + $results_messages[] = "Message has been sent using " . strtoupper($_POST["test_type"]); + } catch (phpmailerException $e) { + throw new phpmailerAppException("Unable to send to: " . $to . ': ' . $e->getMessage()); + } + + $example_code .= "\n\ntry {"; + $example_code .= "\n \$mail->send();"; + $example_code .= "\n \$results_messages[] = \"Message has been sent using " . + strtoupper($_POST['test_type']) . "\";"; + $example_code .= "\n}"; + $example_code .= "\ncatch (phpmailerException \$e) {"; + $example_code .= "\n throw new phpmailerAppException('Unable to send to: ' . \$to. ': '.\$e->getMessage());"; + $example_code .= "\n}"; + } +} catch (phpmailerAppException $e) { + $results_messages[] = $e->errorMessage(); +} +$example_code .= "\n}"; +$example_code .= "\ncatch (phpmailerAppException \$e) {"; +$example_code .= "\n \$results_messages[] = \$e->errorMessage();"; +$example_code .= "\n}"; +$example_code .= "\n\nif (count(\$results_messages) > 0) {"; +$example_code .= "\n echo \"

Run results

\\n\";"; +$example_code .= "\n echo \"
    \\n\";"; +$example_code .= "\nforeach (\$results_messages as \$result) {"; +$example_code .= "\n echo \"
  • \$result
  • \\n\";"; +$example_code .= "\n}"; +$example_code .= "\necho \"
\\n\";"; +$example_code .= "\n}"; +?> + + + + PHPMailer Test Page + + + + + + + + +"; + echo exit("ERROR: Wrong PHP version. Must be PHP 5 or above."); +} + +if (count($results_messages) > 0) { + echo '

Run results

'; + echo '
    '; + foreach ($results_messages as $result) { + echo "
  • $result
  • "; + } + echo '
'; +} + +if (isset($_POST["submit"]) && $_POST["submit"] == "Submit") { + echo "
\n"; + echo "
Script:\n"; + echo "
\n";
+    echo $example_code;
+    echo "\n
\n"; + echo "\n
\n"; +} +?> +
+
+
+
+ Mail Details + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + +
+
Test will include two attachments.
+
+
+
+
+ Mail Test Specs + + + + + +
Test Type +
+ + + required> +
+
+ + + required> +
+
+ + + required> +
+
+ + + required> +
+
+
"> + SMTP Specific Options: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ +
+ +
+ + value=""> +
+ +
+ +
+
+
+
+
+ +
+
+ +
+ +
+
+
+ + \ No newline at end of file diff --git a/libraries/phpmailer/phpmailer/examples/contents.html b/libraries/phpmailer/phpmailer/examples/contents.html new file mode 100644 index 0000000000000..9257f6dd9b356 --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/contents.html @@ -0,0 +1,17 @@ + + + + + PHPMailer Test + + +
+

This is a test of PHPMailer.

+
+ PHPMailer rocks +
+

This example uses HTML.

+

The PHPMailer image at the top has been embedded automatically.

+
+ + diff --git a/libraries/phpmailer/phpmailer/examples/exceptions.phps b/libraries/phpmailer/phpmailer/examples/exceptions.phps new file mode 100644 index 0000000000000..a4b3224d1a441 --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/exceptions.phps @@ -0,0 +1,41 @@ + + + + + PHPMailer - Exceptions test + + +setFrom('from@example.com', 'First Last'); + //Set an alternative reply-to address + $mail->addReplyTo('replyto@example.com', 'First Last'); + //Set who the message is to be sent to + $mail->addAddress('whoto@example.com', 'John Doe'); + //Set the subject line + $mail->Subject = 'PHPMailer Exceptions test'; + //Read an HTML message body from an external file, convert referenced images to embedded, + //and convert the HTML into a basic plain-text alternative body + $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); + //Replace the plain text body with one created manually + $mail->AltBody = 'This is a plain-text message body'; + //Attach an image file + $mail->addAttachment('images/phpmailer_mini.gif'); + //send the message + //Note that we don't need check the response from this because it will throw an exception if it has trouble + $mail->send(); + echo "Message sent!"; +} catch (phpmailerException $e) { + echo $e->errorMessage(); //Pretty error messages from PHPMailer +} catch (Exception $e) { + echo $e->getMessage(); //Boring error messages from anything else! +} +?> + + diff --git a/libraries/phpmailer/phpmailer/examples/gmail.phps b/libraries/phpmailer/phpmailer/examples/gmail.phps new file mode 100644 index 0000000000000..a1b403ffdfb2a --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/gmail.phps @@ -0,0 +1,63 @@ + + + + + PHPMailer - GMail SMTP test + + +isSMTP(); +//Enable SMTP debugging +// 0 = off (for production use) +// 1 = client messages +// 2 = client and server messages +$mail->SMTPDebug = 2; +//Ask for HTML-friendly debug output +$mail->Debugoutput = 'html'; +//Set the hostname of the mail server +$mail->Host = 'smtp.gmail.com'; +//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission +$mail->Port = 587; +//Set the encryption system to use - ssl (deprecated) or tls +$mail->SMTPSecure = 'tls'; +//Whether to use SMTP authentication +$mail->SMTPAuth = true; +//Username to use for SMTP authentication - use full email address for gmail +$mail->Username = "username@gmail.com"; +//Password to use for SMTP authentication +$mail->Password = "yourpassword"; +//Set who the message is to be sent from +$mail->setFrom('from@example.com', 'First Last'); +//Set an alternative reply-to address +$mail->addReplyTo('replyto@example.com', 'First Last'); +//Set who the message is to be sent to +$mail->addAddress('whoto@example.com', 'John Doe'); +//Set the subject line +$mail->Subject = 'PHPMailer GMail SMTP test'; +//Read an HTML message body from an external file, convert referenced images to embedded, +//convert HTML into a basic plain-text alternative body +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); +//Replace the plain text body with one created manually +$mail->AltBody = 'This is a plain-text message body'; +//Attach an image file +$mail->addAttachment('images/phpmailer_mini.gif'); + +//send the message, check for errors +if (!$mail->send()) { + echo "Mailer Error: " . $mail->ErrorInfo; +} else { + echo "Message sent!"; +} +?> + + diff --git a/libraries/phpmailer/phpmailer/examples/images/phpmailer.png b/libraries/phpmailer/phpmailer/examples/images/phpmailer.png new file mode 100644 index 0000000000000000000000000000000000000000..bc7424a3c0dcc6af72af7777de97054d05361aaa GIT binary patch literal 8670 zcmb_?cRZVI-*-^ds+PuHRch~|VnvOjLlAq9P)brH_HLCbEj3y@cI;KOcBxUjBxX^y zV^e$djXu|N-`9OT@A&6UK1t5=x4+->IFHY9{*JtaJi13i$wCPL0BE!{)${-WA}Hb5 z^fDRYdug-OjqpS9RMW%*0HC73_z(e-Q<(sOO9D<%W2EuJ2Ov9ytEi1V!WJg#?fR5p z4FD*3g9wMNFr*Eax2p@>1LUp9{l@}CIKB{zadZ7KK|WFBHhu`2zN&@2{}1AF>y&TNl6icg@}g_ z9BJb%0{6K2UqSvmjvCCv&fV!L(g^|Qx`=CIi$Eb2xw$VA{pjlvViKa_V*iRva8w{*1U*F9J308M*&ty`lHw9lBI372BxRryw?X2!LDIJs#QtIP z@0@?URo!7WNQ65SfpAfRIC;ZdTrWQdp)gQ_(3i^lq|AiLm zFW6L)P!RhcvcDnxqchQic_3U+f9z!?|8n@d@ShH< z2-m0XFb|K51k!)m|6TS^`+vtbfIA`oRntGj|MW8cw_fRAW&K_Fm&5-zvSHp%{|B-! zH2;(A3n}Q&m@rmza)rVF@F8_uTtV!AtN9zgKYCS!3&LIhsf`^>Nk&>)ia_K)#sBp9 zlgs4ax#a#M)!!8VS7!c;FT$;>L`fL@|2+*TQ5M_Q`~m>j&9u~1pxzVfX;kq>278@B z*DpC-hb2}@nwJu*3K-`licm_M<-X6;bBKMf&8$SE|C!u2FV{X9rj6%3?CV7Ywlx5J zXxpd}Y|~{n8a8Uvf@11dIhUH79s83|i|(9DO@VKcJVqzPn>!m1)&lm=Qv)~-PU)g5 z^0jFBm0cqxk{JDI_$y>n% zf&rRjvENlBO~3mW7hJlj5%qzHS?IltsW?2w+OjqL7xwt)_sGcUfh!yeF3>j|bNBe@ zq_h%ain&bGD<>}E?wA`=R=|})Zwx8Rf>JAJv7S4Dq;IY zla;ajN-xPtOUocQ;HY1|UNKQqL0lkq%!S(JOGNCxpf#8AAvWg56fx1>ryHt|f+S-P zmE&SrE?ldEU(S^_?%%cot2;PbJ72)5fdshqzL#LH4vEB$v|uj^Sqo$GdB+NoFQA7w z^!|~U^A#I@AF6&L#)r0@b!g3F`v}}V3%k!{ehqXV^KGdCU(ymVIQOcu#e!|IX@X=L8WkxYc*sAGl z=oS|{J#^NEJR%7?dTZA9cPCE`u^%<(=Q zHheUsj>_yjc(!aeH_|{(bxD<8`%73qAlkFb35_St6(KQjh+FpUm_5bR`v(gUgBjsT zYa8L~`>be??3$YguP~Gp!ugPgj(y(YRE`#!R9G)CGZG?5tDIDrvGYZu>3TI6pw(X9 z&GP`3?HJ7BA0ftSPBE!U0=f5^?MThSBF%r|gNG#mcmHUg7^*y%9@rhXI#&?b!oUkb zN!j`wuB$Vl>ki&Zeohd#D+J)TX4^WYWn?`2`6013puUzPxm32BoWYSlkd+}BEx7fp z6V$mmyN*S`Qd(?OXZ!fnLHCCVdPsKiENvUGxp5|j8UGQF$BPnUEF_7cvX{A}hWfy% z9R)i?7|WI+(s1~w8J^Y{QncdJk6-T_0< zi>=;*8=H=Fg3iGoQ3s9wAGQnfsUaShF~d5_iZ!#P1Q&Rs^Sks~UNqjm0Hm^Nzz1*X z-uEsvGMwG>F%JHCbYo-PLB83}oeZ<>(JrLrR0YO;EnF+bB?hzLLjA?evTWQ*RBJl) zzZrY?b^ER`FmS<5_&f3%yP5WOWJsWdH&&R$fbZ2VOMdS!LR?Q#DUY-c?%uHyM&U+7 zz~Ktv!m^+pfS9hU6Y>yLdiSWhhT5e6r(bl>kCJ}3z=@gZq>qsBSj#u< z`*n1(MlF zoEp?l&ZKiHMn4mBk77j?R8dRymK*jH8ypmH>mT-Cm=$rxNHB+i!*;F)~a2wpm0cpEMVM5~kT|`R>ARXC8 z%O8r5eYp)SV-6^56r2MT_8%KHw*f@a2Y&V+K$uV!f9=z9e0#NaxqPMc@F_uq-X zUfwe6J$(&%{&ir|5y`Z-G=6y%1l^!#DJ@F(G)|lvm394$JR- z)48#c;KyoGc#_KeupOJC36T}&x3`5 zRQZR3zPN0YF-}?|`$qf1R~fS4gys_V4?rg>a60{ zJtN|nuY(3c0|_8!HVyi)VI$-3*~2n_o)tJkqCtVZ^J`~#T^1buS_p(<=6yvCnWTWA z>cAkCTV>Bm=_p*QS}s`5Yi^CT@_4m%hnLN~q!FecGsnenA}b_=2dos*AHAW@y2&`nsi9Fc3 z6IeVzQK$>R71eX{j5UOg!N(un3Z{%X@d?$6lz#Tg_nDKyny;G8$1Euc)|v_luqz*U z@1%$16Pf<%Tajk@eZQmBM>5PjgUGtG5$44Q0O`WL&u&WdHjJD$pR(x5ZAS7~2$KRw z{=L#xEKQ-!#Rxg@HNXAf-PpwXfB|}9oNFey&}${d6xpLGg?2!78UV-E zzrT;)2ruDl8Po9s8HG5HV&;V)je#S4kEc4xpiC34T59IXD#a{Hy_-QNpAv^XTD)gA zD`Q;7vlS!a8XNmxwHmo0EHZxWu*zn4cOA{6fvHQ2k zFoYF}gl+JjrOkhwXxNfDYh9x2lz#SIHe%kFxymNa1q%~ByxW9N?~zE>L2SPxu^-j2lh zV{^we8h#0nTyK`4d@_vGoN8TOFqpn`%Il7<11d$hoq{ZxD1O?zf%Nl2W=E5<1&yvY zzPd>%Q}*Hx{Z_4zM>n@6C{KYWB04m5{0+SQ22yC>En2*8fekV&(;+}7Iagd|ybgO; zfn4e@)$o*5tJCL8+!(7^@U44$-s@;ws7iibI~6c|t*!p&eB5}$`PtEo-qP2cs!6$o z{M6QFBOiQ0MJUaT5U-yw+OJRHWX+g`UsgbVTg~wNXrMOLXu5<|Xnm-CIMGw(ma7@} zsaAd}eD50Lyg^74Z;qJQX1;P?z;Kyz{&ItD#?q&DRu|oXZ|W{P6ny2B?X>zzD52as zk=(kzM0i02a+hAef*44O$pMthTmGK;ZQNEhu+!YrbZoHRoyc{zyfwQ>6|h6$hgdbN z`E|T%LKINr^_kccc>p)m3{qt<_n`Sb(Q0)T*~cy(9N@pk6cqjY0Eep>U&<&$=_s3k zyNA4QE9_D?JCYihXAgc#Mb^k$HCgg>H@@$7UE&WkbFA$x_}OE%c;LJKX~|UDJLacO zKxCiNfw|#Pb=i2+6;n}xhxB}v)!7==%Ylc{vSZ(=MDJ`Qt23A--n@(vuEGcdp$u5m zGh4HKK$T_HH}^+Z*-wun1qZ#Ztkgf*UrQW2{E_Bme5QQcbc!p2hs9F|>}+@TEuGKOp4PWt>UuLBl+jGi zpq87G;oW^1a$oBkt}VO@MXS_B^?M{s-G#R?{U9!*ystIs{?{a%cw!r98N+1}hSyUD z1};R*k7w|>wYWD*whQ@b9U;EYgOhVMRh)rn!*7aiE?JQ#zHKyXV<9AKgNuEgQ^PD@ zY@U;U*5a%96mRf}^vn%d2CYHXv<8<{O$z6XIn1Y+~?~ePcXV3Fk{;A zo;_eyL}t@b*=|x>J2@aRG%yW-zkV!w>Qjj+A}bVXFdXnxl|!5l1Wl*jVN>k3Y&`Qk zpNiH|`lHrw_(Bh_G6} zlyWqfN*I_4%i_1Ji200l?*(A`%8sE3HXjFZD}(bIe;m zXHH+ZCW(j0_Z9kW%)-*$k5|4^DES{)>`y0(6z?-O|JW>JmwM57a=fa*ghd+(J^h?u zRC)Gfq?~rf?~Uu}$&8tSXIL9bsDLOWJF^&(Gkgj%h!0yUDOuPzf9R>7)*>puF!ktK zPQ63F{fS|*HTg&>%wrkk=!c%+VEECb`qfpReV|QgU-ozvDB`<0q+^zdxDl+-=s!N+;F`^QB;5 zCXZllJNZLp{$Uwai7cow8l^+Hot@BSSwf`^r{x}`<2V+m^O;N5@n^sL;ncIEMAvI? z#TCy}S^XHrZYL0DZpsYRf?MXcQV{OVsVXM2uM-ZYCn+(9#cD)?mYW9sDW$2kkGFm- z<~+mOonQ-2cc1O;xhzF7pPnVn{8kd;swdIpY&est9X)P74ST0P!4acJPxoa)k5_b- z_E4#EdCFsP>$lfnqjmjC7CiPLXysN&T~x5(oB=WJVXa;vX94TmEFPR239cIJiVHZX zuve?Y4IXTrEqtNIX6P%xfEXKPNB?-Oa%UyrWJi?x z2T^`%&^W9l*wn?tV(h8~S9%CFYe(V~lD>JQDM4twzO1n$G0p=T*CY^KF)Mj3C%Ao8 ztno`3#Z=^FYs7=}@87+F*UJkze}BZSj$=#ItasDNL)=piUHV99KL}E>-20`e{gr$$ z?y;coe2wMVl5*`S&A40u$V>*wFLd;i(Ffho?7?UDdpTPKWvm&U_Q7g=w0T-DQ3RT3 z0%hO}5>(v7It;!Q`wYK)d(5mPMNwM1xBwIJyYaj%$Tgv&x4a-@{1VS0^RH>)7dHS~ zIWNkt$Cdp!me-ug%_-~ccn$e6knO^{=@GHN(KkYg&YE3PdWd>%Cp8|B6?~2c5EXrn=dYML^X{eQfP$B?9 zIGL+j%WWWKSx6bpVz3Ot0KV~%}FqtI9NbO*wVL<`> zRQ*%!gVe4Wu^VXs%MJ8A+hd?^$Yq`+#fNzwx#_%Dz*AdecBhSk?mNUikapq^=`y40 zNqBXxY=w^;o07VoFT3x_+#=uAPXHn%Z)+ME-MgDXm_|Rk z#^^RQ`pf$Zhv zvQzdZ)(GaZ&MO=)q)_=Ohw~rgeS42+SZxCqFuHwhkLREHYretz+yzg`m?4WYr@6up zRB5YOh`T_L9t%RV0&}`3YgS1z-lt-{`Cca4tM7@LtPv@GUqJuRhm>7@XH^TG)uXK2 zU>Hr9Es}}ZrpSV|Y1rfnNWpDx3ys%YF2D7{;|~LPy7aKT>0;DMzaxdbYxO-lV?J+# zb9Zol0D~skSCs;*V`614Zc}~Ts7$X}N97(FU5(&k^3Qr;fLd@?@9Dky<@&&2!On$w zMN0909<=o4PLCN8u*@JLbGBuPTn26*Uh6vNsn-+wq|j3|ukt2S_hnD-Xg850pKP01 zi_d28*-^DxrcNGGj8mmmiK>b95@mbFR`Q!`&4=7#qbWcj8-`wF;oX#Ni|!s(b)fyT zaPR`XQoO`NI+Fr6XZM{1mUg2>$^e+rJ4ZKc&t0+?z6s|-A*Naufenvd)#-%@4iKKN zw>az-_ga52YT;pAZJk~$9d8_^E=4iWt>xX=y#-k>EVO-cnaTf7lrR0G!C2V1irc3& zTRVB2$f*^cpLH)DV|Lr#vra3G7xGT;ofTfF{orcN#@l-%D4qrZt{qz3`*Vo z8qVp?rIE>sFVe8bP_>(DV8QIGjyBCKALuaAGIkh4^rPJC>9x1#I<~3N`}iU=QoC-+ z7lK5JT7)MQCg&lCA9WiwliupWnNd#{eU{uhy{PDb7^cqIX8rT2%^mGoaBfsD6^4qG zX>dJN`6*Y*beWY9dcvaiZK=Fp3&7B=gSmJ+jL~~5r}-DJk_=R3$|mZ-2B>O`w!Ir% z){TBp6t!Uh^ASN!{u&5!2e`*DGJ42o3d6F5%PsKF>AlO*^2QHGRb)h5%eN6ha~4ZE zkHwFk+o+Nt9@y88Q$q7Ajn62OMCx)LBV$(Vim#KC3&MEVAog>hZF#-rV-iXxc{7jS zXC?T2Q!MR^_; zEt=_8-BI2GW*(**u;+`Do?hy!zgSe;Th1Kn^38{EnxD~$W{n%33w6ufH-=kV>0sNwDXV7VzwXf$QKL>SH?fA zuEJ%A`v?2kb*Xu#e6vPNw5mN{v)r(%eeF2%IMv%^woGR4nWXIw32eT+q{Q`W7t){9 zZWfnQ=7Qx#zKs;)69GS*c%WTSt}QqeuU-A?I)0<>)jRtA!s}DE)M4lc{CqFG<`1_c zV{fu&K6^6T@J!o$M*>QU;g`pI-o&|vsMiwTM?lizwFyDwR$grG+J~{|M#b*tIx<>( zX%2Tmb@nF364oq*q9v4fUK|q|wibLqOv~xA?#nMjTwswJVd>Zq=#LvK0|EUgiYV0A zdm(w=B4?VYwXVp5dV5mOp@rl_>Z;sMr@?1vC*WsY8=AuL-Mcwl_z@m0UD(3HvK?l;T` zxf;qOw|+S`i2j$Mtbigz_II;gCpjW8kHVYwT_c+Xt!3F)?*BMRJQk?H(psl5RGmyT zIc6g=qY>BD__Y{AEZ%a=RP4(0$!Ej!b*C6Whdwr6K&Cx;#2+=6WxnRaM~rdI$|w>% zVS|AKC?1AvRW?pRk_X)B*(?P)rGyPwS|iOi7aiHHGdqqeg>D1RW~ zAbhbp4mTy}+>u6IQ01#5cYlBpr9TQ}j$jnezHFI>N({TEIab|QHyTM|9k>qEsBMjy z<9W~uw0~js6|$)toZO-;8%teR>vypI6)+hurRO>>T9PTV8m@rtX(rvdLo?+K`~yO0XzjT|ck?%~=jHF=V=zPkw)E`6y& zu}}4}{q#?j=*rFq(OAZiiLc#EEl@jL`u0qT&h+~gURD_`N0WT6I#QptUp{Yp9?8Mj ziT2EeAkAUQZwC~HPb$=YE|mLab$sg4%PXB_Y#kpn5!gtJ&6*bGeLQ!4Z;@AJRUj?G zk+A~#oNiRqRmDzp6iL-e&Bs6|G~Rx8{7{pyzfcTLkb=Inv8cb21FiY&B3VM7k15UF zwUpVv5$&E~lJ+CQHl@*jT3LGI*tO?m(ZM~=>D!c}kp&7DE%<;JVnz{rkZIq#_8q~q zo1)1&$@Ddx{UkPRe{-^Sal{O=m(0=Y4o=Cdew33p@(ksgxaabD`#v*MGs<%!UIZ|OZ7_H`0oUs5GQF#EMJ zm7zE3OkzMXS{@_CCH;2b?e!`D7Gz5>(J-RvXt65wF%E^hS1tlka&n0T} zXeNmvORnPvfWR&E@xgkJl)mhHUt*x7eOHVqt;N{7NcV*7%-#{B!0%n|X2Bp>Fgo3iacsgJ4&=8?np5 z`6OFiz;wIzMZlO_*m)40AIYD+JEfP_qx7LL>j`V|{<_D?4Co1pnzGjP;Hxe*f4W^q zTyM>~8T>OZ{r(m8^X^3(Y^Xn%@7xE(16A4YzgtIWi+#~de>rdTUKmInaQvHS>L&;2 UCUCLi;vX1V>W|b)?^=icFF3L%;{X5v literal 0 HcmV?d00001 diff --git a/libraries/phpmailer/phpmailer/examples/images/phpmailer_mini.gif b/libraries/phpmailer/phpmailer/examples/images/phpmailer_mini.gif new file mode 100644 index 0000000000000000000000000000000000000000..dc7d7827cca7fe17cb32e76f0b264842d15f9534 GIT binary patch literal 1042 zcmV+t1nv7rNk%w1VNU=%0M-8hz`($)006;2K*mr|%V1#8aB$XufZLCc;Gdu6udnLA zzwgh__21w6@9+Qr|IEzH$H&LQ!otA7z`nk|yu7@*xw*KwxVN{rwY9ahw6wFcv$C?X zt*x!8si~-_sHUc-q@<*to}QhZot&JUnwpxJn3$E7m6Vi}l9G~Q7s?<@S(b!Mg+*99Zt_S)X2sM8 zY6#>rQ}5oCd1yLWBS>vengia{43J__iUKvA9G(fcYGIi^1Ize3x2@YndQV!Rd1uI@ z0|rn+Iv8oM7=+lg|rL5G907GeCPGaUMVu8 zajG&HZ@0r16-O&zrEyobPs}o`B2}^(1XmI}=G&KwX3u5nRyX3RPp<^URVQrYuFf%E6kqemwY0Kss(X+{f%9HjyERn}LRuIc(2 z_b1+|g{P9(T;cXp(u+e7*!=kS+#669m$E*5NG7S|l1wi7-GbfVC}m+%PI+9FI97B7TbBXwLdKYe z>9wVoVnSKwnqh+3CYx`@=_Z?L!U<-YT7ISHo^@`)!@X(sBXqGbX~ zD4=%+S_hwb(uqc-jkfuypp2qv=9g-QX~v>$jq0bSnD#m6o^@6#DV&7932CBds>-LN zbuQD4ov^Oj>948sYO609JQAy%b;b&;t%I6+>8)bcaKZ(TU@7GeF_1t39oD*dLkk}e z5rGFOyf6a}I;5*F?z-%@>+ZYo#`|s#Hpt+D2u4W2K?o+Kpu!3O2Q2Ww1Q%@Z!3Y + + + + PHPMailer Examples + + +

PHPMailer code examplesPHPMailer logo

+

This folder contains a collection of examples of using PHPMailer.

+

About testing email sending

+

When working on email sending code you'll find yourself worrying about what might happen if all these test emails got sent to your mailing list. The solution is to use a fake mail server, one that acts just like the real thing, but just doesn't actually send anything out. Some offer web interfaces, feedback, logging, the ability to return specific error codes, all things that are useful for testing error handling, authentication etc. Here's a selection of mail testing tools you might like to try:

+
    +
  • FakeEmail, a Python-based fake mail server with a web interface.
  • +
  • smtp-sink, part of the Postfix mail server, so you probably already have this installed. This is used in the Travis-CI configuration to run PHPMailer's unit tests.
  • +
  • FakeSMTP, a Java desktop app with the ability to show an SMTP log and save messages to a folder.
  • +
  • smtp4dev, a dummy SMTP server for Windows.
  • +
  • fakesendmail.sh, part of PHPMailer's test setup, this is a shell script that emulates sendmail for testing 'mail' or 'sendmail' methods in PHPMailer.
  • +
  • msglint, not a mail server, the IETF's MIME structure analyser checks the formatting of your messages.
  • +
+
+

Security note

+

Before running these examples you'll need to rename them with '.php' extensions. They are supplied as '.phps' files which will usually be displayed with syntax highlighting by PHP instead of running them. This prevents potential security issues with running potential spam-gateway code if you happen to deploy these code examples on a live site - please don't do that! Similarly, don't leave your passwords in these files as they will be visible to the world!

+
+

code_generator.phps

+

This script is a simple code generator - fill in the form and hit submit, and it will use when you entered to email you a message, and will also generate PHP code using your settings that you can copy and paste to use in your own apps. If you need to get going quickly, this is probably the best place to start.

+

mail.phps

+

This script is a basic example which creates an email message from an external HTML file, creates a plain text body, sets various addresses, adds an attachment and sends the message. It uses PHP's built-in mail() function which is the simplest to use, but relies on the presence of a local mail server, something which is not usually available on Windows. If you find yourself in that sitution, either install a local mail server, or use a remote one and send using SMTP instead.

+

exceptions.phps

+

The same as the mail example, but shows how to use PHPMailer's optional exceptions for error handling.

+

smtp.phps

+

A simple example sending using SMTP with authentication.

+

smtp_no_auth.phps

+

A simple example sending using SMTP without authentication.

+

sendmail.phps

+

A simple example using sendmail. Sendmail is a program (usually found on Linux/BSD, OS X and other UNIX-alikes) that can be used to submit messages to a local mail server without a lengthy SMTP conversation. It's probably the fastest sending mechanism, but lacks some error reporting features. There are sendmail emulators for most popular mail servers including postfix, qmail, exim etc.

+

gmail.phps

+

Submitting email via Google's Gmail service is a popular use of PHPMailer. It's much the same as normal SMTP sending, just with some specific settings, namely using TLS encryption, authentication is enabled, and it connects to the SMTP submission port 587 on the smtp.gmail.com host. This example does all that.

+

pop_before_smtp.phps

+

Before effective SMTP authentication mechanisms were available, it was common for ISPs to use POP-before-SMTP authentication. As it implies, you authenticate using the POP3 protocol (an older protocol now mostly replaced by the far superior IMAP), and then the SMTP server will allow send access from your IP address for a short while, usually 5-15 minutes. PHPMailer includes a POP3 protocol client, so it can carry out this sequence - it's just like a normal SMTP conversation (without authentication), but connects via POP first.

+

mailing_list.phps

+

This is a somewhat naïve example of sending similar emails to a list of different addresses. It sets up a PHPMailer instance using SMTP, then connects to a MySQL database to retrieve a list of recipients. The code loops over this list, sending email to each person using their info and marks them as sent in the database. It makes use of SMTP keepalive which saves reconnecting and re-authenticating between each message.

+
+

Most of these examples use the 'example.com' domain. This domain is reserved by IANA for illustrative purposes, as documented in RFC 2606. Don't use made-up domains like 'mydomain.com' or 'somedomain.com' in examples as someone, somewhere, probably owns them!

+ + diff --git a/libraries/phpmailer/phpmailer/examples/mail.phps b/libraries/phpmailer/phpmailer/examples/mail.phps new file mode 100644 index 0000000000000..fcc8ef9dc5c73 --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/mail.phps @@ -0,0 +1,37 @@ + + + + + PHPMailer - mail() test + + +setFrom('from@example.com', 'First Last'); +//Set an alternative reply-to address +$mail->addReplyTo('replyto@example.com', 'First Last'); +//Set who the message is to be sent to +$mail->addAddress('whoto@example.com', 'John Doe'); +//Set the subject line +$mail->Subject = 'PHPMailer mail() test'; +//Read an HTML message body from an external file, convert referenced images to embedded, +//convert HTML into a basic plain-text alternative body +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); +//Replace the plain text body with one created manually +$mail->AltBody = 'This is a plain-text message body'; +//Attach an image file +$mail->addAttachment('images/phpmailer_mini.gif'); + +//send the message, check for errors +if (!$mail->send()) { + echo "Mailer Error: " . $mail->ErrorInfo; +} else { + echo "Message sent!"; +} +?> + + diff --git a/libraries/phpmailer/phpmailer/examples/mailing_list.phps b/libraries/phpmailer/phpmailer/examples/mailing_list.phps new file mode 100644 index 0000000000000..8d0fc5fcdecb2 --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/mailing_list.phps @@ -0,0 +1,51 @@ +isSMTP(); +$mail->Host = 'smtp.example.com'; +$mail->SMTPAuth = true; +$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead +$mail->Host = 'mail.example.com'; +$mail->Port = 25; +$mail->Username = 'yourname@example.com'; +$mail->Password = 'yourpassword'; +$mail->setFrom('list@example.com', 'List manager'); +$mail->addReplyTo('list@example.com', 'List manager'); + +$mail->Subject = "PHPMailer Simple database mailing list test"; + +//connect to the database and select the recipients from your mailing list that have not yet been sent to +//You'll need to alter this to match your database +$mysql = mysql_connect('localhost', 'username', 'password'); +mysql_select_db('mydb', $mysql); +$result = mysql_query("SELECT full_name, email, photo FROM mailinglist WHERE sent = false", $mysql); + +while ($row = mysql_fetch_array($result)) { + $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; + $mail->msgHTML($body); + $mail->addAddress($row['email'], $row['full_name']); + $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB + + if (!$mail->send()) { + echo "Mailer Error (" . str_replace("@", "@", $row["email"]) . ') ' . $mail->ErrorInfo . '
'; + break; //Abandon sending + } else { + echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "@", $row['email']) . ')
'; + //Mark it as sent in the DB + mysql_query( + "UPDATE mailinglist SET sent = true WHERE email = '" . mysql_real_escape_string($row['email'], $mysql) . "'" + ); + } + // Clear all addresses and attachments for next loop + $mail->clearAddresses(); + $mail->clearAttachments(); +} diff --git a/libraries/phpmailer/phpmailer/examples/pop_before_smtp.phps b/libraries/phpmailer/phpmailer/examples/pop_before_smtp.phps new file mode 100644 index 0000000000000..d4012cf8bd264 --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/pop_before_smtp.phps @@ -0,0 +1,60 @@ + + + + + PHPMailer - POP-before-SMTP test + + +isSMTP(); + //Enable SMTP debugging + // 0 = off (for production use) + // 1 = client messages + // 2 = client and server messages + $mail->SMTPDebug = 2; + //Ask for HTML-friendly debug output + $mail->Debugoutput = 'html'; + //Set the hostname of the mail server + $mail->Host = "mail.example.com"; + //Set the SMTP port number - likely to be 25, 465 or 587 + $mail->Port = 25; + //Whether to use SMTP authentication + $mail->SMTPAuth = false; + //Set who the message is to be sent from + $mail->setFrom('from@example.com', 'First Last'); + //Set an alternative reply-to address + $mail->addReplyTo('replyto@example.com', 'First Last'); + //Set who the message is to be sent to + $mail->addAddress('whoto@example.com', 'John Doe'); + //Set the subject line + $mail->Subject = 'PHPMailer POP-before-SMTP test'; + //Read an HTML message body from an external file, convert referenced images to embedded, + //and convert the HTML into a basic plain-text alternative body + $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); + //Replace the plain text body with one created manually + $mail->AltBody = 'This is a plain-text message body'; + //Attach an image file + $mail->addAttachment('images/phpmailer_mini.gif'); + //send the message + //Note that we don't need check the response from this because it will throw an exception if it has trouble + $mail->send(); + echo "Message sent!"; +} catch (phpmailerException $e) { + echo $e->errorMessage(); //Pretty error messages from PHPMailer +} catch (Exception $e) { + echo $e->getMessage(); //Boring error messages from anything else! +} +?> + + diff --git a/libraries/phpmailer/phpmailer/examples/scripts/XRegExp.js b/libraries/phpmailer/phpmailer/examples/scripts/XRegExp.js new file mode 100644 index 0000000000000..ebdb9c94859de --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/scripts/XRegExp.js @@ -0,0 +1,664 @@ +// XRegExp 1.5.1 +// (c) 2007-2012 Steven Levithan +// MIT License +// +// Provides an augmented, extensible, cross-browser implementation of regular expressions, +// including support for additional syntax, flags, and methods + +var XRegExp; + +if (XRegExp) { + // Avoid running twice, since that would break references to native globals + throw Error("can't load XRegExp twice in the same frame"); +} + +// Run within an anonymous function to protect variables and avoid new globals +(function (undefined) { + + //--------------------------------- + // Constructor + //--------------------------------- + + // Accepts a pattern and flags; returns a new, extended `RegExp` object. Differs from a native + // regular expression in that additional syntax and flags are supported and cross-browser + // syntax inconsistencies are ameliorated. `XRegExp(/regex/)` clones an existing regex and + // converts to type XRegExp + XRegExp = function (pattern, flags) { + var output = [], + currScope = XRegExp.OUTSIDE_CLASS, + pos = 0, + context, tokenResult, match, chr, regex; + + if (XRegExp.isRegExp(pattern)) { + if (flags !== undefined) + throw TypeError("can't supply flags when constructing one RegExp from another"); + return clone(pattern); + } + // Tokens become part of the regex construction process, so protect against infinite + // recursion when an XRegExp is constructed within a token handler or trigger + if (isInsideConstructor) + throw Error("can't call the XRegExp constructor within token definition functions"); + + flags = flags || ""; + context = { // `this` object for custom tokens + hasNamedCapture: false, + captureNames: [], + hasFlag: function (flag) {return flags.indexOf(flag) > -1;}, + setFlag: function (flag) {flags += flag;} + }; + + while (pos < pattern.length) { + // Check for custom tokens at the current position + tokenResult = runTokens(pattern, pos, currScope, context); + + if (tokenResult) { + output.push(tokenResult.output); + pos += (tokenResult.match[0].length || 1); + } else { + // Check for native multicharacter metasequences (excluding character classes) at + // the current position + if (match = nativ.exec.call(nativeTokens[currScope], pattern.slice(pos))) { + output.push(match[0]); + pos += match[0].length; + } else { + chr = pattern.charAt(pos); + if (chr === "[") + currScope = XRegExp.INSIDE_CLASS; + else if (chr === "]") + currScope = XRegExp.OUTSIDE_CLASS; + // Advance position one character + output.push(chr); + pos++; + } + } + } + + regex = RegExp(output.join(""), nativ.replace.call(flags, flagClip, "")); + regex._xregexp = { + source: pattern, + captureNames: context.hasNamedCapture ? context.captureNames : null + }; + return regex; + }; + + + //--------------------------------- + // Public properties + //--------------------------------- + + XRegExp.version = "1.5.1"; + + // Token scope bitflags + XRegExp.INSIDE_CLASS = 1; + XRegExp.OUTSIDE_CLASS = 2; + + + //--------------------------------- + // Private variables + //--------------------------------- + + var replacementToken = /\$(?:(\d\d?|[$&`'])|{([$\w]+)})/g, + flagClip = /[^gimy]+|([\s\S])(?=[\s\S]*\1)/g, // Nonnative and duplicate flags + quantifier = /^(?:[?*+]|{\d+(?:,\d*)?})\??/, + isInsideConstructor = false, + tokens = [], + // Copy native globals for reference ("native" is an ES3 reserved keyword) + nativ = { + exec: RegExp.prototype.exec, + test: RegExp.prototype.test, + match: String.prototype.match, + replace: String.prototype.replace, + split: String.prototype.split + }, + compliantExecNpcg = nativ.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups + compliantLastIndexIncrement = function () { + var x = /^/g; + nativ.test.call(x, ""); + return !x.lastIndex; + }(), + hasNativeY = RegExp.prototype.sticky !== undefined, + nativeTokens = {}; + + // `nativeTokens` match native multicharacter metasequences only (including deprecated octals, + // excluding character classes) + nativeTokens[XRegExp.INSIDE_CLASS] = /^(?:\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S]))/; + nativeTokens[XRegExp.OUTSIDE_CLASS] = /^(?:\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\d*|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S])|\(\?[:=!]|[?*+]\?|{\d+(?:,\d*)?}\??)/; + + + //--------------------------------- + // Public methods + //--------------------------------- + + // Lets you extend or change XRegExp syntax and create custom flags. This is used internally by + // the XRegExp library and can be used to create XRegExp plugins. This function is intended for + // users with advanced knowledge of JavaScript's regular expression syntax and behavior. It can + // be disabled by `XRegExp.freezeTokens` + XRegExp.addToken = function (regex, handler, scope, trigger) { + tokens.push({ + pattern: clone(regex, "g" + (hasNativeY ? "y" : "")), + handler: handler, + scope: scope || XRegExp.OUTSIDE_CLASS, + trigger: trigger || null + }); + }; + + // Accepts a pattern and flags; returns an extended `RegExp` object. If the pattern and flag + // combination has previously been cached, the cached copy is returned; otherwise the newly + // created regex is cached + XRegExp.cache = function (pattern, flags) { + var key = pattern + "/" + (flags || ""); + return XRegExp.cache[key] || (XRegExp.cache[key] = XRegExp(pattern, flags)); + }; + + // Accepts a `RegExp` instance; returns a copy with the `/g` flag set. The copy has a fresh + // `lastIndex` (set to zero). If you want to copy a regex without forcing the `global` + // property, use `XRegExp(regex)`. Do not use `RegExp(regex)` because it will not preserve + // special properties required for named capture + XRegExp.copyAsGlobal = function (regex) { + return clone(regex, "g"); + }; + + // Accepts a string; returns the string with regex metacharacters escaped. The returned string + // can safely be used at any point within a regex to match the provided literal string. Escaped + // characters are [ ] { } ( ) * + ? - . , \ ^ $ | # and whitespace + XRegExp.escape = function (str) { + return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + }; + + // Accepts a string to search, regex to search with, position to start the search within the + // string (default: 0), and an optional Boolean indicating whether matches must start at-or- + // after the position or at the specified position only. This function ignores the `lastIndex` + // of the provided regex in its own handling, but updates the property for compatibility + XRegExp.execAt = function (str, regex, pos, anchored) { + var r2 = clone(regex, "g" + ((anchored && hasNativeY) ? "y" : "")), + match; + r2.lastIndex = pos = pos || 0; + match = r2.exec(str); // Run the altered `exec` (required for `lastIndex` fix, etc.) + if (anchored && match && match.index !== pos) + match = null; + if (regex.global) + regex.lastIndex = match ? r2.lastIndex : 0; + return match; + }; + + // Breaks the unrestorable link to XRegExp's private list of tokens, thereby preventing + // syntax and flag changes. Should be run after XRegExp and any plugins are loaded + XRegExp.freezeTokens = function () { + XRegExp.addToken = function () { + throw Error("can't run addToken after freezeTokens"); + }; + }; + + // Accepts any value; returns a Boolean indicating whether the argument is a `RegExp` object. + // Note that this is also `true` for regex literals and regexes created by the `XRegExp` + // constructor. This works correctly for variables created in another frame, when `instanceof` + // and `constructor` checks would fail to work as intended + XRegExp.isRegExp = function (o) { + return Object.prototype.toString.call(o) === "[object RegExp]"; + }; + + // Executes `callback` once per match within `str`. Provides a simpler and cleaner way to + // iterate over regex matches compared to the traditional approaches of subverting + // `String.prototype.replace` or repeatedly calling `exec` within a `while` loop + XRegExp.iterate = function (str, regex, callback, context) { + var r2 = clone(regex, "g"), + i = -1, match; + while (match = r2.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.) + if (regex.global) + regex.lastIndex = r2.lastIndex; // Doing this to follow expectations if `lastIndex` is checked within `callback` + callback.call(context, match, ++i, str, regex); + if (r2.lastIndex === match.index) + r2.lastIndex++; + } + if (regex.global) + regex.lastIndex = 0; + }; + + // Accepts a string and an array of regexes; returns the result of using each successive regex + // to search within the matches of the previous regex. The array of regexes can also contain + // objects with `regex` and `backref` properties, in which case the named or numbered back- + // references specified are passed forward to the next regex or returned. E.g.: + // var xregexpImgFileNames = XRegExp.matchChain(html, [ + // {regex: /]+)>/i, backref: 1}, // tag attributes + // {regex: XRegExp('(?ix) \\s src=" (? [^"]+ )'), backref: "src"}, // src attribute values + // {regex: XRegExp("^http://xregexp\\.com(/[^#?]+)", "i"), backref: 1}, // xregexp.com paths + // /[^\/]+$/ // filenames (strip directory paths) + // ]); + XRegExp.matchChain = function (str, chain) { + return function recurseChain (values, level) { + var item = chain[level].regex ? chain[level] : {regex: chain[level]}, + regex = clone(item.regex, "g"), + matches = [], i; + for (i = 0; i < values.length; i++) { + XRegExp.iterate(values[i], regex, function (match) { + matches.push(item.backref ? (match[item.backref] || "") : match[0]); + }); + } + return ((level === chain.length - 1) || !matches.length) ? + matches : recurseChain(matches, level + 1); + }([str], 0); + }; + + + //--------------------------------- + // New RegExp prototype methods + //--------------------------------- + + // Accepts a context object and arguments array; returns the result of calling `exec` with the + // first value in the arguments array. the context is ignored but is accepted for congruity + // with `Function.prototype.apply` + RegExp.prototype.apply = function (context, args) { + return this.exec(args[0]); + }; + + // Accepts a context object and string; returns the result of calling `exec` with the provided + // string. the context is ignored but is accepted for congruity with `Function.prototype.call` + RegExp.prototype.call = function (context, str) { + return this.exec(str); + }; + + + //--------------------------------- + // Overriden native methods + //--------------------------------- + + // Adds named capture support (with backreferences returned as `result.name`), and fixes two + // cross-browser issues per ES3: + // - Captured values for nonparticipating capturing groups should be returned as `undefined`, + // rather than the empty string. + // - `lastIndex` should not be incremented after zero-length matches. + RegExp.prototype.exec = function (str) { + var match, name, r2, origLastIndex; + if (!this.global) + origLastIndex = this.lastIndex; + match = nativ.exec.apply(this, arguments); + if (match) { + // Fix browsers whose `exec` methods don't consistently return `undefined` for + // nonparticipating capturing groups + if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { + r2 = RegExp(this.source, nativ.replace.call(getNativeFlags(this), "g", "")); + // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed + // matching due to characters outside the match + nativ.replace.call((str + "").slice(match.index), r2, function () { + for (var i = 1; i < arguments.length - 2; i++) { + if (arguments[i] === undefined) + match[i] = undefined; + } + }); + } + // Attach named capture properties + if (this._xregexp && this._xregexp.captureNames) { + for (var i = 1; i < match.length; i++) { + name = this._xregexp.captureNames[i - 1]; + if (name) + match[name] = match[i]; + } + } + // Fix browsers that increment `lastIndex` after zero-length matches + if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + } + if (!this.global) + this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) + return match; + }; + + // Fix browser bugs in native method + RegExp.prototype.test = function (str) { + // Use the native `exec` to skip some processing overhead, even though the altered + // `exec` would take care of the `lastIndex` fixes + var match, origLastIndex; + if (!this.global) + origLastIndex = this.lastIndex; + match = nativ.exec.call(this, str); + // Fix browsers that increment `lastIndex` after zero-length matches + if (match && !compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + if (!this.global) + this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) + return !!match; + }; + + // Adds named capture support and fixes browser bugs in native method + String.prototype.match = function (regex) { + if (!XRegExp.isRegExp(regex)) + regex = RegExp(regex); // Native `RegExp` + if (regex.global) { + var result = nativ.match.apply(this, arguments); + regex.lastIndex = 0; // Fix IE bug + return result; + } + return regex.exec(this); // Run the altered `exec` + }; + + // Adds support for `${n}` tokens for named and numbered backreferences in replacement text, + // and provides named backreferences to replacement functions as `arguments[0].name`. Also + // fixes cross-browser differences in replacement text syntax when performing a replacement + // using a nonregex search value, and the value of replacement regexes' `lastIndex` property + // during replacement iterations. Note that this doesn't support SpiderMonkey's proprietary + // third (`flags`) parameter + String.prototype.replace = function (search, replacement) { + var isRegex = XRegExp.isRegExp(search), + captureNames, result, str, origLastIndex; + + // There are too many combinations of search/replacement types/values and browser bugs that + // preclude passing to native `replace`, so don't try + //if (...) + // return nativ.replace.apply(this, arguments); + + if (isRegex) { + if (search._xregexp) + captureNames = search._xregexp.captureNames; // Array or `null` + if (!search.global) + origLastIndex = search.lastIndex; + } else { + search = search + ""; // Type conversion + } + + if (Object.prototype.toString.call(replacement) === "[object Function]") { + result = nativ.replace.call(this + "", search, function () { + if (captureNames) { + // Change the `arguments[0]` string primitive to a String object which can store properties + arguments[0] = new String(arguments[0]); + // Store named backreferences on `arguments[0]` + for (var i = 0; i < captureNames.length; i++) { + if (captureNames[i]) + arguments[0][captureNames[i]] = arguments[i + 1]; + } + } + // Update `lastIndex` before calling `replacement` (fix browsers) + if (isRegex && search.global) + search.lastIndex = arguments[arguments.length - 2] + arguments[0].length; + return replacement.apply(null, arguments); + }); + } else { + str = this + ""; // Type conversion, so `args[args.length - 1]` will be a string (given nonstring `this`) + result = nativ.replace.call(str, search, function () { + var args = arguments; // Keep this function's `arguments` available through closure + return nativ.replace.call(replacement + "", replacementToken, function ($0, $1, $2) { + // Numbered backreference (without delimiters) or special variable + if ($1) { + switch ($1) { + case "$": return "$"; + case "&": return args[0]; + case "`": return args[args.length - 1].slice(0, args[args.length - 2]); + case "'": return args[args.length - 1].slice(args[args.length - 2] + args[0].length); + // Numbered backreference + default: + // What does "$10" mean? + // - Backreference 10, if 10 or more capturing groups exist + // - Backreference 1 followed by "0", if 1-9 capturing groups exist + // - Otherwise, it's the string "$10" + // Also note: + // - Backreferences cannot be more than two digits (enforced by `replacementToken`) + // - "$01" is equivalent to "$1" if a capturing group exists, otherwise it's the string "$01" + // - There is no "$0" token ("$&" is the entire match) + var literalNumbers = ""; + $1 = +$1; // Type conversion; drop leading zero + if (!$1) // `$1` was "0" or "00" + return $0; + while ($1 > args.length - 3) { + literalNumbers = String.prototype.slice.call($1, -1) + literalNumbers; + $1 = Math.floor($1 / 10); // Drop the last digit + } + return ($1 ? args[$1] || "" : "$") + literalNumbers; + } + // Named backreference or delimited numbered backreference + } else { + // What does "${n}" mean? + // - Backreference to numbered capture n. Two differences from "$n": + // - n can be more than two digits + // - Backreference 0 is allowed, and is the entire match + // - Backreference to named capture n, if it exists and is not a number overridden by numbered capture + // - Otherwise, it's the string "${n}" + var n = +$2; // Type conversion; drop leading zeros + if (n <= args.length - 3) + return args[n]; + n = captureNames ? indexOf(captureNames, $2) : -1; + return n > -1 ? args[n + 1] : $0; + } + }); + }); + } + + if (isRegex) { + if (search.global) + search.lastIndex = 0; // Fix IE, Safari bug (last tested IE 9.0.5, Safari 5.1.2 on Windows) + else + search.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) + } + + return result; + }; + + // A consistent cross-browser, ES3 compliant `split` + String.prototype.split = function (s /* separator */, limit) { + // If separator `s` is not a regex, use the native `split` + if (!XRegExp.isRegExp(s)) + return nativ.split.apply(this, arguments); + + var str = this + "", // Type conversion + output = [], + lastLastIndex = 0, + match, lastLength; + + // Behavior for `limit`: if it's... + // - `undefined`: No limit + // - `NaN` or zero: Return an empty array + // - A positive number: Use `Math.floor(limit)` + // - A negative number: No limit + // - Other: Type-convert, then use the above rules + if (limit === undefined || +limit < 0) { + limit = Infinity; + } else { + limit = Math.floor(+limit); + if (!limit) + return []; + } + + // This is required if not `s.global`, and it avoids needing to set `s.lastIndex` to zero + // and restore it to its original value when we're done using the regex + s = XRegExp.copyAsGlobal(s); + + while (match = s.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.) + if (s.lastIndex > lastLastIndex) { + output.push(str.slice(lastLastIndex, match.index)); + + if (match.length > 1 && match.index < str.length) + Array.prototype.push.apply(output, match.slice(1)); + + lastLength = match[0].length; + lastLastIndex = s.lastIndex; + + if (output.length >= limit) + break; + } + + if (s.lastIndex === match.index) + s.lastIndex++; + } + + if (lastLastIndex === str.length) { + if (!nativ.test.call(s, "") || lastLength) + output.push(""); + } else { + output.push(str.slice(lastLastIndex)); + } + + return output.length > limit ? output.slice(0, limit) : output; + }; + + + //--------------------------------- + // Private helper functions + //--------------------------------- + + // Supporting function for `XRegExp`, `XRegExp.copyAsGlobal`, etc. Returns a copy of a `RegExp` + // instance with a fresh `lastIndex` (set to zero), preserving properties required for named + // capture. Also allows adding new flags in the process of copying the regex + function clone (regex, additionalFlags) { + if (!XRegExp.isRegExp(regex)) + throw TypeError("type RegExp expected"); + var x = regex._xregexp; + regex = XRegExp(regex.source, getNativeFlags(regex) + (additionalFlags || "")); + if (x) { + regex._xregexp = { + source: x.source, + captureNames: x.captureNames ? x.captureNames.slice(0) : null + }; + } + return regex; + } + + function getNativeFlags (regex) { + return (regex.global ? "g" : "") + + (regex.ignoreCase ? "i" : "") + + (regex.multiline ? "m" : "") + + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 + (regex.sticky ? "y" : ""); + } + + function runTokens (pattern, index, scope, context) { + var i = tokens.length, + result, match, t; + // Protect against constructing XRegExps within token handler and trigger functions + isInsideConstructor = true; + // Must reset `isInsideConstructor`, even if a `trigger` or `handler` throws + try { + while (i--) { // Run in reverse order + t = tokens[i]; + if ((scope & t.scope) && (!t.trigger || t.trigger.call(context))) { + t.pattern.lastIndex = index; + match = t.pattern.exec(pattern); // Running the altered `exec` here allows use of named backreferences, etc. + if (match && match.index === index) { + result = { + output: t.handler.call(context, match, scope), + match: match + }; + break; + } + } + } + } catch (err) { + throw err; + } finally { + isInsideConstructor = false; + } + return result; + } + + function indexOf (array, item, from) { + if (Array.prototype.indexOf) // Use the native array method if available + return array.indexOf(item, from); + for (var i = from || 0; i < array.length; i++) { + if (array[i] === item) + return i; + } + return -1; + } + + + //--------------------------------- + // Built-in tokens + //--------------------------------- + + // Augment XRegExp's regular expression syntax and flags. Note that when adding tokens, the + // third (`scope`) argument defaults to `XRegExp.OUTSIDE_CLASS` + + // Comment pattern: (?# ) + XRegExp.addToken( + /\(\?#[^)]*\)/, + function (match) { + // Keep tokens separated unless the following token is a quantifier + return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)"; + } + ); + + // Capturing group (match the opening parenthesis only). + // Required for support of named capturing groups + XRegExp.addToken( + /\((?!\?)/, + function () { + this.captureNames.push(null); + return "("; + } + ); + + // Named capturing group (match the opening delimiter only): (? + XRegExp.addToken( + /\(\?<([$\w]+)>/, + function (match) { + this.captureNames.push(match[1]); + this.hasNamedCapture = true; + return "("; + } + ); + + // Named backreference: \k + XRegExp.addToken( + /\\k<([\w$]+)>/, + function (match) { + var index = indexOf(this.captureNames, match[1]); + // Keep backreferences separate from subsequent literal numbers. Preserve back- + // references to named groups that are undefined at this point as literal strings + return index > -1 ? + "\\" + (index + 1) + (isNaN(match.input.charAt(match.index + match[0].length)) ? "" : "(?:)") : + match[0]; + } + ); + + // Empty character class: [] or [^] + XRegExp.addToken( + /\[\^?]/, + function (match) { + // For cross-browser compatibility with ES3, convert [] to \b\B and [^] to [\s\S]. + // (?!) should work like \b\B, but is unreliable in Firefox + return match[0] === "[]" ? "\\b\\B" : "[\\s\\S]"; + } + ); + + // Mode modifier at the start of the pattern only, with any combination of flags imsx: (?imsx) + // Does not support x(?i), (?-i), (?i-m), (?i: ), (?i)(?m), etc. + XRegExp.addToken( + /^\(\?([imsx]+)\)/, + function (match) { + this.setFlag(match[1]); + return ""; + } + ); + + // Whitespace and comments, in free-spacing (aka extended) mode only + XRegExp.addToken( + /(?:\s+|#.*)+/, + function (match) { + // Keep tokens separated unless the following token is a quantifier + return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)"; + }, + XRegExp.OUTSIDE_CLASS, + function () {return this.hasFlag("x");} + ); + + // Dot, in dotall (aka singleline) mode only + XRegExp.addToken( + /\./, + function () {return "[\\s\\S]";}, + XRegExp.OUTSIDE_CLASS, + function () {return this.hasFlag("s");} + ); + + + //--------------------------------- + // Backward compatibility + //--------------------------------- + + // Uncomment the following block for compatibility with XRegExp 1.0-1.2: + /* + XRegExp.matchWithinChain = XRegExp.matchChain; + RegExp.prototype.addFlags = function (s) {return clone(this, s);}; + RegExp.prototype.execAll = function (s) {var r = []; XRegExp.iterate(s, this, function (m) {r.push(m);}); return r;}; + RegExp.prototype.forEachExec = function (s, f, c) {return XRegExp.iterate(s, this, f, c);}; + RegExp.prototype.validate = function (s) {var r = RegExp("^(?:" + this.source + ")$(?!\\s)", getNativeFlags(this)); if (this.global) this.lastIndex = 0; return s.search(r) === 0;}; + */ + +})(); + diff --git a/libraries/phpmailer/phpmailer/examples/scripts/shAutoloader.js b/libraries/phpmailer/phpmailer/examples/scripts/shAutoloader.js new file mode 100644 index 0000000000000..9f5942ee27d58 --- /dev/null +++ b/libraries/phpmailer/phpmailer/examples/scripts/shAutoloader.js @@ -0,0 +1,122 @@ +(function() { + +var sh = SyntaxHighlighter; + +/** + * Provides functionality to dynamically load only the brushes that a needed to render the current page. + * + * There are two syntaxes that autoload understands. For example: + * + * SyntaxHighlighter.autoloader( + * [ 'applescript', 'Scripts/shBrushAppleScript.js' ], + * [ 'actionscript3', 'as3', 'Scripts/shBrushAS3.js' ] + * ); + * + * or a more easily comprehendable one: + * + * SyntaxHighlighter.autoloader( + * 'applescript Scripts/shBrushAppleScript.js', + * 'actionscript3 as3 Scripts/shBrushAS3.js' + * ); + */ +sh.autoloader = function() +{ + var list = arguments, + elements = sh.findElements(), + brushes = {}, + scripts = {}, + all = SyntaxHighlighter.all, + allCalled = false, + allParams = null, + i + ; + + SyntaxHighlighter.all = function(params) + { + allParams = params; + allCalled = true; + }; + + function addBrush(aliases, url) + { + for (var i = 0; i < aliases.length; i++) + brushes[aliases[i]] = url; + }; + + function getAliases(item) + { + return item.pop + ? item + : item.split(/\s+/) + ; + } + + // create table of aliases and script urls + for (i = 0; i < list.length; i++) + { + var aliases = getAliases(list[i]), + url = aliases.pop() + ; + + addBrush(aliases, url); + } + + // dynamically add