From dccdeca2581f705c69eb4266aa646173f588a9de Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Wed, 15 Feb 2012 20:40:37 +0100 Subject: [PATCH] remove the 3rdparty files. everything is now in https://gitorious.org/owncloud/3rdparty --- 3rdparty/Console/Getopt.php | 251 - 3rdparty/Crypt_Blowfish/Blowfish.php | 317 - .../Crypt_Blowfish/Blowfish/DefaultKey.php | 327 -- 3rdparty/MDB2.php | 4316 -------------- 3rdparty/MDB2/Date.php | 183 - 3rdparty/MDB2/Driver/Datatype/Common.php | 1824 ------ 3rdparty/MDB2/Driver/Datatype/mysql.php | 553 -- 3rdparty/MDB2/Driver/Datatype/pgsql.php | 554 -- 3rdparty/MDB2/Driver/Datatype/sqlite.php | 409 -- 3rdparty/MDB2/Driver/Function/Common.php | 293 - 3rdparty/MDB2/Driver/Function/mysql.php | 136 - 3rdparty/MDB2/Driver/Function/pgsql.php | 115 - 3rdparty/MDB2/Driver/Function/sqlite.php | 162 - 3rdparty/MDB2/Driver/Manager/Common.php | 1014 ---- 3rdparty/MDB2/Driver/Manager/mysql.php | 1432 ----- 3rdparty/MDB2/Driver/Manager/pgsql.php | 951 --- 3rdparty/MDB2/Driver/Manager/sqlite.php | 1366 ----- 3rdparty/MDB2/Driver/Native/Common.php | 61 - 3rdparty/MDB2/Driver/Native/mysql.php | 60 - 3rdparty/MDB2/Driver/Native/pgsql.php | 88 - 3rdparty/MDB2/Driver/Native/sqlite.php | 60 - 3rdparty/MDB2/Driver/Reverse/Common.php | 517 -- 3rdparty/MDB2/Driver/Reverse/mysql.php | 536 -- 3rdparty/MDB2/Driver/Reverse/pgsql.php | 573 -- 3rdparty/MDB2/Driver/Reverse/sqlite.php | 609 -- 3rdparty/MDB2/Driver/mysql.php | 1700 ------ 3rdparty/MDB2/Driver/pgsql.php | 1519 ----- 3rdparty/MDB2/Driver/sqlite.php | 1088 ---- 3rdparty/MDB2/Extended.php | 721 --- 3rdparty/MDB2/Iterator.php | 259 - 3rdparty/MDB2/LOB.php | 264 - 3rdparty/MDB2/Schema.php | 2763 --------- 3rdparty/MDB2/Schema/Parser.php | 812 --- 3rdparty/MDB2/Schema/Parser2.php | 624 -- 3rdparty/MDB2/Schema/Reserved/ibase.php | 436 -- 3rdparty/MDB2/Schema/Reserved/mssql.php | 258 - 3rdparty/MDB2/Schema/Reserved/mysql.php | 284 - 3rdparty/MDB2/Schema/Reserved/oci8.php | 171 - 3rdparty/MDB2/Schema/Reserved/pgsql.php | 147 - 3rdparty/MDB2/Schema/Tool.php | 560 -- .../MDB2/Schema/Tool/ParameterException.php | 6 - 3rdparty/MDB2/Schema/Validate.php | 917 --- 3rdparty/MDB2/Schema/Writer.php | 581 -- 3rdparty/PEAR.php | 1055 ---- 3rdparty/PEAR/Autoloader.php | 208 - 3rdparty/PEAR/Builder.php | 426 -- 3rdparty/PEAR/Command.php | 398 -- 3rdparty/PEAR/Command/Auth.php | 155 - 3rdparty/PEAR/Command/Build.php | 89 - 3rdparty/PEAR/Command/Common.php | 249 - 3rdparty/PEAR/Command/Config.php | 225 - 3rdparty/PEAR/Command/Install.php | 470 -- 3rdparty/PEAR/Command/Mirror.php | 101 - 3rdparty/PEAR/Command/Package.php | 819 --- 3rdparty/PEAR/Command/Registry.php | 351 -- 3rdparty/PEAR/Command/Remote.php | 435 -- 3rdparty/PEAR/Common.php | 2094 ------- 3rdparty/PEAR/Config.php | 1169 ---- 3rdparty/PEAR/Dependency.php | 487 -- 3rdparty/PEAR/Downloader.php | 680 --- 3rdparty/PEAR/ErrorStack.php | 981 ---- 3rdparty/PEAR/Exception.php | 359 -- 3rdparty/PEAR/Frontend/CLI.php | 509 -- 3rdparty/PEAR/Installer.php | 1068 ---- 3rdparty/PEAR/Packager.php | 165 - 3rdparty/PEAR/Registry.php | 538 -- 3rdparty/PEAR/Remote.php | 394 -- 3rdparty/PEAR/RunTest.php | 363 -- 3rdparty/README | 2 + 3rdparty/Sabre.includes.php | 127 - 3rdparty/Sabre/CalDAV/Backend/Abstract.php | 163 - 3rdparty/Sabre/CalDAV/Backend/PDO.php | 386 -- 3rdparty/Sabre/CalDAV/Calendar.php | 318 - 3rdparty/Sabre/CalDAV/CalendarObject.php | 260 - 3rdparty/Sabre/CalDAV/CalendarRootNode.php | 75 - .../Exception/InvalidICalendarObject.php | 18 - 3rdparty/Sabre/CalDAV/ICSExportPlugin.php | 124 - 3rdparty/Sabre/CalDAV/ICalendar.php | 18 - 3rdparty/Sabre/CalDAV/ICalendarObject.php | 20 - 3rdparty/Sabre/CalDAV/ICalendarUtil.php | 157 - 3rdparty/Sabre/CalDAV/Plugin.php | 788 --- .../Sabre/CalDAV/Principal/Collection.php | 31 - 3rdparty/Sabre/CalDAV/Principal/ProxyRead.php | 178 - .../Sabre/CalDAV/Principal/ProxyWrite.php | 178 - 3rdparty/Sabre/CalDAV/Principal/User.php | 122 - .../SupportedCalendarComponentSet.php | 85 - .../CalDAV/Property/SupportedCalendarData.php | 38 - .../CalDAV/Property/SupportedCollationSet.php | 44 - 3rdparty/Sabre/CalDAV/Server.php | 65 - 3rdparty/Sabre/CalDAV/UserCalendars.php | 280 - 3rdparty/Sabre/CalDAV/Version.php | 24 - 3rdparty/Sabre/CalDAV/XMLUtil.php | 208 - 3rdparty/Sabre/CardDAV/AddressBook.php | 293 - .../Sabre/CardDAV/AddressBookQueryParser.php | 211 - 3rdparty/Sabre/CardDAV/AddressBookRoot.php | 78 - 3rdparty/Sabre/CardDAV/Backend/Abstract.php | 121 - 3rdparty/Sabre/CardDAV/Backend/PDO.php | 277 - 3rdparty/Sabre/CardDAV/Card.php | 220 - 3rdparty/Sabre/CardDAV/IAddressBook.php | 18 - 3rdparty/Sabre/CardDAV/ICard.php | 18 - 3rdparty/Sabre/CardDAV/IDirectory.php | 21 - 3rdparty/Sabre/CardDAV/Plugin.php | 463 -- .../CardDAV/Property/SupportedAddressData.php | 69 - 3rdparty/Sabre/CardDAV/UserAddressBooks.php | 240 - 3rdparty/Sabre/CardDAV/Version.php | 26 - .../Sabre/DAV/Auth/Backend/AbstractBasic.php | 79 - .../Sabre/DAV/Auth/Backend/AbstractDigest.php | 96 - 3rdparty/Sabre/DAV/Auth/Backend/Apache.php | 60 - 3rdparty/Sabre/DAV/Auth/Backend/File.php | 76 - 3rdparty/Sabre/DAV/Auth/Backend/PDO.php | 66 - 3rdparty/Sabre/DAV/Auth/IBackend.php | 34 - 3rdparty/Sabre/DAV/Auth/Plugin.php | 111 - .../Sabre/DAV/Browser/GuessContentType.php | 97 - .../Sabre/DAV/Browser/MapGetToPropFind.php | 54 - 3rdparty/Sabre/DAV/Browser/Plugin.php | 285 - 3rdparty/Sabre/DAV/Client.php | 431 -- 3rdparty/Sabre/DAV/Collection.php | 90 - 3rdparty/Sabre/DAV/Directory.php | 17 - 3rdparty/Sabre/DAV/Exception.php | 63 - 3rdparty/Sabre/DAV/Exception/BadRequest.php | 28 - 3rdparty/Sabre/DAV/Exception/Conflict.php | 28 - .../Sabre/DAV/Exception/ConflictingLock.php | 35 - 3rdparty/Sabre/DAV/Exception/FileNotFound.php | 28 - 3rdparty/Sabre/DAV/Exception/Forbidden.php | 27 - .../DAV/Exception/InsufficientStorage.php | 27 - .../DAV/Exception/InvalidResourceType.php | 33 - .../Exception/LockTokenMatchesRequestUri.php | 39 - 3rdparty/Sabre/DAV/Exception/Locked.php | 67 - .../Sabre/DAV/Exception/MethodNotAllowed.php | 44 - .../Sabre/DAV/Exception/NotAuthenticated.php | 28 - .../Sabre/DAV/Exception/NotImplemented.php | 27 - .../DAV/Exception/PreconditionFailed.php | 69 - .../DAV/Exception/ReportNotImplemented.php | 30 - .../RequestedRangeNotSatisfiable.php | 29 - .../DAV/Exception/UnsupportedMediaType.php | 28 - 3rdparty/Sabre/DAV/FS/Directory.php | 121 - 3rdparty/Sabre/DAV/FS/File.php | 89 - 3rdparty/Sabre/DAV/FS/Node.php | 81 - 3rdparty/Sabre/DAV/FSExt/Directory.php | 135 - 3rdparty/Sabre/DAV/FSExt/File.php | 88 - 3rdparty/Sabre/DAV/FSExt/Node.php | 276 - 3rdparty/Sabre/DAV/File.php | 81 - 3rdparty/Sabre/DAV/ICollection.php | 58 - 3rdparty/Sabre/DAV/IExtendedCollection.php | 28 - 3rdparty/Sabre/DAV/IFile.php | 63 - 3rdparty/Sabre/DAV/ILockable.php | 38 - 3rdparty/Sabre/DAV/INode.php | 44 - 3rdparty/Sabre/DAV/IProperties.php | 67 - 3rdparty/Sabre/DAV/IQuota.php | 27 - 3rdparty/Sabre/DAV/Locks/Backend/Abstract.php | 50 - 3rdparty/Sabre/DAV/Locks/Backend/FS.php | 189 - 3rdparty/Sabre/DAV/Locks/Backend/File.php | 175 - 3rdparty/Sabre/DAV/Locks/Backend/PDO.php | 165 - 3rdparty/Sabre/DAV/Locks/LockInfo.php | 81 - 3rdparty/Sabre/DAV/Locks/Plugin.php | 680 --- 3rdparty/Sabre/DAV/Mount/Plugin.php | 79 - 3rdparty/Sabre/DAV/Node.php | 55 - 3rdparty/Sabre/DAV/ObjectTree.php | 154 - 3rdparty/Sabre/DAV/Property.php | 25 - .../Sabre/DAV/Property/GetLastModified.php | 75 - 3rdparty/Sabre/DAV/Property/Href.php | 91 - 3rdparty/Sabre/DAV/Property/HrefList.php | 96 - 3rdparty/Sabre/DAV/Property/IHref.php | 25 - 3rdparty/Sabre/DAV/Property/LockDiscovery.php | 102 - 3rdparty/Sabre/DAV/Property/ResourceType.php | 125 - 3rdparty/Sabre/DAV/Property/Response.php | 156 - 3rdparty/Sabre/DAV/Property/ResponseList.php | 58 - 3rdparty/Sabre/DAV/Property/SupportedLock.php | 76 - .../Sabre/DAV/Property/SupportedReportSet.php | 110 - 3rdparty/Sabre/DAV/Server.php | 1941 ------ 3rdparty/Sabre/DAV/ServerPlugin.php | 90 - 3rdparty/Sabre/DAV/SimpleCollection.php | 106 - 3rdparty/Sabre/DAV/SimpleDirectory.php | 21 - 3rdparty/Sabre/DAV/SimpleFile.php | 120 - 3rdparty/Sabre/DAV/StringUtil.php | 91 - .../Sabre/DAV/TemporaryFileFilterPlugin.php | 279 - 3rdparty/Sabre/DAV/Tree.php | 192 - 3rdparty/Sabre/DAV/Tree/Filesystem.php | 124 - 3rdparty/Sabre/DAV/URLUtil.php | 125 - 3rdparty/Sabre/DAV/UUIDUtil.php | 64 - 3rdparty/Sabre/DAV/Version.php | 24 - 3rdparty/Sabre/DAV/XMLUtil.php | 183 - .../DAVACL/AbstractPrincipalCollection.php | 121 - .../Sabre/DAVACL/Exception/AceConflict.php | 34 - .../Sabre/DAVACL/Exception/NeedPrivileges.php | 80 - .../Sabre/DAVACL/Exception/NoAbstract.php | 34 - .../Exception/NotRecognizedPrincipal.php | 34 - .../Exception/NotSupportedPrivilege.php | 34 - 3rdparty/Sabre/DAVACL/IACL.php | 58 - 3rdparty/Sabre/DAVACL/IPrincipal.php | 75 - 3rdparty/Sabre/DAVACL/IPrincipalBackend.php | 73 - 3rdparty/Sabre/DAVACL/Plugin.php | 1238 ---- 3rdparty/Sabre/DAVACL/Principal.php | 263 - .../Sabre/DAVACL/PrincipalBackend/PDO.php | 206 - 3rdparty/Sabre/DAVACL/PrincipalCollection.php | 35 - 3rdparty/Sabre/DAVACL/Property/Acl.php | 186 - .../Property/CurrentUserPrivilegeSet.php | 75 - 3rdparty/Sabre/DAVACL/Property/Principal.php | 154 - .../DAVACL/Property/SupportedPrivilegeSet.php | 92 - 3rdparty/Sabre/DAVACL/Version.php | 24 - 3rdparty/Sabre/HTTP/AWSAuth.php | 226 - 3rdparty/Sabre/HTTP/AbstractAuth.php | 111 - 3rdparty/Sabre/HTTP/BasicAuth.php | 61 - 3rdparty/Sabre/HTTP/DigestAuth.php | 234 - 3rdparty/Sabre/HTTP/Request.php | 243 - 3rdparty/Sabre/HTTP/Response.php | 152 - 3rdparty/Sabre/HTTP/Util.php | 65 - 3rdparty/Sabre/HTTP/Version.php | 24 - 3rdparty/Sabre/LICENCE | 27 - 3rdparty/Sabre/VObject/Component.php | 254 - 3rdparty/Sabre/VObject/Element.php | 15 - 3rdparty/Sabre/VObject/Element/DateTime.php | 245 - .../Sabre/VObject/Element/MultiDateTime.php | 168 - 3rdparty/Sabre/VObject/ElementList.php | 172 - 3rdparty/Sabre/VObject/Node.php | 149 - 3rdparty/Sabre/VObject/Parameter.php | 81 - 3rdparty/Sabre/VObject/ParseException.php | 12 - 3rdparty/Sabre/VObject/Property.php | 289 - 3rdparty/Sabre/VObject/Reader.php | 191 - 3rdparty/Sabre/VObject/Version.php | 24 - 3rdparty/Sabre/VObject/includes.php | 29 - 3rdparty/Sabre/autoload.php | 27 - 3rdparty/System.php | 540 -- 3rdparty/XML/Parser.php | 667 --- 3rdparty/XML/RPC.php | 1951 ------ 3rdparty/XML/RPC/Server.php | 624 -- 3rdparty/css/chosen-sprite.png | Bin 742 -> 0 bytes 3rdparty/css/chosen.css | 341 -- 3rdparty/css/chosen/chosen-sprite.png | Bin 3998 -> 0 bytes 3rdparty/css/chosen/chosen.css | 368 -- 3rdparty/fullcalendar/GPL-LICENSE.txt | 278 - 3rdparty/fullcalendar/MIT-LICENSE.txt | 20 - 3rdparty/fullcalendar/changelog.txt | 313 - 3rdparty/fullcalendar/css/fullcalendar.css | 616 -- .../fullcalendar/css/fullcalendar.print.css | 59 - 3rdparty/fullcalendar/js/fullcalendar.js | 5210 ----------------- 3rdparty/fullcalendar/js/fullcalendar.min.js | 113 - 3rdparty/fullcalendar/js/gcal.js | 112 - 3rdparty/js/chosen/LICENSE.md | 24 - 3rdparty/js/chosen/README.md | 46 - 3rdparty/js/chosen/VERSION | 1 - 3rdparty/js/chosen/chosen.jquery.js | 857 --- 3rdparty/js/chosen/chosen.jquery.min.js | 10 - .../HELP_MY_TESTS_DONT_WORK_ANYMORE | 399 -- 3rdparty/simpletest/LICENSE | 502 -- 3rdparty/simpletest/README | 102 - 3rdparty/simpletest/VERSION | 1 - 3rdparty/simpletest/arguments.php | 224 - 3rdparty/simpletest/authentication.php | 237 - 3rdparty/simpletest/autorun.php | 101 - 3rdparty/simpletest/browser.php | 1144 ---- 3rdparty/simpletest/collector.php | 122 - 3rdparty/simpletest/compatibility.php | 166 - 3rdparty/simpletest/cookies.php | 380 -- 3rdparty/simpletest/default_reporter.php | 163 - 3rdparty/simpletest/detached.php | 96 - .../docs/en/authentication_documentation.html | 378 -- .../docs/en/browser_documentation.html | 501 -- 3rdparty/simpletest/docs/en/docs.css | 121 - .../docs/en/expectation_documentation.html | 476 -- .../docs/en/form_testing_documentation.html | 351 -- .../docs/en/group_test_documentation.html | 252 - 3rdparty/simpletest/docs/en/index.html | 542 -- .../docs/en/mock_objects_documentation.html | 870 --- 3rdparty/simpletest/docs/en/overview.html | 487 -- .../docs/en/partial_mocks_documentation.html | 457 -- .../docs/en/reporter_documentation.html | 616 -- .../docs/en/unit_test_documentation.html | 442 -- .../docs/en/web_tester_documentation.html | 588 -- .../docs/fr/authentication_documentation.html | 372 -- .../docs/fr/browser_documentation.html | 500 -- 3rdparty/simpletest/docs/fr/docs.css | 84 - .../docs/fr/expectation_documentation.html | 451 -- .../docs/fr/form_testing_documentation.html | 363 -- .../docs/fr/group_test_documentation.html | 265 - 3rdparty/simpletest/docs/fr/index.html | 576 -- .../docs/fr/mock_objects_documentation.html | 933 --- 3rdparty/simpletest/docs/fr/overview.html | 321 - .../docs/fr/partial_mocks_documentation.html | 475 -- .../docs/fr/reporter_documentation.html | 630 -- .../docs/fr/unit_test_documentation.html | 447 -- .../docs/fr/web_tester_documentation.html | 570 -- 3rdparty/simpletest/dumper.php | 407 -- 3rdparty/simpletest/eclipse.php | 307 - 3rdparty/simpletest/encoding.php | 649 -- 3rdparty/simpletest/errors.php | 267 - 3rdparty/simpletest/exceptions.php | 226 - 3rdparty/simpletest/expectation.php | 984 ---- .../simpletest/extensions/pear_test_case.php | 196 - 3rdparty/simpletest/extensions/testdox.php | 53 - .../simpletest/extensions/testdox/test.php | 107 - 3rdparty/simpletest/form.php | 361 -- 3rdparty/simpletest/frames.php | 592 -- 3rdparty/simpletest/http.php | 628 -- 3rdparty/simpletest/invoker.php | 139 - 3rdparty/simpletest/mock_objects.php | 1641 ------ 3rdparty/simpletest/page.php | 542 -- 3rdparty/simpletest/php_parser.php | 1054 ---- 3rdparty/simpletest/recorder.php | 101 - 3rdparty/simpletest/reflection_php4.php | 136 - 3rdparty/simpletest/reflection_php5.php | 386 -- 3rdparty/simpletest/remote.php | 115 - 3rdparty/simpletest/reporter.php | 445 -- 3rdparty/simpletest/scorer.php | 875 --- 3rdparty/simpletest/selector.php | 141 - 3rdparty/simpletest/shell_tester.php | 330 -- 3rdparty/simpletest/simpletest.php | 391 -- 3rdparty/simpletest/socket.php | 312 - 3rdparty/simpletest/tag.php | 1527 ----- 3rdparty/simpletest/test/acceptance_test.php | 1729 ------ 3rdparty/simpletest/test/adapter_test.php | 50 - 3rdparty/simpletest/test/all_tests.php | 13 - 3rdparty/simpletest/test/arguments_test.php | 82 - .../simpletest/test/authentication_test.php | 145 - 3rdparty/simpletest/test/autorun_test.php | 23 - 3rdparty/simpletest/test/bad_test_suite.php | 10 - 3rdparty/simpletest/test/browser_test.php | 802 --- 3rdparty/simpletest/test/collector_test.php | 50 - .../simpletest/test/command_line_test.php | 40 - .../simpletest/test/compatibility_test.php | 87 - 3rdparty/simpletest/test/cookies_test.php | 227 - 3rdparty/simpletest/test/detached_test.php | 15 - 3rdparty/simpletest/test/dumper_test.php | 88 - 3rdparty/simpletest/test/eclipse_test.php | 32 - 3rdparty/simpletest/test/encoding_test.php | 240 - 3rdparty/simpletest/test/errors_test.php | 229 - 3rdparty/simpletest/test/exceptions_test.php | 183 - 3rdparty/simpletest/test/expectation_test.php | 317 - 3rdparty/simpletest/test/form_test.php | 344 -- 3rdparty/simpletest/test/frames_test.php | 549 -- 3rdparty/simpletest/test/http_test.php | 492 -- 3rdparty/simpletest/test/interfaces_test.php | 137 - .../test/interfaces_test_php5_1.php | 14 - 3rdparty/simpletest/test/live_test.php | 47 - .../simpletest/test/mock_objects_test.php | 985 ---- 3rdparty/simpletest/test/page_test.php | 166 - 3rdparty/simpletest/test/parse_error_test.php | 9 - 3rdparty/simpletest/test/parsing_test.php | 642 -- 3rdparty/simpletest/test/php_parser_test.php | 489 -- 3rdparty/simpletest/test/recorder_test.php | 23 - .../simpletest/test/reflection_php5_test.php | 263 - 3rdparty/simpletest/test/remote_test.php | 19 - 3rdparty/simpletest/test/shell_test.php | 38 - .../simpletest/test/shell_tester_test.php | 42 - 3rdparty/simpletest/test/simpletest_test.php | 58 - 3rdparty/simpletest/test/site/file.html | 6 - 3rdparty/simpletest/test/socket_test.php | 25 - .../test/support/collector/collectable.1 | 0 .../test/support/collector/collectable.2 | 0 .../test/support/empty_test_file.php | 3 - .../simpletest/test/support/failing_test.php | 9 - .../simpletest/test/support/latin1_sample | 1 - .../simpletest/test/support/passing_test.php | 9 - .../test/support/recorder_sample.php | 14 - .../simpletest/test/support/spl_examples.php | 15 - .../support/supplementary_upload_sample.txt | 1 - 3rdparty/simpletest/test/support/test1.php | 7 - .../simpletest/test/support/upload_sample.txt | 1 - 3rdparty/simpletest/test/tag_test.php | 554 -- .../simpletest/test/test_with_parse_error.php | 8 - 3rdparty/simpletest/test/unit_tester_test.php | 61 - 3rdparty/simpletest/test/unit_tests.php | 49 - 3rdparty/simpletest/test/url_test.php | 515 -- 3rdparty/simpletest/test/user_agent_test.php | 348 -- 3rdparty/simpletest/test/visual_test.php | 495 -- 3rdparty/simpletest/test/web_tester_test.php | 155 - 3rdparty/simpletest/test/xml_test.php | 187 - 3rdparty/simpletest/test_case.php | 658 --- 3rdparty/simpletest/tidy_parser.php | 382 -- 3rdparty/simpletest/unit_tester.php | 413 -- 3rdparty/simpletest/url.php | 550 -- 3rdparty/simpletest/user_agent.php | 328 -- 3rdparty/simpletest/web_tester.php | 1532 ----- 3rdparty/simpletest/xml.php | 647 -- 3rdparty/timepicker/GPL-LICENSE.txt | 278 - 3rdparty/timepicker/MIT-LICENSE.txt | 20 - .../ui-bg_diagonals-thick_18_b81900_40x40.png | Bin 260 -> 0 bytes .../ui-bg_diagonals-thick_20_666666_40x40.png | Bin 251 -> 0 bytes .../images/ui-bg_flat_10_000000_40x100.png | Bin 178 -> 0 bytes .../images/ui-bg_glass_100_f6f6f6_1x400.png | Bin 104 -> 0 bytes .../images/ui-bg_glass_100_fdf5ce_1x400.png | Bin 125 -> 0 bytes .../images/ui-bg_glass_65_ffffff_1x400.png | Bin 105 -> 0 bytes .../ui-bg_gloss-wave_35_f6a828_500x100.png | Bin 3762 -> 0 bytes .../ui-bg_highlight-soft_100_eeeeee_1x100.png | Bin 90 -> 0 bytes .../ui-bg_highlight-soft_75_ffe45c_1x100.png | Bin 129 -> 0 bytes .../images/ui-icons_222222_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_228ef1_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_ef8c08_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_ffd27a_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_ffffff_256x240.png | Bin 4369 -> 0 bytes .../css/include/jquery-1.5.1.min.js | 16 - .../css/include/jquery-ui-1.8.14.custom.css | 568 -- .../css/include/jquery.ui.core.min.js | 17 - .../css/include/jquery.ui.position.min.js | 16 - .../css/include/jquery.ui.tabs.min.js | 35 - .../css/include/jquery.ui.widget.min.js | 15 - .../ui-bg_diagonals-thick_18_b81900_40x40.png | Bin 260 -> 0 bytes .../ui-bg_diagonals-thick_20_666666_40x40.png | Bin 251 -> 0 bytes .../images/ui-bg_flat_10_000000_40x100.png | Bin 178 -> 0 bytes .../images/ui-bg_glass_100_f6f6f6_1x400.png | Bin 104 -> 0 bytes .../images/ui-bg_glass_100_fdf5ce_1x400.png | Bin 125 -> 0 bytes .../images/ui-bg_glass_65_ffffff_1x400.png | Bin 105 -> 0 bytes .../ui-bg_gloss-wave_35_f6a828_500x100.png | Bin 3762 -> 0 bytes .../ui-bg_highlight-soft_100_eeeeee_1x100.png | Bin 90 -> 0 bytes .../ui-bg_highlight-soft_75_ffe45c_1x100.png | Bin 129 -> 0 bytes .../images/ui-icons_222222_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_228ef1_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_ef8c08_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_ffd27a_256x240.png | Bin 4369 -> 0 bytes .../images/ui-icons_ffffff_256x240.png | Bin 4369 -> 0 bytes .../timepicker/css/jquery.ui.timepicker.css | 69 - 3rdparty/timepicker/js/i18n/i18n.html | 73 - .../js/i18n/jquery.ui.timepicker-de.js | 9 - .../js/i18n/jquery.ui.timepicker-fr.js | 13 - .../js/i18n/jquery.ui.timepicker-ja.js | 9 - .../timepicker/js/jquery.ui.timepicker.js | 1345 ----- 3rdparty/timepicker/releases.txt | 105 - 3rdparty/when/MIT-LICENSE.txt | 9 - 3rdparty/when/When.php | 731 --- 419 files changed, 2 insertions(+), 123978 deletions(-) delete mode 100644 3rdparty/Console/Getopt.php delete mode 100644 3rdparty/Crypt_Blowfish/Blowfish.php delete mode 100644 3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php delete mode 100644 3rdparty/MDB2.php delete mode 100644 3rdparty/MDB2/Date.php delete mode 100644 3rdparty/MDB2/Driver/Datatype/Common.php delete mode 100644 3rdparty/MDB2/Driver/Datatype/mysql.php delete mode 100644 3rdparty/MDB2/Driver/Datatype/pgsql.php delete mode 100644 3rdparty/MDB2/Driver/Datatype/sqlite.php delete mode 100644 3rdparty/MDB2/Driver/Function/Common.php delete mode 100644 3rdparty/MDB2/Driver/Function/mysql.php delete mode 100644 3rdparty/MDB2/Driver/Function/pgsql.php delete mode 100644 3rdparty/MDB2/Driver/Function/sqlite.php delete mode 100644 3rdparty/MDB2/Driver/Manager/Common.php delete mode 100644 3rdparty/MDB2/Driver/Manager/mysql.php delete mode 100644 3rdparty/MDB2/Driver/Manager/pgsql.php delete mode 100644 3rdparty/MDB2/Driver/Manager/sqlite.php delete mode 100644 3rdparty/MDB2/Driver/Native/Common.php delete mode 100644 3rdparty/MDB2/Driver/Native/mysql.php delete mode 100644 3rdparty/MDB2/Driver/Native/pgsql.php delete mode 100644 3rdparty/MDB2/Driver/Native/sqlite.php delete mode 100644 3rdparty/MDB2/Driver/Reverse/Common.php delete mode 100644 3rdparty/MDB2/Driver/Reverse/mysql.php delete mode 100644 3rdparty/MDB2/Driver/Reverse/pgsql.php delete mode 100644 3rdparty/MDB2/Driver/Reverse/sqlite.php delete mode 100644 3rdparty/MDB2/Driver/mysql.php delete mode 100644 3rdparty/MDB2/Driver/pgsql.php delete mode 100644 3rdparty/MDB2/Driver/sqlite.php delete mode 100644 3rdparty/MDB2/Extended.php delete mode 100644 3rdparty/MDB2/Iterator.php delete mode 100644 3rdparty/MDB2/LOB.php delete mode 100644 3rdparty/MDB2/Schema.php delete mode 100644 3rdparty/MDB2/Schema/Parser.php delete mode 100644 3rdparty/MDB2/Schema/Parser2.php delete mode 100644 3rdparty/MDB2/Schema/Reserved/ibase.php delete mode 100644 3rdparty/MDB2/Schema/Reserved/mssql.php delete mode 100644 3rdparty/MDB2/Schema/Reserved/mysql.php delete mode 100644 3rdparty/MDB2/Schema/Reserved/oci8.php delete mode 100644 3rdparty/MDB2/Schema/Reserved/pgsql.php delete mode 100644 3rdparty/MDB2/Schema/Tool.php delete mode 100644 3rdparty/MDB2/Schema/Tool/ParameterException.php delete mode 100644 3rdparty/MDB2/Schema/Validate.php delete mode 100644 3rdparty/MDB2/Schema/Writer.php delete mode 100644 3rdparty/PEAR.php delete mode 100644 3rdparty/PEAR/Autoloader.php delete mode 100644 3rdparty/PEAR/Builder.php delete mode 100644 3rdparty/PEAR/Command.php delete mode 100644 3rdparty/PEAR/Command/Auth.php delete mode 100644 3rdparty/PEAR/Command/Build.php delete mode 100644 3rdparty/PEAR/Command/Common.php delete mode 100644 3rdparty/PEAR/Command/Config.php delete mode 100644 3rdparty/PEAR/Command/Install.php delete mode 100644 3rdparty/PEAR/Command/Mirror.php delete mode 100644 3rdparty/PEAR/Command/Package.php delete mode 100644 3rdparty/PEAR/Command/Registry.php delete mode 100644 3rdparty/PEAR/Command/Remote.php delete mode 100644 3rdparty/PEAR/Common.php delete mode 100644 3rdparty/PEAR/Config.php delete mode 100644 3rdparty/PEAR/Dependency.php delete mode 100644 3rdparty/PEAR/Downloader.php delete mode 100644 3rdparty/PEAR/ErrorStack.php delete mode 100644 3rdparty/PEAR/Exception.php delete mode 100644 3rdparty/PEAR/Frontend/CLI.php delete mode 100644 3rdparty/PEAR/Installer.php delete mode 100644 3rdparty/PEAR/Packager.php delete mode 100644 3rdparty/PEAR/Registry.php delete mode 100644 3rdparty/PEAR/Remote.php delete mode 100644 3rdparty/PEAR/RunTest.php create mode 100644 3rdparty/README delete mode 100644 3rdparty/Sabre.includes.php delete mode 100644 3rdparty/Sabre/CalDAV/Backend/Abstract.php delete mode 100644 3rdparty/Sabre/CalDAV/Backend/PDO.php delete mode 100644 3rdparty/Sabre/CalDAV/Calendar.php delete mode 100644 3rdparty/Sabre/CalDAV/CalendarObject.php delete mode 100644 3rdparty/Sabre/CalDAV/CalendarRootNode.php delete mode 100644 3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php delete mode 100644 3rdparty/Sabre/CalDAV/ICSExportPlugin.php delete mode 100644 3rdparty/Sabre/CalDAV/ICalendar.php delete mode 100644 3rdparty/Sabre/CalDAV/ICalendarObject.php delete mode 100644 3rdparty/Sabre/CalDAV/ICalendarUtil.php delete mode 100644 3rdparty/Sabre/CalDAV/Plugin.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/Collection.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/ProxyRead.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/User.php delete mode 100644 3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php delete mode 100644 3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php delete mode 100644 3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php delete mode 100644 3rdparty/Sabre/CalDAV/Server.php delete mode 100644 3rdparty/Sabre/CalDAV/UserCalendars.php delete mode 100644 3rdparty/Sabre/CalDAV/Version.php delete mode 100644 3rdparty/Sabre/CalDAV/XMLUtil.php delete mode 100644 3rdparty/Sabre/CardDAV/AddressBook.php delete mode 100644 3rdparty/Sabre/CardDAV/AddressBookQueryParser.php delete mode 100644 3rdparty/Sabre/CardDAV/AddressBookRoot.php delete mode 100644 3rdparty/Sabre/CardDAV/Backend/Abstract.php delete mode 100644 3rdparty/Sabre/CardDAV/Backend/PDO.php delete mode 100644 3rdparty/Sabre/CardDAV/Card.php delete mode 100644 3rdparty/Sabre/CardDAV/IAddressBook.php delete mode 100644 3rdparty/Sabre/CardDAV/ICard.php delete mode 100644 3rdparty/Sabre/CardDAV/IDirectory.php delete mode 100644 3rdparty/Sabre/CardDAV/Plugin.php delete mode 100644 3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php delete mode 100644 3rdparty/Sabre/CardDAV/UserAddressBooks.php delete mode 100644 3rdparty/Sabre/CardDAV/Version.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/AbstractBasic.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/Apache.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/File.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/PDO.php delete mode 100644 3rdparty/Sabre/DAV/Auth/IBackend.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Browser/GuessContentType.php delete mode 100644 3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php delete mode 100644 3rdparty/Sabre/DAV/Browser/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Client.php delete mode 100644 3rdparty/Sabre/DAV/Collection.php delete mode 100644 3rdparty/Sabre/DAV/Directory.php delete mode 100644 3rdparty/Sabre/DAV/Exception.php delete mode 100644 3rdparty/Sabre/DAV/Exception/BadRequest.php delete mode 100644 3rdparty/Sabre/DAV/Exception/Conflict.php delete mode 100644 3rdparty/Sabre/DAV/Exception/ConflictingLock.php delete mode 100644 3rdparty/Sabre/DAV/Exception/FileNotFound.php delete mode 100644 3rdparty/Sabre/DAV/Exception/Forbidden.php delete mode 100644 3rdparty/Sabre/DAV/Exception/InsufficientStorage.php delete mode 100644 3rdparty/Sabre/DAV/Exception/InvalidResourceType.php delete mode 100644 3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php delete mode 100644 3rdparty/Sabre/DAV/Exception/Locked.php delete mode 100644 3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php delete mode 100644 3rdparty/Sabre/DAV/Exception/NotAuthenticated.php delete mode 100644 3rdparty/Sabre/DAV/Exception/NotImplemented.php delete mode 100644 3rdparty/Sabre/DAV/Exception/PreconditionFailed.php delete mode 100644 3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php delete mode 100644 3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php delete mode 100644 3rdparty/Sabre/DAV/Exception/UnsupportedMediaType.php delete mode 100644 3rdparty/Sabre/DAV/FS/Directory.php delete mode 100644 3rdparty/Sabre/DAV/FS/File.php delete mode 100644 3rdparty/Sabre/DAV/FS/Node.php delete mode 100644 3rdparty/Sabre/DAV/FSExt/Directory.php delete mode 100644 3rdparty/Sabre/DAV/FSExt/File.php delete mode 100644 3rdparty/Sabre/DAV/FSExt/Node.php delete mode 100644 3rdparty/Sabre/DAV/File.php delete mode 100644 3rdparty/Sabre/DAV/ICollection.php delete mode 100644 3rdparty/Sabre/DAV/IExtendedCollection.php delete mode 100644 3rdparty/Sabre/DAV/IFile.php delete mode 100644 3rdparty/Sabre/DAV/ILockable.php delete mode 100644 3rdparty/Sabre/DAV/INode.php delete mode 100644 3rdparty/Sabre/DAV/IProperties.php delete mode 100644 3rdparty/Sabre/DAV/IQuota.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/Abstract.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/FS.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/File.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/PDO.php delete mode 100644 3rdparty/Sabre/DAV/Locks/LockInfo.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Mount/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Node.php delete mode 100644 3rdparty/Sabre/DAV/ObjectTree.php delete mode 100644 3rdparty/Sabre/DAV/Property.php delete mode 100644 3rdparty/Sabre/DAV/Property/GetLastModified.php delete mode 100644 3rdparty/Sabre/DAV/Property/Href.php delete mode 100644 3rdparty/Sabre/DAV/Property/HrefList.php delete mode 100644 3rdparty/Sabre/DAV/Property/IHref.php delete mode 100644 3rdparty/Sabre/DAV/Property/LockDiscovery.php delete mode 100644 3rdparty/Sabre/DAV/Property/ResourceType.php delete mode 100644 3rdparty/Sabre/DAV/Property/Response.php delete mode 100644 3rdparty/Sabre/DAV/Property/ResponseList.php delete mode 100644 3rdparty/Sabre/DAV/Property/SupportedLock.php delete mode 100644 3rdparty/Sabre/DAV/Property/SupportedReportSet.php delete mode 100644 3rdparty/Sabre/DAV/Server.php delete mode 100644 3rdparty/Sabre/DAV/ServerPlugin.php delete mode 100644 3rdparty/Sabre/DAV/SimpleCollection.php delete mode 100644 3rdparty/Sabre/DAV/SimpleDirectory.php delete mode 100644 3rdparty/Sabre/DAV/SimpleFile.php delete mode 100644 3rdparty/Sabre/DAV/StringUtil.php delete mode 100644 3rdparty/Sabre/DAV/TemporaryFileFilterPlugin.php delete mode 100644 3rdparty/Sabre/DAV/Tree.php delete mode 100644 3rdparty/Sabre/DAV/Tree/Filesystem.php delete mode 100644 3rdparty/Sabre/DAV/URLUtil.php delete mode 100644 3rdparty/Sabre/DAV/UUIDUtil.php delete mode 100644 3rdparty/Sabre/DAV/Version.php delete mode 100644 3rdparty/Sabre/DAV/XMLUtil.php delete mode 100644 3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/AceConflict.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NoAbstract.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php delete mode 100644 3rdparty/Sabre/DAVACL/IACL.php delete mode 100644 3rdparty/Sabre/DAVACL/IPrincipal.php delete mode 100644 3rdparty/Sabre/DAVACL/IPrincipalBackend.php delete mode 100644 3rdparty/Sabre/DAVACL/Plugin.php delete mode 100644 3rdparty/Sabre/DAVACL/Principal.php delete mode 100644 3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php delete mode 100644 3rdparty/Sabre/DAVACL/PrincipalCollection.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/Acl.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/Principal.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php delete mode 100644 3rdparty/Sabre/DAVACL/Version.php delete mode 100644 3rdparty/Sabre/HTTP/AWSAuth.php delete mode 100644 3rdparty/Sabre/HTTP/AbstractAuth.php delete mode 100644 3rdparty/Sabre/HTTP/BasicAuth.php delete mode 100644 3rdparty/Sabre/HTTP/DigestAuth.php delete mode 100644 3rdparty/Sabre/HTTP/Request.php delete mode 100644 3rdparty/Sabre/HTTP/Response.php delete mode 100644 3rdparty/Sabre/HTTP/Util.php delete mode 100644 3rdparty/Sabre/HTTP/Version.php delete mode 100644 3rdparty/Sabre/LICENCE delete mode 100644 3rdparty/Sabre/VObject/Component.php delete mode 100644 3rdparty/Sabre/VObject/Element.php delete mode 100644 3rdparty/Sabre/VObject/Element/DateTime.php delete mode 100644 3rdparty/Sabre/VObject/Element/MultiDateTime.php delete mode 100644 3rdparty/Sabre/VObject/ElementList.php delete mode 100644 3rdparty/Sabre/VObject/Node.php delete mode 100644 3rdparty/Sabre/VObject/Parameter.php delete mode 100644 3rdparty/Sabre/VObject/ParseException.php delete mode 100644 3rdparty/Sabre/VObject/Property.php delete mode 100644 3rdparty/Sabre/VObject/Reader.php delete mode 100644 3rdparty/Sabre/VObject/Version.php delete mode 100644 3rdparty/Sabre/VObject/includes.php delete mode 100644 3rdparty/Sabre/autoload.php delete mode 100644 3rdparty/System.php delete mode 100644 3rdparty/XML/Parser.php delete mode 100644 3rdparty/XML/RPC.php delete mode 100644 3rdparty/XML/RPC/Server.php delete mode 100644 3rdparty/css/chosen-sprite.png delete mode 100644 3rdparty/css/chosen.css delete mode 100644 3rdparty/css/chosen/chosen-sprite.png delete mode 100644 3rdparty/css/chosen/chosen.css delete mode 100644 3rdparty/fullcalendar/GPL-LICENSE.txt delete mode 100644 3rdparty/fullcalendar/MIT-LICENSE.txt delete mode 100644 3rdparty/fullcalendar/changelog.txt delete mode 100644 3rdparty/fullcalendar/css/fullcalendar.css delete mode 100644 3rdparty/fullcalendar/css/fullcalendar.print.css delete mode 100644 3rdparty/fullcalendar/js/fullcalendar.js delete mode 100644 3rdparty/fullcalendar/js/fullcalendar.min.js delete mode 100644 3rdparty/fullcalendar/js/gcal.js delete mode 100644 3rdparty/js/chosen/LICENSE.md delete mode 100644 3rdparty/js/chosen/README.md delete mode 100644 3rdparty/js/chosen/VERSION delete mode 100644 3rdparty/js/chosen/chosen.jquery.js delete mode 100644 3rdparty/js/chosen/chosen.jquery.min.js delete mode 100755 3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE delete mode 100755 3rdparty/simpletest/LICENSE delete mode 100755 3rdparty/simpletest/README delete mode 100755 3rdparty/simpletest/VERSION delete mode 100755 3rdparty/simpletest/arguments.php delete mode 100644 3rdparty/simpletest/authentication.php delete mode 100644 3rdparty/simpletest/autorun.php delete mode 100644 3rdparty/simpletest/browser.php delete mode 100644 3rdparty/simpletest/collector.php delete mode 100755 3rdparty/simpletest/compatibility.php delete mode 100644 3rdparty/simpletest/cookies.php delete mode 100644 3rdparty/simpletest/default_reporter.php delete mode 100755 3rdparty/simpletest/detached.php delete mode 100644 3rdparty/simpletest/docs/en/authentication_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/browser_documentation.html delete mode 100755 3rdparty/simpletest/docs/en/docs.css delete mode 100644 3rdparty/simpletest/docs/en/expectation_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/form_testing_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/group_test_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/index.html delete mode 100644 3rdparty/simpletest/docs/en/mock_objects_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/overview.html delete mode 100644 3rdparty/simpletest/docs/en/partial_mocks_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/reporter_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/unit_test_documentation.html delete mode 100644 3rdparty/simpletest/docs/en/web_tester_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/authentication_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/browser_documentation.html delete mode 100755 3rdparty/simpletest/docs/fr/docs.css delete mode 100644 3rdparty/simpletest/docs/fr/expectation_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/form_testing_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/group_test_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/index.html delete mode 100644 3rdparty/simpletest/docs/fr/mock_objects_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/overview.html delete mode 100644 3rdparty/simpletest/docs/fr/partial_mocks_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/reporter_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/unit_test_documentation.html delete mode 100644 3rdparty/simpletest/docs/fr/web_tester_documentation.html delete mode 100755 3rdparty/simpletest/dumper.php delete mode 100644 3rdparty/simpletest/eclipse.php delete mode 100644 3rdparty/simpletest/encoding.php delete mode 100644 3rdparty/simpletest/errors.php delete mode 100755 3rdparty/simpletest/exceptions.php delete mode 100755 3rdparty/simpletest/expectation.php delete mode 100755 3rdparty/simpletest/extensions/pear_test_case.php delete mode 100755 3rdparty/simpletest/extensions/testdox.php delete mode 100755 3rdparty/simpletest/extensions/testdox/test.php delete mode 100644 3rdparty/simpletest/form.php delete mode 100755 3rdparty/simpletest/frames.php delete mode 100644 3rdparty/simpletest/http.php delete mode 100755 3rdparty/simpletest/invoker.php delete mode 100755 3rdparty/simpletest/mock_objects.php delete mode 100755 3rdparty/simpletest/page.php delete mode 100755 3rdparty/simpletest/php_parser.php delete mode 100644 3rdparty/simpletest/recorder.php delete mode 100644 3rdparty/simpletest/reflection_php4.php delete mode 100644 3rdparty/simpletest/reflection_php5.php delete mode 100644 3rdparty/simpletest/remote.php delete mode 100755 3rdparty/simpletest/reporter.php delete mode 100644 3rdparty/simpletest/scorer.php delete mode 100755 3rdparty/simpletest/selector.php delete mode 100644 3rdparty/simpletest/shell_tester.php delete mode 100644 3rdparty/simpletest/simpletest.php delete mode 100755 3rdparty/simpletest/socket.php delete mode 100644 3rdparty/simpletest/tag.php delete mode 100644 3rdparty/simpletest/test/acceptance_test.php delete mode 100755 3rdparty/simpletest/test/adapter_test.php delete mode 100755 3rdparty/simpletest/test/all_tests.php delete mode 100755 3rdparty/simpletest/test/arguments_test.php delete mode 100755 3rdparty/simpletest/test/authentication_test.php delete mode 100755 3rdparty/simpletest/test/autorun_test.php delete mode 100755 3rdparty/simpletest/test/bad_test_suite.php delete mode 100755 3rdparty/simpletest/test/browser_test.php delete mode 100755 3rdparty/simpletest/test/collector_test.php delete mode 100755 3rdparty/simpletest/test/command_line_test.php delete mode 100755 3rdparty/simpletest/test/compatibility_test.php delete mode 100755 3rdparty/simpletest/test/cookies_test.php delete mode 100755 3rdparty/simpletest/test/detached_test.php delete mode 100755 3rdparty/simpletest/test/dumper_test.php delete mode 100755 3rdparty/simpletest/test/eclipse_test.php delete mode 100755 3rdparty/simpletest/test/encoding_test.php delete mode 100755 3rdparty/simpletest/test/errors_test.php delete mode 100755 3rdparty/simpletest/test/exceptions_test.php delete mode 100755 3rdparty/simpletest/test/expectation_test.php delete mode 100755 3rdparty/simpletest/test/form_test.php delete mode 100755 3rdparty/simpletest/test/frames_test.php delete mode 100755 3rdparty/simpletest/test/http_test.php delete mode 100755 3rdparty/simpletest/test/interfaces_test.php delete mode 100755 3rdparty/simpletest/test/interfaces_test_php5_1.php delete mode 100755 3rdparty/simpletest/test/live_test.php delete mode 100755 3rdparty/simpletest/test/mock_objects_test.php delete mode 100755 3rdparty/simpletest/test/page_test.php delete mode 100755 3rdparty/simpletest/test/parse_error_test.php delete mode 100755 3rdparty/simpletest/test/parsing_test.php delete mode 100755 3rdparty/simpletest/test/php_parser_test.php delete mode 100755 3rdparty/simpletest/test/recorder_test.php delete mode 100755 3rdparty/simpletest/test/reflection_php5_test.php delete mode 100755 3rdparty/simpletest/test/remote_test.php delete mode 100755 3rdparty/simpletest/test/shell_test.php delete mode 100755 3rdparty/simpletest/test/shell_tester_test.php delete mode 100755 3rdparty/simpletest/test/simpletest_test.php delete mode 100755 3rdparty/simpletest/test/site/file.html delete mode 100755 3rdparty/simpletest/test/socket_test.php delete mode 100755 3rdparty/simpletest/test/support/collector/collectable.1 delete mode 100755 3rdparty/simpletest/test/support/collector/collectable.2 delete mode 100755 3rdparty/simpletest/test/support/empty_test_file.php delete mode 100755 3rdparty/simpletest/test/support/failing_test.php delete mode 100755 3rdparty/simpletest/test/support/latin1_sample delete mode 100755 3rdparty/simpletest/test/support/passing_test.php delete mode 100755 3rdparty/simpletest/test/support/recorder_sample.php delete mode 100755 3rdparty/simpletest/test/support/spl_examples.php delete mode 100755 3rdparty/simpletest/test/support/supplementary_upload_sample.txt delete mode 100755 3rdparty/simpletest/test/support/test1.php delete mode 100755 3rdparty/simpletest/test/support/upload_sample.txt delete mode 100755 3rdparty/simpletest/test/tag_test.php delete mode 100755 3rdparty/simpletest/test/test_with_parse_error.php delete mode 100755 3rdparty/simpletest/test/unit_tester_test.php delete mode 100755 3rdparty/simpletest/test/unit_tests.php delete mode 100755 3rdparty/simpletest/test/url_test.php delete mode 100755 3rdparty/simpletest/test/user_agent_test.php delete mode 100755 3rdparty/simpletest/test/visual_test.php delete mode 100755 3rdparty/simpletest/test/web_tester_test.php delete mode 100755 3rdparty/simpletest/test/xml_test.php delete mode 100644 3rdparty/simpletest/test_case.php delete mode 100755 3rdparty/simpletest/tidy_parser.php delete mode 100755 3rdparty/simpletest/unit_tester.php delete mode 100644 3rdparty/simpletest/url.php delete mode 100644 3rdparty/simpletest/user_agent.php delete mode 100644 3rdparty/simpletest/web_tester.php delete mode 100755 3rdparty/simpletest/xml.php delete mode 100644 3rdparty/timepicker/GPL-LICENSE.txt delete mode 100644 3rdparty/timepicker/MIT-LICENSE.txt delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_18_b81900_40x40.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_20_666666_40x40.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_flat_10_000000_40x100.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_glass_100_f6f6f6_1x400.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_glass_100_fdf5ce_1x400.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_glass_65_ffffff_1x400.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_gloss-wave_35_f6a828_500x100.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_100_eeeeee_1x100.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_75_ffe45c_1x100.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-icons_222222_256x240.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-icons_228ef1_256x240.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-icons_ef8c08_256x240.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-icons_ffd27a_256x240.png delete mode 100644 3rdparty/timepicker/css/include/images/ui-icons_ffffff_256x240.png delete mode 100644 3rdparty/timepicker/css/include/jquery-1.5.1.min.js delete mode 100644 3rdparty/timepicker/css/include/jquery-ui-1.8.14.custom.css delete mode 100644 3rdparty/timepicker/css/include/jquery.ui.core.min.js delete mode 100644 3rdparty/timepicker/css/include/jquery.ui.position.min.js delete mode 100644 3rdparty/timepicker/css/include/jquery.ui.tabs.min.js delete mode 100644 3rdparty/timepicker/css/include/jquery.ui.widget.min.js delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_flat_10_000000_40x100.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_222222_256x240.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_228ef1_256x240.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ef8c08_256x240.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffd27a_256x240.png delete mode 100644 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffffff_256x240.png delete mode 100644 3rdparty/timepicker/css/jquery.ui.timepicker.css delete mode 100644 3rdparty/timepicker/js/i18n/i18n.html delete mode 100644 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-de.js delete mode 100644 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-fr.js delete mode 100644 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-ja.js delete mode 100644 3rdparty/timepicker/js/jquery.ui.timepicker.js delete mode 100644 3rdparty/timepicker/releases.txt delete mode 100644 3rdparty/when/MIT-LICENSE.txt delete mode 100755 3rdparty/when/When.php diff --git a/3rdparty/Console/Getopt.php b/3rdparty/Console/Getopt.php deleted file mode 100644 index aec980b34d..0000000000 --- a/3rdparty/Console/Getopt.php +++ /dev/null @@ -1,251 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Getopt.php,v 1.21.4.7 2003/12/05 21:57:01 andrei Exp $ - -require_once( 'PEAR.php'); - -/** - * Command-line options parsing class. - * - * @author Andrei Zmievski - * - */ -class Console_Getopt { - /** - * Parses the command-line options. - * - * The first parameter to this function should be the list of command-line - * arguments without the leading reference to the running program. - * - * The second parameter is a string of allowed short options. Each of the - * option letters can be followed by a colon ':' to specify that the option - * requires an argument, or a double colon '::' to specify that the option - * takes an optional argument. - * - * The third argument is an optional array of allowed long options. The - * leading '--' should not be included in the option name. Options that - * require an argument should be followed by '=', and options that take an - * option argument should be followed by '=='. - * - * The return value is an array of two elements: the list of parsed - * options and the list of non-option command-line arguments. Each entry in - * the list of parsed options is a pair of elements - the first one - * specifies the option, and the second one specifies the option argument, - * if there was one. - * - * Long and short options can be mixed. - * - * Most of the semantics of this function are based on GNU getopt_long(). - * - * @param array $args an array of command-line arguments - * @param string $short_options specifies the list of allowed short options - * @param array $long_options specifies the list of allowed long options - * - * @return array two-element array containing the list of parsed options and - * the non-option arguments - * - * @access public - * - */ - function getopt2($args, $short_options, $long_options = null) - { - return Console_Getopt::doGetopt(2, $args, $short_options, $long_options); - } - - /** - * This function expects $args to start with the script name (POSIX-style). - * Preserved for backwards compatibility. - * @see getopt2() - */ - function getopt($args, $short_options, $long_options = null) - { - return Console_Getopt::doGetopt(1, $args, $short_options, $long_options); - } - - /** - * The actual implementation of the argument parsing code. - */ - function doGetopt($version, $args, $short_options, $long_options = null) - { - // in case you pass directly readPHPArgv() as the first arg - if (PEAR::isError($args)) { - return $args; - } - if (empty($args)) { - return array(array(), array()); - } - $opts = array(); - $non_opts = array(); - - settype($args, 'array'); - - if ($long_options) { - sort($long_options); - } - - /* - * Preserve backwards compatibility with callers that relied on - * erroneous POSIX fix. - */ - if ($version < 2) { - if (isset($args[0]{0}) && $args[0]{0} != '-') { - array_shift($args); - } - } - - reset($args); - while (list($i, $arg) = each($args)) { - - /* The special element '--' means explicit end of - options. Treat the rest of the arguments as non-options - and end the loop. */ - if ($arg == '--') { - $non_opts = array_merge($non_opts, array_slice($args, $i + 1)); - break; - } - - if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) { - $non_opts = array_merge($non_opts, array_slice($args, $i)); - break; - } elseif (strlen($arg) > 1 && $arg{1} == '-') { - $error = Console_Getopt::_parseLongOption(substr($arg, 2), $long_options, $opts, $args); - if (PEAR::isError($error)) - return $error; - } else { - $error = Console_Getopt::_parseShortOption(substr($arg, 1), $short_options, $opts, $args); - if (PEAR::isError($error)) - return $error; - } - } - - return array($opts, $non_opts); - } - - /** - * @access private - * - */ - function _parseShortOption($arg, $short_options, &$opts, &$args) - { - for ($i = 0; $i < strlen($arg); $i++) { - $opt = $arg{$i}; - $opt_arg = null; - - /* Try to find the short option in the specifier string. */ - if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') - { - return PEAR::raiseError("Console_Getopt: unrecognized option -- $opt"); - } - - if (strlen($spec) > 1 && $spec{1} == ':') { - if (strlen($spec) > 2 && $spec{2} == ':') { - if ($i + 1 < strlen($arg)) { - /* Option takes an optional argument. Use the remainder of - the arg string if there is anything left. */ - $opts[] = array($opt, substr($arg, $i + 1)); - break; - } - } else { - /* Option requires an argument. Use the remainder of the arg - string if there is anything left. */ - if ($i + 1 < strlen($arg)) { - $opts[] = array($opt, substr($arg, $i + 1)); - break; - } else if (list(, $opt_arg) = each($args)) - /* Else use the next argument. */; - else - return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt"); - } - } - - $opts[] = array($opt, $opt_arg); - } - } - - /** - * @access private - * - */ - function _parseLongOption($arg, $long_options, &$opts, &$args) - { - @list($opt, $opt_arg) = explode('=', $arg); - $opt_len = strlen($opt); - - for ($i = 0; $i < count($long_options); $i++) { - $long_opt = $long_options[$i]; - $opt_start = substr($long_opt, 0, $opt_len); - - /* Option doesn't match. Go on to the next one. */ - if ($opt_start != $opt) - continue; - - $opt_rest = substr($long_opt, $opt_len); - - /* Check that the options uniquely matches one of the allowed - options. */ - if ($opt_rest != '' && $opt{0} != '=' && - $i + 1 < count($long_options) && - $opt == substr($long_options[$i+1], 0, $opt_len)) { - return PEAR::raiseError("Console_Getopt: option --$opt is ambiguous"); - } - - if (substr($long_opt, -1) == '=') { - if (substr($long_opt, -2) != '==') { - /* Long option requires an argument. - Take the next argument if one wasn't specified. */; - if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) { - return PEAR::raiseError("Console_Getopt: option --$opt requires an argument"); - } - } - } else if ($opt_arg) { - return PEAR::raiseError("Console_Getopt: option --$opt doesn't allow an argument"); - } - - $opts[] = array('--' . $opt, $opt_arg); - return; - } - - return PEAR::raiseError("Console_Getopt: unrecognized option --$opt"); - } - - /** - * Safely read the $argv PHP array across different PHP configurations. - * Will take care on register_globals and register_argc_argv ini directives - * - * @access public - * @return mixed the $argv PHP array or PEAR error if not registered - */ - function readPHPArgv() - { - global $argv; - if (!is_array($argv)) { - if (!@is_array($_SERVER['argv'])) { - if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) { - return PEAR::raiseError("Console_Getopt: Could not read cmd args (register_argc_argv=Off?)"); - } - return $GLOBALS['HTTP_SERVER_VARS']['argv']; - } - return $_SERVER['argv']; - } - return $argv; - } - -} - -?> diff --git a/3rdparty/Crypt_Blowfish/Blowfish.php b/3rdparty/Crypt_Blowfish/Blowfish.php deleted file mode 100644 index a7b8948f04..0000000000 --- a/3rdparty/Crypt_Blowfish/Blowfish.php +++ /dev/null @@ -1,317 +0,0 @@ - - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id: Blowfish.php,v 1.81 2005/05/30 18:40:36 mfonda Exp $ - * @link http://pear.php.net/package/Crypt_Blowfish - */ - - -require_once 'PEAR.php'; - - -/** - * - * Example usage: - * $bf = new Crypt_Blowfish('some secret key!'); - * $encrypted = $bf->encrypt('this is some example plain text'); - * $plaintext = $bf->decrypt($encrypted); - * echo "plain text: $plaintext"; - * - * - * @category Encryption - * @package Crypt_Blowfish - * @author Matthew Fonda - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @link http://pear.php.net/package/Crypt_Blowfish - * @version @package_version@ - * @access public - */ -class Crypt_Blowfish -{ - /** - * P-Array contains 18 32-bit subkeys - * - * @var array - * @access private - */ - var $_P = array(); - - - /** - * Array of four S-Blocks each containing 256 32-bit entries - * - * @var array - * @access private - */ - var $_S = array(); - - /** - * Mcrypt td resource - * - * @var resource - * @access private - */ - var $_td = null; - - /** - * Initialization vector - * - * @var string - * @access private - */ - var $_iv = null; - - - /** - * Crypt_Blowfish Constructor - * Initializes the Crypt_Blowfish object, and gives a sets - * the secret key - * - * @param string $key - * @access public - */ - function Crypt_Blowfish($key) - { - if (extension_loaded('mcrypt')) { - $this->_td = mcrypt_module_open(MCRYPT_BLOWFISH, '', 'ecb', ''); - $this->_iv = mcrypt_create_iv(8, MCRYPT_RAND); - } - $this->setKey($key); - } - - /** - * Deprecated isReady method - * - * @return bool - * @access public - * @deprecated - */ - function isReady() - { - return true; - } - - /** - * Deprecated init method - init is now a private - * method and has been replaced with _init - * - * @return bool - * @access public - * @deprecated - * @see Crypt_Blowfish::_init() - */ - function init() - { - $this->_init(); - } - - /** - * Initializes the Crypt_Blowfish object - * - * @access private - */ - function _init() - { - $defaults = new Crypt_Blowfish_DefaultKey(); - $this->_P = $defaults->P; - $this->_S = $defaults->S; - } - - /** - * Enciphers a single 64 bit block - * - * @param int &$Xl - * @param int &$Xr - * @access private - */ - function _encipher(&$Xl, &$Xr) - { - for ($i = 0; $i < 16; $i++) { - $temp = $Xl ^ $this->_P[$i]; - $Xl = ((($this->_S[0][($temp>>24) & 255] + - $this->_S[1][($temp>>16) & 255]) ^ - $this->_S[2][($temp>>8) & 255]) + - $this->_S[3][$temp & 255]) ^ $Xr; - $Xr = $temp; - } - $Xr = $Xl ^ $this->_P[16]; - $Xl = $temp ^ $this->_P[17]; - } - - - /** - * Deciphers a single 64 bit block - * - * @param int &$Xl - * @param int &$Xr - * @access private - */ - function _decipher(&$Xl, &$Xr) - { - for ($i = 17; $i > 1; $i--) { - $temp = $Xl ^ $this->_P[$i]; - $Xl = ((($this->_S[0][($temp>>24) & 255] + - $this->_S[1][($temp>>16) & 255]) ^ - $this->_S[2][($temp>>8) & 255]) + - $this->_S[3][$temp & 255]) ^ $Xr; - $Xr = $temp; - } - $Xr = $Xl ^ $this->_P[1]; - $Xl = $temp ^ $this->_P[0]; - } - - - /** - * Encrypts a string - * - * @param string $plainText - * @return string Returns cipher text on success, PEAR_Error on failure - * @access public - */ - function encrypt($plainText) - { - if (!is_string($plainText)) { - PEAR::raiseError('Plain text must be a string', 0, PEAR_ERROR_DIE); - } - - if (extension_loaded('mcrypt')) { - return mcrypt_generic($this->_td, $plainText); - } - - $cipherText = ''; - $len = strlen($plainText); - $plainText .= str_repeat(chr(0),(8 - ($len%8))%8); - for ($i = 0; $i < $len; $i += 8) { - list(,$Xl,$Xr) = unpack("N2",substr($plainText,$i,8)); - $this->_encipher($Xl, $Xr); - $cipherText .= pack("N2", $Xl, $Xr); - } - return $cipherText; - } - - - /** - * Decrypts an encrypted string - * - * @param string $cipherText - * @return string Returns plain text on success, PEAR_Error on failure - * @access public - */ - function decrypt($cipherText) - { - if (!is_string($cipherText)) { - PEAR::raiseError('Chiper text must be a string', 1, PEAR_ERROR_DIE); - } - - if (extension_loaded('mcrypt')) { - return mdecrypt_generic($this->_td, $cipherText); - } - - $plainText = ''; - $len = strlen($cipherText); - $cipherText .= str_repeat(chr(0),(8 - ($len%8))%8); - for ($i = 0; $i < $len; $i += 8) { - list(,$Xl,$Xr) = unpack("N2",substr($cipherText,$i,8)); - $this->_decipher($Xl, $Xr); - $plainText .= pack("N2", $Xl, $Xr); - } - return $plainText; - } - - - /** - * Sets the secret key - * The key must be non-zero, and less than or equal to - * 56 characters in length. - * - * @param string $key - * @return bool Returns true on success, PEAR_Error on failure - * @access public - */ - function setKey($key) - { - if (!is_string($key)) { - PEAR::raiseError('Key must be a string', 2, PEAR_ERROR_DIE); - } - - $len = strlen($key); - - if ($len > 56 || $len == 0) { - PEAR::raiseError('Key must be less than 56 characters and non-zero. Supplied key length: ' . $len, 3, PEAR_ERROR_DIE); - } - - if (extension_loaded('mcrypt')) { - mcrypt_generic_init($this->_td, $key, $this->_iv); - return true; - } - - require_once 'Blowfish/DefaultKey.php'; - $this->_init(); - - $k = 0; - $data = 0; - $datal = 0; - $datar = 0; - - for ($i = 0; $i < 18; $i++) { - $data = 0; - for ($j = 4; $j > 0; $j--) { - $data = $data << 8 | ord($key{$k}); - $k = ($k+1) % $len; - } - $this->_P[$i] ^= $data; - } - - for ($i = 0; $i <= 16; $i += 2) { - $this->_encipher($datal, $datar); - $this->_P[$i] = $datal; - $this->_P[$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[0][$i] = $datal; - $this->_S[0][$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[1][$i] = $datal; - $this->_S[1][$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[2][$i] = $datal; - $this->_S[2][$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[3][$i] = $datal; - $this->_S[3][$i+1] = $datar; - } - - return true; - } - -} - -?> diff --git a/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php b/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php deleted file mode 100644 index 2ff8ac788a..0000000000 --- a/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php +++ /dev/null @@ -1,327 +0,0 @@ - - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id: DefaultKey.php,v 1.81 2005/05/30 18:40:37 mfonda Exp $ - * @link http://pear.php.net/package/Crypt_Blowfish - */ - - -/** - * Class containing default key - * - * @category Encryption - * @package Crypt_Blowfish - * @author Matthew Fonda - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @link http://pear.php.net/package/Crypt_Blowfish - * @version @package_version@ - * @access public - */ -class Crypt_Blowfish_DefaultKey -{ - var $P = array(); - - var $S = array(); - - function Crypt_Blowfish_DefaultKey() - { - $this->P = array( - 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, - 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, - 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, - 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, - 0x9216D5D9, 0x8979FB1B - ); - - $this->S = array( - array( - 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, - 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, - 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, - 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, - 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, - 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, - 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, - 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, - 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, - 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, - 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, - 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, - 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, - 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, - 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, - 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, - 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, - 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, - 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, - 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, - 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, - 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, - 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, - 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, - 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, - 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, - 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, - 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, - 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, - 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, - 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, - 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, - 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, - 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, - 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, - 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, - 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, - 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, - 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, - 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, - 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, - 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, - 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, - 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, - 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, - 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, - 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, - 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, - 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, - 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, - 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, - 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, - 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, - 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, - 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, - 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, - 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, - 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, - 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, - 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, - 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, - 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, - 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, - 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A - ), - array( - 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, - 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, - 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, - 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, - 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, - 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, - 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, - 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, - 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, - 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, - 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, - 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, - 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, - 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, - 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, - 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, - 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, - 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, - 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, - 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, - 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, - 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, - 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, - 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, - 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, - 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, - 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, - 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, - 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, - 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, - 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, - 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, - 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, - 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, - 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, - 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, - 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, - 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, - 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, - 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, - 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, - 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, - 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, - 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, - 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, - 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, - 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, - 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, - 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, - 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, - 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, - 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, - 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, - 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, - 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, - 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, - 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, - 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, - 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, - 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, - 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, - 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, - 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, - 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 - ), - array( - 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, - 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, - 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, - 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, - 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, - 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, - 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, - 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, - 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, - 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, - 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, - 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, - 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, - 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, - 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, - 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, - 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, - 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, - 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, - 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, - 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, - 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, - 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, - 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, - 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, - 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, - 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, - 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, - 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, - 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, - 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, - 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, - 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, - 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, - 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, - 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, - 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, - 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, - 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, - 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, - 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, - 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, - 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, - 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, - 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, - 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, - 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, - 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, - 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, - 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, - 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, - 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, - 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, - 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, - 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, - 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, - 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, - 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, - 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, - 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, - 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, - 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, - 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, - 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 - ), - array( - 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, - 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, - 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, - 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, - 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, - 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, - 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, - 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, - 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, - 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, - 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, - 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, - 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, - 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, - 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, - 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, - 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, - 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, - 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, - 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, - 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, - 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, - 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, - 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, - 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, - 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, - 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, - 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, - 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, - 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, - 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, - 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, - 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, - 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, - 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, - 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, - 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, - 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, - 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, - 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, - 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, - 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, - 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, - 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, - 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, - 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, - 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, - 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, - 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, - 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, - 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, - 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, - 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, - 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, - 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, - 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, - 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, - 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, - 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, - 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, - 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, - 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, - 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, - 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 - ) - ); - } - -} - -?> diff --git a/3rdparty/MDB2.php b/3rdparty/MDB2.php deleted file mode 100644 index aa7ec6ba09..0000000000 --- a/3rdparty/MDB2.php +++ /dev/null @@ -1,4316 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: MDB2.php,v 1.335 2008/11/29 14:57:01 afz Exp $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -require_once('PEAR.php'); - -// {{{ Error constants - -/** - * The method mapErrorCode in each MDB2_dbtype implementation maps - * native error codes to one of these. - * - * If you add an error code here, make sure you also add a textual - * version of it in MDB2::errorMessage(). - */ - -define('MDB2_OK', true); -define('MDB2_ERROR', -1); -define('MDB2_ERROR_SYNTAX', -2); -define('MDB2_ERROR_CONSTRAINT', -3); -define('MDB2_ERROR_NOT_FOUND', -4); -define('MDB2_ERROR_ALREADY_EXISTS', -5); -define('MDB2_ERROR_UNSUPPORTED', -6); -define('MDB2_ERROR_MISMATCH', -7); -define('MDB2_ERROR_INVALID', -8); -define('MDB2_ERROR_NOT_CAPABLE', -9); -define('MDB2_ERROR_TRUNCATED', -10); -define('MDB2_ERROR_INVALID_NUMBER', -11); -define('MDB2_ERROR_INVALID_DATE', -12); -define('MDB2_ERROR_DIVZERO', -13); -define('MDB2_ERROR_NODBSELECTED', -14); -define('MDB2_ERROR_CANNOT_CREATE', -15); -define('MDB2_ERROR_CANNOT_DELETE', -16); -define('MDB2_ERROR_CANNOT_DROP', -17); -define('MDB2_ERROR_NOSUCHTABLE', -18); -define('MDB2_ERROR_NOSUCHFIELD', -19); -define('MDB2_ERROR_NEED_MORE_DATA', -20); -define('MDB2_ERROR_NOT_LOCKED', -21); -define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22); -define('MDB2_ERROR_INVALID_DSN', -23); -define('MDB2_ERROR_CONNECT_FAILED', -24); -define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25); -define('MDB2_ERROR_NOSUCHDB', -26); -define('MDB2_ERROR_ACCESS_VIOLATION', -27); -define('MDB2_ERROR_CANNOT_REPLACE', -28); -define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29); -define('MDB2_ERROR_DEADLOCK', -30); -define('MDB2_ERROR_CANNOT_ALTER', -31); -define('MDB2_ERROR_MANAGER', -32); -define('MDB2_ERROR_MANAGER_PARSE', -33); -define('MDB2_ERROR_LOADMODULE', -34); -define('MDB2_ERROR_INSUFFICIENT_DATA', -35); -define('MDB2_ERROR_NO_PERMISSION', -36); -define('MDB2_ERROR_DISCONNECT_FAILED', -37); - -// }}} -// {{{ Verbose constants -/** - * These are just helper constants to more verbosely express parameters to prepare() - */ - -define('MDB2_PREPARE_MANIP', false); -define('MDB2_PREPARE_RESULT', null); - -// }}} -// {{{ Fetchmode constants - -/** - * This is a special constant that tells MDB2 the user hasn't specified - * any particular get mode, so the default should be used. - */ -define('MDB2_FETCHMODE_DEFAULT', 0); - -/** - * Column data indexed by numbers, ordered from 0 and up - */ -define('MDB2_FETCHMODE_ORDERED', 1); - -/** - * Column data indexed by column names - */ -define('MDB2_FETCHMODE_ASSOC', 2); - -/** - * Column data as object properties - */ -define('MDB2_FETCHMODE_OBJECT', 3); - -/** - * For multi-dimensional results: normally the first level of arrays - * is the row number, and the second level indexed by column number or name. - * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays - * is the column name, and the second level the row number. - */ -define('MDB2_FETCHMODE_FLIPPED', 4); - -// }}} -// {{{ Portability mode constants - -/** - * Portability: turn off all portability features. - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_NONE', 0); - -/** - * Portability: convert names of tables and fields to case defined in the - * "field_case" option when using the query*(), fetch*() and tableInfo() methods. - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_FIX_CASE', 1); - -/** - * Portability: right trim the data output by query*() and fetch*(). - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_RTRIM', 2); - -/** - * Portability: force reporting the number of rows deleted. - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_DELETE_COUNT', 4); - -/** - * Portability: not needed in MDB2 (just left here for compatibility to DB) - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_NUMROWS', 8); - -/** - * Portability: makes certain error messages in certain drivers compatible - * with those from other DBMS's. - * - * + mysql, mysqli: change unique/primary key constraints - * MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT - * - * + odbc(access): MS's ODBC driver reports 'no such field' as code - * 07001, which means 'too few parameters.' When this option is on - * that code gets mapped to MDB2_ERROR_NOSUCHFIELD. - * - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_ERRORS', 16); - -/** - * Portability: convert empty values to null strings in data output by - * query*() and fetch*(). - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32); - -/** - * Portability: removes database/table qualifiers from associative indexes - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64); - -/** - * Portability: turn on all portability features. - * @see MDB2_Driver_Common::setOption() - */ -define('MDB2_PORTABILITY_ALL', 127); - -// }}} -// {{{ Globals for class instance tracking - -/** - * These are global variables that are used to track the various class instances - */ - -$GLOBALS['_MDB2_databases'] = array(); -$GLOBALS['_MDB2_dsninfo_default'] = array( - 'phptype' => false, - 'dbsyntax' => false, - 'username' => false, - 'password' => false, - 'protocol' => false, - 'hostspec' => false, - 'port' => false, - 'socket' => false, - 'database' => false, - 'mode' => false, -); - -// }}} -// {{{ class MDB2 - -/** - * The main 'MDB2' class is simply a container class with some static - * methods for creating DB objects as well as some utility functions - * common to all parts of DB. - * - * The object model of MDB2 is as follows (indentation means inheritance): - * - * MDB2 The main MDB2 class. This is simply a utility class - * with some 'static' methods for creating MDB2 objects as - * well as common utility functions for other MDB2 classes. - * - * MDB2_Driver_Common The base for each MDB2 implementation. Provides default - * | implementations (in OO lingo virtual methods) for - * | the actual DB implementations as well as a bunch of - * | query utility functions. - * | - * +-MDB2_Driver_mysql The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common. - * When calling MDB2::factory or MDB2::connect for MySQL - * connections, the object returned is an instance of this - * class. - * +-MDB2_Driver_pgsql The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common. - * When calling MDB2::factory or MDB2::connect for PostGreSQL - * connections, the object returned is an instance of this - * class. - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2 -{ - // {{{ function setOptions(&$db, $options) - - /** - * set option array in an exiting database object - * - * @param MDB2_Driver_Common MDB2 object - * @param array An associative array of option names and their values. - * - * @return mixed MDB2_OK or a PEAR Error object - * - * @access public - */ - static function setOptions(&$db, $options) - { - if (is_array($options)) { - foreach ($options as $option => $value) { - $test = $db->setOption($option, $value); - if (PEAR::isError($test)) { - return $test; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ function classExists($classname) - - /** - * Checks if a class exists without triggering __autoload - * - * @param string classname - * - * @return bool true success and false on error - * @static - * @access public - */ - static function classExists($classname) - { - if (version_compare(phpversion(), "5.0", ">=")) { - return class_exists($classname, false); - } - return class_exists($classname); - } - - // }}} - // {{{ function loadClass($class_name, $debug) - - /** - * Loads a PEAR class. - * - * @param string classname to load - * @param bool if errors should be suppressed - * - * @return mixed true success or PEAR_Error on failure - * - * @access public - */ - static function loadClass($class_name, $debug) - { - if (!MDB2::classExists($class_name)) { - $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php'; - if ($debug) { - $include = include_once($file_name); - } else { - $include = include_once($file_name); - } - if (!$include) { - if (!MDB2::fileExists($file_name)) { - $msg = "unable to find package '$class_name' file '$file_name'"; - } else { - $msg = "unable to load class '$class_name' from file '$file_name'"; - } - $err =MDB2::raiseErrorStatic(MDB2_ERROR_NOT_FOUND, null, null, $msg); - return $err; - } - } - return MDB2_OK; - } - - // }}} - // {{{ function &factory($dsn, $options = false) - - /** - * Create a new MDB2 object for the specified database type - * - * IMPORTANT: In order for MDB2 to work properly it is necessary that - * you make sure that you work with a reference of the original - * object instead of a copy (this is a PHP4 quirk). - * - * For example: - * $db =& MDB2::factory($dsn); - * ^^ - * And not: - * $db = MDB2::factory($dsn); - * - * @param mixed 'data source name', see the MDB2::parseDSN - * method for a description of the dsn format. - * Can also be specified as an array of the - * format returned by MDB2::parseDSN. - * @param array An associative array of option names and - * their values. - * - * @return mixed a newly created MDB2 object, or false on error - * - * @access public - */ - static function factory($dsn, $options = false) - { - $dsninfo = MDB2::parseDSN($dsn); - if (empty($dsninfo['phptype'])) { - $err =MDB2::raiseErrorStatic(MDB2_ERROR_NOT_FOUND, - null, null, 'no RDBMS driver specified'); - return $err; - } - $class_name = 'MDB2_Driver_'.$dsninfo['phptype']; - - $debug = (!empty($options['debug'])); - $err = MDB2::loadClass($class_name, $debug); - if (PEAR::isError($err)) { - return $err; - } - - $db =new $class_name(); - $db->setDSN($dsninfo); - $err = MDB2::setOptions($db, $options); - if (PEAR::isError($err)) { - return $err; - } - - return $db; - } - - // }}} - // {{{ function &connect($dsn, $options = false) - - /** - * Create a new MDB2_Driver_* connection object and connect to the specified - * database - * - * IMPORTANT: In order for MDB2 to work properly it is necessary that - * you make sure that you work with a reference of the original - * object instead of a copy (this is a PHP4 quirk). - * - * For example: - * $db =& MDB2::connect($dsn); - * ^^ - * And not: - * $db = MDB2::connect($dsn); - * ^^ - * - * @param mixed $dsn 'data source name', see the MDB2::parseDSN - * method for a description of the dsn format. - * Can also be specified as an array of the - * format returned by MDB2::parseDSN. - * @param array $options An associative array of option names and - * their values. - * - * @return mixed a newly created MDB2 connection object, or a MDB2 - * error object on error - * - * @access public - * @see MDB2::parseDSN - */ - function &connect($dsn, $options = false) - { - $db =MDB2::factory($dsn, $options); - if (PEAR::isError($db)) { - return $db; - } - - $err = $db->connect(); - if (PEAR::isError($err)) { - $dsn = $db->getDSN('string', 'xxx'); - $db->disconnect(); - $err->addUserInfo($dsn); - return $err; - } - - return $db; - } - - // }}} - // {{{ function &singleton($dsn = null, $options = false) - - /** - * Returns a MDB2 connection with the requested DSN. - * A new MDB2 connection object is only created if no object with the - * requested DSN exists yet. - * - * IMPORTANT: In order for MDB2 to work properly it is necessary that - * you make sure that you work with a reference of the original - * object instead of a copy (this is a PHP4 quirk). - * - * For example: - * $db =& MDB2::singleton($dsn); - * ^^ - * And not: - * $db = MDB2::singleton($dsn); - * ^^ - * - * @param mixed 'data source name', see the MDB2::parseDSN - * method for a description of the dsn format. - * Can also be specified as an array of the - * format returned by MDB2::parseDSN. - * @param array An associative array of option names and - * their values. - * - * @return mixed a newly created MDB2 connection object, or a MDB2 - * error object on error - * - * @access public - * @see MDB2::parseDSN - */ - function &singleton($dsn = null, $options = false) - { - if ($dsn) { - $dsninfo = MDB2::parseDSN($dsn); - $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo); - $keys = array_keys($GLOBALS['_MDB2_databases']); - for ($i=0, $j=count($keys); $i<$j; ++$i) { - if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) { - $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array'); - if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) { - MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options); - return $GLOBALS['_MDB2_databases'][$keys[$i]]; - } - } - } - } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) { - $db =$GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])]; - return $db; - } - $db =MDB2::factory($dsn, $options); - return $db; - } - - // }}} - // {{{ function areEquals() - - /** - * It looks like there's a memory leak in array_diff() in PHP 5.1.x, - * so use this method instead. - * @see http://pear.php.net/bugs/bug.php?id=11790 - * - * @param array $arr1 - * @param array $arr2 - * @return boolean - */ - static function areEquals($arr1, $arr2) - { - if (count($arr1) != count($arr2)) { - return false; - } - foreach (array_keys($arr1) as $k) { - if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) { - return false; - } - } - return true; - } - - // }}} - // {{{ function loadFile($file) - - /** - * load a file (like 'Date') - * - * @param string name of the file in the MDB2 directory (without '.php') - * - * @return string name of the file that was included - * - * @access public - */ - function loadFile($file) - { - $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php'; - if (!MDB2::fileExists($file_name)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'unable to find: '.$file_name); - } - if (!include_once($file_name)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'unable to load driver class: '.$file_name); - } - return $file_name; - } - - // }}} - // {{{ function apiVersion() - - /** - * Return the MDB2 API version - * - * @return string the MDB2 API version number - * - * @access public - */ - function apiVersion() - { - return '2.5.0b2'; - } - - // }}} - // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null) - - /** - * This method is used to communicate an error and invoke error - * callbacks etc. Basically a wrapper for PEAR::raiseError - * without the message string. - * - * @param mixed int error code - * - * @param int error mode, see PEAR_Error docs - * - * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the - * error level (E_USER_NOTICE etc). If error mode is - * PEAR_ERROR_CALLBACK, this is the callback function, - * either as a function name, or as an array of an - * object and method name. For other error modes this - * parameter is ignored. - * - * @param string Extra debug information. Defaults to the last - * query and native error code. - * - * @return PEAR_Error instance of a PEAR Error object - * - * @access private - * @see PEAR_Error - */ - function raiseError($code = null, - $mode = null, - $options = null, - $userinfo = null, - $dummy1 = null, - $dummy2 = null, - $dummy3 = false) - { - $err =PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true); - return $err; - } - static function raiseErrorStatic($code = null, - $mode = null, - $options = null, - $userinfo = null, - $dummy1 = null, - $dummy2 = null, - $dummy3 = false) - { - $pear=new PEAR(); - $err =$pear->raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true); - return $err; - } - - // }}} - // {{{ function isError($data, $code = null) - - /** - * Tell whether a value is a MDB2 error. - * - * @param mixed the value to test - * @param int if is an error object, return true - * only if $code is a string and - * $db->getMessage() == $code or - * $code is an integer and $db->getCode() == $code - * - * @return bool true if parameter is an error - * - * @access public - */ - static function isError($data, $code = null) - { - if ($data instanceof MDB2_Error) { - if (is_null($code)) { - return true; - } elseif (is_string($code)) { - return $data->getMessage() === $code; - } else { - $code = (array)$code; - return in_array($data->getCode(), $code); - } - } - return false; - } - - // }}} - // {{{ function isConnection($value) - - /** - * Tell whether a value is a MDB2 connection - * - * @param mixed value to test - * - * @return bool whether $value is a MDB2 connection - * - * @access public - */ - static function isConnection($value) - { - return ($value instanceof MDB2_Driver_Common); - } - - // }}} - // {{{ function isResult($value) - - /** - * Tell whether a value is a MDB2 result - * - * @param mixed value to test - * - * @return bool whether $value is a MDB2 result - * - * @access public - */ - static function isResult($value) - { - return $value instanceof MDB2_Result; - } - - // }}} - // {{{ function isResultCommon($value) - - /** - * Tell whether a value is a MDB2 result implementing the common interface - * - * @param mixed value to test - * - * @return bool whether $value is a MDB2 result implementing the common interface - * - * @access public - */ - static function isResultCommon($value) - { - return ($value instanceof MDB2_Result_Common); - } - - // }}} - // {{{ function isStatement($value) - - /** - * Tell whether a value is a MDB2 statement interface - * - * @param mixed value to test - * - * @return bool whether $value is a MDB2 statement interface - * - * @access public - */ - static function isStatement($value) - { - return $value instanceof MDB2_Statement_Common; - } - - // }}} - // {{{ function errorMessage($value = null) - - /** - * Return a textual error message for a MDB2 error code - * - * @param int|array integer error code, - null to get the current error code-message map, - or an array with a new error code-message map - * - * @return string error message, or false if the error code was - * not recognized - * - * @access public - */ - static function errorMessage($value = null) - { - static $errorMessages; - - if (is_array($value)) { - $errorMessages = $value; - return MDB2_OK; - } - - if (!isset($errorMessages)) { - $errorMessages = array( - MDB2_OK => 'no error', - MDB2_ERROR => 'unknown error', - MDB2_ERROR_ALREADY_EXISTS => 'already exists', - MDB2_ERROR_CANNOT_CREATE => 'can not create', - MDB2_ERROR_CANNOT_ALTER => 'can not alter', - MDB2_ERROR_CANNOT_REPLACE => 'can not replace', - MDB2_ERROR_CANNOT_DELETE => 'can not delete', - MDB2_ERROR_CANNOT_DROP => 'can not drop', - MDB2_ERROR_CONSTRAINT => 'constraint violation', - MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint', - MDB2_ERROR_DIVZERO => 'division by zero', - MDB2_ERROR_INVALID => 'invalid', - MDB2_ERROR_INVALID_DATE => 'invalid date or time', - MDB2_ERROR_INVALID_NUMBER => 'invalid number', - MDB2_ERROR_MISMATCH => 'mismatch', - MDB2_ERROR_NODBSELECTED => 'no database selected', - MDB2_ERROR_NOSUCHFIELD => 'no such field', - MDB2_ERROR_NOSUCHTABLE => 'no such table', - MDB2_ERROR_NOT_CAPABLE => 'MDB2 backend not capable', - MDB2_ERROR_NOT_FOUND => 'not found', - MDB2_ERROR_NOT_LOCKED => 'not locked', - MDB2_ERROR_SYNTAX => 'syntax error', - MDB2_ERROR_UNSUPPORTED => 'not supported', - MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row', - MDB2_ERROR_INVALID_DSN => 'invalid DSN', - MDB2_ERROR_CONNECT_FAILED => 'connect failed', - MDB2_ERROR_NEED_MORE_DATA => 'insufficient data supplied', - MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found', - MDB2_ERROR_NOSUCHDB => 'no such database', - MDB2_ERROR_ACCESS_VIOLATION => 'insufficient permissions', - MDB2_ERROR_LOADMODULE => 'error while including on demand module', - MDB2_ERROR_TRUNCATED => 'truncated', - MDB2_ERROR_DEADLOCK => 'deadlock detected', - MDB2_ERROR_NO_PERMISSION => 'no permission', - MDB2_ERROR_DISCONNECT_FAILED => 'disconnect failed', - ); - } - - if (is_null($value)) { - return $errorMessages; - } - - if (PEAR::isError($value)) { - $value = $value->getCode(); - } - - return isset($errorMessages[$value]) ? - $errorMessages[$value] : $errorMessages[MDB2_ERROR]; - } - - // }}} - // {{{ function parseDSN($dsn) - - /** - * Parse a data source name. - * - * Additional keys can be added by appending a URI query string to the - * end of the DSN. - * - * The format of the supplied DSN is in its fullest form: - * - * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true - * - * - * Most variations are allowed: - * - * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 - * phptype://username:password@hostspec/database_name - * phptype://username:password@hostspec - * phptype://username@hostspec - * phptype://hostspec/database - * phptype://hostspec - * phptype(dbsyntax) - * phptype - * - * - * @param string Data Source Name to be parsed - * - * @return array an associative array with the following keys: - * + phptype: Database backend used in PHP (mysql, odbc etc.) - * + dbsyntax: Database used with regards to SQL syntax etc. - * + protocol: Communication protocol to use (tcp, unix etc.) - * + hostspec: Host specification (hostname[:port]) - * + database: Database to use on the DBMS server - * + username: User name for login - * + password: Password for login - * - * @access public - * @author Tomas V.V.Cox - */ - static function parseDSN($dsn) - { - $parsed = $GLOBALS['_MDB2_dsninfo_default']; - - if (is_array($dsn)) { - $dsn = array_merge($parsed, $dsn); - if (!$dsn['dbsyntax']) { - $dsn['dbsyntax'] = $dsn['phptype']; - } - return $dsn; - } - - // Find phptype and dbsyntax - if (($pos = strpos($dsn, '://')) !== false) { - $str = substr($dsn, 0, $pos); - $dsn = substr($dsn, $pos + 3); - } else { - $str = $dsn; - $dsn = null; - } - - // Get phptype and dbsyntax - // $str => phptype(dbsyntax) - if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { - $parsed['phptype'] = $arr[1]; - $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; - } else { - $parsed['phptype'] = $str; - $parsed['dbsyntax'] = $str; - } - - if (!count($dsn)) { - return $parsed; - } - - // Get (if found): username and password - // $dsn => username:password@protocol+hostspec/database - if (($at = strrpos($dsn,'@')) !== false) { - $str = substr($dsn, 0, $at); - $dsn = substr($dsn, $at + 1); - if (($pos = strpos($str, ':')) !== false) { - $parsed['username'] = rawurldecode(substr($str, 0, $pos)); - $parsed['password'] = rawurldecode(substr($str, $pos + 1)); - } else { - $parsed['username'] = rawurldecode($str); - } - } - - // Find protocol and hostspec - - // $dsn => proto(proto_opts)/database - if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { - $proto = $match[1]; - $proto_opts = $match[2] ? $match[2] : false; - $dsn = $match[3]; - - // $dsn => protocol+hostspec/database (old format) - } else { - if (strpos($dsn, '+') !== false) { - list($proto, $dsn) = explode('+', $dsn, 2); - } - if ( strpos($dsn, '//') === 0 - && strpos($dsn, '/', 2) !== false - && $parsed['phptype'] == 'oci8' - ) { - //oracle's "Easy Connect" syntax: - //"username/password@[//]host[:port][/service_name]" - //e.g. "scott/tiger@//mymachine:1521/oracle" - $proto_opts = $dsn; - $dsn = substr($proto_opts, strrpos($proto_opts, '/') + 1); - } elseif (strpos($dsn, '/') !== false) { - list($proto_opts, $dsn) = explode('/', $dsn, 2); - } else { - $proto_opts = $dsn; - $dsn = null; - } - } - - // process the different protocol options - $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; - $proto_opts = rawurldecode($proto_opts); - if (strpos($proto_opts, ':') !== false) { - list($proto_opts, $parsed['port']) = explode(':', $proto_opts); - } - if ($parsed['protocol'] == 'tcp') { - $parsed['hostspec'] = $proto_opts; - } elseif ($parsed['protocol'] == 'unix') { - $parsed['socket'] = $proto_opts; - } - - // Get dabase if any - // $dsn => database - if ($dsn) { - // /database - if (($pos = strpos($dsn, '?')) === false) { - $parsed['database'] = $dsn; - // /database?param1=value1¶m2=value2 - } else { - $parsed['database'] = substr($dsn, 0, $pos); - $dsn = substr($dsn, $pos + 1); - if (strpos($dsn, '&') !== false) { - $opts = explode('&', $dsn); - } else { // database?param1=value1 - $opts = array($dsn); - } - foreach ($opts as $opt) { - list($key, $value) = explode('=', $opt); - if (!isset($parsed[$key])) { - // don't allow params overwrite - $parsed[$key] = rawurldecode($value); - } - } - } - } - - return $parsed; - } - - // }}} - // {{{ function fileExists($file) - - /** - * Checks if a file exists in the include path - * - * @param string filename - * - * @return bool true success and false on error - * - * @access public - */ - static function fileExists($file) - { - // safe_mode does notwork with is_readable() - if (!@ini_get('safe_mode')) { - $dirs = explode(PATH_SEPARATOR, ini_get('include_path')); - array_unshift($dirs,OC::$SERVERROOT); - array_unshift($dirs,OC::$SERVERROOT. DIRECTORY_SEPARATOR .'inc'); -// print_r($dirs);die(); - foreach ($dirs as $dir) { - if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) { - return true; - } - } - } else { - $fp = @fopen($file, 'r', true); - if (is_resource($fp)) { - @fclose($fp); - return true; - } - } - return false; - } - // }}} -} - -// }}} -// {{{ class MDB2_Error extends PEAR_Error - -/** - * MDB2_Error implements a class for reporting portable database error - * messages. - * - * @package MDB2 - * @category Database - * @author Stig Bakken - */ -class MDB2_Error extends PEAR_Error -{ - // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null) - - /** - * MDB2_Error constructor. - * - * @param mixed MDB2 error code, or string with error message. - * @param int what 'error mode' to operate in - * @param int what error level to use for $mode raPEAR_ERROR_TRIGGER - * @param mixed additional debug info, such as the last query - */ - function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, - $level = E_USER_NOTICE, $debuginfo = null, $dummy = null) - { - if (is_null($code)) { - $code = MDB2_ERROR; - } - $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code, - $mode, $level, $debuginfo); - } - - // }}} -} - -// }}} -// {{{ class MDB2_Driver_Common extends PEAR - -/** - * MDB2_Driver_Common: Base class that is extended by each MDB2 driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Common extends PEAR -{ - // {{{ Variables (Properties) - - /** - * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array - * @var int - * @access public - */ - var $db_index = 0; - - /** - * DSN used for the next query - * @var array - * @access protected - */ - var $dsn = array(); - - /** - * DSN that was used to create the current connection - * @var array - * @access protected - */ - var $connected_dsn = array(); - - /** - * connection resource - * @var mixed - * @access protected - */ - var $connection = 0; - - /** - * if the current opened connection is a persistent connection - * @var bool - * @access protected - */ - var $opened_persistent; - - /** - * the name of the database for the next query - * @var string - * @access protected - */ - var $database_name = ''; - - /** - * the name of the database currently selected - * @var string - * @access protected - */ - var $connected_database_name = ''; - - /** - * server version information - * @var string - * @access protected - */ - var $connected_server_info = ''; - - /** - * list of all supported features of the given driver - * @var array - * @access public - */ - var $supported = array( - 'sequences' => false, - 'indexes' => false, - 'affected_rows' => false, - 'summary_functions' => false, - 'order_by_text' => false, - 'transactions' => false, - 'savepoints' => false, - 'current_id' => false, - 'limit_queries' => false, - 'LOBs' => false, - 'replace' => false, - 'sub_selects' => false, - 'triggers' => false, - 'auto_increment' => false, - 'primary_key' => false, - 'result_introspection' => false, - 'prepared_statements' => false, - 'identifier_quoting' => false, - 'pattern_escaping' => false, - 'new_link' => false, - ); - - /** - * Array of supported options that can be passed to the MDB2 instance. - * - * The options can be set during object creation, using - * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can - * also be set after the object is created, using MDB2::setOptions() or - * MDB2_Driver_Common::setOption(). - * The list of available option includes: - *
    - *
  • $options['ssl'] -> boolean: determines if ssl should be used for connections
  • - *
  • $options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names
  • - *
  • $options['disable_query'] -> boolean: determines if queries should be executed
  • - *
  • $options['result_class'] -> string: class used for result sets
  • - *
  • $options['buffered_result_class'] -> string: class used for buffered result sets
  • - *
  • $options['result_wrap_class'] -> string: class used to wrap result sets into
  • - *
  • $options['result_buffering'] -> boolean should results be buffered or not?
  • - *
  • $options['fetch_class'] -> string: class to use when fetch mode object is used
  • - *
  • $options['persistent'] -> boolean: persistent connection?
  • - *
  • $options['debug'] -> integer: numeric debug level
  • - *
  • $options['debug_handler'] -> string: function/method that captures debug messages
  • - *
  • $options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler
  • - *
  • $options['default_text_field_length'] -> integer: default text field length to use
  • - *
  • $options['lob_buffer_length'] -> integer: LOB buffer length
  • - *
  • $options['log_line_break'] -> string: line-break format
  • - *
  • $options['idxname_format'] -> string: pattern for index name
  • - *
  • $options['seqname_format'] -> string: pattern for sequence name
  • - *
  • $options['savepoint_format'] -> string: pattern for auto generated savepoint names
  • - *
  • $options['statement_format'] -> string: pattern for prepared statement names
  • - *
  • $options['seqcol_name'] -> string: sequence column name
  • - *
  • $options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used
  • - *
  • $options['use_transactions'] -> boolean: if transaction use should be enabled
  • - *
  • $options['decimal_places'] -> integer: number of decimal places to handle
  • - *
  • $options['portability'] -> integer: portability constant
  • - *
  • $options['modules'] -> array: short to long module name mapping for __call()
  • - *
  • $options['emulate_prepared'] -> boolean: force prepared statements to be emulated
  • - *
  • $options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes
  • - *
  • $options['datatype_map_callback'] -> array: callback function/method that should be called
  • - *
  • $options['bindname_format'] -> string: regular expression pattern for named parameters
  • - *
  • $options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed
  • - *
  • $options['max_identifiers_length'] -> integer: max identifier length
  • - *
  • $options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
  • - *
  • $options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
  • - *
- * - * @var array - * @access public - * @see MDB2::connect() - * @see MDB2::factory() - * @see MDB2::singleton() - * @see MDB2_Driver_Common::setOption() - */ - var $options = array( - 'ssl' => false, - 'field_case' => CASE_LOWER, - 'disable_query' => false, - 'result_class' => 'MDB2_Result_%s', - 'buffered_result_class' => 'MDB2_BufferedResult_%s', - 'result_wrap_class' => false, - 'result_buffering' => true, - 'fetch_class' => 'stdClass', - 'persistent' => false, - 'debug' => 0, - 'debug_handler' => 'MDB2_defaultDebugOutput', - 'debug_expanded_output' => false, - 'default_text_field_length' => 4096, - 'lob_buffer_length' => 8192, - 'log_line_break' => "\n", - 'idxname_format' => '%s_idx', - 'seqname_format' => '%s_seq', - 'savepoint_format' => 'MDB2_SAVEPOINT_%s', - 'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s', - 'seqcol_name' => 'sequence', - 'quote_identifier' => false, - 'use_transactions' => true, - 'decimal_places' => 2, - 'portability' => MDB2_PORTABILITY_ALL, - 'modules' => array( - 'ex' => 'Extended', - 'dt' => 'Datatype', - 'mg' => 'Manager', - 'rv' => 'Reverse', - 'na' => 'Native', - 'fc' => 'Function', - ), - 'emulate_prepared' => false, - 'datatype_map' => array(), - 'datatype_map_callback' => array(), - 'nativetype_map_callback' => array(), - 'lob_allow_url_include' => false, - 'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)', - 'max_identifiers_length' => 30, - 'default_fk_action_onupdate' => 'RESTRICT', - 'default_fk_action_ondelete' => 'RESTRICT', - ); - - /** - * string array - * @var string - * @access protected - */ - var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false); - - /** - * identifier quoting - * @var array - * @access protected - */ - var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"'); - - /** - * sql comments - * @var array - * @access protected - */ - var $sql_comments = array( - array('start' => '--', 'end' => "\n", 'escape' => false), - array('start' => '/*', 'end' => '*/', 'escape' => false), - ); - - /** - * comparision wildcards - * @var array - * @access protected - */ - var $wildcards = array('%', '_'); - - /** - * column alias keyword - * @var string - * @access protected - */ - var $as_keyword = ' AS '; - - /** - * warnings - * @var array - * @access protected - */ - var $warnings = array(); - - /** - * string with the debugging information - * @var string - * @access public - */ - var $debug_output = ''; - - /** - * determine if there is an open transaction - * @var bool - * @access protected - */ - var $in_transaction = false; - - /** - * the smart transaction nesting depth - * @var int - * @access protected - */ - var $nested_transaction_counter = null; - - /** - * the first error that occured inside a nested transaction - * @var MDB2_Error|bool - * @access protected - */ - var $has_transaction_error = false; - - /** - * result offset used in the next query - * @var int - * @access protected - */ - var $offset = 0; - - /** - * result limit used in the next query - * @var int - * @access protected - */ - var $limit = 0; - - /** - * Database backend used in PHP (mysql, odbc etc.) - * @var string - * @access public - */ - var $phptype; - - /** - * Database used with regards to SQL syntax etc. - * @var string - * @access public - */ - var $dbsyntax; - - /** - * the last query sent to the driver - * @var string - * @access public - */ - var $last_query; - - /** - * the default fetchmode used - * @var int - * @access protected - */ - var $fetchmode = MDB2_FETCHMODE_ORDERED; - - /** - * array of module instances - * @var array - * @access protected - */ - var $modules = array(); - - /** - * determines of the PHP4 destructor emulation has been enabled yet - * @var array - * @access protected - */ - var $destructor_registered = true; - - // }}} - // {{{ constructor: function __construct() - - /** - * Constructor - */ - function __construct() - { - end($GLOBALS['_MDB2_databases']); - $db_index = key($GLOBALS['_MDB2_databases']) + 1; - $GLOBALS['_MDB2_databases'][$db_index] = &$this; - $this->db_index = $db_index; - } - - - // }}} - // {{{ destructor: function __destruct() - - /** - * Destructor - */ - function __destruct() - { - $this->disconnect(false); - } - - // }}} - // {{{ function free() - - /** - * Free the internal references so that the instance can be destroyed - * - * @return bool true on success, false if result is invalid - * - * @access public - */ - function free() - { - unset($GLOBALS['_MDB2_databases'][$this->db_index]); - unset($this->db_index); - return MDB2_OK; - } - - // }}} - // {{{ function __toString() - - /** - * String conversation - * - * @return string representation of the object - * - * @access public - */ - function __toString() - { - $info = get_class($this); - $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')'; - if ($this->connection) { - $info.= ' [connected]'; - } - return $info; - } - - // }}} - // {{{ function errorInfo($error = null) - - /** - * This method is used to collect information about an error - * - * @param mixed error code or resource - * - * @return array with MDB2 errorcode, native error code, native message - * - * @access public - */ - function errorInfo($error = null) - { - return array($error, null, null); - } - - // }}} - // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null) - - /** - * This method is used to communicate an error and invoke error - * callbacks etc. Basically a wrapper for PEAR::raiseError - * without the message string. - * - * @param mixed $code integer error code, or a PEAR error object (all - * other parameters are ignored if this parameter is - * an object - * @param int $mode error mode, see PEAR_Error docs - * @param mixed $options If error mode is PEAR_ERROR_TRIGGER, this is the - * error level (E_USER_NOTICE etc). If error mode is - * PEAR_ERROR_CALLBACK, this is the callback function, - * either as a function name, or as an array of an - * object and method name. For other error modes this - * parameter is ignored. - * @param string $userinfo Extra debug information. Defaults to the last - * query and native error code. - * @param string $method name of the method that triggered the error - * @param string $dummy1 not used - * @param bool $dummy2 not used - * - * @return PEAR_Error instance of a PEAR Error object - * @access public - * @see PEAR_Error - */ - function raiseError($code = null, - $mode = null, - $options = null, - $userinfo = null, - $method = null, - $dummy1 = null, - $dummy2 = false - ) { - $userinfo = "[Error message: $userinfo]\n"; - // The error is yet a MDB2 error object - if (PEAR::isError($code)) { - // because we use the static PEAR::raiseError, our global - // handler should be used if it is set - if (is_null($mode) && !empty($this->_default_error_mode)) { - $mode = $this->_default_error_mode; - $options = $this->_default_error_options; - } - if (is_null($userinfo)) { - $userinfo = $code->getUserinfo(); - } - $code = $code->getCode(); - } elseif ($code == MDB2_ERROR_NOT_FOUND) { - // extension not loaded: don't call $this->errorInfo() or the script - // will die - } elseif (isset($this->connection)) { - if (!empty($this->last_query)) { - $userinfo.= "[Last executed query: {$this->last_query}]\n"; - } - $native_errno = $native_msg = null; - list($code, $native_errno, $native_msg) = $this->errorInfo($code); - if (!is_null($native_errno) && $native_errno !== '') { - $userinfo.= "[Native code: $native_errno]\n"; - } - if (!is_null($native_msg) && $native_msg !== '') { - $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n"; - } - echo $userinfo; - if (!is_null($method)) { - $userinfo = $method.': '.$userinfo; - } - } - - $err = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true); - if ($err->getMode() !== PEAR_ERROR_RETURN - && isset($this->nested_transaction_counter) && !$this->has_transaction_error) { - $this->has_transaction_error =$err; - } - return $err; - } - - // }}} - // {{{ function resetWarnings() - - /** - * reset the warning array - * - * @return void - * - * @access public - */ - function resetWarnings() - { - $this->warnings = array(); - } - - // }}} - // {{{ function getWarnings() - - /** - * Get all warnings in reverse order. - * This means that the last warning is the first element in the array - * - * @return array with warnings - * - * @access public - * @see resetWarnings() - */ - function getWarnings() - { - return array_reverse($this->warnings); - } - - // }}} - // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass') - - /** - * Sets which fetch mode should be used by default on queries - * on this connection - * - * @param int MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC - * or MDB2_FETCHMODE_OBJECT - * @param string the class name of the object to be returned - * by the fetch methods when the - * MDB2_FETCHMODE_OBJECT mode is selected. - * If no class is specified by default a cast - * to object from the assoc array row will be - * done. There is also the possibility to use - * and extend the 'MDB2_row' class. - * - * @return mixed MDB2_OK or MDB2 Error Object - * - * @access public - * @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT - */ - function setFetchMode($fetchmode, $object_class = 'stdClass') - { - switch ($fetchmode) { - case MDB2_FETCHMODE_OBJECT: - $this->options['fetch_class'] = $object_class; - case MDB2_FETCHMODE_ORDERED: - case MDB2_FETCHMODE_ASSOC: - $this->fetchmode = $fetchmode; - break; - default: - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'invalid fetchmode mode', __FUNCTION__); - } - - return MDB2_OK; - } - - // }}} - // {{{ function setOption($option, $value) - - /** - * set the option for the db class - * - * @param string option name - * @param mixed value for the option - * - * @return mixed MDB2_OK or MDB2 Error Object - * - * @access public - */ - function setOption($option, $value) - { - if (array_key_exists($option, $this->options)) { - $this->options[$option] = $value; - return MDB2_OK; - } - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - "unknown option $option", __FUNCTION__); - } - - // }}} - // {{{ function getOption($option) - - /** - * Returns the value of an option - * - * @param string option name - * - * @return mixed the option value or error object - * - * @access public - */ - function getOption($option) - { - if (array_key_exists($option, $this->options)) { - return $this->options[$option]; - } - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - "unknown option $option", __FUNCTION__); - } - - // }}} - // {{{ function debug($message, $scope = '', $is_manip = null) - - /** - * set a debug message - * - * @param string message that should be appended to the debug variable - * @param string usually the method name that triggered the debug call: - * for example 'query', 'prepare', 'execute', 'parameters', - * 'beginTransaction', 'commit', 'rollback' - * @param array contains context information about the debug() call - * common keys are: is_manip, time, result etc. - * - * @return void - * - * @access public - */ - function debug($message, $scope = '', $context = array()) - { - if ($this->options['debug'] && $this->options['debug_handler']) { - if (!$this->options['debug_expanded_output']) { - if (!empty($context['when']) && $context['when'] !== 'pre') { - return null; - } - $context = empty($context['is_manip']) ? false : $context['is_manip']; - } - return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context)); - } - return null; - } - - // }}} - // {{{ function getDebugOutput() - - /** - * output debug info - * - * @return string content of the debug_output class variable - * - * @access public - */ - function getDebugOutput() - { - return $this->debug_output; - } - - // }}} - // {{{ function escape($text) - - /** - * Quotes a string so it can be safely used in a query. It will quote - * the text so it can safely be used within a query. - * - * @param string the input string to quote - * @param bool escape wildcards - * - * @return string quoted string - * - * @access public - */ - function escape($text, $escape_wildcards = false) - { - if ($escape_wildcards) { - $text = $this->escapePattern($text); - } - - $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text); - return $text; - } - - // }}} - // {{{ function escapePattern($text) - - /** - * Quotes pattern (% and _) characters in a string) - * - * @param string the input string to quote - * - * @return string quoted string - * - * @access public - */ - function escapePattern($text) - { - if ($this->string_quoting['escape_pattern']) { - $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text); - foreach ($this->wildcards as $wildcard) { - $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text); - } - } - return $text; - } - - // }}} - // {{{ function quoteIdentifier($str, $check_option = false) - - /** - * Quote a string so it can be safely used as a table or column name - * - * Delimiting style depends on which database driver is being used. - * - * NOTE: just because you CAN use delimited identifiers doesn't mean - * you SHOULD use them. In general, they end up causing way more - * problems than they solve. - * - * NOTE: if you have table names containing periods, don't use this method - * (@see bug #11906) - * - * Portability is broken by using the following characters inside - * delimited identifiers: - * + backtick (`) -- due to MySQL - * + double quote (") -- due to Oracle - * + brackets ([ or ]) -- due to Access - * - * Delimited identifiers are known to generally work correctly under - * the following drivers: - * + mssql - * + mysql - * + mysqli - * + oci8 - * + pgsql - * + sqlite - * - * InterBase doesn't seem to be able to use delimited identifiers - * via PHP 4. They work fine under PHP 5. - * - * @param string identifier name to be quoted - * @param bool check the 'quote_identifier' option - * - * @return string quoted identifier string - * - * @access public - */ - function quoteIdentifier($str, $check_option = false) - { - if ($check_option && !$this->options['quote_identifier']) { - return $str; - } - $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str); - $parts = explode('.', $str); - foreach (array_keys($parts) as $k) { - $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end']; - } - return implode('.', $parts); - } - - // }}} - // {{{ function getAsKeyword() - - /** - * Gets the string to alias column - * - * @return string to use when aliasing a column - */ - function getAsKeyword() - { - return $this->as_keyword; - } - - // }}} - // {{{ function getConnection() - - /** - * Returns a native connection - * - * @return mixed a valid MDB2 connection object, - * or a MDB2 error object on error - * - * @access public - */ - function getConnection() - { - $result = $this->connect(); - if (PEAR::isError($result)) { - return $result; - } - return $this->connection; - } - - // }}} - // {{{ function _fixResultArrayValues(&$row, $mode) - - /** - * Do all necessary conversions on result arrays to fix DBMS quirks - * - * @param array the array to be fixed (passed by reference) - * @param array bit-wise addition of the required portability modes - * - * @return void - * - * @access protected - */ - function _fixResultArrayValues(&$row, $mode) - { - switch ($mode) { - case MDB2_PORTABILITY_EMPTY_TO_NULL: - foreach ($row as $key => $value) { - if ($value === '') { - $row[$key] = null; - } - } - break; - case MDB2_PORTABILITY_RTRIM: - foreach ($row as $key => $value) { - if (is_string($value)) { - $row[$key] = rtrim($value); - } - } - break; - case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES: - $tmp_row = array(); - foreach ($row as $key => $value) { - $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value; - } - $row = $tmp_row; - break; - case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL): - foreach ($row as $key => $value) { - if ($value === '') { - $row[$key] = null; - } elseif (is_string($value)) { - $row[$key] = rtrim($value); - } - } - break; - case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES): - $tmp_row = array(); - foreach ($row as $key => $value) { - if (is_string($value)) { - $value = rtrim($value); - } - $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value; - } - $row = $tmp_row; - break; - case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES): - $tmp_row = array(); - foreach ($row as $key => $value) { - if ($value === '') { - $value = null; - } - $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value; - } - $row = $tmp_row; - break; - case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES): - $tmp_row = array(); - foreach ($row as $key => $value) { - if ($value === '') { - $value = null; - } elseif (is_string($value)) { - $value = rtrim($value); - } - $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value; - } - $row = $tmp_row; - break; - } - } - - // }}} - // {{{ function &loadModule($module, $property = null, $phptype_specific = null) - - /** - * loads a module - * - * @param string name of the module that should be loaded - * (only used for error messages) - * @param string name of the property into which the class will be loaded - * @param bool if the class to load for the module is specific to the - * phptype - * - * @return object on success a reference to the given module is returned - * and on failure a PEAR error - * - * @access public - */ - function &loadModule($module, $property = null, $phptype_specific = null) - { - if (!$property) { - $property = strtolower($module); - } - - if (!isset($this->{$property})) { - $version = $phptype_specific; - if ($phptype_specific !== false) { - $version = true; - $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype; - $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php'; - } - if ($phptype_specific === false - || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name)) - ) { - $version = false; - $class_name = 'MDB2_'.$module; - $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php'; - } - - $err = MDB2::loadClass($class_name, $this->getOption('debug')); - if (PEAR::isError($err)) { - return $err; - } - // load module in a specific version - if ($version) { - if (method_exists($class_name, 'getClassName')) { - $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index); - if ($class_name != $class_name_new) { - $class_name = $class_name_new; - $err = MDB2::loadClass($class_name, $this->getOption('debug')); - if (PEAR::isError($err)) { - return $err; - } - } - } - } - - if (!MDB2::classExists($class_name)) { - $err =$this->raiseError(MDB2_ERROR_LOADMODULE, null, null, - "unable to load module '$module' into property '$property'", __FUNCTION__); - return $err; - } - $this->{$property} = new $class_name($this->db_index); - $this->modules[$module] =$this->{$property}; - if ($version) { - // this will be used in the connect method to determine if the module - // needs to be loaded with a different version if the server - // version changed in between connects - $this->loaded_version_modules[] = $property; - } - } - - return $this->{$property}; - } - - // }}} - // {{{ function __call($method, $params) - - /** - * Calls a module method using the __call magic method - * - * @param string Method name. - * @param array Arguments. - * - * @return mixed Returned value. - */ - function __call($method, $params) - { - $module = null; - if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match) - && isset($this->options['modules'][$match[1]]) - ) { - $module = $this->options['modules'][$match[1]]; - $method = strtolower($match[2]).$match[3]; - if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) { - $result =& $this->loadModule($module); - if (PEAR::isError($result)) { - return $result; - } - } - } else { - foreach ($this->modules as $key => $foo) { - if (is_object($this->modules[$key]) - && method_exists($this->modules[$key], $method) - ) { - $module = $key; - break; - } - } - } - if (!is_null($module)) { - return call_user_func_array(array(&$this->modules[$module], $method), $params); - } - trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR); - } - - // }}} - // {{{ function beginTransaction($savepoint = null) - - /** - * Start a transaction or set a savepoint. - * - * @param string name of a savepoint to set - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function beginTransaction($savepoint = null) - { - $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'transactions are not supported', __FUNCTION__); - } - - // }}} - // {{{ function commit($savepoint = null) - - /** - * Commit the database changes done during a transaction that is in - * progress or release a savepoint. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after committing the pending changes. - * - * @param string name of a savepoint to release - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function commit($savepoint = null) - { - $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'commiting transactions is not supported', __FUNCTION__); - } - - // }}} - // {{{ function rollback($savepoint = null) - - /** - * Cancel any database changes done during a transaction or since a specific - * savepoint that is in progress. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after canceling the pending changes. - * - * @param string name of a savepoint to rollback to - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function rollback($savepoint = null) - { - $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'rolling back transactions is not supported', __FUNCTION__); - } - - // }}} - // {{{ function inTransaction($ignore_nested = false) - - /** - * If a transaction is currently open. - * - * @param bool if the nested transaction count should be ignored - * @return int|bool - an integer with the nesting depth is returned if a - * nested transaction is open - * - true is returned for a normal open transaction - * - false is returned if no transaction is open - * - * @access public - */ - function inTransaction($ignore_nested = false) - { - if (!$ignore_nested && isset($this->nested_transaction_counter)) { - return $this->nested_transaction_counter; - } - return $this->in_transaction; - } - - // }}} - // {{{ function setTransactionIsolation($isolation) - - /** - * Set the transacton isolation level. - * - * @param string standard isolation level - * READ UNCOMMITTED (allows dirty reads) - * READ COMMITTED (prevents dirty reads) - * REPEATABLE READ (prevents nonrepeatable reads) - * SERIALIZABLE (prevents phantom reads) - * @param array some transaction options: - * 'wait' => 'WAIT' | 'NO WAIT' - * 'rw' => 'READ WRITE' | 'READ ONLY' - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - * @since 2.1.1 - */ - static function setTransactionIsolation($isolation, $options = array()) - { - $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true)); - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'isolation level setting is not supported', __FUNCTION__); - } - - // }}} - // {{{ function beginNestedTransaction($savepoint = false) - - /** - * Start a nested transaction. - * - * @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure - * - * @access public - * @since 2.1.1 - */ - function beginNestedTransaction() - { - if ($this->in_transaction) { - ++$this->nested_transaction_counter; - $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter); - if ($this->supports('savepoints') && $savepoint) { - return $this->beginTransaction($savepoint); - } - return MDB2_OK; - } - $this->has_transaction_error = false; - $result = $this->beginTransaction(); - $this->nested_transaction_counter = 1; - return $result; - } - - // }}} - // {{{ function completeNestedTransaction($force_rollback = false, $release = false) - - /** - * Finish a nested transaction by rolling back if an error occured or - * committing otherwise. - * - * @param bool if the transaction should be rolled back regardless - * even if no error was set within the nested transaction - * @return mixed MDB_OK on commit/counter decrementing, false on rollback - * and a MDB2 error on failure - * - * @access public - * @since 2.1.1 - */ - function completeNestedTransaction($force_rollback = false) - { - if ($this->nested_transaction_counter > 1) { - $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter); - if ($this->supports('savepoints') && $savepoint) { - if ($force_rollback || $this->has_transaction_error) { - $result = $this->rollback($savepoint); - if (!PEAR::isError($result)) { - $result = false; - $this->has_transaction_error = false; - } - } else { - $result = $this->commit($savepoint); - } - } else { - $result = MDB2_OK; - } - --$this->nested_transaction_counter; - return $result; - } - - $this->nested_transaction_counter = null; - $result = MDB2_OK; - - // transaction has not yet been rolled back - if ($this->in_transaction) { - if ($force_rollback || $this->has_transaction_error) { - $result = $this->rollback(); - if (!PEAR::isError($result)) { - $result = false; - } - } else { - $result = $this->commit(); - } - } - $this->has_transaction_error = false; - return $result; - } - - // }}} - // {{{ function failNestedTransaction($error = null, $immediately = false) - - /** - * Force setting nested transaction to failed. - * - * @param mixed value to return in getNestededTransactionError() - * @param bool if the transaction should be rolled back immediately - * @return bool MDB2_OK - * - * @access public - * @since 2.1.1 - */ - function failNestedTransaction($error = null, $immediately = false) - { - if (is_null($error)) { - $error = $this->has_transaction_error ? $this->has_transaction_error : true; - } elseif (!$error) { - $error = true; - } - $this->has_transaction_error = $error; - if (!$immediately) { - return MDB2_OK; - } - return $this->rollback(); - } - - // }}} - // {{{ function getNestedTransactionError() - - /** - * The first error that occured since the transaction start. - * - * @return MDB2_Error|bool MDB2 error object if an error occured or false. - * - * @access public - * @since 2.1.1 - */ - function getNestedTransactionError() - { - return $this->has_transaction_error; - } - - // }}} - // {{{ connect() - - /** - * Connect to the database - * - * @return true on success, MDB2 Error Object on failure - */ - function connect() - { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ setCharset($charset, $connection = null) - - /** - * Set the charset on the current connection - * - * @param string charset - * @param resource connection handle - * - * @return true on success, MDB2 Error Object on failure - */ - function setCharset($charset, $connection = null) - { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function disconnect($force = true) - - /** - * Log out and disconnect from the database. - * - * @param boolean $force whether the disconnect should be forced even if the - * connection is opened persistently - * - * @return mixed true on success, false if not connected and error object on error - * - * @access public - */ - function disconnect($force = true) - { - $this->connection = 0; - $this->connected_dsn = array(); - $this->connected_database_name = ''; - $this->opened_persistent = null; - $this->connected_server_info = ''; - $this->in_transaction = null; - $this->nested_transaction_counter = null; - return MDB2_OK; - } - - // }}} - // {{{ function setDatabase($name) - - /** - * Select a different database - * - * @param string name of the database that should be selected - * - * @return string name of the database previously connected to - * - * @access public - */ - function setDatabase($name) - { - $previous_database_name = (isset($this->database_name)) ? $this->database_name : ''; - $this->database_name = $name; - if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) { - $this->disconnect(false); - } - return $previous_database_name; - } - - // }}} - // {{{ function getDatabase() - - /** - * Get the current database - * - * @return string name of the database - * - * @access public - */ - function getDatabase() - { - return $this->database_name; - } - - // }}} - // {{{ function setDSN($dsn) - - /** - * set the DSN - * - * @param mixed DSN string or array - * - * @return MDB2_OK - * - * @access public - */ - function setDSN($dsn) - { - $dsn_default = $GLOBALS['_MDB2_dsninfo_default']; - $dsn = MDB2::parseDSN($dsn); - if (array_key_exists('database', $dsn)) { - $this->database_name = $dsn['database']; - unset($dsn['database']); - } - $this->dsn = array_merge($dsn_default, $dsn); - return $this->disconnect(false); - } - - // }}} - // {{{ function getDSN($type = 'string', $hidepw = false) - - /** - * return the DSN as a string - * - * @param string format to return ("array", "string") - * @param string string to hide the password with - * - * @return mixed DSN in the chosen type - * - * @access public - */ - function getDSN($type = 'string', $hidepw = false) - { - $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn); - $dsn['phptype'] = $this->phptype; - $dsn['database'] = $this->database_name; - if ($hidepw) { - $dsn['password'] = $hidepw; - } - switch ($type) { - // expand to include all possible options - case 'string': - $dsn = $dsn['phptype']. - ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : ''). - '://'.$dsn['username'].':'. - $dsn['password'].'@'.$dsn['hostspec']. - ($dsn['port'] ? (':'.$dsn['port']) : ''). - '/'.$dsn['database']; - break; - case 'array': - default: - break; - } - return $dsn; - } - - // }}} - // {{{ _isNewLinkSet() - - /** - * Check if the 'new_link' option is set - * - * @return boolean - * - * @access protected - */ - function _isNewLinkSet() - { - return (isset($this->dsn['new_link']) - && ($this->dsn['new_link'] === true - || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link'])) - || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link']) - ) - ); - } - - // }}} - // {{{ function &standaloneQuery($query, $types = null, $is_manip = false) - - /** - * execute a query as database administrator - * - * @param string the SQL query - * @param mixed array that contains the types of the columns in - * the result set - * @param bool if the query is a manipulation query - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function &standaloneQuery($query, $types = null, $is_manip = false) - { - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $query = $this->_modifyQuery($query, $is_manip, $limit, $offset); - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $result =$this->_doQuery($query, $is_manip, $connection, false); - if (PEAR::isError($result)) { - return $result; - } - - if ($is_manip) { - $affected_rows = $this->_affectedRows($connection, $result); - return $affected_rows; - } - $result =$this->_wrapResult($result, $types, true, false, $limit, $offset); - return $result; - } - - // }}} - // {{{ function _modifyQuery($query, $is_manip, $limit, $offset) - - /** - * Changes a query string for various DBMS specific reasons - * - * @param string query to modify - * @param bool if it is a DML query - * @param int limit the number of rows - * @param int start reading from given offset - * - * @return string modified query - * - * @access protected - */ - function _modifyQuery($query, $is_manip, $limit, $offset) - { - return $query; - } - - // }}} - // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null) - - /** - * Execute a query - * @param string query - * @param bool if the query is a manipulation query - * @param resource connection handle - * @param string database name - * - * @return result or error object - * - * @access protected - */ - function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null) - { - $this->last_query = $query; - $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre')); - if ($result) { - if (PEAR::isError($result)) { - return $result; - } - $query = $result; - } - $err =$this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $err; - } - - // }}} - // {{{ function _affectedRows($connection, $result = null) - - /** - * Returns the number of rows affected - * - * @param resource result handle - * @param resource connection handle - * - * @return mixed MDB2 Error Object or the number of rows affected - * - * @access private - */ - function _affectedRows($connection, $result = null) - { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function &exec($query) - - /** - * Execute a manipulation query to the database and return the number of affected rows - * - * @param string the SQL query - * - * @return mixed number of affected rows on success, a MDB2 error on failure - * - * @access public - */ - function &exec($query) - { - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $query = $this->_modifyQuery($query, true, $limit, $offset); - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $result =$this->_doQuery($query, true, $connection, $this->database_name); - if (PEAR::isError($result)) { - return $result; - } - - $affectedRows = $this->_affectedRows($connection, $result); - return $affectedRows; - } - - // }}} - // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false) - - /** - * Send a query to the database and return any results - * - * @param string the SQL query - * @param mixed array that contains the types of the columns in - * the result set - * @param mixed string which specifies which result class to use - * @param mixed string which specifies which class to wrap results in - * - * @return mixed an MDB2_Result handle on success, a MDB2 error on failure - * - * @access public - */ - function &query($query, $types = null, $result_class = true, $result_wrap_class = false) - { - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $query = $this->_modifyQuery($query, false, $limit, $offset); - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $result =$this->_doQuery($query, false, $connection, $this->database_name); - if (PEAR::isError($result)) { - return $result; - } - - $result =$this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset); - return $result; - } - - // }}} - // {{{ function &_wrapResult($result, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null) - - /** - * wrap a result set into the correct class - * - * @param resource result handle - * @param mixed array that contains the types of the columns in - * the result set - * @param mixed string which specifies which result class to use - * @param mixed string which specifies which class to wrap results in - * @param string number of rows to select - * @param string first row to select - * - * @return mixed an MDB2_Result, a MDB2 error on failure - * - * @access protected - */ - function &_wrapResult($result, $types = array(), $result_class = true, - $result_wrap_class = false, $limit = null, $offset = null) - { - if ($types === true) { - if ($this->supports('result_introspection')) { - $this->loadModule('Reverse', null, true); - $tableInfo = $this->reverse->tableInfo($result); - if (PEAR::isError($tableInfo)) { - return $tableInfo; - } - $types = array(); - foreach ($tableInfo as $field) { - $types[] = $field['mdb2type']; - } - } else { - $types = null; - } - } - - if ($result_class === true) { - $result_class = $this->options['result_buffering'] - ? $this->options['buffered_result_class'] : $this->options['result_class']; - } - - if ($result_class) { - $class_name = sprintf($result_class, $this->phptype); - if (!MDB2::classExists($class_name)) { - $err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'result class does not exist '.$class_name, __FUNCTION__); - return $err; - } - $result =new $class_name($this, $result, $limit, $offset); - if (!MDB2::isResultCommon($result)) { - $err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'result class is not extended from MDB2_Result_Common', __FUNCTION__); - return $err; - } - if (!empty($types)) { - $err = $result->setResultTypes($types); - if (PEAR::isError($err)) { - $result->free(); - return $err; - } - } - } - if ($result_wrap_class === true) { - $result_wrap_class = $this->options['result_wrap_class']; - } - if ($result_wrap_class) { - if (!MDB2::classExists($result_wrap_class)) { - $err =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'result wrap class does not exist '.$result_wrap_class, __FUNCTION__); - return $err; - } - $result = new $result_wrap_class($result, $this->fetchmode); - } - return $result; - } - - // }}} - // {{{ function getServerVersion($native = false) - - /** - * return version information about the server - * - * @param bool determines if the raw version string should be returned - * - * @return mixed array with version information or row string - * - * @access public - */ - function getServerVersion($native = false) - { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function setLimit($limit, $offset = null) - - /** - * set the range of the next query - * - * @param string number of rows to select - * @param string first row to select - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function setLimit($limit, $offset = null) - { - if (!$this->supports('limit_queries')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'limit is not supported by this driver', __FUNCTION__); - } - $limit = (int)$limit; - if ($limit < 0) { - return $this->raiseError(MDB2_ERROR_SYNTAX, null, null, - 'it was not specified a valid selected range row limit', __FUNCTION__); - } - $this->limit = $limit; - if (!is_null($offset)) { - $offset = (int)$offset; - if ($offset < 0) { - return $this->raiseError(MDB2_ERROR_SYNTAX, null, null, - 'it was not specified a valid first selected range row', __FUNCTION__); - } - $this->offset = $offset; - } - return MDB2_OK; - } - - // }}} - // {{{ function subSelect($query, $type = false) - - /** - * simple subselect emulation: leaves the query untouched for all RDBMS - * that support subselects - * - * @param string the SQL query for the subselect that may only - * return a column - * @param string determines type of the field - * - * @return string the query - * - * @access public - */ - function subSelect($query, $type = false) - { - if ($this->supports('sub_selects') === true) { - return $query; - } - - if (!$this->supports('sub_selects')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - $col = $this->queryCol($query, $type); - if (PEAR::isError($col)) { - return $col; - } - if (!is_array($col) || count($col) == 0) { - return 'NULL'; - } - if ($type) { - $this->loadModule('Datatype', null, true); - return $this->datatype->implodeArray($col, $type); - } - return implode(', ', $col); - } - - // }}} - // {{{ function replace($table, $fields) - - /** - * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT - * query, except that if there is already a row in the table with the same - * key field values, the old row is deleted before the new row is inserted. - * - * The REPLACE type of query does not make part of the SQL standards. Since - * practically only MySQL and SQLite implement it natively, this type of - * query isemulated through this method for other DBMS using standard types - * of queries inside a transaction to assure the atomicity of the operation. - * - * @param string name of the table on which the REPLACE query will - * be executed. - * @param array associative array that describes the fields and the - * values that will be inserted or updated in the specified table. The - * indexes of the array are the names of all the fields of the table. - * The values of the array are also associative arrays that describe - * the values and other properties of the table fields. - * - * Here follows a list of field properties that need to be specified: - * - * value - * Value to be assigned to the specified field. This value may be - * of specified in database independent type format as this - * function can perform the necessary datatype conversions. - * - * Default: this property is required unless the Null property is - * set to 1. - * - * type - * Name of the type of the field. Currently, all types MDB2 - * are supported except for clob and blob. - * - * Default: no type conversion - * - * null - * bool property that indicates that the value for this field - * should be set to null. - * - * The default value for fields missing in INSERT queries may be - * specified the definition of a table. Often, the default value - * is already null, but since the REPLACE may be emulated using - * an UPDATE query, make sure that all fields of the table are - * listed in this function argument array. - * - * Default: 0 - * - * key - * bool property that indicates that this field should be - * handled as a primary key or at least as part of the compound - * unique index of the table that will determine the row that will - * updated if it exists or inserted a new row otherwise. - * - * This function will fail if no key field is specified or if the - * value of a key field is set to null because fields that are - * part of unique index they may not be null. - * - * Default: 0 - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function replace($table, $fields) - { - if (!$this->supports('replace')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'replace query is not supported', __FUNCTION__); - } - $count = count($fields); - $condition = $values = array(); - for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) { - $name = key($fields); - if (isset($fields[$name]['null']) && $fields[$name]['null']) { - $value = 'NULL'; - } else { - $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null; - $value = $this->quote($fields[$name]['value'], $type); - } - $values[$name] = $value; - if (isset($fields[$name]['key']) && $fields[$name]['key']) { - if ($value === 'NULL') { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'key value '.$name.' may not be NULL', __FUNCTION__); - } - $condition[] = $this->quoteIdentifier($name, true) . '=' . $value; - } - } - if (empty($condition)) { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'not specified which fields are keys', __FUNCTION__); - } - - $result = null; - $in_transaction = $this->in_transaction; - if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) { - return $result; - } - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $condition = ' WHERE '.implode(' AND ', $condition); - $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition; - $result =$this->_doQuery($query, true, $connection); - if (!PEAR::isError($result)) { - $affected_rows = $this->_affectedRows($connection, $result); - $insert = ''; - foreach ($values as $key => $value) { - $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true); - } - $values = implode(', ', $values); - $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)"; - $result =$this->_doQuery($query, true, $connection); - if (!PEAR::isError($result)) { - $affected_rows += $this->_affectedRows($connection, $result);; - } - } - - if (!$in_transaction) { - if (PEAR::isError($result)) { - $this->rollback(); - } else { - $result = $this->commit(); - } - } - - if (PEAR::isError($result)) { - return $result; - } - - return $affected_rows; - } - - // }}} - // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array()) - - /** - * Prepares a query for multiple execution with execute(). - * With some database backends, this is emulated. - * prepare() requires a generic query as string like - * 'INSERT INTO numbers VALUES(?,?)' or - * 'INSERT INTO numbers VALUES(:foo,:bar)'. - * The ? and :name and are placeholders which can be set using - * bindParam() and the query can be sent off using the execute() method. - * The allowed format for :name can be set with the 'bindname_format' option. - * - * @param string the query to prepare - * @param mixed array that contains the types of the placeholders - * @param mixed array that contains the types of the columns in - * the result set or MDB2_PREPARE_RESULT, if set to - * MDB2_PREPARE_MANIP the query is handled as a manipulation query - * @param mixed key (field) value (parameter) pair for all lob placeholders - * - * @return mixed resource handle for the prepared query on success, - * a MDB2 error on failure - * - * @access public - * @see bindParam, execute - */ - function &prepare($query, $types = null, $result_types = null, $lobs = array()) - { - $is_manip = ($result_types === MDB2_PREPARE_MANIP); - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre')); - if ($result) { - if (PEAR::isError($result)) { - return $result; - } - $query = $result; - } - $placeholder_type_guess = $placeholder_type = null; - $question = '?'; - $colon = ':'; - $positions = array(); - $position = 0; - while ($position < strlen($query)) { - $q_position = strpos($query, $question, $position); - $c_position = strpos($query, $colon, $position); - if ($q_position && $c_position) { - $p_position = min($q_position, $c_position); - } elseif ($q_position) { - $p_position = $q_position; - } elseif ($c_position) { - $p_position = $c_position; - } else { - break; - } - if (is_null($placeholder_type)) { - $placeholder_type_guess = $query[$p_position]; - } - - $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position); - if (PEAR::isError($new_pos)) { - return $new_pos; - } - if ($new_pos != $position) { - $position = $new_pos; - continue; //evaluate again starting from the new position - } - - if ($query[$position] == $placeholder_type_guess) { - if (is_null($placeholder_type)) { - $placeholder_type = $query[$p_position]; - $question = $colon = $placeholder_type; - if (!empty($types) && is_array($types)) { - if ($placeholder_type == ':') { - if (is_int(key($types))) { - $types_tmp = $types; - $types = array(); - $count = -1; - } - } else { - $types = array_values($types); - } - } - } - if ($placeholder_type == ':') { - $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s'; - $parameter = preg_replace($regexp, '\\1', $query); - if ($parameter === '') { - $err =$this->raiseError(MDB2_ERROR_SYNTAX, null, null, - 'named parameter name must match "bindname_format" option', __FUNCTION__); - return $err; - } - $positions[$p_position] = $parameter; - $query = substr_replace($query, '?', $position, strlen($parameter)+1); - // use parameter name in type array - if (isset($count) && isset($types_tmp[++$count])) { - $types[$parameter] = $types_tmp[$count]; - } - } else { - $positions[$p_position] = count($positions); - } - $position = $p_position + 1; - } else { - $position = $p_position; - } - } - $class_name = 'MDB2_Statement_'.$this->phptype; - $statement = null; - $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset); - $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj)); - return $obj; - } - - // }}} - // {{{ function _skipDelimitedStrings($query, $position, $p_position) - - /** - * Utility method, used by prepare() to avoid replacing placeholders within delimited strings. - * Check if the placeholder is contained within a delimited string. - * If so, skip it and advance the position, otherwise return the current position, - * which is valid - * - * @param string $query - * @param integer $position current string cursor position - * @param integer $p_position placeholder position - * - * @return mixed integer $new_position on success - * MDB2_Error on failure - * - * @access protected - */ - function _skipDelimitedStrings($query, $position, $p_position) - { - $ignores = $this->string_quoting; - $ignores[] = $this->identifier_quoting; - $ignores = array_merge($ignores, $this->sql_comments); - - foreach ($ignores as $ignore) { - if (!empty($ignore['start'])) { - if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) { - $end_quote = $start_quote; - do { - if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) { - if ($ignore['end'] === "\n") { - $end_quote = strlen($query) - 1; - } else { - $err =$this->raiseError(MDB2_ERROR_SYNTAX, null, null, - 'query with an unterminated text string specified', __FUNCTION__); - return $err; - } - } - } while ($ignore['escape'] - && $end_quote-1 != $start_quote - && $query[($end_quote - 1)] == $ignore['escape'] - && ( $ignore['escape_pattern'] !== $ignore['escape'] - || $query[($end_quote - 2)] != $ignore['escape']) - ); - - $position = $end_quote + 1; - return $position; - } - } - } - return $position; - } - - // }}} - // {{{ function quote($value, $type = null, $quote = true) - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string text string value that is intended to be converted. - * @param string type to which the value should be converted to - * @param bool quote - * @param bool escape wildcards - * - * @return string text string that represents the given argument value in - * a DBMS specific format. - * - * @access public - */ - function quote($value, $type = null, $quote = true, $escape_wildcards = false) - { - $result = $this->loadModule('Datatype', null, true); - if (PEAR::isError($result)) { - return $result; - } - - return $this->datatype->quote($value, $type, $quote, $escape_wildcards); - } - - // }}} - // {{{ function getDeclaration($type, $name, $field) - - /** - * Obtain DBMS specific SQL code portion needed to declare - * of the given type - * - * @param string type to which the value should be converted to - * @param string name the field to be declared. - * @param string definition of the field - * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * - * @access public - */ - function getDeclaration($type, $name, $field) - { - $result = $this->loadModule('Datatype', null, true); - if (PEAR::isError($result)) { - return $result; - } - return $this->datatype->getDeclaration($type, $name, $field); - } - - // }}} - // {{{ function compareDefinition($current, $previous) - - /** - * Obtain an array of changes that may need to applied - * - * @param array new definition - * @param array old definition - * - * @return array containing all changes that will need to be applied - * - * @access public - */ - function compareDefinition($current, $previous) - { - $result = $this->loadModule('Datatype', null, true); - if (PEAR::isError($result)) { - return $result; - } - return $this->datatype->compareDefinition($current, $previous); - } - - // }}} - // {{{ function supports($feature) - - /** - * Tell whether a DB implementation or its backend extension - * supports a given feature. - * - * @param string name of the feature (see the MDB2 class doc) - * - * @return bool|string if this DB implementation supports a given feature - * false means no, true means native, - * 'emulated' means emulated - * - * @access public - */ - function supports($feature) - { - if (array_key_exists($feature, $this->supported)) { - return $this->supported[$feature]; - } - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - "unknown support feature $feature", __FUNCTION__); - } - - // }}} - // {{{ function getSequenceName($sqn) - - /** - * adds sequence name formatting to a sequence name - * - * @param string name of the sequence - * - * @return string formatted sequence name - * - * @access public - */ - function getSequenceName($sqn) - { - return sprintf($this->options['seqname_format'], - preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn)); - } - - // }}} - // {{{ function getIndexName($idx) - - /** - * adds index name formatting to a index name - * - * @param string name of the index - * - * @return string formatted index name - * - * @access public - */ - function getIndexName($idx) - { - return sprintf($this->options['idxname_format'], - preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx)); - } - - // }}} - // {{{ function nextID($seq_name, $ondemand = true) - - /** - * Returns the next free id of a sequence - * - * @param string name of the sequence - * @param bool when true missing sequences are automatic created - * - * @return mixed MDB2 Error Object or id - * - * @access public - */ - function nextID($seq_name, $ondemand = true) - { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function lastInsertID($table = null, $field = null) - - /** - * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) - * - * @param string name of the table into which a new row was inserted - * @param string name of the field into which a new row was inserted - * - * @return mixed MDB2 Error Object or id - * - * @access public - */ - function lastInsertID($table = null, $field = null) - { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function currID($seq_name) - - /** - * Returns the current id of a sequence - * - * @param string name of the sequence - * - * @return mixed MDB2 Error Object or id - * - * @access public - */ - function currID($seq_name) - { - $this->warnings[] = 'database does not support getting current - sequence value, the sequence value was incremented'; - return $this->nextID($seq_name); - } - - // }}} - // {{{ function queryOne($query, $type = null, $colnum = 0) - - /** - * Execute the specified query, fetch the value from the first column of - * the first row of the result set and then frees - * the result set. - * - * @param string $query the SELECT query statement to be executed. - * @param string $type optional argument that specifies the expected - * datatype of the result set field, so that an eventual - * conversion may be performed. The default datatype is - * text, meaning that no conversion is performed - * @param mixed $colnum the column number (or name) to fetch - * - * @return mixed MDB2_OK or field value on success, a MDB2 error on failure - * - * @access public - */ - function queryOne($query, $type = null, $colnum = 0) - { - $result = $this->query($query, $type); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $one = $result->fetchOne($colnum); - $result->free(); - return $one; - } - - // }}} - // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT) - - /** - * Execute the specified query, fetch the values from the first - * row of the result set into an array and then frees - * the result set. - * - * @param string the SELECT query statement to be executed. - * @param array optional array argument that specifies a list of - * expected datatypes of the result set columns, so that the eventual - * conversions may be performed. The default list of datatypes is - * empty, meaning that no conversion is performed. - * @param int how the array data should be indexed - * - * @return mixed MDB2_OK or data array on success, a MDB2 error on failure - * - * @access public - */ - function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT) - { - $result = $this->query($query, $types); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $row = $result->fetchRow($fetchmode); - $result->free(); - return $row; - } - - // }}} - // {{{ function queryCol($query, $type = null, $colnum = 0) - - /** - * Execute the specified query, fetch the value from the first column of - * each row of the result set into an array and then frees the result set. - * - * @param string $query the SELECT query statement to be executed. - * @param string $type optional argument that specifies the expected - * datatype of the result set field, so that an eventual - * conversion may be performed. The default datatype is text, - * meaning that no conversion is performed - * @param mixed $colnum the column number (or name) to fetch - * - * @return mixed MDB2_OK or data array on success, a MDB2 error on failure - * @access public - */ - function queryCol($query, $type = null, $colnum = 0) - { - $result = $this->query($query, $type); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $col = $result->fetchCol($colnum); - $result->free(); - return $col; - } - - // }}} - // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false) - - /** - * Execute the specified query, fetch all the rows of the result set into - * a two dimensional array and then frees the result set. - * - * @param string the SELECT query statement to be executed. - * @param array optional array argument that specifies a list of - * expected datatypes of the result set columns, so that the eventual - * conversions may be performed. The default list of datatypes is - * empty, meaning that no conversion is performed. - * @param int how the array data should be indexed - * @param bool if set to true, the $all will have the first - * column as its first dimension - * @param bool used only when the query returns exactly - * two columns. If true, the values of the returned array will be - * one-element arrays instead of scalars. - * @param bool if true, the values of the returned array is - * wrapped in another array. If the same key value (in the first - * column) repeats itself, the values will be appended to this array - * instead of overwriting the existing values. - * - * @return mixed MDB2_OK or data array on success, a MDB2 error on failure - * - * @access public - */ - function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, - $rekey = false, $force_array = false, $group = false) - { - $result = $this->query($query, $types); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group); - $result->free(); - return $all; - } - - // }}} -} - -// }}} -// {{{ class MDB2_Result - -/** - * The dummy class that all user space result classes should extend from - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Result -{ -} - -// }}} -// {{{ class MDB2_Result_Common extends MDB2_Result - -/** - * The common result class for MDB2 result objects - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Result_Common extends MDB2_Result -{ - // {{{ Variables (Properties) - - var $db; - var $result; - var $rownum = -1; - var $types = array(); - var $values = array(); - var $offset; - var $offset_count = 0; - var $limit; - var $column_names; - - // }}} - // {{{ constructor: function __construct(&$db, &$result, $limit = 0, $offset = 0) - - /** - * Constructor - */ - function __construct(&$db, &$result, $limit = 0, $offset = 0) - { - $this->db =$db; - $this->result =$result; - $this->offset = $offset; - $this->limit = max(0, $limit - 1); - } - - - // }}} - // {{{ function setResultTypes($types) - - /** - * Define the list of types to be associated with the columns of a given - * result set. - * - * This function may be called before invoking fetchRow(), fetchOne(), - * fetchCol() and fetchAll() so that the necessary data type - * conversions are performed on the data to be retrieved by them. If this - * function is not called, the type of all result set columns is assumed - * to be text, thus leading to not perform any conversions. - * - * @param array variable that lists the - * data types to be expected in the result set columns. If this array - * contains less types than the number of columns that are returned - * in the result set, the remaining columns are assumed to be of the - * type text. Currently, the types clob and blob are not fully - * supported. - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function setResultTypes($types) - { - $load = $this->db->loadModule('Datatype', null, true); - if (PEAR::isError($load)) { - return $load; - } - $types = $this->db->datatype->checkResultTypes($types); - if (PEAR::isError($types)) { - return $types; - } - $this->types = $types; - return MDB2_OK; - } - - // }}} - // {{{ function seek($rownum = 0) - - /** - * Seek to a specific row in a result set - * - * @param int number of the row where the data can be found - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function seek($rownum = 0) - { - $target_rownum = $rownum - 1; - if ($this->rownum > $target_rownum) { - return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'seeking to previous rows not implemented', __FUNCTION__); - } - while ($this->rownum < $target_rownum) { - $this->fetchRow(); - } - return MDB2_OK; - } - - // }}} - // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null) - - /** - * Fetch and return a row of data - * - * @param int how the array data should be indexed - * @param int number of the row where the data can be found - * - * @return int data array on success, a MDB2 error on failure - * - * @access public - */ - function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null) - { - $err =$this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $err; - } - - // }}} - // {{{ function fetchOne($colnum = 0) - - /** - * fetch single column from the next row from a result set - * - * @param int|string the column number (or name) to fetch - * @param int number of the row where the data can be found - * - * @return string data on success, a MDB2 error on failure - * @access public - */ - function fetchOne($colnum = 0, $rownum = null) - { - $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC; - $row = $this->fetchRow($fetchmode, $rownum); - if (!is_array($row) || PEAR::isError($row)) { - return $row; - } - if (!array_key_exists($colnum, $row)) { - return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null, - 'column is not defined in the result set: '.$colnum, __FUNCTION__); - } - return $row[$colnum]; - } - - // }}} - // {{{ function fetchCol($colnum = 0) - - /** - * Fetch and return a column from the current row pointer position - * - * @param int|string the column number (or name) to fetch - * - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function fetchCol($colnum = 0) - { - $column = array(); - $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC; - $row = $this->fetchRow($fetchmode); - if (is_array($row)) { - if (!array_key_exists($colnum, $row)) { - return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null, - 'column is not defined in the result set: '.$colnum, __FUNCTION__); - } - do { - $column[] = $row[$colnum]; - } while (is_array($row = $this->fetchRow($fetchmode))); - } - if (PEAR::isError($row)) { - return $row; - } - return $column; - } - - // }}} - // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false) - - /** - * Fetch and return all rows from the current row pointer position - * - * @param int $fetchmode the fetch mode to use: - * + MDB2_FETCHMODE_ORDERED - * + MDB2_FETCHMODE_ASSOC - * + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED - * + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED - * @param bool if set to true, the $all will have the first - * column as its first dimension - * @param bool used only when the query returns exactly - * two columns. If true, the values of the returned array will be - * one-element arrays instead of scalars. - * @param bool if true, the values of the returned array is - * wrapped in another array. If the same key value (in the first - * column) repeats itself, the values will be appended to this array - * instead of overwriting the existing values. - * - * @return mixed data array on success, a MDB2 error on failure - * - * @access public - * @see getAssoc() - */ - function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, - $force_array = false, $group = false) - { - $all = array(); - $row = $this->fetchRow($fetchmode); - if (PEAR::isError($row)) { - return $row; - } elseif (!$row) { - return $all; - } - - $shift_array = $rekey ? false : null; - if (!is_null($shift_array)) { - if (is_object($row)) { - $colnum = count(get_object_vars($row)); - } else { - $colnum = count($row); - } - if ($colnum < 2) { - return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null, - 'rekey feature requires atleast 2 column', __FUNCTION__); - } - $shift_array = (!$force_array && $colnum == 2); - } - - if ($rekey) { - do { - if (is_object($row)) { - $arr = get_object_vars($row); - $key = reset($arr); - unset($row->{$key}); - } else { - if ($fetchmode & MDB2_FETCHMODE_ASSOC) { - $key = reset($row); - unset($row[key($row)]); - } else { - $key = array_shift($row); - } - if ($shift_array) { - $row = array_shift($row); - } - } - if ($group) { - $all[$key][] = $row; - } else { - $all[$key] = $row; - } - } while (($row = $this->fetchRow($fetchmode))); - } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) { - do { - foreach ($row as $key => $val) { - $all[$key][] = $val; - } - } while (($row = $this->fetchRow($fetchmode))); - } else { - do { - $all[] = $row; - } while (($row = $this->fetchRow($fetchmode))); - } - - return $all; - } - - // }}} - // {{{ function rowCount() - /** - * Returns the actual row number that was last fetched (count from 0) - * @return int - * - * @access public - */ - function rowCount() - { - return $this->rownum + 1; - } - - // }}} - // {{{ function numRows() - - /** - * Returns the number of rows in a result object - * - * @return mixed MDB2 Error Object or the number of rows - * - * @access public - */ - function numRows() - { - return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function nextResult() - - /** - * Move the internal result pointer to the next available result - * - * @return true on success, false if there is no more result set or an error object on failure - * - * @access public - */ - function nextResult() - { - return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function getColumnNames() - - /** - * Retrieve the names of columns returned by the DBMS in a query result or - * from the cache. - * - * @param bool If set to true the values are the column names, - * otherwise the names of the columns are the keys. - * @return mixed Array variable that holds the names of columns or an - * MDB2 error on failure. - * Some DBMS may not return any columns when the result set - * does not contain any rows. - * - * @access public - */ - function getColumnNames($flip = false) - { - if (!isset($this->column_names)) { - $result = $this->_getColumnNames(); - if (PEAR::isError($result)) { - return $result; - } - $this->column_names = $result; - } - if ($flip) { - return array_flip($this->column_names); - } - return $this->column_names; - } - - // }}} - // {{{ function _getColumnNames() - - /** - * Retrieve the names of columns returned by the DBMS in a query result. - * - * @return mixed Array variable that holds the names of columns as keys - * or an MDB2 error on failure. - * Some DBMS may not return any columns when the result set - * does not contain any rows. - * - * @access private - */ - function _getColumnNames() - { - return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function numCols() - - /** - * Count the number of columns returned by the DBMS in a query result. - * - * @return mixed integer value with the number of columns, a MDB2 error - * on failure - * - * @access public - */ - function numCols() - { - return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ function getResource() - - /** - * return the resource associated with the result object - * - * @return resource - * - * @access public - */ - function getResource() - { - return $this->result; - } - - // }}} - // {{{ function bindColumn($column, &$value, $type = null) - - /** - * Set bind variable to a column. - * - * @param int column number or name - * @param mixed variable reference - * @param string specifies the type of the field - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function bindColumn($column, &$value, $type = null) - { - if (!is_numeric($column)) { - $column_names = $this->getColumnNames(); - if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($this->db->options['field_case'] == CASE_LOWER) { - $column = strtolower($column); - } else { - $column = strtoupper($column); - } - } - $column = $column_names[$column]; - } - $this->values[$column] =$value; - if (!is_null($type)) { - $this->types[$column] = $type; - } - return MDB2_OK; - } - - // }}} - // {{{ function _assignBindColumns($row) - - /** - * Bind a variable to a value in the result row. - * - * @param array row data - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access private - */ - function _assignBindColumns($row) - { - $row = array_values($row); - foreach ($row as $column => $value) { - if (array_key_exists($column, $this->values)) { - $this->values[$column] = $value; - } - } - return MDB2_OK; - } - - // }}} - // {{{ function free() - - /** - * Free the internal resources associated with result. - * - * @return bool true on success, false if result is invalid - * - * @access public - */ - function free() - { - $this->result = false; - return MDB2_OK; - } - - // }}} -} - -// }}} -// {{{ class MDB2_Row - -/** - * The simple class that accepts row data as an array - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Row -{ - // {{{ constructor: function __construct(&$row) - - /** - * constructor - * - * @param resource row data as array - */ - function __construct(&$row) - { - foreach ($row as $key => $value) { - $this->$key = &$row[$key]; - } - } -} - -// }}} -// {{{ class MDB2_Statement_Common - -/** - * The common statement class for MDB2 statement objects - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Statement_Common -{ - // {{{ Variables (Properties) - - var $db; - var $statement; - var $query; - var $result_types; - var $types; - var $values = array(); - var $limit; - var $offset; - var $is_manip; - - // }}} - // {{{ constructor: function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null) - - /** - * Constructor - */ - function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null) - { - $this->db =$db; - $this->statement =$statement; - $this->positions = $positions; - $this->query = $query; - $this->types = (array)$types; - $this->result_types = (array)$result_types; - $this->limit = $limit; - $this->is_manip = $is_manip; - $this->offset = $offset; - } - - - // }}} - // {{{ function bindValue($parameter, &$value, $type = null) - - /** - * Set the value of a parameter of a prepared query. - * - * @param int the order number of the parameter in the query - * statement. The order number of the first parameter is 1. - * @param mixed value that is meant to be assigned to specified - * parameter. The type of the value depends on the $type argument. - * @param string specifies the type of the field - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function bindValue($parameter, $value, $type = null) - { - if (!is_numeric($parameter)) { - $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter); - } - if (!in_array($parameter, $this->positions)) { - return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__); - } - $this->values[$parameter] = $value; - if (!is_null($type)) { - $this->types[$parameter] = $type; - } - return MDB2_OK; - } - - // }}} - // {{{ function bindValueArray($values, $types = null) - - /** - * Set the values of multiple a parameter of a prepared query in bulk. - * - * @param array specifies all necessary information - * for bindValue() the array elements must use keys corresponding to - * the number of the position of the parameter. - * @param array specifies the types of the fields - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - * @see bindParam() - */ - function bindValueArray($values, $types = null) - { - $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null); - $parameters = array_keys($values); - foreach ($parameters as $key => $parameter) { - $this->db->pushErrorHandling(PEAR_ERROR_RETURN); - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - $err = $this->bindValue($parameter, $values[$parameter], $types[$key]); - $this->db->popExpect(); - $this->db->popErrorHandling(); - if (PEAR::isError($err)) { - if ($err->getCode() == MDB2_ERROR_NOT_FOUND) { - //ignore (extra value for missing placeholder) - continue; - } - return $err; - } - } - return MDB2_OK; - } - - // }}} - // {{{ function bindParam($parameter, &$value, $type = null) - - /** - * Bind a variable to a parameter of a prepared query. - * - * @param int the order number of the parameter in the query - * statement. The order number of the first parameter is 1. - * @param mixed variable that is meant to be bound to specified - * parameter. The type of the value depends on the $type argument. - * @param string specifies the type of the field - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function bindParam($parameter, &$value, $type = null) - { - if (!is_numeric($parameter)) { - $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter); - } - if (!in_array($parameter, $this->positions)) { - return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__); - } - $this->values[$parameter] =$value; - if (!is_null($type)) { - $this->types[$parameter] = $type; - } - return MDB2_OK; - } - - // }}} - // {{{ function bindParamArray(&$values, $types = null) - - /** - * Bind the variables of multiple a parameter of a prepared query in bulk. - * - * @param array specifies all necessary information - * for bindParam() the array elements must use keys corresponding to - * the number of the position of the parameter. - * @param array specifies the types of the fields - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - * @see bindParam() - */ - function bindParamArray(&$values, $types = null) - { - $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null); - $parameters = array_keys($values); - foreach ($parameters as $key => $parameter) { - $err = $this->bindParam($parameter, $values[$parameter], $types[$key]); - if (PEAR::isError($err)) { - return $err; - } - } - return MDB2_OK; - } - - // }}} - // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false) - - /** - * Execute a prepared query statement. - * - * @param array specifies all necessary information - * for bindParam() the array elements must use keys corresponding - * to the number of the position of the parameter. - * @param mixed specifies which result class to use - * @param mixed specifies which class to wrap results in - * - * @return mixed MDB2_Result or integer (affected rows) on success, - * a MDB2 error on failure - * @access public - */ - function &execute($values = null, $result_class = true, $result_wrap_class = false) - { - if (is_null($this->positions)) { - return $this->db->raiseError(MDB2_ERROR, null, null, - 'Prepared statement has already been freed', __FUNCTION__); - } - - $values = (array)$values; - if (!empty($values)) { - $err = $this->bindValueArray($values); - if (PEAR::isError($err)) { - return $this->db->raiseError(MDB2_ERROR, null, null, - 'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__); - } - } - $result =$this->_execute($result_class, $result_wrap_class); - return $result; - } - - // }}} - // {{{ function &_execute($result_class = true, $result_wrap_class = false) - - /** - * Execute a prepared query statement helper method. - * - * @param mixed specifies which result class to use - * @param mixed specifies which class to wrap results in - * - * @return mixed MDB2_Result or integer (affected rows) on success, - * a MDB2 error on failure - * @access private - */ - function &_execute($result_class = true, $result_wrap_class = false) - { - $this->last_query = $this->query; - $query = ''; - $last_position = 0; - foreach ($this->positions as $current_position => $parameter) { - if (!array_key_exists($parameter, $this->values)) { - return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__); - } - $value = $this->values[$parameter]; - $query.= substr($this->query, $last_position, $current_position - $last_position); - if (!isset($value)) { - $value_quoted = 'NULL'; - } else { - $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null; - $value_quoted = $this->db->quote($value, $type); - if (PEAR::isError($value_quoted)) { - return $value_quoted; - } - } - $query.= $value_quoted; - $last_position = $current_position + 1; - } - $query.= substr($this->query, $last_position); - - $this->db->offset = $this->offset; - $this->db->limit = $this->limit; - if ($this->is_manip) { - $result = $this->db->exec($query); - } else { - $result =$this->db->query($query, $this->result_types, $result_class, $result_wrap_class); - } - return $result; - } - - // }}} - // {{{ function free() - - /** - * Release resources allocated for the specified prepared query. - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function free() - { - if (is_null($this->positions)) { - return $this->db->raiseError(MDB2_ERROR, null, null, - 'Prepared statement has already been freed', __FUNCTION__); - } - - $this->statement = null; - $this->positions = null; - $this->query = null; - $this->types = null; - $this->result_types = null; - $this->limit = null; - $this->is_manip = null; - $this->offset = null; - $this->values = null; - - return MDB2_OK; - } - - // }}} -} - -// }}} -// {{{ class MDB2_Module_Common - -/** - * The common modules class for MDB2 module objects - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Module_Common -{ - // {{{ Variables (Properties) - - /** - * contains the key to the global MDB2 instance array of the associated - * MDB2 instance - * - * @var int - * @access protected - */ - var $db_index; - - // }}} - // {{{ constructor: function __construct($db_index) - - /** - * Constructor - */ - function __construct($db_index) - { - $this->db_index = $db_index; - } - - // }}} - // {{{ function &getDBInstance() - - /** - * Get the instance of MDB2 associated with the module instance - * - * @return object MDB2 instance or a MDB2 error on failure - * - * @access public - */ - function getDBInstance() - { - if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) { - $result =$GLOBALS['_MDB2_databases'][$this->db_index]; - } else { - $result =$this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'could not find MDB2 instance'); - } - return $result; - } - - // }}} -} - -// }}} -// {{{ function MDB2_closeOpenTransactions() - -/** - * Close any open transactions form persistent connections - * - * @return void - * - * @access public - */ - -function MDB2_closeOpenTransactions() -{ - reset($GLOBALS['_MDB2_databases']); - while (next($GLOBALS['_MDB2_databases'])) { - $key = key($GLOBALS['_MDB2_databases']); - if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent - && $GLOBALS['_MDB2_databases'][$key]->in_transaction - ) { - $GLOBALS['_MDB2_databases'][$key]->rollback(); - } - } -} - -// }}} -// {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null) - -/** - * default debug output handler - * - * @param object reference to an MDB2 database object - * @param string usually the method name that triggered the debug call: - * for example 'query', 'prepare', 'execute', 'parameters', - * 'beginTransaction', 'commit', 'rollback' - * @param string message that should be appended to the debug variable - * @param array contains context information about the debug() call - * common keys are: is_manip, time, result etc. - * - * @return void|string optionally return a modified message, this allows - * rewriting a query before being issued or prepared - * - * @access public - */ -function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array()) -{ - $db->debug_output.= $scope.'('.$db->db_index.'): '; - $db->debug_output.= $message.$db->getOption('log_line_break'); - return $message; -} - -// }}} -?> diff --git a/3rdparty/MDB2/Date.php b/3rdparty/MDB2/Date.php deleted file mode 100644 index ce846543a5..0000000000 --- a/3rdparty/MDB2/Date.php +++ /dev/null @@ -1,183 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Date.php,v 1.10 2006/03/01 12:15:32 lsmith Exp $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * Several methods to convert the MDB2 native timestamp format (ISO based) - * to and from data structures that are convenient to worth with in side of php. - * For more complex date arithmetic please take a look at the Date package in PEAR - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Date -{ - // {{{ mdbNow() - - /** - * return the current datetime - * - * @return string current datetime in the MDB2 format - * @access public - */ - function mdbNow() - { - return date('Y-m-d H:i:s'); - } - // }}} - - // {{{ mdbToday() - - /** - * return the current date - * - * @return string current date in the MDB2 format - * @access public - */ - function mdbToday() - { - return date('Y-m-d'); - } - // }}} - - // {{{ mdbTime() - - /** - * return the current time - * - * @return string current time in the MDB2 format - * @access public - */ - function mdbTime() - { - return date('H:i:s'); - } - // }}} - - // {{{ date2Mdbstamp() - - /** - * convert a date into a MDB2 timestamp - * - * @param int hour of the date - * @param int minute of the date - * @param int second of the date - * @param int month of the date - * @param int day of the date - * @param int year of the date - * - * @return string a valid MDB2 timestamp - * @access public - */ - function date2Mdbstamp($hour = null, $minute = null, $second = null, - $month = null, $day = null, $year = null) - { - return MDB2_Date::unix2Mdbstamp(mktime($hour, $minute, $second, $month, $day, $year, -1)); - } - // }}} - - // {{{ unix2Mdbstamp() - - /** - * convert a unix timestamp into a MDB2 timestamp - * - * @param int a valid unix timestamp - * - * @return string a valid MDB2 timestamp - * @access public - */ - function unix2Mdbstamp($unix_timestamp) - { - return date('Y-m-d H:i:s', $unix_timestamp); - } - // }}} - - // {{{ mdbstamp2Unix() - - /** - * convert a MDB2 timestamp into a unix timestamp - * - * @param int a valid MDB2 timestamp - * @return string unix timestamp with the time stored in the MDB2 format - * - * @access public - */ - function mdbstamp2Unix($mdb_timestamp) - { - $arr = MDB2_Date::mdbstamp2Date($mdb_timestamp); - - return mktime($arr['hour'], $arr['minute'], $arr['second'], $arr['month'], $arr['day'], $arr['year'], -1); - } - // }}} - - // {{{ mdbstamp2Date() - - /** - * convert a MDB2 timestamp into an array containing all - * values necessary to pass to php's date() function - * - * @param int a valid MDB2 timestamp - * - * @return array with the time split - * @access public - */ - function mdbstamp2Date($mdb_timestamp) - { - list($arr['year'], $arr['month'], $arr['day'], $arr['hour'], $arr['minute'], $arr['second']) = - sscanf($mdb_timestamp, "%04u-%02u-%02u %02u:%02u:%02u"); - return $arr; - } - // }}} -} - -?> diff --git a/3rdparty/MDB2/Driver/Datatype/Common.php b/3rdparty/MDB2/Driver/Datatype/Common.php deleted file mode 100644 index 85a74f64fc..0000000000 --- a/3rdparty/MDB2/Driver/Datatype/Common.php +++ /dev/null @@ -1,1824 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.139 2008/12/04 11:50:42 afz Exp $ - -require_once('MDB2/LOB.php'); - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * MDB2_Driver_Common: Base class that is extended by each MDB2 driver - * - * To load this module in the MDB2 object: - * $mdb->loadModule('Datatype'); - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Datatype_Common extends MDB2_Module_Common -{ - var $valid_default_values = array( - 'text' => '', - 'boolean' => true, - 'integer' => 0, - 'decimal' => 0.0, - 'float' => 0.0, - 'timestamp' => '1970-01-01 00:00:00', - 'time' => '00:00:00', - 'date' => '1970-01-01', - 'clob' => '', - 'blob' => '', - ); - - /** - * contains all LOB objects created with this MDB2 instance - * @var array - * @access protected - */ - var $lobs = array(); - - // }}} - // {{{ getValidTypes() - - /** - * Get the list of valid types - * - * This function returns an array of valid types as keys with the values - * being possible default values for all native datatypes and mapped types - * for custom datatypes. - * - * @return mixed array on success, a MDB2 error on failure - * @access public - */ - function getValidTypes() - { - $types = $this->valid_default_values; - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if (!empty($db->options['datatype_map'])) { - foreach ($db->options['datatype_map'] as $type => $mapped_type) { - if (array_key_exists($mapped_type, $types)) { - $types[$type] = $types[$mapped_type]; - } elseif (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type, 'mapped_type' => $mapped_type); - $default = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter)); - $types[$type] = $default; - } - } - } - return $types; - } - - // }}} - // {{{ checkResultTypes() - - /** - * Define the list of types to be associated with the columns of a given - * result set. - * - * This function may be called before invoking fetchRow(), fetchOne() - * fetchCole() and fetchAll() so that the necessary data type - * conversions are performed on the data to be retrieved by them. If this - * function is not called, the type of all result set columns is assumed - * to be text, thus leading to not perform any conversions. - * - * @param array $types array variable that lists the - * data types to be expected in the result set columns. If this array - * contains less types than the number of columns that are returned - * in the result set, the remaining columns are assumed to be of the - * type text. Currently, the types clob and blob are not fully - * supported. - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function checkResultTypes($types) - { - $types = is_array($types) ? $types : array($types); - foreach ($types as $key => $type) { - if (!isset($this->valid_default_values[$type])) { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if (empty($db->options['datatype_map'][$type])) { - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - $type.' for '.$key.' is not a supported column type', __FUNCTION__); - } - } - } - return $types; - } - - // }}} - // {{{ _baseConvertResult() - - /** - * General type conversion method - * - * @param mixed $value reference to a value to be converted - * @param string $type specifies which type to convert to - * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text - * @return object an MDB2 error on failure - * @access protected - */ - function _baseConvertResult($value, $type, $rtrim = true) - { - switch ($type) { - case 'text': - if ($rtrim) { - $value = rtrim($value); - } - return $value; - case 'integer': - return intval($value); - case 'boolean': - return !empty($value); - case 'decimal': - return $value; - case 'float': - return doubleval($value); - case 'date': - return $value; - case 'time': - return $value; - case 'timestamp': - return $value; - case 'clob': - case 'blob': - $this->lobs[] = array( - 'buffer' => null, - 'position' => 0, - 'lob_index' => null, - 'endOfLOB' => false, - 'resource' => $value, - 'value' => null, - 'loaded' => false, - ); - end($this->lobs); - $lob_index = key($this->lobs); - $this->lobs[$lob_index]['lob_index'] = $lob_index; - return fopen('MDB2LOB://'.$lob_index.'@'.$this->db_index, 'r+'); - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_INVALID, null, null, - 'attempt to convert result value to an unknown type :' . $type, __FUNCTION__); - } - - // }}} - // {{{ convertResult() - - /** - * Convert a value to a RDBMS indipendent MDB2 type - * - * @param mixed $value value to be converted - * @param string $type specifies which type to convert to - * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text - * @return mixed converted value - * @access public - */ - function convertResult($value, $type, $rtrim = true) - { - if (is_null($value)) { - return null; - } - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if (!empty($db->options['datatype_map'][$type])) { - $type = $db->options['datatype_map'][$type]; - if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type, 'value' => $value, 'rtrim' => $rtrim); - return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter)); - } - } - return $this->_baseConvertResult($value, $type, $rtrim); - } - - // }}} - // {{{ convertResultRow() - - /** - * Convert a result row - * - * @param array $types - * @param array $row specifies the types to convert to - * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text - * @return mixed MDB2_OK on success, an MDB2 error on failure - * @access public - */ - function convertResultRow($types, $row, $rtrim = true) - { - $types = $this->_sortResultFieldTypes(array_keys($row), $types); - foreach ($row as $key => $value) { - if (empty($types[$key])) { - continue; - } - $value = $this->convertResult($row[$key], $types[$key], $rtrim); - if (PEAR::isError($value)) { - return $value; - } - $row[$key] = $value; - } - return $row; - } - - // }}} - // {{{ _sortResultFieldTypes() - - /** - * convert a result row - * - * @param array $types - * @param array $row specifies the types to convert to - * @param bool $rtrim if to rtrim text values or not - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function _sortResultFieldTypes($columns, $types) - { - $n_cols = count($columns); - $n_types = count($types); - if ($n_cols > $n_types) { - for ($i= $n_cols - $n_types; $i >= 0; $i--) { - $types[] = null; - } - } - $sorted_types = array(); - foreach ($columns as $col) { - $sorted_types[$col] = null; - } - foreach ($types as $name => $type) { - if (array_key_exists($name, $sorted_types)) { - $sorted_types[$name] = $type; - unset($types[$name]); - } - } - // if there are left types in the array, fill the null values of the - // sorted array with them, in order. - if (count($types)) { - reset($types); - foreach (array_keys($sorted_types) as $k) { - if (is_null($sorted_types[$k])) { - $sorted_types[$k] = current($types); - next($types); - } - } - } - return $sorted_types; - } - - // }}} - // {{{ getDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare - * of the given type - * - * @param string $type type to which the value should be converted to - * @param string $name name the field to be declared. - * @param string $field definition of the field - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access public - */ - function getDeclaration($type, $name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!empty($db->options['datatype_map'][$type])) { - $type = $db->options['datatype_map'][$type]; - if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type, 'name' => $name, 'field' => $field); - return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter)); - } - $field['type'] = $type; - } - - if (!method_exists($this, "_get{$type}Declaration")) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'type not defined: '.$type, __FUNCTION__); - } - return $this->{"_get{$type}Declaration"}($name, $field); - } - - // }}} - // {{{ getTypeDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an text type - * field to be used in statements like CREATE TABLE. - * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the text - * field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * default - * Text value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access public - */ - function getTypeDeclaration($field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - switch ($field['type']) { - case 'text': - $length = !empty($field['length']) ? $field['length'] : $db->options['default_text_field_length']; - $fixed = !empty($field['fixed']) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - return 'TEXT'; - case 'blob': - return 'TEXT'; - case 'integer': - return 'INT'; - case 'boolean': - return 'INT'; - case 'date': - return 'CHAR ('.strlen('YYYY-MM-DD').')'; - case 'time': - return 'CHAR ('.strlen('HH:MM:SS').')'; - case 'timestamp': - return 'CHAR ('.strlen('YYYY-MM-DD HH:MM:SS').')'; - case 'float': - return 'TEXT'; - case 'decimal': - return 'TEXT'; - } - return ''; - } - - // }}} - // {{{ _getDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare a generic type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the text - * field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * default - * Text value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * charset - * Text value with the default CHARACTER SET for this field. - * collation - * Text value with the default COLLATION for this field. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field, or a MDB2_Error on failure - * @access protected - */ - function _getDeclaration($name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - $declaration_options = $db->datatype->_getDeclarationOptions($field); - if (PEAR::isError($declaration_options)) { - return $declaration_options; - } - return $name.' '.$this->getTypeDeclaration($field).$declaration_options; - } - - // }}} - // {{{ _getDeclarationOptions() - - /** - * Obtain DBMS specific SQL code portion needed to declare a generic type - * field to be used in statement like CREATE TABLE, without the field name - * and type values (ie. just the character set, default value, if the - * field is permitted to be NULL or not, and the collation options). - * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Text value to be used as default for this field. - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * charset - * Text value with the default CHARACTER SET for this field. - * collation - * Text value with the default COLLATION for this field. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field's options. - * @access protected - */ - function _getDeclarationOptions($field) - { - $charset = empty($field['charset']) ? '' : - ' '.$this->_getCharsetFieldDeclaration($field['charset']); - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $default = ''; - if (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $valid_default_values = $this->getValidTypes(); - $field['default'] = $valid_default_values[$field['type']]; - if ($field['default'] === ''&& ($db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)) { - $field['default'] = ' '; - } - } - if (!is_null($field['default'])) { - $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']); - } - } - - $collation = empty($field['collation']) ? '' : - ' '.$this->_getCollationFieldDeclaration($field['collation']); - - return $charset.$default.$notnull.$collation; - } - - // }}} - // {{{ _getCharsetFieldDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration to be used in statements like CREATE TABLE. - * - * @param string $charset name of the charset - * @return string DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration. - */ - function _getCharsetFieldDeclaration($charset) - { - return ''; - } - - // }}} - // {{{ _getCollationFieldDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration to be used in statements like CREATE TABLE. - * - * @param string $collation name of the collation - * @return string DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration. - */ - function _getCollationFieldDeclaration($collation) - { - return ''; - } - - // }}} - // {{{ _getIntegerDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an integer type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * unsigned - * Boolean flag that indicates whether the field should be - * declared as unsigned integer if possible. - * - * default - * Integer value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getIntegerDeclaration($name, $field) - { - if (!empty($field['unsigned'])) { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer"; - } - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ _getTextDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an text type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the text - * field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * default - * Text value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getTextDeclaration($name, $field) - { - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ _getCLOBDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an character - * large object type field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the large - * object field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access public - */ - function _getCLOBDeclaration($name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$notnull; - } - - // }}} - // {{{ _getBLOBDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an binary large - * object type field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the large - * object field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getBLOBDeclaration($name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$notnull; - } - - // }}} - // {{{ _getBooleanDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare a boolean type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Boolean value to be used as default for this field. - * - * notnullL - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getBooleanDeclaration($name, $field) - { - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ _getDateDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare a date type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Date value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getDateDeclaration($name, $field) - { - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ _getTimestampDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare a timestamp - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Timestamp value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getTimestampDeclaration($name, $field) - { - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ _getTimeDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare a time - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Time value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getTimeDeclaration($name, $field) - { - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ _getFloatDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare a float type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Float value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getFloatDeclaration($name, $field) - { - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ _getDecimalDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare a decimal type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Decimal value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getDecimalDeclaration($name, $field) - { - return $this->_getDeclaration($name, $field); - } - - // }}} - // {{{ compareDefinition() - - /** - * Obtain an array of changes that may need to applied - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access public - */ - function compareDefinition($current, $previous) - { - $type = !empty($current['type']) ? $current['type'] : null; - - if (!method_exists($this, "_compare{$type}Definition")) { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('current' => $current, 'previous' => $previous); - $change = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter)); - return $change; - } - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'type "'.$current['type'].'" is not yet supported', __FUNCTION__); - } - - if (empty($previous['type']) || $previous['type'] != $type) { - return $current; - } - - $change = $this->{"_compare{$type}Definition"}($current, $previous); - - if ($previous['type'] != $type) { - $change['type'] = true; - } - - $previous_notnull = !empty($previous['notnull']) ? $previous['notnull'] : false; - $notnull = !empty($current['notnull']) ? $current['notnull'] : false; - if ($previous_notnull != $notnull) { - $change['notnull'] = true; - } - - $previous_default = array_key_exists('default', $previous) ? $previous['default'] : - ($previous_notnull ? '' : null); - $default = array_key_exists('default', $current) ? $current['default'] : - ($notnull ? '' : null); - if ($previous_default !== $default) { - $change['default'] = true; - } - - return $change; - } - - // }}} - // {{{ _compareIntegerDefinition() - - /** - * Obtain an array of changes that may need to applied to an integer field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareIntegerDefinition($current, $previous) - { - $change = array(); - $previous_unsigned = !empty($previous['unsigned']) ? $previous['unsigned'] : false; - $unsigned = !empty($current['unsigned']) ? $current['unsigned'] : false; - if ($previous_unsigned != $unsigned) { - $change['unsigned'] = true; - } - $previous_autoincrement = !empty($previous['autoincrement']) ? $previous['autoincrement'] : false; - $autoincrement = !empty($current['autoincrement']) ? $current['autoincrement'] : false; - if ($previous_autoincrement != $autoincrement) { - $change['autoincrement'] = true; - } - return $change; - } - - // }}} - // {{{ _compareTextDefinition() - - /** - * Obtain an array of changes that may need to applied to an text field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareTextDefinition($current, $previous) - { - $change = array(); - $previous_length = !empty($previous['length']) ? $previous['length'] : 0; - $length = !empty($current['length']) ? $current['length'] : 0; - if ($previous_length != $length) { - $change['length'] = true; - } - $previous_fixed = !empty($previous['fixed']) ? $previous['fixed'] : 0; - $fixed = !empty($current['fixed']) ? $current['fixed'] : 0; - if ($previous_fixed != $fixed) { - $change['fixed'] = true; - } - return $change; - } - - // }}} - // {{{ _compareCLOBDefinition() - - /** - * Obtain an array of changes that may need to applied to an CLOB field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareCLOBDefinition($current, $previous) - { - return $this->_compareTextDefinition($current, $previous); - } - - // }}} - // {{{ _compareBLOBDefinition() - - /** - * Obtain an array of changes that may need to applied to an BLOB field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareBLOBDefinition($current, $previous) - { - return $this->_compareTextDefinition($current, $previous); - } - - // }}} - // {{{ _compareDateDefinition() - - /** - * Obtain an array of changes that may need to applied to an date field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareDateDefinition($current, $previous) - { - return array(); - } - - // }}} - // {{{ _compareTimeDefinition() - - /** - * Obtain an array of changes that may need to applied to an time field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareTimeDefinition($current, $previous) - { - return array(); - } - - // }}} - // {{{ _compareTimestampDefinition() - - /** - * Obtain an array of changes that may need to applied to an timestamp field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareTimestampDefinition($current, $previous) - { - return array(); - } - - // }}} - // {{{ _compareBooleanDefinition() - - /** - * Obtain an array of changes that may need to applied to an boolean field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareBooleanDefinition($current, $previous) - { - return array(); - } - - // }}} - // {{{ _compareFloatDefinition() - - /** - * Obtain an array of changes that may need to applied to an float field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareFloatDefinition($current, $previous) - { - return array(); - } - - // }}} - // {{{ _compareDecimalDefinition() - - /** - * Obtain an array of changes that may need to applied to an decimal field - * - * @param array $current new definition - * @param array $previous old definition - * @return array containing all changes that will need to be applied - * @access protected - */ - function _compareDecimalDefinition($current, $previous) - { - return array(); - } - - // }}} - // {{{ quote() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param string $type type to which the value should be converted to - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access public - */ - function quote($value, $type = null, $quote = true, $escape_wildcards = false) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (is_null($value) - || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL) - ) { - if (!$quote) { - return null; - } - return 'NULL'; - } - - if (is_null($type)) { - switch (gettype($value)) { - case 'integer': - $type = 'integer'; - break; - case 'double': - // todo: default to decimal as float is quite unusual - // $type = 'float'; - $type = 'decimal'; - break; - case 'boolean': - $type = 'boolean'; - break; - case 'array': - $value = serialize($value); - case 'object': - $type = 'text'; - break; - default: - if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) { - $type = 'timestamp'; - } elseif (preg_match('/^\d{2}:\d{2}$/', $value)) { - $type = 'time'; - } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) { - $type = 'date'; - } else { - $type = 'text'; - } - break; - } - } elseif (!empty($db->options['datatype_map'][$type])) { - $type = $db->options['datatype_map'][$type]; - if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type, 'value' => $value, 'quote' => $quote, 'escape_wildcards' => $escape_wildcards); - return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter)); - } - } - - if (!method_exists($this, "_quote{$type}")) { - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'type not defined: '.$type, __FUNCTION__); - } - $value = $this->{"_quote{$type}"}($value, $quote, $escape_wildcards); - if ($quote && $escape_wildcards && $db->string_quoting['escape_pattern'] - && $db->string_quoting['escape'] !== $db->string_quoting['escape_pattern'] - ) { - $value.= $this->patternEscapeString(); - } - return $value; - } - - // }}} - // {{{ _quoteInteger() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteInteger($value, $quote, $escape_wildcards) - { - return (int)$value; - } - - // }}} - // {{{ _quoteText() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that already contains any DBMS specific - * escaped character sequences. - * @access protected - */ - function _quoteText($value, $quote, $escape_wildcards) - { - if (!$quote) { - return $value; - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $value = $db->escape($value, $escape_wildcards); - if (PEAR::isError($value)) { - return $value; - } - return "'".$value."'"; - } - - // }}} - // {{{ _readFile() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _readFile($value) - { - $close = false; - if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) { - $close = true; - if ($match[1] == 'file://') { - $value = $match[2]; - } - $value = @fopen($value, 'r'); - } - - if (is_resource($value)) { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $fp = $value; - $value = ''; - while (!@feof($fp)) { - $value.= @fread($fp, $db->options['lob_buffer_length']); - } - if ($close) { - @fclose($fp); - } - } - - return $value; - } - - // }}} - // {{{ _quoteLOB() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteLOB($value, $quote, $escape_wildcards) - { - $value = $this->_readFile($value); - if (PEAR::isError($value)) { - return $value; - } - return $this->_quoteText($value, $quote, $escape_wildcards); - } - - // }}} - // {{{ _quoteCLOB() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteCLOB($value, $quote, $escape_wildcards) - { - return $this->_quoteLOB($value, $quote, $escape_wildcards); - } - - // }}} - // {{{ _quoteBLOB() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteBLOB($value, $quote, $escape_wildcards) - { - return $this->_quoteLOB($value, $quote, $escape_wildcards); - } - - // }}} - // {{{ _quoteBoolean() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteBoolean($value, $quote, $escape_wildcards) - { - return ($value ? 1 : 0); - } - - // }}} - // {{{ _quoteDate() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteDate($value, $quote, $escape_wildcards) - { - if ($value === 'CURRENT_DATE') { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) { - return $db->function->now('date'); - } - return 'CURRENT_DATE'; - } - return $this->_quoteText($value, $quote, $escape_wildcards); - } - - // }}} - // {{{ _quoteTimestamp() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteTimestamp($value, $quote, $escape_wildcards) - { - if ($value === 'CURRENT_TIMESTAMP') { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) { - return $db->function->now('timestamp'); - } - return 'CURRENT_TIMESTAMP'; - } - return $this->_quoteText($value, $quote, $escape_wildcards); - } - - // }}} - // {{{ _quoteTime() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteTime($value, $quote, $escape_wildcards) - { - if ($value === 'CURRENT_TIME') { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) { - return $db->function->now('time'); - } - return 'CURRENT_TIME'; - } - return $this->_quoteText($value, $quote, $escape_wildcards); - } - - // }}} - // {{{ _quoteFloat() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteFloat($value, $quote, $escape_wildcards) - { - if (preg_match('/^(.*)e([-+])(\d+)$/i', $value, $matches)) { - $decimal = $this->_quoteDecimal($matches[1], $quote, $escape_wildcards); - $sign = $matches[2]; - $exponent = str_pad($matches[3], 2, '0', STR_PAD_LEFT); - $value = $decimal.'E'.$sign.$exponent; - } else { - $value = $this->_quoteDecimal($value, $quote, $escape_wildcards); - } - return $value; - } - - // }}} - // {{{ _quoteDecimal() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteDecimal($value, $quote, $escape_wildcards) - { - $value = (string)$value; - $value = preg_replace('/[^\d\.,\-+eE]/', '', $value); - if (preg_match('/[^\.\d]/', $value)) { - if (strpos($value, ',')) { - // 1000,00 - if (!strpos($value, '.')) { - // convert the last "," to a "." - $value = strrev(str_replace(',', '.', strrev($value))); - // 1.000,00 - } elseif (strpos($value, '.') && strpos($value, '.') < strpos($value, ',')) { - $value = str_replace('.', '', $value); - // convert the last "," to a "." - $value = strrev(str_replace(',', '.', strrev($value))); - // 1,000.00 - } else { - $value = str_replace(',', '', $value); - } - } - } - return $value; - } - - // }}} - // {{{ writeLOBToFile() - - /** - * retrieve LOB from the database - * - * @param resource $lob stream handle - * @param string $file name of the file into which the LOb should be fetched - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access protected - */ - function writeLOBToFile($lob, $file) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (preg_match('/^(\w+:\/\/)(.*)$/', $file, $match)) { - if ($match[1] == 'file://') { - $file = $match[2]; - } - } - - $fp = @fopen($file, 'wb'); - while (!@feof($lob)) { - $result = @fread($lob, $db->options['lob_buffer_length']); - $read = strlen($result); - if (@fwrite($fp, $result, $read) != $read) { - @fclose($fp); - return $db->raiseError(MDB2_ERROR, null, null, - 'could not write to the output file', __FUNCTION__); - } - } - @fclose($fp); - return MDB2_OK; - } - - // }}} - // {{{ _retrieveLOB() - - /** - * retrieve LOB from the database - * - * @param array $lob array - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access protected - */ - function _retrieveLOB(&$lob) - { - if (is_null($lob['value'])) { - $lob['value'] = $lob['resource']; - } - $lob['loaded'] = true; - return MDB2_OK; - } - - // }}} - // {{{ readLOB() - - /** - * Read data from large object input stream. - * - * @param resource $lob stream handle - * @param string $data reference to a variable that will hold data - * to be read from the large object input stream - * @param integer $length value that indicates the largest ammount ofdata - * to be read from the large object input stream. - * @return mixed the effective number of bytes read from the large object - * input stream on sucess or an MDB2 error object. - * @access public - * @see endOfLOB() - */ - function _readLOB($lob, $length) - { - return substr($lob['value'], $lob['position'], $length); - } - - // }}} - // {{{ _endOfLOB() - - /** - * Determine whether it was reached the end of the large object and - * therefore there is no more data to be read for the its input stream. - * - * @param array $lob array - * @return mixed true or false on success, a MDB2 error on failure - * @access protected - */ - function _endOfLOB($lob) - { - return $lob['endOfLOB']; - } - - // }}} - // {{{ destroyLOB() - - /** - * Free any resources allocated during the lifetime of the large object - * handler object. - * - * @param resource $lob stream handle - * @access public - */ - function destroyLOB($lob) - { - $lob_data = stream_get_meta_data($lob); - $lob_index = $lob_data['wrapper_data']->lob_index; - fclose($lob); - if (isset($this->lobs[$lob_index])) { - $this->_destroyLOB($this->lobs[$lob_index]); - unset($this->lobs[$lob_index]); - } - return MDB2_OK; - } - - // }}} - // {{{ _destroyLOB() - - /** - * Free any resources allocated during the lifetime of the large object - * handler object. - * - * @param array $lob array - * @access private - */ - function _destroyLOB(&$lob) - { - return MDB2_OK; - } - - // }}} - // {{{ implodeArray() - - /** - * apply a type to all values of an array and return as a comma seperated string - * useful for generating IN statements - * - * @access public - * - * @param array $array data array - * @param string $type determines type of the field - * - * @return string comma seperated values - */ - function implodeArray($array, $type = false) - { - if (!is_array($array) || empty($array)) { - return 'NULL'; - } - if ($type) { - foreach ($array as $value) { - $return[] = $this->quote($value, $type); - } - } else { - $return = $array; - } - return implode(', ', $return); - } - - // }}} - // {{{ matchPattern() - - /** - * build a pattern matching string - * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) - * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) - * - * @return string SQL pattern - */ - function matchPattern($pattern, $operator = null, $field = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $match = ''; - if (!is_null($operator)) { - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - if (is_null($field)) { - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'case insensitive LIKE matching requires passing the field name', __FUNCTION__); - } - $db->loadModule('Function', null, true); - $match = $db->function->lower($field).' LIKE '; - break; - // case sensitive - case 'LIKE': - $match = is_null($field) ? 'LIKE ' : $field.' LIKE '; - break; - default: - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'not a supported operator type:'. $operator, __FUNCTION__); - } - } - $match.= "'"; - foreach ($pattern as $key => $value) { - if ($key % 2) { - $match.= $value; - } else { - if ($operator === 'ILIKE') { - $value = strtolower($value); - } - $escaped = $db->escape($value); - if (PEAR::isError($escaped)) { - return $escaped; - } - $match.= $db->escapePattern($escaped); - } - } - $match.= "'"; - $match.= $this->patternEscapeString(); - return $match; - } - - // }}} - // {{{ patternEscapeString() - - /** - * build string to define pattern escape character - * - * @access public - * - * @return string define pattern escape character - */ - function patternEscapeString() - { - return ''; - } - - // }}} - // {{{ mapNativeDatatype() - - /** - * Maps a native array description of a field to a MDB2 datatype and length - * - * @param array $field native field description - * @return array containing the various possible types, length, sign, fixed - * @access public - */ - function mapNativeDatatype($field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - // If the user has specified an option to map the native field - // type to a custom MDB2 datatype... - $db_type = strtok($field['type'], '(), '); - if (!empty($db->options['nativetype_map_callback'][$db_type])) { - return call_user_func_array($db->options['nativetype_map_callback'][$db_type], array($db, $field)); - } - - // Otherwise perform the built-in (i.e. normal) MDB2 native type to - // MDB2 datatype conversion - return $this->_mapNativeDatatype($field); - } - - // }}} - // {{{ _mapNativeDatatype() - - /** - * Maps a native array description of a field to a MDB2 datatype and length - * - * @param array $field native field description - * @return array containing the various possible types, length, sign, fixed - * @access public - */ - function _mapNativeDatatype($field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ mapPrepareDatatype() - - /** - * Maps an mdb2 datatype to mysqli prepare type - * - * @param string $type - * @return string - * @access public - */ - function mapPrepareDatatype($type) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!empty($db->options['datatype_map'][$type])) { - $type = $db->options['datatype_map'][$type]; - if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type); - return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter)); - } - } - - return $type; - } -} -?> diff --git a/3rdparty/MDB2/Driver/Datatype/mysql.php b/3rdparty/MDB2/Driver/Datatype/mysql.php deleted file mode 100644 index 93dd40524e..0000000000 --- a/3rdparty/MDB2/Driver/Datatype/mysql.php +++ /dev/null @@ -1,553 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.65 2008/02/22 19:23:49 quipo Exp $ -// - -require_once('MDB2/Driver/Datatype/Common.php'); - -/** - * MDB2 MySQL driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Datatype_mysql extends MDB2_Driver_Datatype_Common -{ - // {{{ _getCharsetFieldDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration to be used in statements like CREATE TABLE. - * - * @param string $charset name of the charset - * @return string DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration. - */ - function _getCharsetFieldDeclaration($charset) - { - return 'CHARACTER SET '.$charset; - } - - // }}} - // {{{ _getCollationFieldDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration to be used in statements like CREATE TABLE. - * - * @param string $collation name of the collation - * @return string DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration. - */ - function _getCollationFieldDeclaration($collation) - { - return 'COLLATE '.$collation; - } - - // }}} - // {{{ getTypeDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an text type - * field to be used in statements like CREATE TABLE. - * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the text - * field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * default - * Text value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access public - */ - function getTypeDeclaration($field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - switch ($field['type']) { - case 'text': - if (empty($field['length']) && array_key_exists('default', $field)) { - $field['length'] = $db->varchar_max_length; - } - $length = !empty($field['length']) ? $field['length'] : false; - $fixed = !empty($field['fixed']) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYTEXT'; - } elseif ($length <= 65532) { - return 'TEXT'; - } elseif ($length <= 16777215) { - return 'MEDIUMTEXT'; - } - } - return 'LONGTEXT'; - case 'blob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYBLOB'; - } elseif ($length <= 65532) { - return 'BLOB'; - } elseif ($length <= 16777215) { - return 'MEDIUMBLOB'; - } - } - return 'LONGBLOB'; - case 'integer': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 1) { - return 'TINYINT'; - } elseif ($length == 2) { - return 'SMALLINT'; - } elseif ($length == 3) { - return 'MEDIUMINT'; - } elseif ($length == 4) { - return 'INT'; - } elseif ($length > 4) { - return 'BIGINT'; - } - } - return 'INT'; - case 'boolean': - return 'TINYINT(1)'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME'; - case 'timestamp': - return 'DATETIME'; - case 'float': - return 'DOUBLE'; - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places']; - return 'DECIMAL('.$length.','.$scale.')'; - } - return ''; - } - - // }}} - // {{{ _getIntegerDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an integer type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: - * - * unsigned - * Boolean flag that indicates whether the field - * should be declared as unsigned integer if - * possible. - * - * default - * Integer value to be used as default for this - * field. - * - * notnull - * Boolean flag that indicates whether this field is - * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getIntegerDeclaration($name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $default = $autoinc = ''; - if (!empty($field['autoincrement'])) { - $autoinc = ' AUTO_INCREMENT PRIMARY KEY'; - } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $field['default'] = empty($field['notnull']) ? null : 0; - } - $default = ' DEFAULT '.$this->quote($field['default'], 'integer'); - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc; - } - - // }}} - // {{{ _getFloatDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an float type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: - * - * unsigned - * Boolean flag that indicates whether the field - * should be declared as unsigned float if - * possible. - * - * default - * float value to be used as default for this - * field. - * - * notnull - * Boolean flag that indicates whether this field is - * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getFloatDeclaration($name, $field) - { - // Since AUTO_INCREMENT can be used for integer or floating-point types, - // reuse the INTEGER declaration - // @see http://bugs.mysql.com/bug.php?id=31032 - return $this->_getIntegerDeclaration($name, $field); - } - - // }}} - // {{{ _getDecimalDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an decimal type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: - * - * unsigned - * Boolean flag that indicates whether the field - * should be declared as unsigned integer if - * possible. - * - * default - * Decimal value to be used as default for this - * field. - * - * notnull - * Boolean flag that indicates whether this field is - * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getDecimalDeclaration($name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $default = ''; - if (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $field['default'] = empty($field['notnull']) ? null : 0; - } - $default = ' DEFAULT '.$this->quote($field['default'], 'integer'); - } elseif (empty($field['notnull'])) { - $default = ' DEFAULT NULL'; - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull; - } - - // }}} - // {{{ matchPattern() - - /** - * build a pattern matching string - * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) - * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) - * - * @return string SQL pattern - */ - function matchPattern($pattern, $operator = null, $field = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $match = ''; - if (!is_null($operator)) { - $field = is_null($field) ? '' : $field.' '; - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - $match = $field.'LIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE BINARY '; - break; - default: - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'not a supported operator type:'. $operator, __FUNCTION__); - } - } - $match.= "'"; - foreach ($pattern as $key => $value) { - if ($key % 2) { - $match.= $value; - } else { - $match.= $db->escapePattern($db->escape($value)); - } - } - $match.= "'"; - $match.= $this->patternEscapeString(); - return $match; - } - - // }}} - // {{{ _mapNativeDatatype() - - /** - * Maps a native array description of a field to a MDB2 datatype and length - * - * @param array $field native field description - * @return array containing the various possible types, length, sign, fixed - * @access public - */ - function _mapNativeDatatype($field) - { - $db_type = strtolower($field['type']); - $db_type = strtok($db_type, '(), '); - if ($db_type == 'national') { - $db_type = strtok('(), '); - } - if (!empty($field['length'])) { - $length = strtok($field['length'], ', '); - $decimal = strtok(', '); - } else { - $length = strtok('(), '); - $decimal = strtok('(), '); - } - $type = array(); - $unsigned = $fixed = null; - switch ($db_type) { - case 'tinyint': - $type[] = 'integer'; - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 1; - break; - case 'smallint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 2; - break; - case 'mediumint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 3; - break; - case 'int': - case 'integer': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 4; - break; - case 'bigint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 8; - break; - case 'tinytext': - case 'mediumtext': - case 'longtext': - case 'text': - case 'varchar': - $fixed = false; - case 'string': - case 'char': - $type[] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } elseif (strstr($db_type, 'text')) { - $type[] = 'clob'; - if ($decimal == 'binary') { - $type[] = 'blob'; - } - $type = array_reverse($type); - } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'enum': - $type[] = 'text'; - preg_match_all('/\'.+\'/U', $field['type'], $matches); - $length = 0; - $fixed = false; - if (is_array($matches)) { - foreach ($matches[0] as $value) { - $length = max($length, strlen($value)-2); - } - if ($length == '1' && count($matches[0]) == 2) { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - } - $type[] = 'integer'; - case 'set': - $fixed = false; - $type[] = 'text'; - $type[] = 'integer'; - break; - case 'date': - $type[] = 'date'; - $length = null; - break; - case 'datetime': - case 'timestamp': - $type[] = 'timestamp'; - $length = null; - break; - case 'time': - $type[] = 'time'; - $length = null; - break; - case 'float': - case 'double': - case 'real': - $type[] = 'float'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - break; - case 'unknown': - case 'decimal': - case 'numeric': - $type[] = 'decimal'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - if ($decimal !== false) { - $length = $length.','.$decimal; - } - break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - $type[] = 'blob'; - $length = null; - break; - case 'binary': - case 'varbinary': - $type[] = 'blob'; - break; - case 'year': - $type[] = 'integer'; - $type[] = 'date'; - $length = null; - break; - default: - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'unknown database attribute type: '.$db_type, __FUNCTION__); - } - - if ((int)$length <= 0) { - $length = null; - } - - return array($type, $length, $unsigned, $fixed); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Datatype/pgsql.php b/3rdparty/MDB2/Driver/Datatype/pgsql.php deleted file mode 100644 index e72aa743b7..0000000000 --- a/3rdparty/MDB2/Driver/Datatype/pgsql.php +++ /dev/null @@ -1,554 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php,v 1.93 2008/08/28 20:32:57 afz Exp $ - -require_once('MDB2/Driver/Datatype/Common.php'); - -/** - * MDB2 PostGreSQL driver - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -class MDB2_Driver_Datatype_pgsql extends MDB2_Driver_Datatype_Common -{ - // {{{ _baseConvertResult() - - /** - * General type conversion method - * - * @param mixed $value refernce to a value to be converted - * @param string $type specifies which type to convert to - * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text - * @return object a MDB2 error on failure - * @access protected - */ - function _baseConvertResult($value, $type, $rtrim = true) - { - if (is_null($value)) { - return null; - } - switch ($type) { - case 'boolean': - return $value == 't'; - case 'float': - return doubleval($value); - case 'date': - return $value; - case 'time': - return substr($value, 0, strlen('HH:MM:SS')); - case 'timestamp': - return substr($value, 0, strlen('YYYY-MM-DD HH:MM:SS')); - case 'blob': - $value = pg_unescape_bytea($value); - return parent::_baseConvertResult($value, $type, $rtrim); - } - return parent::_baseConvertResult($value, $type, $rtrim); - } - - // }}} - // {{{ getTypeDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an text type - * field to be used in statements like CREATE TABLE. - * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the text - * field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * default - * Text value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access public - */ - function getTypeDeclaration($field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - switch ($field['type']) { - case 'text': - $length = !empty($field['length']) ? $field['length'] : false; - $fixed = !empty($field['fixed']) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - return 'TEXT'; - case 'blob': - return 'BYTEA'; - case 'integer': - if (!empty($field['autoincrement'])) { - if (!empty($field['length'])) { - $length = $field['length']; - if ($length > 4) { - return 'BIGSERIAL PRIMARY KEY'; - } - } - return 'SERIAL PRIMARY KEY'; - } - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 2) { - return 'SMALLINT'; - } elseif ($length == 3 || $length == 4) { - return 'INT'; - } elseif ($length > 4) { - return 'BIGINT'; - } - } - return 'INT'; - case 'boolean': - return 'BOOLEAN'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME without time zone'; - case 'timestamp': - return 'TIMESTAMP without time zone'; - case 'float': - return 'FLOAT8'; - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places']; - return 'NUMERIC('.$length.','.$scale.')'; - } - } - - // }}} - // {{{ _getIntegerDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an integer type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * unsigned - * Boolean flag that indicates whether the field should be - * declared as unsigned integer if possible. - * - * default - * Integer value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getIntegerDeclaration($name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!empty($field['unsigned'])) { - $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer"; - } - if (!empty($field['autoincrement'])) { - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field); - } - $default = ''; - if (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $field['default'] = empty($field['notnull']) ? null : 0; - } - $default = ' DEFAULT '.$this->quote($field['default'], 'integer'); - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$default.$notnull; - } - - // }}} - // {{{ _quoteCLOB() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteCLOB($value, $quote, $escape_wildcards) - { - return $this->_quoteText($value, $quote, $escape_wildcards); - } - - // }}} - // {{{ _quoteBLOB() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteBLOB($value, $quote, $escape_wildcards) - { - if (!$quote) { - return $value; - } - if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $connection = $db->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - $value = @pg_escape_bytea($connection, $value); - } else { - $value = @pg_escape_bytea($value); - } - return "'".$value."'"; - } - - // }}} - // {{{ _quoteBoolean() - - /** - * Convert a text value into a DBMS specific format that is suitable to - * compose query statements. - * - * @param string $value text string value that is intended to be converted. - * @param bool $quote determines if the value should be quoted and escaped - * @param bool $escape_wildcards if to escape escape wildcards - * @return string text string that represents the given argument value in - * a DBMS specific format. - * @access protected - */ - function _quoteBoolean($value, $quote, $escape_wildcards) - { - $value = $value ? 't' : 'f'; - if (!$quote) { - return $value; - } - return "'".$value."'"; - } - - // }}} - // {{{ matchPattern() - - /** - * build a pattern matching string - * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) - * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) - * - * @return string SQL pattern - */ - function matchPattern($pattern, $operator = null, $field = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $match = ''; - if (!is_null($operator)) { - $field = is_null($field) ? '' : $field.' '; - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - $match = $field.'ILIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE '; - break; - default: - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'not a supported operator type:'. $operator, __FUNCTION__); - } - } - $match.= "'"; - foreach ($pattern as $key => $value) { - if ($key % 2) { - $match.= $value; - } else { - $match.= $db->escapePattern($db->escape($value)); - } - } - $match.= "'"; - $match.= $this->patternEscapeString(); - return $match; - } - - // }}} - // {{{ patternEscapeString() - - /** - * build string to define escape pattern string - * - * @access public - * - * - * @return string define escape pattern - */ - function patternEscapeString() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - return ' ESCAPE '.$this->quote($db->string_quoting['escape_pattern']); - } - - // }}} - // {{{ _mapNativeDatatype() - - /** - * Maps a native array description of a field to a MDB2 datatype and length - * - * @param array $field native field description - * @return array containing the various possible types, length, sign, fixed - * @access public - */ - function _mapNativeDatatype($field) - { - $db_type = strtolower($field['type']); - $length = $field['length']; - $type = array(); - $unsigned = $fixed = null; - switch ($db_type) { - case 'smallint': - case 'int2': - $type[] = 'integer'; - $unsigned = false; - $length = 2; - if ($length == '2') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - break; - case 'int': - case 'int4': - case 'integer': - case 'serial': - case 'serial4': - $type[] = 'integer'; - $unsigned = false; - $length = 4; - break; - case 'bigint': - case 'int8': - case 'bigserial': - case 'serial8': - $type[] = 'integer'; - $unsigned = false; - $length = 8; - break; - case 'bool': - case 'boolean': - $type[] = 'boolean'; - $length = null; - break; - case 'text': - case 'varchar': - $fixed = false; - case 'unknown': - case 'char': - case 'bpchar': - $type[] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } elseif (strstr($db_type, 'text')) { - $type[] = 'clob'; - $type = array_reverse($type); - } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'date': - $type[] = 'date'; - $length = null; - break; - case 'datetime': - case 'timestamp': - case 'timestamptz': - $type[] = 'timestamp'; - $length = null; - break; - case 'time': - $type[] = 'time'; - $length = null; - break; - case 'float': - case 'float4': - case 'float8': - case 'double': - case 'real': - $type[] = 'float'; - break; - case 'decimal': - case 'money': - case 'numeric': - $type[] = 'decimal'; - if (isset($field['scale'])) { - $length = $length.','.$field['scale']; - } - break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - case 'bytea': - $type[] = 'blob'; - $length = null; - break; - case 'oid': - $type[] = 'blob'; - $type[] = 'clob'; - $length = null; - break; - case 'year': - $type[] = 'integer'; - $type[] = 'date'; - $length = null; - break; - default: - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'unknown database attribute type: '.$db_type, __FUNCTION__); - } - - if ((int)$length <= 0) { - $length = null; - } - - return array($type, $length, $unsigned, $fixed); - } - - // }}} - // {{{ mapPrepareDatatype() - - /** - * Maps an mdb2 datatype to native prepare type - * - * @param string $type - * @return string - * @access public - */ - function mapPrepareDatatype($type) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!empty($db->options['datatype_map'][$type])) { - $type = $db->options['datatype_map'][$type]; - if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type); - return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter)); - } - } - - switch ($type) { - case 'integer': - return 'int'; - case 'boolean': - return 'bool'; - case 'decimal': - case 'float': - return 'numeric'; - case 'clob': - return 'text'; - case 'blob': - return 'bytea'; - default: - break; - } - return $type; - } - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Datatype/sqlite.php b/3rdparty/MDB2/Driver/Datatype/sqlite.php deleted file mode 100644 index 9e57e7e567..0000000000 --- a/3rdparty/MDB2/Driver/Datatype/sqlite.php +++ /dev/null @@ -1,409 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.67 2008/02/22 19:58:06 quipo Exp $ -// - -require_once('MDB2/Driver/Datatype/Common.php'); - -/** - * MDB2 SQLite driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Datatype_sqlite extends MDB2_Driver_Datatype_Common -{ - // {{{ _getCollationFieldDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration to be used in statements like CREATE TABLE. - * - * @param string $collation name of the collation - * - * @return string DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration. - */ - function _getCollationFieldDeclaration($collation) - { - return 'COLLATE '.$collation; - } - - // }}} - // {{{ getTypeDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an text type - * field to be used in statements like CREATE TABLE. - * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * length - * Integer value that determines the maximum length of the text - * field. If this argument is missing the field should be - * declared to have the longest length allowed by the DBMS. - * - * default - * Text value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access public - */ - function getTypeDeclaration($field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - switch ($field['type']) { - case 'text': - $length = !empty($field['length']) - ? $field['length'] : false; - $fixed = !empty($field['fixed']) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYTEXT'; - } elseif ($length <= 65532) { - return 'TEXT'; - } elseif ($length <= 16777215) { - return 'MEDIUMTEXT'; - } - } - return 'LONGTEXT'; - case 'blob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYBLOB'; - } elseif ($length <= 65532) { - return 'BLOB'; - } elseif ($length <= 16777215) { - return 'MEDIUMBLOB'; - } - } - return 'LONGBLOB'; - case 'integer': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 2) { - return 'SMALLINT'; - } elseif ($length == 3 || $length == 4) { - return 'INTEGER'; - } elseif ($length > 4) { - return 'BIGINT'; - } - } - return 'INTEGER'; - case 'boolean': - return 'BOOLEAN'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME'; - case 'timestamp': - return 'DATETIME'; - case 'float': - return 'DOUBLE'.($db->options['fixed_float'] ? '('. - ($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : ''); - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places']; - return 'DECIMAL('.$length.','.$scale.')'; - } - return ''; - } - - // }}} - // {{{ _getIntegerDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an integer type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: - * - * unsigned - * Boolean flag that indicates whether the field - * should be declared as unsigned integer if - * possible. - * - * default - * Integer value to be used as default for this - * field. - * - * notnull - * Boolean flag that indicates whether this field is - * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected - */ - function _getIntegerDeclaration($name, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $default = $autoinc = ''; - if (!empty($field['autoincrement'])) { - $autoinc = ' PRIMARY KEY'; - } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $field['default'] = empty($field['notnull']) ? null : 0; - } - $default = ' DEFAULT '.$this->quote($field['default'], 'integer'); - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc; - } - - // }}} - // {{{ matchPattern() - - /** - * build a pattern matching string - * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) - * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) - * - * @return string SQL pattern - */ - function matchPattern($pattern, $operator = null, $field = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $match = ''; - if (!is_null($operator)) { - $field = is_null($field) ? '' : $field.' '; - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - $match = $field.'LIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE '; - break; - default: - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'not a supported operator type:'. $operator, __FUNCTION__); - } - } - $match.= "'"; - foreach ($pattern as $key => $value) { - if ($key % 2) { - $match.= $value; - } else { - $match.= $db->escapePattern($db->escape($value)); - } - } - $match.= "'"; - $match.= $this->patternEscapeString(); - return $match; - } - - // }}} - // {{{ _mapNativeDatatype() - - /** - * Maps a native array description of a field to a MDB2 datatype and length - * - * @param array $field native field description - * @return array containing the various possible types, length, sign, fixed - * @access public - */ - function _mapNativeDatatype($field) - { - $db_type = strtolower($field['type']); - $length = !empty($field['length']) ? $field['length'] : null; - $unsigned = !empty($field['unsigned']) ? $field['unsigned'] : null; - $fixed = null; - $type = array(); - switch ($db_type) { - case 'boolean': - $type[] = 'boolean'; - break; - case 'tinyint': - $type[] = 'integer'; - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 1; - break; - case 'smallint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 2; - break; - case 'mediumint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 3; - break; - case 'int': - case 'integer': - case 'serial': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 4; - break; - case 'bigint': - case 'bigserial': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 8; - break; - case 'clob': - $type[] = 'clob'; - $fixed = false; - break; - case 'tinytext': - case 'mediumtext': - case 'longtext': - case 'text': - case 'varchar': - case 'varchar2': - $fixed = false; - case 'char': - $type[] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } elseif (strstr($db_type, 'text')) { - $type[] = 'clob'; - $type = array_reverse($type); - } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'date': - $type[] = 'date'; - $length = null; - break; - case 'datetime': - case 'timestamp': - $type[] = 'timestamp'; - $length = null; - break; - case 'time': - $type[] = 'time'; - $length = null; - break; - case 'float': - case 'double': - case 'real': - $type[] = 'float'; - break; - case 'decimal': - case 'numeric': - $type[] = 'decimal'; - $length = $length.','.$field['decimal']; - break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - $type[] = 'blob'; - $length = null; - break; - case 'year': - $type[] = 'integer'; - $type[] = 'date'; - $length = null; - break; - default: - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'unknown database attribute type: '.$db_type, __FUNCTION__); - } - - if ((int)$length <= 0) { - $length = null; - } - - return array($type, $length, $unsigned, $fixed); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Function/Common.php b/3rdparty/MDB2/Driver/Function/Common.php deleted file mode 100644 index 731f06882c..0000000000 --- a/3rdparty/MDB2/Driver/Function/Common.php +++ /dev/null @@ -1,293 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.21 2008/02/17 18:51:39 quipo Exp $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * Base class for the function modules that is extended by each MDB2 driver - * - * To load this module in the MDB2 object: - * $mdb->loadModule('Function'); - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Function_Common extends MDB2_Module_Common -{ - // {{{ executeStoredProc() - - /** - * Execute a stored procedure and return any results - * - * @param string $name string that identifies the function to execute - * @param mixed $params array that contains the paramaters to pass the stored proc - * @param mixed $types array that contains the types of the columns in - * the result set - * @param mixed $result_class string which specifies which result class to use - * @param mixed $result_wrap_class string which specifies which class to wrap results in - * - * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $error; - } - - // }}} - // {{{ functionTable() - - /** - * return string for internal table used when calling only a function - * - * @return string for internal table used when calling only a function - * @access public - */ - function functionTable() - { - return ''; - } - - // }}} - // {{{ now() - - /** - * Return string to call a variable with the current timestamp inside an SQL statement - * There are three special variables for current date and time: - * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type) - * - CURRENT_DATE (date, DATE type) - * - CURRENT_TIME (time, TIME type) - * - * @param string $type 'timestamp' | 'time' | 'date' - * - * @return string to call a variable with the current timestamp - * @access public - */ - function now($type = 'timestamp') - { - switch ($type) { - case 'time': - return 'CURRENT_TIME'; - case 'date': - return 'CURRENT_DATE'; - case 'timestamp': - default: - return 'CURRENT_TIMESTAMP'; - } - } - - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $error; - } - - // }}} - // {{{ substring() - - /** - * return string to call a function to get a substring inside an SQL statement - * - * @return string to call a function to get a substring - * @access public - */ - function substring($value, $position = 1, $length = null) - { - if (!is_null($length)) { - return "SUBSTRING($value FROM $position FOR $length)"; - } - return "SUBSTRING($value FROM $position)"; - } - - // }}} - // {{{ replace() - - /** - * return string to call a function to get replace inside an SQL statement. - * - * @return string to call a function to get a replace - * @access public - */ - function replace($str, $from_str, $to_str) - { - return "REPLACE($str, $from_str , $to_str)"; - } - - // }}} - // {{{ concat() - - /** - * Returns string to concatenate two or more string parameters - * - * @param string $value1 - * @param string $value2 - * @param string $values... - * - * @return string to concatenate two strings - * @access public - */ - function concat($value1, $value2) - { - $args = func_get_args(); - return "(".implode(' || ', $args).")"; - } - - // }}} - // {{{ random() - - /** - * return string to call a function to get random value inside an SQL statement - * - * @return return string to generate float between 0 and 1 - * @access public - */ - function random() - { - return 'RAND()'; - } - - // }}} - // {{{ lower() - - /** - * return string to call a function to lower the case of an expression - * - * @param string $expression - * - * @return return string to lower case of an expression - * @access public - */ - function lower($expression) - { - return "LOWER($expression)"; - } - - // }}} - // {{{ upper() - - /** - * return string to call a function to upper the case of an expression - * - * @param string $expression - * - * @return return string to upper case of an expression - * @access public - */ - function upper($expression) - { - return "UPPER($expression)"; - } - - // }}} - // {{{ length() - - /** - * return string to call a function to get the length of a string expression - * - * @param string $expression - * - * @return return string to get the string expression length - * @access public - */ - function length($expression) - { - return "LENGTH($expression)"; - } - - // }}} - // {{{ guid() - - /** - * Returns global unique identifier - * - * @return string to get global unique identifier - * @access public - */ - function guid() - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $error; - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Function/mysql.php b/3rdparty/MDB2/Driver/Function/mysql.php deleted file mode 100644 index 44183c3aa0..0000000000 --- a/3rdparty/MDB2/Driver/Function/mysql.php +++ /dev/null @@ -1,136 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.12 2008/02/17 18:54:08 quipo Exp $ -// - -require_once('MDB2/Driver/Function/Common.php'); - -/** - * MDB2 MySQL driver for the function modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Function_mysql extends MDB2_Driver_Function_Common -{ - // }}} - // {{{ executeStoredProc() - - /** - * Execute a stored procedure and return any results - * - * @param string $name string that identifies the function to execute - * @param mixed $params array that contains the paramaters to pass the stored proc - * @param mixed $types array that contains the types of the columns in - * the result set - * @param mixed $result_class string which specifies which result class to use - * @param mixed $result_wrap_class string which specifies which class to wrap results in - * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'CALL '.$name; - $query .= $params ? '('.implode(', ', $params).')' : '()'; - return $db->query($query, $types, $result_class, $result_wrap_class); - } - - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - return 'UNIX_TIMESTAMP('. $expression.')'; - } - - // }}} - // {{{ concat() - - /** - * Returns string to concatenate two or more string parameters - * - * @param string $value1 - * @param string $value2 - * @param string $values... - * @return string to concatenate two strings - * @access public - **/ - function concat($value1, $value2) - { - $args = func_get_args(); - return "CONCAT(".implode(', ', $args).")"; - } - - // }}} - // {{{ guid() - - /** - * Returns global unique identifier - * - * @return string to get global unique identifier - * @access public - */ - function guid() - { - return 'UUID()'; - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Function/pgsql.php b/3rdparty/MDB2/Driver/Function/pgsql.php deleted file mode 100644 index 173bfc9149..0000000000 --- a/3rdparty/MDB2/Driver/Function/pgsql.php +++ /dev/null @@ -1,115 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php,v 1.11 2008/11/09 19:46:50 quipo Exp $ - -require_once('MDB2/Driver/Function/Common.php'); - -/** - * MDB2 MySQL driver for the function modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Function_pgsql extends MDB2_Driver_Function_Common -{ - // {{{ executeStoredProc() - - /** - * Execute a stored procedure and return any results - * - * @param string $name string that identifies the function to execute - * @param mixed $params array that contains the paramaters to pass the stored proc - * @param mixed $types array that contains the types of the columns in - * the result set - * @param mixed $result_class string which specifies which result class to use - * @param mixed $result_wrap_class string which specifies which class to wrap results in - * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SELECT * FROM '.$name; - $query .= $params ? '('.implode(', ', $params).')' : '()'; - return $db->query($query, $types, $result_class, $result_wrap_class); - } - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - return 'EXTRACT(EPOCH FROM DATE_TRUNC(\'seconds\', CAST ((' . $expression . ') AS TIMESTAMP)))'; - } - - // }}} - // {{{ random() - - /** - * return string to call a function to get random value inside an SQL statement - * - * @return return string to generate float between 0 and 1 - * @access public - */ - function random() - { - return 'RANDOM()'; - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Function/sqlite.php b/3rdparty/MDB2/Driver/Function/sqlite.php deleted file mode 100644 index 8a5b7ec8fa..0000000000 --- a/3rdparty/MDB2/Driver/Function/sqlite.php +++ /dev/null @@ -1,162 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.10 2008/02/17 18:54:08 quipo Exp $ -// - -require_once('MDB2/Driver/Function/Common.php'); - -/** - * MDB2 SQLite driver for the function modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Function_sqlite extends MDB2_Driver_Function_Common -{ - // {{{ constructor - - /** - * Constructor - */ - function __construct($db_index) - { - parent::__construct($db_index); - // create all sorts of UDFs - } - - // {{{ now() - - /** - * Return string to call a variable with the current timestamp inside an SQL statement - * There are three special variables for current date and time. - * - * @return string to call a variable with the current timestamp - * @access public - */ - function now($type = 'timestamp') - { - switch ($type) { - case 'time': - return 'time(\'now\')'; - case 'date': - return 'date(\'now\')'; - case 'timestamp': - default: - return 'datetime(\'now\')'; - } - } - - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - return 'strftime("%s",'. $expression.', "utc")'; - } - - // }}} - // {{{ substring() - - /** - * return string to call a function to get a substring inside an SQL statement - * - * @return string to call a function to get a substring - * @access public - */ - function substring($value, $position = 1, $length = null) - { - if (!is_null($length)) { - return "substr($value,$position,$length)"; - } - return "substr($value,$position,length($value))"; - } - - // }}} - // {{{ random() - - /** - * return string to call a function to get random value inside an SQL statement - * - * @return return string to generate float between 0 and 1 - * @access public - */ - function random() - { - return '((RANDOM()+2147483648)/4294967296)'; - } - - // }}} - // {{{ replace() - - /** - * return string to call a function to get a replacement inside an SQL statement. - * - * @return string to call a function to get a replace - * @access public - */ - function replace($str, $from_str, $to_str) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $error; - } - - // }}} -} -?> diff --git a/3rdparty/MDB2/Driver/Manager/Common.php b/3rdparty/MDB2/Driver/Manager/Common.php deleted file mode 100644 index 9e16749bff..0000000000 --- a/3rdparty/MDB2/Driver/Manager/Common.php +++ /dev/null @@ -1,1014 +0,0 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.72 2009/01/14 15:00:40 quipo Exp $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - * @author Lorenzo Alberton - */ - -/** - * Base class for the management modules that is extended by each MDB2 driver - * - * To load this module in the MDB2 object: - * $mdb->loadModule('Manager'); - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Manager_Common extends MDB2_Module_Common -{ - // {{{ splitTableSchema() - - /** - * Split the "[owner|schema].table" notation into an array - * - * @param string $table [schema and] table name - * - * @return array array(schema, table) - * @access private - */ - function splitTableSchema($table) - { - $ret = array(); - if (strpos($table, '.') !== false) { - return explode('.', $table); - } - return array(null, $table); - } - - // }}} - // {{{ getFieldDeclarationList() - - /** - * Get declaration of a number of field in bulk - * - * @param array $fields a multidimensional associative array. - * The first dimension determines the field name, while the second - * dimension is keyed with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: - * - * default - * Boolean value to be used as default for this field. - * - * notnull - * Boolean flag that indicates whether this field is constrained - * to not be set to null. - * - * @return mixed string on success, a MDB2 error on failure - * @access public - */ - function getFieldDeclarationList($fields) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!is_array($fields) || empty($fields)) { - return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'missing any fields', __FUNCTION__); - } - foreach ($fields as $field_name => $field) { - $query = $db->getDeclaration($field['type'], $field_name, $field); - if (PEAR::isError($query)) { - return $query; - } - $query_fields[] = $query; - } - return implode(', ', $query_fields); - } - - // }}} - // {{{ _fixSequenceName() - - /** - * Removes any formatting in an sequence name using the 'seqname_format' option - * - * @param string $sqn string that containts name of a potential sequence - * @param bool $check if only formatted sequences should be returned - * @return string name of the sequence with possible formatting removed - * @access protected - */ - function _fixSequenceName($sqn, $check = false) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $seq_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['seqname_format']).'$/i'; - $seq_name = preg_replace($seq_pattern, '\\1', $sqn); - if ($seq_name && !strcasecmp($sqn, $db->getSequenceName($seq_name))) { - return $seq_name; - } - if ($check) { - return false; - } - return $sqn; - } - - // }}} - // {{{ _fixIndexName() - - /** - * Removes any formatting in an index name using the 'idxname_format' option - * - * @param string $idx string that containts name of anl index - * @return string name of the index with eventual formatting removed - * @access protected - */ - function _fixIndexName($idx) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $idx_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['idxname_format']).'$/i'; - $idx_name = preg_replace($idx_pattern, '\\1', $idx); - if ($idx_name && !strcasecmp($idx, $db->getIndexName($idx_name))) { - return $idx_name; - } - return $idx; - } - - // }}} - // {{{ createDatabase() - - /** - * create a new database - * - * @param string $name name of the database that should be created - * @param array $options array with charset, collation info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createDatabase($database, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ alterDatabase() - - /** - * alter an existing database - * - * @param string $name name of the database that should be created - * @param array $options array with charset, collation info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function alterDatabase($database, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ dropDatabase() - - /** - * drop an existing database - * - * @param string $name name of the database that should be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropDatabase($database) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ _getCreateTableQuery() - - /** - * Create a basic SQL query for a new table creation - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * @param array $options An associative array of table options - * - * @return mixed string (the SQL query) on success, a MDB2 error on failure - * @see createTable() - */ - function _getCreateTableQuery($name, $fields, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!$name) { - return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null, - 'no valid table name specified', __FUNCTION__); - } - if (empty($fields)) { - return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null, - 'no fields specified for table "'.$name.'"', __FUNCTION__); - } - $query_fields = $this->getFieldDeclarationList($fields); - if (PEAR::isError($query_fields)) { - return $query_fields; - } - if (!empty($options['primary'])) { - $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')'; - } - - $name = $db->quoteIdentifier($name, true); - $result = 'CREATE '; - if (!empty($options['temporary'])) { - $result .= $this->_getTemporaryTableQuery(); - } - $result .= " TABLE $name ($query_fields)"; - return $result; - } - - // }}} - // {{{ _getTemporaryTableQuery() - - /** - * A method to return the required SQL string that fits between CREATE ... TABLE - * to create the table as a temporary table. - * - * Should be overridden in driver classes to return the correct string for the - * specific database type. - * - * The default is to return the string "TEMPORARY" - this will result in a - * SQL error for any database that does not support temporary tables, or that - * requires a different SQL command from "CREATE TEMPORARY TABLE". - * - * @return string The string required to be placed between "CREATE" and "TABLE" - * to generate a temporary table, if possible. - */ - function _getTemporaryTableQuery() - { - return 'TEMPORARY'; - } - - // }}} - // {{{ createTable() - - /** - * create a new table - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'temporary' => true|false, - * ); - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createTable($name, $fields, $options = array()) - { - $query = $this->_getCreateTableQuery($name, $fields, $options); - if (PEAR::isError($query)) { - return $query; - } - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $result = $db->exec($query); - if (PEAR::isError($result)) { - return $result; - } - return MDB2_OK; - } - - // }}} - // {{{ dropTable() - - /** - * drop an existing table - * - * @param string $name name of the table that should be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("DROP TABLE $name"); - } - - // }}} - // {{{ truncateTable() - - /** - * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported, - * it falls back to a DELETE FROM TABLE query) - * - * @param string $name name of the table that should be truncated - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function truncateTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("DELETE FROM $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ alterTable() - - /** - * alter an existing table - * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: - * - * name - * - * New name for the table. - * - * add - * - * Associative array with the names of fields to be added as - * indexes of the array. The value of each entry of the array - * should be set to another associative array with the properties - * of the fields to be added. The properties of the fields should - * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @access public - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - */ - function alterTable($name, $changes, $check) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listDatabases() - - /** - * list all databases - * - * @return mixed array of database names on success, a MDB2 error on failure - * @access public - */ - function listDatabases() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implementedd', __FUNCTION__); - } - - // }}} - // {{{ listUsers() - - /** - * list all users - * - * @return mixed array of user names on success, a MDB2 error on failure - * @access public - */ - function listUsers() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listViews() - - /** - * list all views in the current database - * - * @param string database, the current is default - * NB: not all the drivers can get the view names from - * a database other than the current one - * @return mixed array of view names on success, a MDB2 error on failure - * @access public - */ - function listViews($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listTableViews() - - /** - * list the views in the database that reference a given table - * - * @param string table for which all referenced views should be found - * @return mixed array of view names on success, a MDB2 error on failure - * @access public - */ - function listTableViews($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listTableTriggers() - - /** - * list all triggers in the database that reference a given table - * - * @param string table for which all referenced triggers should be found - * @return mixed array of trigger names on success, a MDB2 error on failure - * @access public - */ - function listTableTriggers($table = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listFunctions() - - /** - * list all functions in the current database - * - * @return mixed array of function names on success, a MDB2 error on failure - * @access public - */ - function listFunctions() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listTables() - - /** - * list all tables in the current database - * - * @param string database, the current is default. - * NB: not all the drivers can get the table names from - * a database other than the current one - * @return mixed array of table names on success, a MDB2 error on failure - * @access public - */ - function listTables($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listTableFields() - - /** - * list all fields in a table in the current database - * - * @param string $table name of table that should be used in method - * @return mixed array of field names on success, a MDB2 error on failure - * @access public - */ - function listTableFields($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ createIndex() - - /** - * Get the stucture of a field into an array - * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. - * - * Currently, only the sorting property is supported. It should be used - * to define the sorting direction of the index. It may be set to either - * ascending or descending. - * - * Not all DBMS support index sorting direction configuration. The DBMS - * drivers of those that do not support it ignore this property. Use the - * function supports() to determine whether the DBMS driver can manage indexes. - * - * Example - * array( - * 'fields' => array( - * 'user_name' => array( - * 'sorting' => 'ascending' - * ), - * 'last_login' => array() - * ) - * ) - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createIndex($table, $name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - $query = "CREATE INDEX $name ON $table"; - $fields = array(); - foreach (array_keys($definition['fields']) as $field) { - $fields[] = $db->quoteIdentifier($field, true); - } - $query .= ' ('. implode(', ', $fields) . ')'; - return $db->exec($query); - } - - // }}} - // {{{ dropIndex() - - /** - * drop existing index - * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropIndex($table, $name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($db->getIndexName($name), true); - return $db->exec("DROP INDEX $name"); - } - - // }}} - // {{{ listTableIndexes() - - /** - * list all indexes in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of index names on success, a MDB2 error on failure - * @access public - */ - function listTableIndexes($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ _getAdvancedFKOptions() - - /** - * Return the FOREIGN KEY query section dealing with non-standard options - * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... - * - * @param array $definition - * @return string - * @access protected - */ - function _getAdvancedFKOptions($definition) - { - return ''; - } - - // }}} - // {{{ createConstraint() - - /** - * create a constraint on a table - * - * @param string $table name of the table on which the constraint is to be created - * @param string $name name of the constraint to be created - * @param array $definition associative array that defines properties of the constraint to be created. - * The full structure of the array looks like this: - *
-     *          array (
-     *              [primary] => 0
-     *              [unique]  => 0
-     *              [foreign] => 1
-     *              [check]   => 0
-     *              [fields] => array (
-     *                  [field1name] => array() // one entry per each field covered
-     *                  [field2name] => array() // by the index
-     *                  [field3name] => array(
-     *                      [sorting]  => ascending
-     *                      [position] => 3
-     *                  )
-     *              )
-     *              [references] => array(
-     *                  [table] => name
-     *                  [fields] => array(
-     *                      [field1name] => array(  //one entry per each referenced field
-     *                           [position] => 1
-     *                      )
-     *                  )
-     *              )
-     *              [deferrable] => 0
-     *              [initiallydeferred] => 0
-     *              [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [match] => SIMPLE|PARTIAL|FULL
-     *          );
-     *          
- * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createConstraint($table, $name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - $query = "ALTER TABLE $table ADD CONSTRAINT $name"; - if (!empty($definition['primary'])) { - $query.= ' PRIMARY KEY'; - } elseif (!empty($definition['unique'])) { - $query.= ' UNIQUE'; - } elseif (!empty($definition['foreign'])) { - $query.= ' FOREIGN KEY'; - } - $fields = array(); - foreach (array_keys($definition['fields']) as $field) { - $fields[] = $db->quoteIdentifier($field, true); - } - $query .= ' ('. implode(', ', $fields) . ')'; - if (!empty($definition['foreign'])) { - $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true); - $referenced_fields = array(); - foreach (array_keys($definition['references']['fields']) as $field) { - $referenced_fields[] = $db->quoteIdentifier($field, true); - } - $query .= ' ('. implode(', ', $referenced_fields) . ')'; - $query .= $this->_getAdvancedFKOptions($definition); - } - return $db->exec($query); - } - - // }}} - // {{{ dropConstraint() - - /** - * drop existing constraint - * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropConstraint($table, $name, $primary = false) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - return $db->exec("ALTER TABLE $table DROP CONSTRAINT $name"); - } - - // }}} - // {{{ listTableConstraints() - - /** - * list all constraints in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of constraint names on success, a MDB2 error on failure - * @access public - */ - function listTableConstraints($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ createSequence() - - /** - * create sequence - * - * @param string $seq_name name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createSequence($seq_name, $start = 1) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ dropSequence() - - /** - * drop existing sequence - * - * @param string $seq_name name of the sequence to be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropSequence($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ listSequences() - - /** - * list all sequences in the current database - * - * @param string database, the current is default - * NB: not all the drivers can get the sequence names from - * a database other than the current one - * @return mixed array of sequence names on success, a MDB2 error on failure - * @access public - */ - function listSequences($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Manager/mysql.php b/3rdparty/MDB2/Driver/Manager/mysql.php deleted file mode 100644 index 099ed48a84..0000000000 --- a/3rdparty/MDB2/Driver/Manager/mysql.php +++ /dev/null @@ -1,1432 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.113 2008/11/23 20:30:29 quipo Exp $ -// - -require_once('MDB2/Driver/Manager/Common.php'); - -/** - * MDB2 MySQL driver for the management modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Manager_mysql extends MDB2_Driver_Manager_Common -{ - - // }}} - // {{{ createDatabase() - - /** - * create a new database - * - * @param string $name name of the database that should be created - * @param array $options array with charset, collation info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createDatabase($name, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - $query = 'CREATE DATABASE ' . $name; - if (!empty($options['charset'])) { - $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text'); - } - if (!empty($options['collation'])) { - $query .= ' COLLATE ' . $db->quote($options['collation'], 'text'); - } - return $db->standaloneQuery($query, null, true); - } - - // }}} - // {{{ alterDatabase() - - /** - * alter an existing database - * - * @param string $name name of the database that is intended to be changed - * @param array $options array with charset, collation info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function alterDatabase($name, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true); - if (!empty($options['charset'])) { - $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text'); - } - if (!empty($options['collation'])) { - $query .= ' COLLATE ' . $db->quote($options['collation'], 'text'); - } - return $db->standaloneQuery($query, null, true); - } - - // }}} - // {{{ dropDatabase() - - /** - * drop an existing database - * - * @param string $name name of the database that should be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropDatabase($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - $query = "DROP DATABASE $name"; - return $db->standaloneQuery($query, null, true); - } - - // }}} - // {{{ _getAdvancedFKOptions() - - /** - * Return the FOREIGN KEY query section dealing with non-standard options - * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... - * - * @param array $definition - * @return string - * @access protected - */ - function _getAdvancedFKOptions($definition) - { - $query = ''; - if (!empty($definition['match'])) { - $query .= ' MATCH '.$definition['match']; - } - if (!empty($definition['onupdate'])) { - $query .= ' ON UPDATE '.$definition['onupdate']; - } - if (!empty($definition['ondelete'])) { - $query .= ' ON DELETE '.$definition['ondelete']; - } - return $query; - } - - // }}} - // {{{ createTable() - - /** - * create a new table - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createTable($name, $fields, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - // if we have an AUTO_INCREMENT column and a PK on more than one field, - // we have to handle it differently... - $autoincrement = null; - if (empty($options['primary'])) { - $pk_fields = array(); - foreach ($fields as $fieldname => $def) { - if (!empty($def['primary'])) { - $pk_fields[$fieldname] = true; - } - if (!empty($def['autoincrement'])) { - $autoincrement = $fieldname; - } - } - if (!is_null($autoincrement) && count($pk_fields) > 1) { - $options['primary'] = $pk_fields; - } else { - // the PK constraint is on max one field => OK - $autoincrement = null; - } - } - - $query = $this->_getCreateTableQuery($name, $fields, $options); - if (PEAR::isError($query)) { - return $query; - } - - if (!is_null($autoincrement)) { - // we have to remove the PK clause added by _getIntegerDeclaration() - $query = str_replace('AUTO_INCREMENT PRIMARY KEY', 'AUTO_INCREMENT', $query); - } - - $options_strings = array(); - - if (!empty($options['comment'])) { - $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text'); - } - - if (!empty($options['charset'])) { - $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; - if (!empty($options['collate'])) { - $options_strings['charset'].= ' COLLATE '.$options['collate']; - } - } - - $type = false; - if (!empty($options['type'])) { - $type = $options['type']; - } elseif ($db->options['default_table_type']) { - $type = $db->options['default_table_type']; - } - if ($type) { - $options_strings[] = "ENGINE = $type"; - } - - if (!empty($options_strings)) { - $query .= ' '.implode(' ', $options_strings); - } - $result = $db->exec($query); - if (PEAR::isError($result)) { - return $result; - } - return MDB2_OK; - } - - // }}} - // {{{ dropTable() - - /** - * drop an existing table - * - * @param string $name name of the table that should be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - //delete the triggers associated to existing FK constraints - $constraints = $this->listTableConstraints($name); - if (!PEAR::isError($constraints) && !empty($constraints)) { - $db->loadModule('Reverse', null, true); - foreach ($constraints as $constraint) { - $definition = $db->reverse->getTableConstraintDefinition($name, $constraint); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - - return parent::dropTable($name); - } - - // }}} - // {{{ truncateTable() - - /** - * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported, - * it falls back to a DELETE FROM TABLE query) - * - * @param string $name name of the table that should be truncated - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function truncateTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("TRUNCATE TABLE $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (empty($table)) { - $table = $this->listTables(); - if (PEAR::isError($table)) { - return $table; - } - } - if (is_array($table)) { - foreach (array_keys($table) as $k) { - $table[$k] = $db->quoteIdentifier($table[$k], true); - } - $table = implode(', ', $table); - } else { - $table = $db->quoteIdentifier($table, true); - } - - $result = $db->exec('OPTIMIZE TABLE '.$table); - if (PEAR::isError($result)) { - return $result; - } - if (!empty($options['analyze'])) { - return $db->exec('ANALYZE TABLE '.$table); - } - return MDB2_OK; - } - - // }}} - // {{{ alterTable() - - /** - * alter an existing table - * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: - * - * name - * - * New name for the table. - * - * add - * - * Associative array with the names of fields to be added as - * indexes of the array. The value of each entry of the array - * should be set to another associative array with the properties - * of the fields to be added. The properties of the fields should - * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @access public - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - */ - function alterTable($name, $changes, $check) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - foreach ($changes as $change_name => $change) { - switch ($change_name) { - case 'add': - case 'remove': - case 'change': - case 'rename': - case 'name': - break; - default: - return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, - 'change type "'.$change_name.'" not yet supported', __FUNCTION__); - } - } - - if ($check) { - return MDB2_OK; - } - - $query = ''; - if (!empty($changes['name'])) { - $change_name = $db->quoteIdentifier($changes['name'], true); - $query .= 'RENAME TO ' . $change_name; - } - - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $field_name => $field) { - if ($query) { - $query.= ', '; - } - $query.= 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field); - } - } - - if (!empty($changes['remove']) && is_array($changes['remove'])) { - foreach ($changes['remove'] as $field_name => $field) { - if ($query) { - $query.= ', '; - } - $field_name = $db->quoteIdentifier($field_name, true); - $query.= 'DROP ' . $field_name; - } - } - - $rename = array(); - if (!empty($changes['rename']) && is_array($changes['rename'])) { - foreach ($changes['rename'] as $field_name => $field) { - $rename[$field['name']] = $field_name; - } - } - - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $field_name => $field) { - if ($query) { - $query.= ', '; - } - if (isset($rename[$field_name])) { - $old_field_name = $rename[$field_name]; - unset($rename[$field_name]); - } else { - $old_field_name = $field_name; - } - $old_field_name = $db->quoteIdentifier($old_field_name, true); - $query.= "CHANGE $old_field_name " . $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']); - } - } - - if (!empty($rename) && is_array($rename)) { - foreach ($rename as $rename_name => $renamed_field) { - if ($query) { - $query.= ', '; - } - $field = $changes['rename'][$renamed_field]; - $renamed_field = $db->quoteIdentifier($renamed_field, true); - $query.= 'CHANGE ' . $renamed_field . ' ' . $db->getDeclaration($field['definition']['type'], $field['name'], $field['definition']); - } - } - - if (!$query) { - return MDB2_OK; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("ALTER TABLE $name $query"); - } - - // }}} - // {{{ listDatabases() - - /** - * list all databases - * - * @return mixed array of database names on success, a MDB2 error on failure - * @access public - */ - function listDatabases() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $result = $db->queryCol('SHOW DATABASES'); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listUsers() - - /** - * list all users - * - * @return mixed array of user names on success, a MDB2 error on failure - * @access public - */ - function listUsers() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->queryCol('SELECT DISTINCT USER FROM mysql.USER'); - } - - // }}} - // {{{ listFunctions() - - /** - * list all functions in the current database - * - * @return mixed array of function names on success, a MDB2 error on failure - * @access public - */ - function listFunctions() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM mysql.proc"; - /* - SELECT ROUTINE_NAME - FROM INFORMATION_SCHEMA.ROUTINES - WHERE ROUTINE_TYPE = 'FUNCTION' - */ - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTableTriggers() - - /** - * list all triggers in the database that reference a given table - * - * @param string table for which all referenced triggers should be found - * @return mixed array of trigger names on success, a MDB2 error on failure - * @access public - */ - function listTableTriggers($table = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SHOW TRIGGERS'; - if (!is_null($table)) { - $table = $db->quote($table, 'text'); - $query .= " LIKE $table"; - } - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTables() - - /** - * list all tables in the current database - * - * @param string database, the current is default - * @return mixed array of table names on success, a MDB2 error on failure - * @access public - */ - function listTables($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SHOW /*!50002 FULL*/ TABLES"; - if (!is_null($database)) { - $query .= " FROM $database"; - } - $query.= "/*!50002 WHERE Table_type = 'BASE TABLE'*/"; - - $table_names = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED); - if (PEAR::isError($table_names)) { - return $table_names; - } - - $result = array(); - foreach ($table_names as $table) { - if (!$this->_fixSequenceName($table[0], true)) { - $result[] = $table[0]; - } - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listViews() - - /** - * list all views in the current database - * - * @param string database, the current is default - * @return mixed array of view names on success, a MDB2 error on failure - * @access public - */ - function listViews($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SHOW FULL TABLES'; - if (!is_null($database)) { - $query.= " FROM $database"; - } - $query.= " WHERE Table_type = 'VIEW'"; - - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTableFields() - - /** - * list all fields in a table in the current database - * - * @param string $table name of table that should be used in method - * @return mixed array of field names on success, a MDB2 error on failure - * @access public - */ - function listTableFields($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quoteIdentifier($table, true); - $result = $db->queryCol("SHOW COLUMNS FROM $table"); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ createIndex() - - /** - * Get the stucture of a field into an array - * - * @author Leoncx - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. - * - * Currently, only the sorting property is supported. It should be used - * to define the sorting direction of the index. It may be set to either - * ascending or descending. - * - * Not all DBMS support index sorting direction configuration. The DBMS - * drivers of those that do not support it ignore this property. Use the - * function supports() to determine whether the DBMS driver can manage indexes. - * - * Example - * array( - * 'fields' => array( - * 'user_name' => array( - * 'sorting' => 'ascending' - * 'length' => 10 - * ), - * 'last_login' => array() - * ) - * ) - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createIndex($table, $name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - $query = "CREATE INDEX $name ON $table"; - $fields = array(); - foreach ($definition['fields'] as $field => $fieldinfo) { - if (!empty($fieldinfo['length'])) { - $fields[] = $db->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')'; - } else { - $fields[] = $db->quoteIdentifier($field, true); - } - } - $query .= ' ('. implode(', ', $fields) . ')'; - return $db->exec($query); - } - - // }}} - // {{{ dropIndex() - - /** - * drop existing index - * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropIndex($table, $name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - return $db->exec("DROP INDEX $name ON $table"); - } - - // }}} - // {{{ listTableIndexes() - - /** - * list all indexes in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of index names on success, a MDB2 error on failure - * @access public - */ - function listTableIndexes($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $key_name = 'Key_name'; - $non_unique = 'Non_unique'; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - $non_unique = strtolower($non_unique); - } else { - $key_name = strtoupper($key_name); - $non_unique = strtoupper($non_unique); - } - } - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW INDEX FROM $table"; - $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $index_data) { - if ($index_data[$non_unique] && ($index = $this->_fixIndexName($index_data[$key_name]))) { - $result[$index] = true; - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($result); - } - - // }}} - // {{{ createConstraint() - - /** - * create a constraint on a table - * - * @param string $table name of the table on which the constraint is to be created - * @param string $name name of the constraint to be created - * @param array $definition associative array that defines properties of the constraint to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. - * - * Example - * array( - * 'fields' => array( - * 'user_name' => array(), - * 'last_login' => array() - * ) - * ) - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createConstraint($table, $name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $type = ''; - $idx_name = $db->quoteIdentifier($db->getIndexName($name), true); - if (!empty($definition['primary'])) { - $type = 'PRIMARY'; - $idx_name = 'KEY'; - } elseif (!empty($definition['unique'])) { - $type = 'UNIQUE'; - } elseif (!empty($definition['foreign'])) { - $type = 'CONSTRAINT'; - } - if (empty($type)) { - return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'invalid definition, could not create constraint', __FUNCTION__); - } - - $table_quoted = $db->quoteIdentifier($table, true); - $query = "ALTER TABLE $table_quoted ADD $type $idx_name"; - if (!empty($definition['foreign'])) { - $query .= ' FOREIGN KEY'; - } - $fields = array(); - foreach ($definition['fields'] as $field => $fieldinfo) { - $quoted = $db->quoteIdentifier($field, true); - if (!empty($fieldinfo['length'])) { - $quoted .= '(' . $fieldinfo['length'] . ')'; - } - $fields[] = $quoted; - } - $query .= ' ('. implode(', ', $fields) . ')'; - if (!empty($definition['foreign'])) { - $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true); - $referenced_fields = array(); - foreach (array_keys($definition['references']['fields']) as $field) { - $referenced_fields[] = $db->quoteIdentifier($field, true); - } - $query .= ' ('. implode(', ', $referenced_fields) . ')'; - $query .= $this->_getAdvancedFKOptions($definition); - - // add index on FK column(s) or we can't add a FK constraint - // @see http://forums.mysql.com/read.php?22,19755,226009 - $result = $this->createIndex($table, $name.'_fkidx', $definition); - if (PEAR::isError($result)) { - return $result; - } - } - $res = $db->exec($query); - if (PEAR::isError($res)) { - return $res; - } - if (!empty($definition['foreign'])) { - return $this->_createFKTriggers($table, array($name => $definition)); - } - return MDB2_OK; - } - - // }}} - // {{{ dropConstraint() - - /** - * drop existing constraint - * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropConstraint($table, $name, $primary = false) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if ($primary || strtolower($name) == 'primary') { - $query = 'ALTER TABLE '. $db->quoteIdentifier($table, true) .' DROP PRIMARY KEY'; - return $db->exec($query); - } - - //is it a FK constraint? If so, also delete the associated triggers - $db->loadModule('Reverse', null, true); - $definition = $db->reverse->getTableConstraintDefinition($table, $name); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - //first drop the FK enforcing triggers - $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - //then drop the constraint itself - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - $query = "ALTER TABLE $table DROP FOREIGN KEY $name"; - return $db->exec($query); - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - $query = "ALTER TABLE $table DROP INDEX $name"; - return $db->exec($query); - } - - // }}} - // {{{ _createFKTriggers() - - /** - * Create triggers to enforce the FOREIGN KEY constraint on the table - * - * NB: since there's no RAISE_APPLICATION_ERROR facility in mysql, - * we call a non-existent procedure to raise the FK violation message. - * @see http://forums.mysql.com/read.php?99,55108,71877#msg-71877 - * - * @param string $table table name - * @param array $foreign_keys FOREIGN KEY definitions - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access private - */ - function _createFKTriggers($table, $foreign_keys) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - // create triggers to enforce FOREIGN KEY constraints - if ($db->supports('triggers') && !empty($foreign_keys)) { - $table_quoted = $db->quoteIdentifier($table, true); - foreach ($foreign_keys as $fkname => $fkdef) { - if (empty($fkdef)) { - continue; - } - //set actions to default if not set - $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']); - $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']); - - $trigger_names = array( - 'insert' => $fkname.'_insert_trg', - 'update' => $fkname.'_update_trg', - 'pk_update' => $fkname.'_pk_update_trg', - 'pk_delete' => $fkname.'_pk_delete_trg', - ); - $table_fields = array_keys($fkdef['fields']); - $referenced_fields = array_keys($fkdef['references']['fields']); - - //create the ON [UPDATE|DELETE] triggers on the primary table - $restrict_action = ' IF (SELECT '; - $aliased_fields = array(); - foreach ($table_fields as $field) { - $aliased_fields[] = $table_quoted .'.'.$field .' AS '.$field; - } - $restrict_action .= implode(',', $aliased_fields) - .' FROM '.$table_quoted - .' WHERE '; - $conditions = array(); - $new_values = array(); - $null_values = array(); - for ($i=0; $i OLD.'.$referenced_fields[$i]; - } - $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL' - .' AND (' .implode(' OR ', $conditions2) .')' - .' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();' - .' END IF;'; - - $cascade_action_update = 'UPDATE '.$table_quoted.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions). ';'; - $cascade_action_delete = 'DELETE FROM '.$table_quoted.' WHERE '.implode(' AND ', $conditions). ';'; - $setnull_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions). ';'; - - if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) { - $db->loadModule('Reverse', null, true); - $default_values = array(); - foreach ($table_fields as $table_field) { - $field_definition = $db->reverse->getTableFieldDefinition($table, $field); - if (PEAR::isError($field_definition)) { - return $field_definition; - } - $default_values[] = $table_field .' = '. $field_definition[0]['default']; - } - $setdefault_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions). ';'; - } - - $query = 'CREATE TRIGGER %s' - .' %s ON '.$fkdef['references']['table'] - .' FOR EACH ROW BEGIN ' - .' SET FOREIGN_KEY_CHECKS = 0; '; //only really needed for ON UPDATE CASCADE - - if ('CASCADE' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $cascade_action_update; - } elseif ('SET NULL' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action; - } elseif ('SET DEFAULT' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action; - } elseif ('NO ACTION' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update'); - } elseif ('RESTRICT' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update'); - } - if ('CASCADE' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $cascade_action_delete; - } elseif ('SET NULL' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action; - } elseif ('SET DEFAULT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action; - } elseif ('NO ACTION' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete'); - } elseif ('RESTRICT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete'); - } - $sql_update .= ' SET FOREIGN_KEY_CHECKS = 1; END;'; - $sql_delete .= ' SET FOREIGN_KEY_CHECKS = 1; END;'; - - $db->pushErrorHandling(PEAR_ERROR_RETURN); - $db->expectError(MDB2_ERROR_CANNOT_CREATE); - $result = $db->exec($sql_delete); - $expected_errmsg = 'This MySQL version doesn\'t support multiple triggers with the same action time and event for one table'; - $db->popExpect(); - $db->popErrorHandling(); - if (PEAR::isError($result)) { - if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) { - return $result; - } - $db->warnings[] = $expected_errmsg; - } - $db->pushErrorHandling(PEAR_ERROR_RETURN); - $db->expectError(MDB2_ERROR_CANNOT_CREATE); - $result = $db->exec($sql_update); - $db->popExpect(); - $db->popErrorHandling(); - if (PEAR::isError($result) && $result->getCode() != MDB2_ERROR_CANNOT_CREATE) { - if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) { - return $result; - } - $db->warnings[] = $expected_errmsg; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ _dropFKTriggers() - - /** - * Drop the triggers created to enforce the FOREIGN KEY constraint on the table - * - * @param string $table table name - * @param string $fkname FOREIGN KEY constraint name - * @param string $referenced_table referenced table name - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access private - */ - function _dropFKTriggers($table, $fkname, $referenced_table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $triggers = $this->listTableTriggers($table); - $triggers2 = $this->listTableTriggers($referenced_table); - if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) { - $triggers = array_merge($triggers, $triggers2); - $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i'; - foreach ($triggers as $trigger) { - if (preg_match($pattern, $trigger)) { - $result = $db->exec('DROP TRIGGER '.$trigger); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ listTableConstraints() - - /** - * list all constraints in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of constraint names on success, a MDB2 error on failure - * @access public - */ - function listTableConstraints($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $key_name = 'Key_name'; - $non_unique = 'Non_unique'; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - $non_unique = strtolower($non_unique); - } else { - $key_name = strtoupper($key_name); - $non_unique = strtoupper($non_unique); - } - } - - $query = 'SHOW INDEX FROM ' . $db->quoteIdentifier($table, true); - $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $index_data) { - if (!$index_data[$non_unique]) { - if ($index_data[$key_name] !== 'PRIMARY') { - $index = $this->_fixIndexName($index_data[$key_name]); - } else { - $index = 'PRIMARY'; - } - if (!empty($index)) { - $result[$index] = true; - } - } - } - - //list FOREIGN KEY constraints... - $query = 'SHOW CREATE TABLE '. $db->escape($table); - $definition = $db->queryOne($query, 'text', 1); - if (!PEAR::isError($definition) && !empty($definition)) { - $pattern = '/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN KEY\b/Uims'; - if (preg_match_all($pattern, str_replace('`', '', $definition), $matches) > 0) { - foreach ($matches[1] as $constraint) { - $result[$constraint] = true; - } - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($result); - } - - // }}} - // {{{ createSequence() - - /** - * create sequence - * - * @param string $seq_name name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createSequence($seq_name, $start = 1, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true); - - $options_strings = array(); - - if (!empty($options['comment'])) { - $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text'); - } - - if (!empty($options['charset'])) { - $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; - if (!empty($options['collate'])) { - $options_strings['charset'].= ' COLLATE '.$options['collate']; - } - } - - $type = false; - if (!empty($options['type'])) { - $type = $options['type']; - } elseif ($db->options['default_table_type']) { - $type = $db->options['default_table_type']; - } - if ($type) { - $options_strings[] = "ENGINE = $type"; - } - - $query = "CREATE TABLE $sequence_name ($seqcol_name INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ($seqcol_name))"; - if (!empty($options_strings)) { - $query .= ' '.implode(' ', $options_strings); - } - $res = $db->exec($query); - if (PEAR::isError($res)) { - return $res; - } - - if ($start == 1) { - return MDB2_OK; - } - - $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')'; - $res = $db->exec($query); - if (!PEAR::isError($res)) { - return MDB2_OK; - } - - // Handle error - $result = $db->exec("DROP TABLE $sequence_name"); - if (PEAR::isError($result)) { - return $db->raiseError($result, null, null, - 'could not drop inconsistent sequence table', __FUNCTION__); - } - - return $db->raiseError($res, null, null, - 'could not create sequence table', __FUNCTION__); - } - - // }}} - // {{{ dropSequence() - - /** - * drop existing sequence - * - * @param string $seq_name name of the sequence to be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropSequence($seq_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - return $db->exec("DROP TABLE $sequence_name"); - } - - // }}} - // {{{ listSequences() - - /** - * list all sequences in the current database - * - * @param string database, the current is default - * @return mixed array of sequence names on success, a MDB2 error on failure - * @access public - */ - function listSequences($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SHOW TABLES"; - if (!is_null($database)) { - $query .= " FROM $database"; - } - $table_names = $db->queryCol($query); - if (PEAR::isError($table_names)) { - return $table_names; - } - - $result = array(); - foreach ($table_names as $table_name) { - if ($sqn = $this->_fixSequenceName($table_name, true)) { - $result[] = $sqn; - } - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Manager/pgsql.php b/3rdparty/MDB2/Driver/Manager/pgsql.php deleted file mode 100644 index 44a611d399..0000000000 --- a/3rdparty/MDB2/Driver/Manager/pgsql.php +++ /dev/null @@ -1,951 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php,v 1.87 2008/11/29 14:09:59 afz Exp $ - -require_once('MDB2/Driver/Manager/Common.php'); - -/** - * MDB2 MySQL driver for the management modules - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -class MDB2_Driver_Manager_pgsql extends MDB2_Driver_Manager_Common -{ - // {{{ createDatabase() - - /** - * create a new database - * - * @param string $name name of the database that should be created - * @param array $options array with charset info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createDatabase($name, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - $query = 'CREATE DATABASE ' . $name; - if (!empty($options['charset'])) { - $query .= ' WITH ENCODING ' . $db->quote($options['charset'], 'text'); - } - return $db->standaloneQuery($query, null, true); - } - - // }}} - // {{{ alterDatabase() - - /** - * alter an existing database - * - * @param string $name name of the database that is intended to be changed - * @param array $options array with name, owner info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function alterDatabase($name, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true); - if (!empty($options['name'])) { - $query .= ' RENAME TO ' . $options['name']; - } - if (!empty($options['owner'])) { - $query .= ' OWNER TO ' . $options['owner']; - } - return $db->standaloneQuery($query, null, true); - } - - // }}} - // {{{ dropDatabase() - - /** - * drop an existing database - * - * @param string $name name of the database that should be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropDatabase($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - $query = "DROP DATABASE $name"; - return $db->standaloneQuery($query, null, true); - } - - // }}} - // {{{ _getAdvancedFKOptions() - - /** - * Return the FOREIGN KEY query section dealing with non-standard options - * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... - * - * @param array $definition - * @return string - * @access protected - */ - function _getAdvancedFKOptions($definition) - { - $query = ''; - if (!empty($definition['match'])) { - $query .= ' MATCH '.$definition['match']; - } - if (!empty($definition['onupdate'])) { - $query .= ' ON UPDATE '.$definition['onupdate']; - } - if (!empty($definition['ondelete'])) { - $query .= ' ON DELETE '.$definition['ondelete']; - } - if (!empty($definition['deferrable'])) { - $query .= ' DEFERRABLE'; - } else { - $query .= ' NOT DEFERRABLE'; - } - if (!empty($definition['initiallydeferred'])) { - $query .= ' INITIALLY DEFERRED'; - } else { - $query .= ' INITIALLY IMMEDIATE'; - } - return $query; - } - - // }}} - // {{{ truncateTable() - - /** - * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported, - * it falls back to a DELETE FROM TABLE query) - * - * @param string $name name of the table that should be truncated - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function truncateTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("TRUNCATE TABLE $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $query = 'VACUUM'; - - if (!empty($options['full'])) { - $query .= ' FULL'; - } - if (!empty($options['freeze'])) { - $query .= ' FREEZE'; - } - if (!empty($options['analyze'])) { - $query .= ' ANALYZE'; - } - - if (!empty($table)) { - $query .= ' '.$db->quoteIdentifier($table, true); - } - return $db->exec($query); - } - - // }}} - // {{{ alterTable() - - /** - * alter an existing table - * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: - * - * name - * - * New name for the table. - * - * add - * - * Associative array with the names of fields to be added as - * indexes of the array. The value of each entry of the array - * should be set to another associative array with the properties - * of the fields to be added. The properties of the fields should - * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @access public - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - */ - function alterTable($name, $changes, $check) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - foreach ($changes as $change_name => $change) { - switch ($change_name) { - case 'add': - case 'remove': - case 'change': - case 'name': - case 'rename': - break; - default: - return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, - 'change type "'.$change_name.'\" not yet supported', __FUNCTION__); - } - } - - if ($check) { - return MDB2_OK; - } - - $name = $db->quoteIdentifier($name, true); - - if (!empty($changes['remove']) && is_array($changes['remove'])) { - foreach ($changes['remove'] as $field_name => $field) { - $field_name = $db->quoteIdentifier($field_name, true); - $query = 'DROP ' . $field_name; - $result = $db->exec("ALTER TABLE $name $query"); - if (PEAR::isError($result)) { - return $result; - } - } - } - - if (!empty($changes['rename']) && is_array($changes['rename'])) { - foreach ($changes['rename'] as $field_name => $field) { - $field_name = $db->quoteIdentifier($field_name, true); - $result = $db->exec("ALTER TABLE $name RENAME COLUMN $field_name TO ".$db->quoteIdentifier($field['name'], true)); - if (PEAR::isError($result)) { - return $result; - } - } - } - - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $field_name => $field) { - $query = 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field); - $result = $db->exec("ALTER TABLE $name $query"); - if (PEAR::isError($result)) { - return $result; - } - } - } - - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $field_name => $field) { - $field_name = $db->quoteIdentifier($field_name, true); - if (!empty($field['definition']['type'])) { - $server_info = $db->getServerVersion(); - if (PEAR::isError($server_info)) { - return $server_info; - } - if (is_array($server_info) && $server_info['major'] < 8) { - return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, - 'changing column type for "'.$change_name.'\" requires PostgreSQL 8.0 or above', __FUNCTION__); - } - $db->loadModule('Datatype', null, true); - $type = $db->datatype->getTypeDeclaration($field['definition']); - if($type=='SERIAL PRIMARY KEY'){//not correct when altering a table, since serials arent a real type - $type='INTEGER';//use integer instead - } - $query = "ALTER $field_name TYPE $type USING CAST($field_name AS $type)"; - $result = $db->exec("ALTER TABLE $name $query"); - if (PEAR::isError($result)) { - return $result; - } - } - if (array_key_exists('default', $field['definition'])) { - $query = "ALTER $field_name SET DEFAULT ".$db->quote($field['definition']['default'], $field['definition']['type']); - $result = $db->exec("ALTER TABLE $name $query"); - if (PEAR::isError($result)) { - return $result; - } - } - if (!empty($field['definition']['notnull'])) { - $query = "ALTER $field_name ".($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL'; - $result = $db->exec("ALTER TABLE $name $query"); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - - if (!empty($changes['name'])) { - $change_name = $db->quoteIdentifier($changes['name'], true); - $result = $db->exec("ALTER TABLE $name RENAME TO ".$change_name); - if (PEAR::isError($result)) { - return $result; - } - } - - return MDB2_OK; - } - - // }}} - // {{{ listDatabases() - - /** - * list all databases - * - * @return mixed array of database names on success, a MDB2 error on failure - * @access public - */ - function listDatabases() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SELECT datname FROM pg_database'; - $result2 = $db->standaloneQuery($query, array('text'), false); - if (!MDB2::isResultCommon($result2)) { - return $result2; - } - - $result = $result2->fetchCol(); - $result2->free(); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listUsers() - - /** - * list all users - * - * @return mixed array of user names on success, a MDB2 error on failure - * @access public - */ - function listUsers() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SELECT usename FROM pg_user'; - $result2 = $db->standaloneQuery($query, array('text'), false); - if (!MDB2::isResultCommon($result2)) { - return $result2; - } - - $result = $result2->fetchCol(); - $result2->free(); - return $result; - } - - // }}} - // {{{ listViews() - - /** - * list all views in the current database - * - * @return mixed array of view names on success, a MDB2 error on failure - * @access public - */ - function listViews($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT viewname - FROM pg_views - WHERE schemaname NOT IN ('pg_catalog', 'information_schema') - AND viewname !~ '^pg_'"; - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTableViews() - - /** - * list the views in the database that reference a given table - * - * @param string table for which all referenced views should be found - * @return mixed array of view names on success, a MDB2 error on failure - * @access public - */ - function listTableViews($table) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SELECT viewname FROM pg_views NATURAL JOIN pg_tables'; - $query.= ' WHERE tablename ='.$db->quote($table, 'text'); - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listFunctions() - - /** - * list all functions in the current database - * - * @return mixed array of function names on success, a MDB2 error on failure - * @access public - */ - function listFunctions() - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = " - SELECT - proname - FROM - pg_proc pr, - pg_type tp - WHERE - tp.oid = pr.prorettype - AND pr.proisagg = FALSE - AND tp.typname <> 'trigger' - AND pr.pronamespace IN - (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')"; - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTableTriggers() - - /** - * list all triggers in the database that reference a given table - * - * @param string table for which all referenced triggers should be found - * @return mixed array of trigger names on success, a MDB2 error on failure - * @access public - */ - function listTableTriggers($table = null) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SELECT trg.tgname AS trigger_name - FROM pg_trigger trg, - pg_class tbl - WHERE trg.tgrelid = tbl.oid'; - if (!is_null($table)) { - $table = $db->quote(strtoupper($table), 'text'); - $query .= " AND tbl.relname = $table"; - } - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTables() - - /** - * list all tables in the current database - * - * @return mixed array of table names on success, a MDB2 error on failure - * @access public - */ - function listTables($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - // gratuitously stolen from PEAR DB _getSpecialQuery in pgsql.php - $query = 'SELECT c.relname AS "Name"' - . ' FROM pg_class c, pg_user u' - . ' WHERE c.relowner = u.usesysid' - . " AND c.relkind = 'r'" - . ' AND NOT EXISTS' - . ' (SELECT 1 FROM pg_views' - . ' WHERE viewname = c.relname)' - . " AND c.relname !~ '^(pg_|sql_)'" - . ' UNION' - . ' SELECT c.relname AS "Name"' - . ' FROM pg_class c' - . " WHERE c.relkind = 'r'" - . ' AND NOT EXISTS' - . ' (SELECT 1 FROM pg_views' - . ' WHERE viewname = c.relname)' - . ' AND NOT EXISTS' - . ' (SELECT 1 FROM pg_user' - . ' WHERE usesysid = c.relowner)' - . " AND c.relname !~ '^pg_'"; - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTableFields() - - /** - * list all fields in a table in the current database - * - * @param string $table name of table that should be used in method - * @return mixed array of field names on success, a MDB2 error on failure - * @access public - */ - function listTableFields($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table); - - $table = $db->quoteIdentifier($table, true); - if (!empty($schema)) { - $table = $db->quoteIdentifier($schema, true) . '.' .$table; - } - $db->setLimit(1); - $result2 = $db->query("SELECT * FROM $table LIMIT 1"); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $result2->getColumnNames(); - $result2->free(); - if (PEAR::isError($result)) { - return $result; - } - return array_flip($result); - } - - // }}} - // {{{ listTableIndexes() - - /** - * list all indexes in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of index names on success, a MDB2 error on failure - * @access public - */ - function listTableIndexes($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table); - - $table = $db->quote($table, 'text'); - $subquery = "SELECT indexrelid - FROM pg_index - LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid - LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid - WHERE pg_class.relname = $table - AND indisunique != 't' - AND indisprimary != 't'"; - if (!empty($schema)) { - $subquery .= ' AND pg_namespace.nspname = '.$db->quote($schema, 'text'); - } - $query = "SELECT relname FROM pg_class WHERE oid IN ($subquery)"; - $indexes = $db->queryCol($query, 'text'); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $index) { - $index = $this->_fixIndexName($index); - if (!empty($index)) { - $result[$index] = true; - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($result); - } - - // }}} - // {{{ dropConstraint() - - /** - * drop existing constraint - * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropConstraint($table, $name, $primary = false) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - // is it an UNIQUE index? - $query = 'SELECT relname - FROM pg_class - WHERE oid IN ( - SELECT indexrelid - FROM pg_index, pg_class - WHERE pg_class.relname = '.$db->quote($table, 'text').' - AND pg_class.oid = pg_index.indrelid - AND indisunique = \'t\') - EXCEPT - SELECT conname - FROM pg_constraint, pg_class - WHERE pg_constraint.conrelid = pg_class.oid - AND relname = '. $db->quote($table, 'text'); - $unique = $db->queryCol($query, 'text'); - if (PEAR::isError($unique) || empty($unique)) { - // not an UNIQUE index, maybe a CONSTRAINT - return parent::dropConstraint($table, $name, $primary); - } - - if (in_array($name, $unique)) { - return $db->exec('DROP INDEX '.$db->quoteIdentifier($name, true)); - } - $idxname = $db->getIndexName($name); - if (in_array($idxname, $unique)) { - return $db->exec('DROP INDEX '.$db->quoteIdentifier($idxname, true)); - } - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $name . ' is not an existing constraint for table ' . $table, __FUNCTION__); - } - - // }}} - // {{{ listTableConstraints() - - /** - * list all constraints in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of constraint names on success, a MDB2 error on failure - * @access public - */ - function listTableConstraints($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table); - - $table = $db->quote($table, 'text'); - $query = 'SELECT conname - FROM pg_constraint - LEFT JOIN pg_class ON pg_constraint.conrelid = pg_class.oid - LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid - WHERE relname = ' .$table; - if (!empty($schema)) { - $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text'); - } - $query .= ' - UNION DISTINCT - SELECT relname - FROM pg_class - WHERE oid IN ( - SELECT indexrelid - FROM pg_index - LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid - LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid - WHERE pg_class.relname = '.$table.' - AND indisunique = \'t\''; - if (!empty($schema)) { - $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text'); - } - $query .= ')'; - $constraints = $db->queryCol($query); - if (PEAR::isError($constraints)) { - return $constraints; - } - - $result = array(); - foreach ($constraints as $constraint) { - $constraint = $this->_fixIndexName($constraint); - if (!empty($constraint)) { - $result[$constraint] = true; - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE - && $db->options['field_case'] == CASE_LOWER - ) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($result); - } - - // }}} - // {{{ createSequence() - - /** - * create sequence - * - * @param string $seq_name name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createSequence($seq_name, $start = 1) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - return $db->exec("CREATE SEQUENCE $sequence_name INCREMENT 1". - ($start < 1 ? " MINVALUE $start" : '')." START $start"); - } - - // }}} - // {{{ dropSequence() - - /** - * drop existing sequence - * - * @param string $seq_name name of the sequence to be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropSequence($seq_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - return $db->exec("DROP SEQUENCE $sequence_name"); - } - - // }}} - // {{{ listSequences() - - /** - * list all sequences in the current database - * - * @return mixed array of sequence names on success, a MDB2 error on failure - * @access public - */ - function listSequences($database = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT relname FROM pg_class WHERE relkind = 'S' AND relnamespace IN"; - $query.= "(SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')"; - $table_names = $db->queryCol($query); - if (PEAR::isError($table_names)) { - return $table_names; - } - $result = array(); - foreach ($table_names as $table_name) { - $result[] = $this->_fixSequenceName($table_name); - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Manager/sqlite.php b/3rdparty/MDB2/Driver/Manager/sqlite.php deleted file mode 100644 index 1b7239876f..0000000000 --- a/3rdparty/MDB2/Driver/Manager/sqlite.php +++ /dev/null @@ -1,1366 +0,0 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.76 2008/05/31 11:48:48 quipo Exp $ -// - -require_once('MDB2/Driver/Manager/Common.php'); - -/** - * MDB2 SQLite driver for the management modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - * @author Lorenzo Alberton - */ -class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common -{ - // {{{ createDatabase() - - /** - * create a new database - * - * @param string $name name of the database that should be created - * @param array $options array with charset info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createDatabase($name, $options = array()) - { - $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $database_file = $db->_getDatabaseFile($name); - if (file_exists($database_file)) { - return $db->raiseError(MDB2_ERROR_ALREADY_EXISTS, null, null, - 'database already exists', __FUNCTION__); - } - $php_errormsg = ''; - $database_file="$datadir/$database_file.db"; - $handle = sqlite_open($database_file, $db->dsn['mode'], $php_errormsg); - if (!$handle) { - return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null, - (isset($php_errormsg) ? $php_errormsg : 'could not create the database file'), __FUNCTION__); - } - if (!empty($options['charset'])) { - $query = 'PRAGMA encoding = ' . $db->quote($options['charset'], 'text'); - @sqlite_query($query, $handle); - } - @sqlite_close($handle); - return MDB2_OK; - } - - // }}} - // {{{ dropDatabase() - - /** - * drop an existing database - * - * @param string $name name of the database that should be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropDatabase($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $database_file = $db->_getDatabaseFile($name); - if (!@file_exists($database_file)) { - return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null, - 'database does not exist', __FUNCTION__); - } - $result = @unlink($database_file); - if (!$result) { - return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null, - (isset($php_errormsg) ? $php_errormsg : 'could not remove the database file'), __FUNCTION__); - } - return MDB2_OK; - } - - // }}} - // {{{ _getAdvancedFKOptions() - - /** - * Return the FOREIGN KEY query section dealing with non-standard options - * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... - * - * @param array $definition - * @return string - * @access protected - */ - function _getAdvancedFKOptions($definition) - { - $query = ''; - if (!empty($definition['match'])) { - $query .= ' MATCH '.$definition['match']; - } - if (!empty($definition['onupdate']) && (strtoupper($definition['onupdate']) != 'NO ACTION')) { - $query .= ' ON UPDATE '.$definition['onupdate']; - } - if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) { - $query .= ' ON DELETE '.$definition['ondelete']; - } - if (!empty($definition['deferrable'])) { - $query .= ' DEFERRABLE'; - } else { - $query .= ' NOT DEFERRABLE'; - } - if (!empty($definition['initiallydeferred'])) { - $query .= ' INITIALLY DEFERRED'; - } else { - $query .= ' INITIALLY IMMEDIATE'; - } - return $query; - } - - // }}} - // {{{ _getCreateTableQuery() - - /** - * Create a basic SQL query for a new table creation - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * @param array $options An associative array of table options - * @return mixed string (the SQL query) on success, a MDB2 error on failure - * @see createTable() - */ - function _getCreateTableQuery($name, $fields, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!$name) { - return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null, - 'no valid table name specified', __FUNCTION__); - } - if (empty($fields)) { - return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null, - 'no fields specified for table "'.$name.'"', __FUNCTION__); - } - $query_fields = $this->getFieldDeclarationList($fields); - if (PEAR::isError($query_fields)) { - return $query_fields; - } - if (!empty($options['primary'])) { - $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')'; - } - if (!empty($options['foreign_keys'])) { - foreach ($options['foreign_keys'] as $fkname => $fkdef) { - if (empty($fkdef)) { - continue; - } - $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', ', array_keys($fkdef['fields'])).')'; - $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', ', array_keys($fkdef['references']['fields'])).')'; - $query_fields.= $this->_getAdvancedFKOptions($fkdef); - } - } - - $name = $db->quoteIdentifier($name, true); - $result = 'CREATE '; - if (!empty($options['temporary'])) { - $result .= $this->_getTemporaryTableQuery(); - } - $result .= " TABLE $name ($query_fields)"; - return $result; - } - - // }}} - // {{{ createTable() - - /** - * create a new table - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition - * of each field of the new table - * @param array $options An associative array of table options - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createTable($name, $fields, $options = array()) - { - $result = parent::createTable($name, $fields, $options); - if (PEAR::isError($result)) { - return $result; - } - // create triggers to enforce FOREIGN KEY constraints - if (!empty($options['foreign_keys'])) { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - foreach ($options['foreign_keys'] as $fkname => $fkdef) { - if (empty($fkdef)) { - continue; - } - //set actions to default if not set - $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']); - $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']); - - $trigger_names = array( - 'insert' => $fkname.'_insert_trg', - 'update' => $fkname.'_update_trg', - 'pk_update' => $fkname.'_pk_update_trg', - 'pk_delete' => $fkname.'_pk_delete_trg', - ); - - //create the [insert|update] triggers on the FK table - $table_fields = array_keys($fkdef['fields']); - $referenced_fields = array_keys($fkdef['references']['fields']); - $query = 'CREATE TRIGGER %s BEFORE %s ON '.$name - .' FOR EACH ROW BEGIN' - .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')' - .' WHERE (SELECT '; - $aliased_fields = array(); - foreach ($referenced_fields as $field) { - $aliased_fields[] = $fkdef['references']['table'] .'.'.$field .' AS '.$field; - } - $query .= implode(',', $aliased_fields) - .' FROM '.$fkdef['references']['table'] - .' WHERE '; - $conditions = array(); - for ($i=0; $iexec(sprintf($query, $trigger_names['insert'], 'INSERT', 'insert')); - if (PEAR::isError($result)) { - return $result; - } - - $result = $db->exec(sprintf($query, $trigger_names['update'], 'UPDATE', 'update')); - if (PEAR::isError($result)) { - return $result; - } - - //create the ON [UPDATE|DELETE] triggers on the primary table - $restrict_action = 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')' - .' WHERE (SELECT '; - $aliased_fields = array(); - foreach ($table_fields as $field) { - $aliased_fields[] = $name .'.'.$field .' AS '.$field; - } - $restrict_action .= implode(',', $aliased_fields) - .' FROM '.$name - .' WHERE '; - $conditions = array(); - $new_values = array(); - $null_values = array(); - for ($i=0; $i OLD.'.$referenced_fields[$i]; - } - $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL' - .' AND (' .implode(' OR ', $conditions2) .')'; - - $cascade_action_update = 'UPDATE '.$name.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions); - $cascade_action_delete = 'DELETE FROM '.$name.' WHERE '.implode(' AND ', $conditions); - $setnull_action = 'UPDATE '.$name.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions); - - if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) { - $db->loadModule('Reverse', null, true); - $default_values = array(); - foreach ($table_fields as $table_field) { - $field_definition = $db->reverse->getTableFieldDefinition($name, $field); - if (PEAR::isError($field_definition)) { - return $field_definition; - } - $default_values[] = $table_field .' = '. $field_definition[0]['default']; - } - $setdefault_action = 'UPDATE '.$name.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions); - } - - $query = 'CREATE TRIGGER %s' - .' %s ON '.$fkdef['references']['table'] - .' FOR EACH ROW BEGIN '; - - if ('CASCADE' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . $cascade_action_update. '; END;'; - } elseif ('SET NULL' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action. '; END;'; - } elseif ('SET DEFAULT' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action. '; END;'; - } elseif ('NO ACTION' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . '; END;'; - } elseif ('RESTRICT' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . '; END;'; - } - if ('CASCADE' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . $cascade_action_delete. '; END;'; - } elseif ('SET NULL' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action. '; END;'; - } elseif ('SET DEFAULT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action. '; END;'; - } elseif ('NO ACTION' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . '; END;'; - } elseif ('RESTRICT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . '; END;'; - } - - if (PEAR::isError($result)) { - return $result; - } - $result = $db->exec($sql_delete); - if (PEAR::isError($result)) { - return $result; - } - $result = $db->exec($sql_update); - if (PEAR::isError($result)) { - return $result; - } - } - } - if (PEAR::isError($result)) { - return $result; - } - return MDB2_OK; - } - - // }}} - // {{{ dropTable() - - /** - * drop an existing table - * - * @param string $name name of the table that should be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - //delete the triggers associated to existing FK constraints - $constraints = $this->listTableConstraints($name); - if (!PEAR::isError($constraints) && !empty($constraints)) { - $db->loadModule('Reverse', null, true); - foreach ($constraints as $constraint) { - $definition = $db->reverse->getTableConstraintDefinition($name, $constraint); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("DROP TABLE $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'VACUUM'; - if (!empty($table)) { - $query .= ' '.$db->quoteIdentifier($table, true); - } - return $db->exec($query); - } - - // }}} - // {{{ alterTable() - - /** - * alter an existing table - * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: - * - * name - * - * New name for the table. - * - * add - * - * Associative array with the names of fields to be added as - * indexes of the array. The value of each entry of the array - * should be set to another associative array with the properties - * of the fields to be added. The properties of the fields should - * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @access public - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - */ - function alterTable($name, $changes, $check, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - foreach ($changes as $change_name => $change) { - switch ($change_name) { - case 'add': - case 'remove': - case 'change': - case 'name': - case 'rename': - break; - default: - return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, - 'change type "'.$change_name.'" not yet supported', __FUNCTION__); - } - } - - if ($check) { - return MDB2_OK; - } - - $db->loadModule('Reverse', null, true); - - // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it - $fields = $db->manager->listTableFields($name); - if (PEAR::isError($fields)) { - return $fields; - } - - $fields = array_flip($fields); - foreach ($fields as $field => $value) { - $definition = $db->reverse->getTableFieldDefinition($name, $field); - if (PEAR::isError($definition)) { - return $definition; - } - $fields[$field] = $definition[0]; - } - - $indexes = $db->manager->listTableIndexes($name); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $indexes = array_flip($indexes); - foreach ($indexes as $index => $value) { - $definition = $db->reverse->getTableIndexDefinition($name, $index); - if (PEAR::isError($definition)) { - return $definition; - } - $indexes[$index] = $definition; - } - - $constraints = $db->manager->listTableConstraints($name); - if (PEAR::isError($constraints)) { - return $constraints; - } - - if (!array_key_exists('foreign_keys', $options)) { - $options['foreign_keys'] = array(); - } - $constraints = array_flip($constraints); - foreach ($constraints as $constraint => $value) { - if (!empty($definition['primary'])) { - if (!array_key_exists('primary', $options)) { - $options['primary'] = $definition['fields']; - //remove from the $constraint array, it's already handled by createTable() - unset($constraints[$constraint]); - } - } else { - $c_definition = $db->reverse->getTableConstraintDefinition($name, $constraint); - if (PEAR::isError($c_definition)) { - return $c_definition; - } - if (!empty($c_definition['foreign'])) { - if (!array_key_exists($constraint, $options['foreign_keys'])) { - $options['foreign_keys'][$constraint] = $c_definition; - } - //remove from the $constraint array, it's already handled by createTable() - unset($constraints[$constraint]); - } else { - $constraints[$constraint] = $c_definition; - } - } - } - - $name_new = $name; - $create_order = $select_fields = array_keys($fields); - foreach ($changes as $change_name => $change) { - switch ($change_name) { - case 'add': - foreach ($change as $field_name => $field) { - $fields[$field_name] = $field; - $create_order[] = $field_name; - } - break; - case 'remove': - foreach ($change as $field_name => $field) { - unset($fields[$field_name]); - $select_fields = array_diff($select_fields, array($field_name)); - $create_order = array_diff($create_order, array($field_name)); - } - break; - case 'change': - foreach ($change as $field_name => $field) { - $fields[$field_name] = $field['definition']; - } - break; - case 'name': - $name_new = $change; - break; - case 'rename': - foreach ($change as $field_name => $field) { - unset($fields[$field_name]); - $fields[$field['name']] = $field['definition']; - $create_order[array_search($field_name, $create_order)] = $field['name']; - } - break; - default: - return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, - 'change type "'.$change_name.'" not yet supported', __FUNCTION__); - } - } - - $data = null; - if (!empty($select_fields)) { - $query = 'SELECT '.implode(', ', $select_fields).' FROM '.$db->quoteIdentifier($name, true); - $data = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED); - } - - $result = $this->dropTable($name); - if (PEAR::isError($result)) { - return $result; - } - - $result = $this->createTable($name_new, $fields, $options); - if (PEAR::isError($result)) { - return $result; - } - - foreach ($indexes as $index => $definition) { - $this->createIndex($name_new, $index, $definition); - } - - foreach ($constraints as $constraint => $definition) { - if(empty($definition['primary']) and empty($definition['foreign'])){ - $this->createConstraint($name_new, $constraint, $definition); - } - } - - if (!empty($select_fields) && !empty($data)) { - $query = 'INSERT INTO '.$db->quoteIdentifier($name_new, true); - $query.= '('.implode(', ', array_slice(array_keys($fields), 0, count($select_fields))).')'; - $query.=' VALUES (?'.str_repeat(', ?', (count($select_fields) - 1)).')'; - $stmt =$db->prepare($query, null, MDB2_PREPARE_MANIP); - if (PEAR::isError($stmt)) { - return $stmt; - } - foreach ($data as $row) { - $result = $stmt->execute($row); - if (PEAR::isError($result)) { - return $result; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ listDatabases() - - /** - * list all databases - * - * @return mixed array of database names on success, a MDB2 error on failure - * @access public - */ - function listDatabases() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'list databases is not supported', __FUNCTION__); - } - - // }}} - // {{{ listUsers() - - /** - * list all users - * - * @return mixed array of user names on success, a MDB2 error on failure - * @access public - */ - function listUsers() - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'list databases is not supported', __FUNCTION__); - } - - // }}} - // {{{ listViews() - - /** - * list all views in the current database - * - * @return mixed array of view names on success, a MDB2 error on failure - * @access public - */ - function listViews($dummy=null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL"; - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTableViews() - - /** - * list the views in the database that reference a given table - * - * @param string table for which all referenced views should be found - * @return mixed array of view names on success, a MDB2 error on failure - * @access public - */ - function listTableViews($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL"; - $views = $db->queryAll($query, array('text', 'text'), MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($views)) { - return $views; - } - $result = array(); - foreach ($views as $row) { - if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) { - if (!empty($row['name'])) { - $result[$row['name']] = true; - } - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($result); - } - - // }}} - // {{{ listTables() - - /** - * list all tables in the current database - * - * @return mixed array of table names on success, a MDB2 error on failure - * @access public - */ - function listTables($dummy=null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; - $table_names = $db->queryCol($query); - if (PEAR::isError($table_names)) { - return $table_names; - } - $result = array(); - foreach ($table_names as $table_name) { - if (!$this->_fixSequenceName($table_name, true)) { - $result[] = $table_name; - } - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listTableFields() - - /** - * list all fields in a table in the current database - * - * @param string $table name of table that should be used in method - * @return mixed array of field names on success, a MDB2 error on failure - * @access public - */ - function listTableFields($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $result = $db->loadModule('Reverse', null, true); - if (PEAR::isError($result)) { - return $result; - } - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= 'name='.$db->quote($table, 'text'); - } - $sql = $db->queryOne($query); - if (PEAR::isError($sql)) { - return $sql; - } - $columns = $db->reverse->_getTableColumns($sql); - $fields = array(); - foreach ($columns as $column) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column['name'] = strtolower($column['name']); - } else { - $column['name'] = strtoupper($column['name']); - } - } else { - $column = array_change_key_case($column, $db->options['field_case']); - } - $fields[] = $column['name']; - } - return $fields; - } - - // }}} - // {{{ listTableTriggers() - - /** - * list all triggers in the database that reference a given table - * - * @param string table for which all referenced triggers should be found - * @return mixed array of trigger names on success, a MDB2 error on failure - * @access public - */ - function listTableTriggers($table = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL"; - if (!is_null($table)) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= ' AND tbl_name='.$db->quote($table, 'text'); - } - } - $result = $db->queryCol($query); - if (PEAR::isError($result)) { - return $result; - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ createIndex() - - /** - * Get the stucture of a field into an array - * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. - * - * Currently, only the sorting property is supported. It should be used - * to define the sorting direction of the index. It may be set to either - * ascending or descending. - * - * Not all DBMS support index sorting direction configuration. The DBMS - * drivers of those that do not support it ignore this property. Use the - * function support() to determine whether the DBMS driver can manage indexes. - - * Example - * array( - * 'fields' => array( - * 'user_name' => array( - * 'sorting' => 'ascending' - * ), - * 'last_login' => array() - * ) - * ) - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createIndex($table, $name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->getIndexName($name); - $query = "CREATE INDEX $name ON $table"; - $fields = array(); - foreach ($definition['fields'] as $field_name => $field) { - $field_string = $field_name; - if (!empty($field['sorting'])) { - switch ($field['sorting']) { - case 'ascending': - $field_string.= ' ASC'; - break; - case 'descending': - $field_string.= ' DESC'; - break; - } - } - $fields[] = $field_string; - } - $query .= ' ('.implode(', ', $fields) . ')'; - return $db->exec($query); - } - - // }}} - // {{{ dropIndex() - - /** - * drop existing index - * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropIndex($table, $name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->getIndexName($name); - return $db->exec("DROP INDEX $name"); - } - - // }}} - // {{{ listTableIndexes() - - /** - * list all indexes in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of index names on success, a MDB2 error on failure - * @access public - */ - function listTableIndexes($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quote($table, 'text'); - $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(tbl_name)='.strtolower($table); - } else { - $query.= "tbl_name=$table"; - } - $query.= " AND sql NOT NULL ORDER BY name"; - $indexes = $db->queryCol($query, 'text'); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $sql) { - if (preg_match("/^create index ([^ ]+) on /i", $sql, $tmp)) { - $index = $this->_fixIndexName($tmp[1]); - if (!empty($index)) { - $result[$index] = true; - } - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($result); - } - - // }}} - // {{{ createConstraint() - - /** - * create a constraint on a table - * - * @param string $table name of the table on which the constraint is to be created - * @param string $name name of the constraint to be created - * @param array $definition associative array that defines properties of the constraint to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. - * - * Example - * array( - * 'fields' => array( - * 'user_name' => array(), - * 'last_login' => array() - * ) - * ) - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createConstraint($table, $name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!empty($definition['primary'])) { - return $db->manager->alterTable($table, array(), false, array('primary' => $definition['fields'])); - } - - if (!empty($definition['foreign'])) { - return $db->manager->alterTable($table, array(), false, array('foreign_keys' => array($name => $definition))); - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->getIndexName($name); - $query = "CREATE UNIQUE INDEX $name ON $table"; - $fields = array(); - foreach ($definition['fields'] as $field_name => $field) { - $field_string = $field_name; - if (!empty($field['sorting'])) { - switch ($field['sorting']) { - case 'ascending': - $field_string.= ' ASC'; - break; - case 'descending': - $field_string.= ' DESC'; - break; - } - } - $fields[] = $field_string; - } - $query .= ' ('.implode(', ', $fields) . ')'; - return $db->exec($query); - } - - // }}} - // {{{ dropConstraint() - - /** - * drop existing constraint - * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropConstraint($table, $name, $primary = false) - { - if ($primary || $name == 'PRIMARY') { - return $this->alterTable($table, array(), false, array('primary' => null)); - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - //is it a FK constraint? If so, also delete the associated triggers - $db->loadModule('Reverse', null, true); - $definition = $db->reverse->getTableConstraintDefinition($table, $name); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - //first drop the FK enforcing triggers - $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - //then drop the constraint itself - return $this->alterTable($table, array(), false, array('foreign_keys' => array($name => null))); - } - - $name = $db->getIndexName($name); - return $db->exec("DROP INDEX $name"); - } - - // }}} - // {{{ _dropFKTriggers() - - /** - * Drop the triggers created to enforce the FOREIGN KEY constraint on the table - * - * @param string $table table name - * @param string $fkname FOREIGN KEY constraint name - * @param string $referenced_table referenced table name - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access private - */ - function _dropFKTriggers($table, $fkname, $referenced_table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $triggers = $this->listTableTriggers($table); - $triggers2 = $this->listTableTriggers($referenced_table); - if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) { - $triggers = array_merge($triggers, $triggers2); - $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i'; - foreach ($triggers as $trigger) { - if (preg_match($pattern, $trigger)) { - $result = $db->exec('DROP TRIGGER '.$trigger); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ listTableConstraints() - - /** - * list all constraints in a table - * - * @param string $table name of table that should be used in method - * @return mixed array of constraint names on success, a MDB2 error on failure - * @access public - */ - function listTableConstraints($table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $table = $db->quote($table, 'text'); - $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(tbl_name)='.strtolower($table); - } else { - $query.= "tbl_name=$table"; - } - $query.= " AND sql NOT NULL ORDER BY name"; - $indexes = $db->queryCol($query, 'text'); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $sql) { - if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) { - $index = $this->_fixIndexName($tmp[1]); - if (!empty($index)) { - $result[$index] = true; - } - } - } - - // also search in table definition for PRIMARY KEYs... - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.strtolower($table); - } else { - $query.= "name=$table"; - } - $query.= " AND sql NOT NULL ORDER BY name"; - $table_def = $db->queryOne($query, 'text'); - if (PEAR::isError($table_def)) { - return $table_def; - } - if (preg_match("/\bPRIMARY\s+KEY\b/i", $table_def, $tmp)) { - $result['primary'] = true; - } - - // ...and for FOREIGN KEYs - if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx", $table_def, $tmp)) { - foreach ($tmp[1] as $fk) { - $result[$fk] = true; - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($result); - } - - // }}} - // {{{ createSequence() - - /** - * create sequence - * - * @param string $seq_name name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createSequence($seq_name, $start = 1) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true); - $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)"; - $res = $db->exec($query); - if (PEAR::isError($res)) { - return $res; - } - if ($start == 1) { - return MDB2_OK; - } - $res = $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')'); - if (!PEAR::isError($res)) { - return MDB2_OK; - } - // Handle error - $result = $db->exec("DROP TABLE $sequence_name"); - if (PEAR::isError($result)) { - return $db->raiseError($result, null, null, - 'could not drop inconsistent sequence table', __FUNCTION__); - } - return $db->raiseError($res, null, null, - 'could not create sequence table', __FUNCTION__); - } - - // }}} - // {{{ dropSequence() - - /** - * drop existing sequence - * - * @param string $seq_name name of the sequence to be dropped - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function dropSequence($seq_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - return $db->exec("DROP TABLE $sequence_name"); - } - - // }}} - // {{{ listSequences() - - /** - * list all sequences in the current database - * - * @return mixed array of sequence names on success, a MDB2 error on failure - * @access public - */ - function listSequences($dummy=null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; - $table_names = $db->queryCol($query); - if (PEAR::isError($table_names)) { - return $table_names; - } - $result = array(); - foreach ($table_names as $table_name) { - if ($sqn = $this->_fixSequenceName($table_name, true)) { - $result[] = $sqn; - } - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} -} -?> diff --git a/3rdparty/MDB2/Driver/Native/Common.php b/3rdparty/MDB2/Driver/Native/Common.php deleted file mode 100644 index c01caa35b7..0000000000 --- a/3rdparty/MDB2/Driver/Native/Common.php +++ /dev/null @@ -1,61 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.2 2007/09/09 13:47:36 quipo Exp $ -// - -/** - * Base class for the natuve modules that is extended by each MDB2 driver - * - * To load this module in the MDB2 object: - * $mdb->loadModule('Native'); - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Native_Common extends MDB2_Module_Common -{ -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Native/mysql.php b/3rdparty/MDB2/Driver/Native/mysql.php deleted file mode 100644 index 90ff068e6f..0000000000 --- a/3rdparty/MDB2/Driver/Native/mysql.php +++ /dev/null @@ -1,60 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $ -// - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 MySQL driver for the native module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common -{ -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Native/pgsql.php b/3rdparty/MDB2/Driver/Native/pgsql.php deleted file mode 100644 index acab8389c8..0000000000 --- a/3rdparty/MDB2/Driver/Native/pgsql.php +++ /dev/null @@ -1,88 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php,v 1.12 2006/07/15 13:07:15 lsmith Exp $ - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 PostGreSQL driver for the native module - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -class MDB2_Driver_Native_pgsql extends MDB2_Driver_Native_Common -{ - // }}} - // {{{ deleteOID() - - /** - * delete an OID - * - * @param integer $OID - * @return mixed MDB2_OK on success or MDB2 Error Object on failure - * @access public - */ - function deleteOID($OID) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $connection = $db->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - if (!@pg_lo_unlink($connection, $OID)) { - return $db->raiseError(null, null, null, - 'Unable to unlink OID: '.$OID, __FUNCTION__); - } - return MDB2_OK; - } - -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Native/sqlite.php b/3rdparty/MDB2/Driver/Native/sqlite.php deleted file mode 100644 index 0213293a50..0000000000 --- a/3rdparty/MDB2/Driver/Native/sqlite.php +++ /dev/null @@ -1,60 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $ -// - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 SQLite driver for the native module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common -{ -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Reverse/Common.php b/3rdparty/MDB2/Driver/Reverse/Common.php deleted file mode 100644 index c78d84f760..0000000000 --- a/3rdparty/MDB2/Driver/Reverse/Common.php +++ /dev/null @@ -1,517 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.43 2009/01/14 15:01:21 quipo Exp $ -// - -/** - * @package MDB2 - * @category Database - */ - -/** - * These are constants for the tableInfo-function - * they are bitwised or'ed. so if there are more constants to be defined - * in the future, adjust MDB2_TABLEINFO_FULL accordingly - */ - -define('MDB2_TABLEINFO_ORDER', 1); -define('MDB2_TABLEINFO_ORDERTABLE', 2); -define('MDB2_TABLEINFO_FULL', 3); - -/** - * Base class for the schema reverse engineering module that is extended by each MDB2 driver - * - * To load this module in the MDB2 object: - * $mdb->loadModule('Reverse'); - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Reverse_Common extends MDB2_Module_Common -{ - // {{{ splitTableSchema() - - /** - * Split the "[owner|schema].table" notation into an array - * - * @param string $table [schema and] table name - * - * @return array array(schema, table) - * @access private - */ - function splitTableSchema($table) - { - $ret = array(); - if (strpos($table, '.') !== false) { - return explode('.', $table); - } - return array(null, $table); - } - - // }}} - // {{{ getTableFieldDefinition() - - /** - * Get the structure of a field into an array - * - * @param string $table name of table that should be used in method - * @param string $field name of field that should be used in method - * @return mixed data array on success, a MDB2 error on failure. - * The returned array contains an array for each field definition, - * with all or some of these indices, depending on the field data type: - * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type] - * @access public - */ - function getTableFieldDefinition($table, $field) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ getTableIndexDefinition() - - /** - * Get the structure of an index into an array - * - * @param string $table name of table that should be used in method - * @param string $index name of index that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * The returned array has this structure: - * - * array ( - * [fields] => array ( - * [field1name] => array() // one entry per each field covered - * [field2name] => array() // by the index - * [field3name] => array( - * [sorting] => ascending - * ) - * ) - * ); - * - * @access public - */ - function getTableIndexDefinition($table, $index) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ getTableConstraintDefinition() - - /** - * Get the structure of an constraints into an array - * - * @param string $table name of table that should be used in method - * @param string $index name of index that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * The returned array has this structure: - *
-     *          array (
-     *              [primary] => 0
-     *              [unique]  => 0
-     *              [foreign] => 1
-     *              [check]   => 0
-     *              [fields] => array (
-     *                  [field1name] => array() // one entry per each field covered
-     *                  [field2name] => array() // by the index
-     *                  [field3name] => array(
-     *                      [sorting]  => ascending
-     *                      [position] => 3
-     *                  )
-     *              )
-     *              [references] => array(
-     *                  [table] => name
-     *                  [fields] => array(
-     *                      [field1name] => array(  //one entry per each referenced field
-     *                           [position] => 1
-     *                      )
-     *                  )
-     *              )
-     *              [deferrable] => 0
-     *              [initiallydeferred] => 0
-     *              [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
-     *              [match] => SIMPLE|PARTIAL|FULL
-     *          );
-     *          
- * @access public - */ - function getTableConstraintDefinition($table, $index) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ getSequenceDefinition() - - /** - * Get the structure of a sequence into an array - * - * @param string $sequence name of sequence that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * The returned array has this structure: - *
-     *          array (
-     *              [start] => n
-     *          );
-     *          
- * @access public - */ - function getSequenceDefinition($sequence) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $start = $db->currId($sequence); - if (PEAR::isError($start)) { - return $start; - } - if ($db->supports('current_id')) { - $start++; - } else { - $db->warnings[] = 'database does not support getting current - sequence value, the sequence value was incremented'; - } - $definition = array(); - if ($start != 1) { - $definition = array('start' => $start); - } - return $definition; - } - - // }}} - // {{{ getTriggerDefinition() - - /** - * Get the structure of a trigger into an array - * - * EXPERIMENTAL - * - * WARNING: this function is experimental and may change the returned value - * at any time until labelled as non-experimental - * - * @param string $trigger name of trigger that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * The returned array has this structure: - *
-     *          array (
-     *              [trigger_name]    => 'trigger name',
-     *              [table_name]      => 'table name',
-     *              [trigger_body]    => 'trigger body definition',
-     *              [trigger_type]    => 'BEFORE' | 'AFTER',
-     *              [trigger_event]   => 'INSERT' | 'UPDATE' | 'DELETE'
-     *                  //or comma separated list of multiple events, when supported
-     *              [trigger_enabled] => true|false
-     *              [trigger_comment] => 'trigger comment',
-     *          );
-     *          
- * The oci8 driver also returns a [when_clause] index. - * @access public - */ - function getTriggerDefinition($trigger) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set - * - * The format of the resulting array depends on which $mode - * you select. The sample output below is based on this query: - *
-     *    SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
-     *    FROM tblFoo
-     *    JOIN tblBar ON tblFoo.fldId = tblBar.fldId
-     * 
- * - *
    - *
  • - * - * null (default) - *
    -     *   [0] => Array (
    -     *       [table] => tblFoo
    -     *       [name] => fldId
    -     *       [type] => int
    -     *       [len] => 11
    -     *       [flags] => primary_key not_null
    -     *   )
    -     *   [1] => Array (
    -     *       [table] => tblFoo
    -     *       [name] => fldPhone
    -     *       [type] => string
    -     *       [len] => 20
    -     *       [flags] =>
    -     *   )
    -     *   [2] => Array (
    -     *       [table] => tblBar
    -     *       [name] => fldId
    -     *       [type] => int
    -     *       [len] => 11
    -     *       [flags] => primary_key not_null
    -     *   )
    -     *   
    - * - *
  • - * - * MDB2_TABLEINFO_ORDER - * - *

    In addition to the information found in the default output, - * a notation of the number of columns is provided by the - * num_fields element while the order - * element provides an array with the column names as the keys and - * their location index number (corresponding to the keys in the - * the default output) as the values.

    - * - *

    If a result set has identical field names, the last one is - * used.

    - * - *
    -     *   [num_fields] => 3
    -     *   [order] => Array (
    -     *       [fldId] => 2
    -     *       [fldTrans] => 1
    -     *   )
    -     *   
    - * - *
  • - * - * MDB2_TABLEINFO_ORDERTABLE - * - *

    Similar to MDB2_TABLEINFO_ORDER but adds more - * dimensions to the array in which the table names are keys and - * the field names are sub-keys. This is helpful for queries that - * join tables which have identical field names.

    - * - *
    -     *   [num_fields] => 3
    -     *   [ordertable] => Array (
    -     *       [tblFoo] => Array (
    -     *           [fldId] => 0
    -     *           [fldPhone] => 1
    -     *       )
    -     *       [tblBar] => Array (
    -     *           [fldId] => 2
    -     *       )
    -     *   )
    -     *   
    - * - *
  • - *
- * - * The flags element contains a space separated list - * of extra information about the field. This data is inconsistent - * between DBMS's due to the way each DBMS works. - * + primary_key - * + unique_key - * + multiple_key - * + not_null - * - * Most DBMS's only provide the table and flags - * elements if $result is a table name. The following DBMS's - * provide full information from queries: - * + fbsql - * + mysql - * - * If the 'portability' option has MDB2_PORTABILITY_FIX_CASE - * turned on, the names of tables and fields will be lower or upper cased. - * - * @param object|string $result MDB2_result object from a query or a - * string containing the name of a table. - * While this also accepts a query result - * resource identifier, this behavior is - * deprecated. - * @param int $mode either unused or one of the tableInfo modes: - * MDB2_TABLEINFO_ORDERTABLE, - * MDB2_TABLEINFO_ORDER or - * MDB2_TABLEINFO_FULL (which does both). - * These are bitwise, so the first two can be - * combined using |. - * - * @return array an associative array with the information requested. - * A MDB2_Error object on failure. - * - * @see MDB2_Driver_Common::setOption() - */ - function tableInfo($result, $mode = null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (!is_string($result)) { - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - $db->loadModule('Manager', null, true); - $fields = $db->manager->listTableFields($result); - if (PEAR::isError($fields)) { - return $fields; - } - - $flags = array(); - - $idxname_format = $db->getOption('idxname_format'); - $db->setOption('idxname_format', '%s'); - - $indexes = $db->manager->listTableIndexes($result); - if (PEAR::isError($indexes)) { - $db->setOption('idxname_format', $idxname_format); - return $indexes; - } - - foreach ($indexes as $index) { - $definition = $this->getTableIndexDefinition($result, $index); - if (PEAR::isError($definition)) { - $db->setOption('idxname_format', $idxname_format); - return $definition; - } - if (count($definition['fields']) > 1) { - foreach ($definition['fields'] as $field => $sort) { - $flags[$field] = 'multiple_key'; - } - } - } - - $constraints = $db->manager->listTableConstraints($result); - if (PEAR::isError($constraints)) { - return $constraints; - } - - foreach ($constraints as $constraint) { - $definition = $this->getTableConstraintDefinition($result, $constraint); - if (PEAR::isError($definition)) { - $db->setOption('idxname_format', $idxname_format); - return $definition; - } - $flag = !empty($definition['primary']) - ? 'primary_key' : (!empty($definition['unique']) - ? 'unique_key' : false); - if ($flag) { - foreach ($definition['fields'] as $field => $sort) { - if (empty($flags[$field]) || $flags[$field] != 'primary_key') { - $flags[$field] = $flag; - } - } - } - } - - $res = array(); - - if ($mode) { - $res['num_fields'] = count($fields); - } - - foreach ($fields as $i => $field) { - $definition = $this->getTableFieldDefinition($result, $field); - if (PEAR::isError($definition)) { - $db->setOption('idxname_format', $idxname_format); - return $definition; - } - $res[$i] = $definition[0]; - $res[$i]['name'] = $field; - $res[$i]['table'] = $result; - $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype'])); - // 'primary_key', 'unique_key', 'multiple_key' - $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field]; - // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]' - if (!empty($res[$i]['notnull'])) { - $res[$i]['flags'].= ' not_null'; - } - if (!empty($res[$i]['unsigned'])) { - $res[$i]['flags'].= ' unsigned'; - } - if (!empty($res[$i]['auto_increment'])) { - $res[$i]['flags'].= ' autoincrement'; - } - if (!empty($res[$i]['default'])) { - $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']); - } - - if ($mode & MDB2_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & MDB2_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - - $db->setOption('idxname_format', $idxname_format); - return $res; - } -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Reverse/mysql.php b/3rdparty/MDB2/Driver/Reverse/mysql.php deleted file mode 100644 index 6e366c22a5..0000000000 --- a/3rdparty/MDB2/Driver/Reverse/mysql.php +++ /dev/null @@ -1,536 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.80 2008/03/26 21:15:37 quipo Exp $ -// - -require_once('MDB2/Driver/Reverse/Common.php'); - -/** - * MDB2 MySQL driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - * @author Lorenzo Alberton - */ -class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common -{ - // {{{ getTableFieldDefinition() - - /** - * Get the structure of a field into an array - * - * @param string $table_name name of table that should be used in method - * @param string $field_name name of field that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableFieldDefinition($table_name, $field_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $result = $db->loadModule('Datatype', null, true); - if (PEAR::isError($result)) { - return $result; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name); - $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($columns)) { - return $columns; - } - foreach ($columns as $column) { - $column = array_change_key_case($column, CASE_LOWER); - $column['name'] = $column['field']; - unset($column['field']); - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column['name'] = strtolower($column['name']); - } else { - $column['name'] = strtoupper($column['name']); - } - } else { - $column = array_change_key_case($column, $db->options['field_case']); - } - if ($field_name == $column['name']) { - $mapped_datatype = $db->datatype->mapNativeDatatype($column); - if (PEAR::isError($mapped_datatype)) { - return $mapped_datatype; - } - list($types, $length, $unsigned, $fixed) = $mapped_datatype; - $notnull = false; - if (empty($column['null']) || $column['null'] !== 'YES') { - $notnull = true; - } - $default = false; - if (array_key_exists('default', $column)) { - $default = $column['default']; - if (is_null($default) && $notnull) { - $default = ''; - } - } - $autoincrement = false; - if (!empty($column['extra']) && $column['extra'] == 'auto_increment') { - $autoincrement = true; - } - $collate = null; - if (!empty($column['collation'])) { - $collate = $column['collation']; - $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate); - } - - $definition[0] = array( - 'notnull' => $notnull, - 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type']) - ); - if (!is_null($length)) { - $definition[0]['length'] = $length; - } - if (!is_null($unsigned)) { - $definition[0]['unsigned'] = $unsigned; - } - if (!is_null($fixed)) { - $definition[0]['fixed'] = $fixed; - } - if ($default !== false) { - $definition[0]['default'] = $default; - } - if ($autoincrement !== false) { - $definition[0]['autoincrement'] = $autoincrement; - } - if (!is_null($collate)) { - $definition[0]['collate'] = $collate; - $definition[0]['charset'] = $charset; - } - foreach ($types as $key => $type) { - $definition[$key] = $definition[0]; - if ($type == 'clob' || $type == 'blob') { - unset($definition[$key]['default']); - } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) { - $definition[$key]['default'] = '0000-00-00 00:00:00'; - } - $definition[$key]['type'] = $type; - $definition[$key]['mdb2type'] = $type; - } - return $definition; - } - } - - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table column', __FUNCTION__); - } - - // }}} - // {{{ getTableIndexDefinition() - - /** - * Get the structure of an index into an array - * - * @param string $table_name name of table that should be used in method - * @param string $index_name name of index that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableIndexDefinition($table_name, $index_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */"; - $index_name_mdb2 = $db->getIndexName($index_name); - $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2))); - if (!PEAR::isError($result) && !is_null($result)) { - // apply 'idxname_format' only if the query succeeded, otherwise - // fallback to the given $index_name, without transformation - $index_name = $index_name_mdb2; - } - $result = $db->query(sprintf($query, $db->quote($index_name))); - if (PEAR::isError($result)) { - return $result; - } - $colpos = 1; - $definition = array(); - while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) { - $row = array_change_key_case($row, CASE_LOWER); - $key_name = $row['key_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - } else { - $key_name = strtoupper($key_name); - } - } - if ($index_name == $key_name) { - if (!$row['non_unique']) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $index_name . ' is not an existing table index', __FUNCTION__); - } - $column_name = $row['column_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column_name = strtolower($column_name); - } else { - $column_name = strtoupper($column_name); - } - } - $definition['fields'][$column_name] = array( - 'position' => $colpos++ - ); - if (!empty($row['collation'])) { - $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A' - ? 'ascending' : 'descending'); - } - } - } - $result->free(); - if (empty($definition['fields'])) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $index_name . ' is not an existing table index', __FUNCTION__); - } - return $definition; - } - - // }}} - // {{{ getTableConstraintDefinition() - - /** - * Get the structure of a constraint into an array - * - * @param string $table_name name of table that should be used in method - * @param string $constraint_name name of constraint that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableConstraintDefinition($table_name, $constraint_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - $constraint_name_original = $constraint_name; - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */"; - if (strtolower($constraint_name) != 'primary') { - $constraint_name_mdb2 = $db->getIndexName($constraint_name); - $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2))); - if (!PEAR::isError($result) && !is_null($result)) { - // apply 'idxname_format' only if the query succeeded, otherwise - // fallback to the given $index_name, without transformation - $constraint_name = $constraint_name_mdb2; - } - } - $result = $db->query(sprintf($query, $db->quote($constraint_name))); - if (PEAR::isError($result)) { - return $result; - } - $colpos = 1; - //default values, eventually overridden - $definition = array( - 'primary' => false, - 'unique' => false, - 'foreign' => false, - 'check' => false, - 'fields' => array(), - 'references' => array( - 'table' => '', - 'fields' => array(), - ), - 'onupdate' => '', - 'ondelete' => '', - 'match' => '', - 'deferrable' => false, - 'initiallydeferred' => false, - ); - while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) { - $row = array_change_key_case($row, CASE_LOWER); - $key_name = $row['key_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - } else { - $key_name = strtoupper($key_name); - } - } - if ($constraint_name == $key_name) { - if ($row['non_unique']) { - //FOREIGN KEY? - return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition); - } - if ($row['key_name'] == 'PRIMARY') { - $definition['primary'] = true; - } elseif (!$row['non_unique']) { - $definition['unique'] = true; - } - $column_name = $row['column_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column_name = strtolower($column_name); - } else { - $column_name = strtoupper($column_name); - } - } - $definition['fields'][$column_name] = array( - 'position' => $colpos++ - ); - if (!empty($row['collation'])) { - $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A' - ? 'ascending' : 'descending'); - } - } - } - $result->free(); - if (empty($definition['fields'])) { - return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition); - } - return $definition; - } - - // }}} - // {{{ _getTableFKConstraintDefinition() - - /** - * Get the FK definition from the CREATE TABLE statement - * - * @param string $table table name - * @param string $constraint_name constraint name - * @param array $definition default values for constraint definition - * - * @return array|PEAR_Error - * @access private - */ - function _getTableFKConstraintDefinition($table, $constraint_name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $query = 'SHOW CREATE TABLE '. $db->escape($table); - $constraint = $db->queryOne($query, 'text', 1); - if (!PEAR::isError($constraint) && !empty($constraint)) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $constraint = strtolower($constraint); - } else { - $constraint = strtoupper($constraint); - } - } - $constraint_name_original = $constraint_name; - $constraint_name = $db->getIndexName($constraint_name); - $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i'; - if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) { - //fallback to original constraint name - $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i'; - } - if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) { - $definition['foreign'] = true; - $column_names = explode(',', $matches[1]); - $referenced_cols = explode(',', $matches[3]); - $definition['references'] = array( - 'table' => $matches[2], - 'fields' => array(), - ); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - $colpos = 1; - foreach ($referenced_cols as $column_name) { - $definition['references']['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - $definition['onupdate'] = 'NO ACTION'; - $definition['ondelete'] = 'NO ACTION'; - $definition['match'] = 'SIMPLE'; - return $definition; - } - } - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - - // }}} - // {{{ getTriggerDefinition() - - /** - * Get the structure of a trigger into an array - * - * EXPERIMENTAL - * - * WARNING: this function is experimental and may change the returned value - * at any time until labelled as non-experimental - * - * @param string $trigger name of trigger that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTriggerDefinition($trigger) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SELECT trigger_name, - event_object_table AS table_name, - action_statement AS trigger_body, - action_timing AS trigger_type, - event_manipulation AS trigger_event - FROM information_schema.triggers - WHERE trigger_name = '. $db->quote($trigger, 'text'); - $types = array( - 'trigger_name' => 'text', - 'table_name' => 'text', - 'trigger_body' => 'text', - 'trigger_type' => 'text', - 'trigger_event' => 'text', - ); - $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($def)) { - return $def; - } - $def['trigger_comment'] = ''; - $def['trigger_enabled'] = true; - return $def; - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set - * - * @param object|string $result MDB2_result object from a query or a - * string containing the name of a table. - * While this also accepts a query result - * resource identifier, this behavior is - * deprecated. - * @param int $mode a valid tableInfo mode - * - * @return array an associative array with the information requested. - * A MDB2_Error object on failure. - * - * @see MDB2_Driver_Common::setOption() - */ - function tableInfo($result, $mode = null) - { - if (is_string($result)) { - return parent::tableInfo($result, $mode); - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result; - if (!is_resource($resource)) { - return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'Could not generate result resource', __FUNCTION__); - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $case_func = 'strtolower'; - } else { - $case_func = 'strtoupper'; - } - } else { - $case_func = 'strval'; - } - - $count = @mysql_num_fields($resource); - $res = array(); - if ($mode) { - $res['num_fields'] = $count; - } - - $db->loadModule('Datatype', null, true); - for ($i = 0; $i < $count; $i++) { - $res[$i] = array( - 'table' => $case_func(@mysql_field_table($resource, $i)), - 'name' => $case_func(@mysql_field_name($resource, $i)), - 'type' => @mysql_field_type($resource, $i), - 'length' => @mysql_field_len($resource, $i), - 'flags' => @mysql_field_flags($resource, $i), - ); - if ($res[$i]['type'] == 'string') { - $res[$i]['type'] = 'char'; - } elseif ($res[$i]['type'] == 'unknown') { - $res[$i]['type'] = 'decimal'; - } - $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]); - if (PEAR::isError($mdb2type_info)) { - return $mdb2type_info; - } - $res[$i]['mdb2type'] = $mdb2type_info[0][0]; - if ($mode & MDB2_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & MDB2_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - - return $res; - } -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Reverse/pgsql.php b/3rdparty/MDB2/Driver/Reverse/pgsql.php deleted file mode 100644 index 8669c2b919..0000000000 --- a/3rdparty/MDB2/Driver/Reverse/pgsql.php +++ /dev/null @@ -1,573 +0,0 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php,v 1.75 2008/08/22 16:36:20 quipo Exp $ - -require_once('MDB2/Driver/Reverse/Common.php'); - -/** - * MDB2 PostGreSQL driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Paul Cooper - * @author Lorenzo Alberton - */ -class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common -{ - // {{{ getTableFieldDefinition() - - /** - * Get the structure of a field into an array - * - * @param string $table_name name of table that should be used in method - * @param string $field_name name of field that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableFieldDefinition($table_name, $field_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $result = $db->loadModule('Datatype', null, true); - if (PEAR::isError($result)) { - return $result; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $query = "SELECT a.attname AS name, - t.typname AS type, - CASE a.attlen - WHEN -1 THEN - CASE t.typname - WHEN 'numeric' THEN (a.atttypmod / 65536) - WHEN 'decimal' THEN (a.atttypmod / 65536) - WHEN 'money' THEN (a.atttypmod / 65536) - ELSE CASE a.atttypmod - WHEN -1 THEN NULL - ELSE a.atttypmod - 4 - END - END - ELSE a.attlen - END AS length, - CASE t.typname - WHEN 'numeric' THEN (a.atttypmod % 65536) - 4 - WHEN 'decimal' THEN (a.atttypmod % 65536) - 4 - WHEN 'money' THEN (a.atttypmod % 65536) - 4 - ELSE 0 - END AS scale, - a.attnotnull, - a.atttypmod, - a.atthasdef, - (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128) - FROM pg_attrdef d - WHERE d.adrelid = a.attrelid - AND d.adnum = a.attnum - AND a.atthasdef - ) as default - FROM pg_attribute a, - pg_class c, - pg_type t - WHERE c.relname = ".$db->quote($table, 'text')." - AND a.atttypid = t.oid - AND c.oid = a.attrelid - AND NOT a.attisdropped - AND a.attnum > 0 - AND a.attname = ".$db->quote($field_name, 'text')." - ORDER BY a.attnum"; - $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($column)) { - return $column; - } - - if (empty($column)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table column', __FUNCTION__); - } - - $column = array_change_key_case($column, CASE_LOWER); - $mapped_datatype = $db->datatype->mapNativeDatatype($column); - if (PEAR::isError($mapped_datatype)) { - return $mapped_datatype; - } - list($types, $length, $unsigned, $fixed) = $mapped_datatype; - $notnull = false; - if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') { - $notnull = true; - } - $default = null; - if ($column['atthasdef'] === 't' - && !preg_match("/nextval\('([^']+)'/", $column['default']) - ) { - $pattern = '/^\'(.*)\'::[\w ]+$/i'; - $default = $column['default'];#substr($column['adsrc'], 1, -1); - if (is_null($default) && $notnull) { - $default = ''; - } elseif (!empty($default) && preg_match($pattern, $default)) { - //remove data type cast - $default = preg_replace ($pattern, '\\1', $default); - } - } - $autoincrement = false; - if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) { - $autoincrement = true; - } - $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']); - if (!is_null($length)) { - $definition[0]['length'] = $length; - } - if (!is_null($unsigned)) { - $definition[0]['unsigned'] = $unsigned; - } - if (!is_null($fixed)) { - $definition[0]['fixed'] = $fixed; - } - if ($default !== false) { - $definition[0]['default'] = $default; - } - if ($autoincrement !== false) { - $definition[0]['autoincrement'] = $autoincrement; - } - foreach ($types as $key => $type) { - $definition[$key] = $definition[0]; - if ($type == 'clob' || $type == 'blob') { - unset($definition[$key]['default']); - } - $definition[$key]['type'] = $type; - $definition[$key]['mdb2type'] = $type; - } - return $definition; - } - - // }}} - // {{{ getTableIndexDefinition() - - /** - * Get the structure of an index into an array - * - * @param string $table_name name of table that should be used in method - * @param string $index_name name of index that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableIndexDefinition($table_name, $index_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $query = 'SELECT relname, indkey FROM pg_index, pg_class'; - $query.= ' WHERE pg_class.oid = pg_index.indexrelid'; - $query.= " AND indisunique != 't' AND indisprimary != 't'"; - $query.= ' AND pg_class.relname = %s'; - $index_name_mdb2 = $db->getIndexName($index_name); - $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($row) || empty($row)) { - // fallback to the given $index_name, without transformation - $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC); - } - if (PEAR::isError($row)) { - return $row; - } - - if (empty($row)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table index', __FUNCTION__); - } - - $row = array_change_key_case($row, CASE_LOWER); - - $db->loadModule('Manager', null, true); - $columns = $db->manager->listTableFields($table_name); - - $definition = array(); - - $index_column_numbers = explode(' ', $row['indkey']); - - $colpos = 1; - foreach ($index_column_numbers as $number) { - $definition['fields'][$columns[($number - 1)]] = array( - 'position' => $colpos++, - 'sorting' => 'ascending', - ); - } - return $definition; - } - - // }}} - // {{{ getTableConstraintDefinition() - - /** - * Get the structure of a constraint into an array - * - * @param string $table_name name of table that should be used in method - * @param string $constraint_name name of constraint that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableConstraintDefinition($table_name, $constraint_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $query = "SELECT c.oid, - c.conname AS constraint_name, - CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\", - CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\", - CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\", - CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\", - CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable, - CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred, - --array_to_string(c.conkey, ' ') AS constraint_key, - t.relname AS table_name, - t2.relname AS references_table, - CASE confupdtype - WHEN 'a' THEN 'NO ACTION' - WHEN 'r' THEN 'RESTRICT' - WHEN 'c' THEN 'CASCADE' - WHEN 'n' THEN 'SET NULL' - WHEN 'd' THEN 'SET DEFAULT' - END AS onupdate, - CASE confdeltype - WHEN 'a' THEN 'NO ACTION' - WHEN 'r' THEN 'RESTRICT' - WHEN 'c' THEN 'CASCADE' - WHEN 'n' THEN 'SET NULL' - WHEN 'd' THEN 'SET DEFAULT' - END AS ondelete, - CASE confmatchtype - WHEN 'u' THEN 'UNSPECIFIED' - WHEN 'f' THEN 'FULL' - WHEN 'p' THEN 'PARTIAL' - END AS match, - --array_to_string(c.confkey, ' ') AS fk_constraint_key, - consrc - FROM pg_constraint c - LEFT JOIN pg_class t ON c.conrelid = t.oid - LEFT JOIN pg_class t2 ON c.confrelid = t2.oid - WHERE c.conname = %s - AND t.relname = " . $db->quote($table, 'text'); - $constraint_name_mdb2 = $db->getIndexName($constraint_name); - $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($row) || empty($row)) { - // fallback to the given $index_name, without transformation - $constraint_name_mdb2 = $constraint_name; - $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC); - } - if (PEAR::isError($row)) { - return $row; - } - $uniqueIndex = false; - if (empty($row)) { - // We might be looking for a UNIQUE index that was not created - // as a constraint but should be treated as such. - $query = 'SELECT relname AS constraint_name, - indkey, - 0 AS "check", - 0 AS "foreign", - 0 AS "primary", - 1 AS "unique", - 0 AS deferrable, - 0 AS initiallydeferred, - NULL AS references_table, - NULL AS onupdate, - NULL AS ondelete, - NULL AS match - FROM pg_index, pg_class - WHERE pg_class.oid = pg_index.indexrelid - AND indisunique = \'t\' - AND pg_class.relname = %s'; - $constraint_name_mdb2 = $db->getIndexName($constraint_name); - $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($row) || empty($row)) { - // fallback to the given $index_name, without transformation - $constraint_name_mdb2 = $constraint_name; - $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC); - } - if (PEAR::isError($row)) { - return $row; - } - if (empty($row)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - $uniqueIndex = true; - } - - $row = array_change_key_case($row, CASE_LOWER); - - $definition = array( - 'primary' => (boolean)$row['primary'], - 'unique' => (boolean)$row['unique'], - 'foreign' => (boolean)$row['foreign'], - 'check' => (boolean)$row['check'], - 'fields' => array(), - 'references' => array( - 'table' => $row['references_table'], - 'fields' => array(), - ), - 'deferrable' => (boolean)$row['deferrable'], - 'initiallydeferred' => (boolean)$row['initiallydeferred'], - 'onupdate' => $row['onupdate'], - 'ondelete' => $row['ondelete'], - 'match' => $row['match'], - ); - - if ($uniqueIndex) { - $db->loadModule('Manager', null, true); - $columns = $db->manager->listTableFields($table_name); - $index_column_numbers = explode(' ', $row['indkey']); - $colpos = 1; - foreach ($index_column_numbers as $number) { - $definition['fields'][$columns[($number - 1)]] = array( - 'position' => $colpos++, - 'sorting' => 'ascending', - ); - } - return $definition; - } - - $query = 'SELECT a.attname - FROM pg_constraint c - LEFT JOIN pg_class t ON c.conrelid = t.oid - LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey) - WHERE c.conname = %s - AND t.relname = ' . $db->quote($table, 'text'); - $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null); - if (PEAR::isError($fields)) { - return $fields; - } - $colpos = 1; - foreach ($fields as $field) { - $definition['fields'][$field] = array( - 'position' => $colpos++, - 'sorting' => 'ascending', - ); - } - - if ($definition['foreign']) { - $query = 'SELECT a.attname - FROM pg_constraint c - LEFT JOIN pg_class t ON c.confrelid = t.oid - LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey) - WHERE c.conname = %s - AND t.relname = ' . $db->quote($definition['references']['table'], 'text'); - $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null); - if (PEAR::isError($foreign_fields)) { - return $foreign_fields; - } - $colpos = 1; - foreach ($foreign_fields as $foreign_field) { - $definition['references']['fields'][$foreign_field] = array( - 'position' => $colpos++, - ); - } - } - - if ($definition['check']) { - $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')"); - // ... - } - return $definition; - } - - // }}} - // {{{ getTriggerDefinition() - - /** - * Get the structure of a trigger into an array - * - * EXPERIMENTAL - * - * WARNING: this function is experimental and may change the returned value - * at any time until labelled as non-experimental - * - * @param string $trigger name of trigger that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - * - * @TODO: add support for plsql functions and functions with args - */ - function getTriggerDefinition($trigger) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT trg.tgname AS trigger_name, - tbl.relname AS table_name, - CASE - WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();' - ELSE '' - END AS trigger_body, - CASE trg.tgtype & cast(2 as int2) - WHEN 0 THEN 'AFTER' - ELSE 'BEFORE' - END AS trigger_type, - CASE trg.tgtype & cast(28 as int2) - WHEN 16 THEN 'UPDATE' - WHEN 8 THEN 'DELETE' - WHEN 4 THEN 'INSERT' - WHEN 20 THEN 'INSERT, UPDATE' - WHEN 28 THEN 'INSERT, UPDATE, DELETE' - WHEN 24 THEN 'UPDATE, DELETE' - WHEN 12 THEN 'INSERT, DELETE' - END AS trigger_event, - CASE trg.tgenabled - WHEN 'O' THEN 't' - ELSE trg.tgenabled - END AS trigger_enabled, - obj_description(trg.oid, 'pg_trigger') AS trigger_comment - FROM pg_trigger trg, - pg_class tbl, - pg_proc p - WHERE trg.tgrelid = tbl.oid - AND trg.tgfoid = p.oid - AND trg.tgname = ". $db->quote($trigger, 'text'); - $types = array( - 'trigger_name' => 'text', - 'table_name' => 'text', - 'trigger_body' => 'text', - 'trigger_type' => 'text', - 'trigger_event' => 'text', - 'trigger_comment' => 'text', - 'trigger_enabled' => 'boolean', - ); - return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set - * - * NOTE: only supports 'table' and 'flags' if $result - * is a table name. - * - * @param object|string $result MDB2_result object from a query or a - * string containing the name of a table. - * While this also accepts a query result - * resource identifier, this behavior is - * deprecated. - * @param int $mode a valid tableInfo mode - * - * @return array an associative array with the information requested. - * A MDB2_Error object on failure. - * - * @see MDB2_Driver_Common::tableInfo() - */ - function tableInfo($result, $mode = null) - { - if (is_string($result)) { - return parent::tableInfo($result, $mode); - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result; - if (!is_resource($resource)) { - return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'Could not generate result resource', __FUNCTION__); - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $case_func = 'strtolower'; - } else { - $case_func = 'strtoupper'; - } - } else { - $case_func = 'strval'; - } - - $count = @pg_num_fields($resource); - $res = array(); - - if ($mode) { - $res['num_fields'] = $count; - } - - $db->loadModule('Datatype', null, true); - for ($i = 0; $i < $count; $i++) { - $res[$i] = array( - 'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '', - 'name' => $case_func(@pg_field_name($resource, $i)), - 'type' => @pg_field_type($resource, $i), - 'length' => @pg_field_size($resource, $i), - 'flags' => '', - ); - $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]); - if (PEAR::isError($mdb2type_info)) { - return $mdb2type_info; - } - $res[$i]['mdb2type'] = $mdb2type_info[0][0]; - if ($mode & MDB2_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & MDB2_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - - return $res; - } -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Reverse/sqlite.php b/3rdparty/MDB2/Driver/Reverse/sqlite.php deleted file mode 100644 index 60c686c418..0000000000 --- a/3rdparty/MDB2/Driver/Reverse/sqlite.php +++ /dev/null @@ -1,609 +0,0 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.80 2008/05/03 10:30:14 quipo Exp $ -// - -require_once('MDB2/Driver/Reverse/Common.php'); - -/** - * MDB2 SQlite driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common -{ - /** - * Remove SQL comments from the field definition - * - * @access private - */ - function _removeComments($sql) { - $lines = explode("\n", $sql); - foreach ($lines as $k => $line) { - $pieces = explode('--', $line); - if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) { - $lines[$k] = substr($line, 0, strpos($line, '--')); - } - } - return implode("\n", $lines); - } - - /** - * - */ - function _getTableColumns($sql) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $start_pos = strpos($sql, '('); - $end_pos = strrpos($sql, ')'); - $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1); - // replace the decimal length-places-separator with a colon - $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def); - $column_def = $this->_removeComments($column_def); - $column_sql = explode(',', $column_def); - $columns = array(); - $count = count($column_sql); - if ($count == 0) { - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'unexpected empty table column definition list', __FUNCTION__); - } - $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i'; - $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i'; - for ($i=0, $j=0; $i<$count; ++$i) { - if (!preg_match($regexp, trim($column_sql[$i]), $matches)) { - if (!preg_match($regexp2, trim($column_sql[$i]))) { - continue; - } - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__); - } - $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting)); - $columns[$j]['type'] = strtolower($matches[2]); - if (isset($matches[4]) && strlen($matches[4])) { - $columns[$j]['length'] = $matches[4]; - } - if (isset($matches[6]) && strlen($matches[6])) { - $columns[$j]['decimal'] = $matches[6]; - } - if (isset($matches[8]) && strlen($matches[8])) { - $columns[$j]['unsigned'] = true; - } - if (isset($matches[9]) && strlen($matches[9])) { - $columns[$j]['autoincrement'] = true; - } - if (isset($matches[12]) && strlen($matches[12])) { - $default = $matches[12]; - if (strlen($default) && $default[0]=="'") { - $default = str_replace("''", "'", substr($default, 1, strlen($default)-2)); - } - if ($default === 'NULL') { - $default = null; - } - $columns[$j]['default'] = $default; - } - if (isset($matches[7]) && strlen($matches[7])) { - $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL'); - } else if (isset($matches[9]) && strlen($matches[9])) { - $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL'); - } else if (isset($matches[13]) && strlen($matches[13])) { - $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL'); - } - ++$j; - } - return $columns; - } - - // {{{ getTableFieldDefinition() - - /** - * Get the stucture of a field into an array - * - * @param string $table_name name of table that should be used in method - * @param string $field_name name of field that should be used in method - * @return mixed data array on success, a MDB2 error on failure. - * The returned array contains an array for each field definition, - * with (some of) these indices: - * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type] - * @access public - */ - function getTableFieldDefinition($table_name, $field_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $result = $db->loadModule('Datatype', null, true); - if (PEAR::isError($result)) { - return $result; - } - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= 'name='.$db->quote($table, 'text'); - } - $sql = $db->queryOne($query); - if (PEAR::isError($sql)) { - return $sql; - } - $columns = $this->_getTableColumns($sql); - foreach ($columns as $column) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column['name'] = strtolower($column['name']); - } else { - $column['name'] = strtoupper($column['name']); - } - } else { - $column = array_change_key_case($column, $db->options['field_case']); - } - if ($field_name == $column['name']) { - $mapped_datatype = $db->datatype->mapNativeDatatype($column); - if (PEAR::isError($mapped_datatype)) { - return $mapped_datatype; - } - list($types, $length, $unsigned, $fixed) = $mapped_datatype; - $notnull = false; - if (!empty($column['notnull'])) { - $notnull = $column['notnull']; - } - $default = false; - if (array_key_exists('default', $column)) { - $default = $column['default']; - if (is_null($default) && $notnull) { - $default = ''; - } - } - $autoincrement = false; - if (!empty($column['autoincrement'])) { - $autoincrement = true; - } - - $definition[0] = array( - 'notnull' => $notnull, - 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type']) - ); - if (!is_null($length)) { - $definition[0]['length'] = $length; - } - if (!is_null($unsigned)) { - $definition[0]['unsigned'] = $unsigned; - } - if (!is_null($fixed)) { - $definition[0]['fixed'] = $fixed; - } - if ($default !== false) { - $definition[0]['default'] = $default; - } - if ($autoincrement !== false) { - $definition[0]['autoincrement'] = $autoincrement; - } - foreach ($types as $key => $type) { - $definition[$key] = $definition[0]; - if ($type == 'clob' || $type == 'blob') { - unset($definition[$key]['default']); - } - $definition[$key]['type'] = $type; - $definition[$key]['mdb2type'] = $type; - } - return $definition; - } - } - - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table column', __FUNCTION__); - } - - // }}} - // {{{ getTableIndexDefinition() - - /** - * Get the stucture of an index into an array - * - * @param string $table_name name of table that should be used in method - * @param string $index_name name of index that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableIndexDefinition($table_name, $index_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text'); - } else { - $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text'); - } - $query.= ' AND sql NOT NULL ORDER BY name'; - $index_name_mdb2 = $db->getIndexName($index_name); - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text')); - } else { - $qry = sprintf($query, $db->quote($index_name_mdb2, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - if (PEAR::isError($sql) || empty($sql)) { - // fallback to the given $index_name, without transformation - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($index_name), 'text')); - } else { - $qry = sprintf($query, $db->quote($index_name, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - } - if (PEAR::isError($sql)) { - return $sql; - } - if (!$sql) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table index', __FUNCTION__); - } - - $sql = strtolower($sql); - $start_pos = strpos($sql, '('); - $end_pos = strrpos($sql, ')'); - $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1); - $column_names = explode(',', $column_names); - - if (preg_match("/^create unique/", $sql)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table index', __FUNCTION__); - } - - $definition = array(); - $count = count($column_names); - for ($i=0; $i<$count; ++$i) { - $column_name = strtok($column_names[$i], ' '); - $collation = strtok(' '); - $definition['fields'][$column_name] = array( - 'position' => $i+1 - ); - if (!empty($collation)) { - $definition['fields'][$column_name]['sorting'] = - ($collation=='ASC' ? 'ascending' : 'descending'); - } - } - - if (empty($definition['fields'])) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table index', __FUNCTION__); - } - return $definition; - } - - // }}} - // {{{ getTableConstraintDefinition() - - /** - * Get the stucture of a constraint into an array - * - * @param string $table_name name of table that should be used in method - * @param string $constraint_name name of constraint that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTableConstraintDefinition($table_name, $constraint_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text'); - } else { - $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text'); - } - $query.= ' AND sql NOT NULL ORDER BY name'; - $constraint_name_mdb2 = $db->getIndexName($constraint_name); - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text')); - } else { - $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - if (PEAR::isError($sql) || empty($sql)) { - // fallback to the given $index_name, without transformation - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text')); - } else { - $qry = sprintf($query, $db->quote($constraint_name, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - } - if (PEAR::isError($sql)) { - return $sql; - } - //default values, eventually overridden - $definition = array( - 'primary' => false, - 'unique' => false, - 'foreign' => false, - 'check' => false, - 'fields' => array(), - 'references' => array( - 'table' => '', - 'fields' => array(), - ), - 'onupdate' => '', - 'ondelete' => '', - 'match' => '', - 'deferrable' => false, - 'initiallydeferred' => false, - ); - if (!$sql) { - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= 'name='.$db->quote($table, 'text'); - } - $query.= " AND sql NOT NULL ORDER BY name"; - $sql = $db->queryOne($query, 'text'); - if (PEAR::isError($sql)) { - return $sql; - } - if ($constraint_name == 'primary') { - // search in table definition for PRIMARY KEYs - if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) { - $definition['primary'] = true; - $definition['fields'] = array(); - $column_names = explode(',', $tmp[1]); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - return $definition; - } - if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) { - $definition['primary'] = true; - $definition['fields'] = array(); - $column_names = explode(',', $tmp[1]); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - return $definition; - } - } else { - // search in table definition for FOREIGN KEYs - $pattern = "/\bCONSTRAINT\b\s+%s\s+ - \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s* - \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s* - (?:\bMATCH\s*([^\s]+))?\s* - (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s* - (?:\bON\s+DELETE\s+([^\s,\)]+))?\s* - /imsx"; - $found_fk = false; - if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) { - $found_fk = true; - } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) { - $found_fk = true; - } - if ($found_fk) { - $definition['foreign'] = true; - $definition['match'] = 'SIMPLE'; - $definition['onupdate'] = 'NO ACTION'; - $definition['ondelete'] = 'NO ACTION'; - $definition['references']['table'] = $tmp[2]; - $column_names = explode(',', $tmp[1]); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - $referenced_cols = explode(',', $tmp[3]); - $colpos = 1; - foreach ($referenced_cols as $column_name) { - $definition['references']['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - if (isset($tmp[4])) { - $definition['match'] = $tmp[4]; - } - if (isset($tmp[5])) { - $definition['onupdate'] = $tmp[5]; - } - if (isset($tmp[6])) { - $definition['ondelete'] = $tmp[6]; - } - return $definition; - } - } - $sql = false; - } - if (!$sql) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - - $sql = strtolower($sql); - $start_pos = strpos($sql, '('); - $end_pos = strrpos($sql, ')'); - $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1); - $column_names = explode(',', $column_names); - - if (!preg_match("/^create unique/", $sql)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - - $definition['unique'] = true; - $count = count($column_names); - for ($i=0; $i<$count; ++$i) { - $column_name = strtok($column_names[$i]," "); - $collation = strtok(" "); - $definition['fields'][$column_name] = array( - 'position' => $i+1 - ); - if (!empty($collation)) { - $definition['fields'][$column_name]['sorting'] = - ($collation=='ASC' ? 'ascending' : 'descending'); - } - } - - if (empty($definition['fields'])) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - return $definition; - } - - // }}} - // {{{ getTriggerDefinition() - - /** - * Get the structure of a trigger into an array - * - * EXPERIMENTAL - * - * WARNING: this function is experimental and may change the returned value - * at any time until labelled as non-experimental - * - * @param string $trigger name of trigger that should be used in method - * @return mixed data array on success, a MDB2 error on failure - * @access public - */ - function getTriggerDefinition($trigger) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name as trigger_name, - tbl_name AS table_name, - sql AS trigger_body, - NULL AS trigger_type, - NULL AS trigger_event, - NULL AS trigger_comment, - 1 AS trigger_enabled - FROM sqlite_master - WHERE type='trigger'"; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text'); - } else { - $query.= ' AND name='.$db->quote($trigger, 'text'); - } - $types = array( - 'trigger_name' => 'text', - 'table_name' => 'text', - 'trigger_body' => 'text', - 'trigger_type' => 'text', - 'trigger_event' => 'text', - 'trigger_comment' => 'text', - 'trigger_enabled' => 'boolean', - ); - $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($def)) { - return $def; - } - if (empty($def)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing trigger', __FUNCTION__); - } - if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) { - $def['trigger_type'] = strtoupper($tmp[1]); - $def['trigger_event'] = strtoupper($tmp[2]); - } - return $def; - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table - * - * @param string $result a string containing the name of a table - * @param int $mode a valid tableInfo mode - * - * @return array an associative array with the information requested. - * A MDB2_Error object on failure. - * - * @see MDB2_Driver_Common::tableInfo() - * @since Method available since Release 1.7.0 - */ - function tableInfo($result, $mode = null) - { - if (is_string($result)) { - return parent::tableInfo($result, $mode); - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null, - 'This DBMS can not obtain tableInfo from result sets', __FUNCTION__); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/mysql.php b/3rdparty/MDB2/Driver/mysql.php deleted file mode 100644 index b9b46c0d76..0000000000 --- a/3rdparty/MDB2/Driver/mysql.php +++ /dev/null @@ -1,1700 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.214 2008/11/16 21:45:08 quipo Exp $ -// - -/** - * MDB2 MySQL driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_mysql extends MDB2_Driver_Common -{ - // {{{ properties - - var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\'); - - var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`'); - - var $sql_comments = array( - array('start' => '-- ', 'end' => "\n", 'escape' => false), - array('start' => '#', 'end' => "\n", 'escape' => false), - array('start' => '/*', 'end' => '*/', 'escape' => false), - ); - - var $server_capabilities_checked = false; - - var $start_transaction = false; - - var $varchar_max_length = 255; - - // }}} - // {{{ constructor - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - - $this->phptype = 'mysql'; - $this->dbsyntax = 'mysql'; - - $this->supported['sequences'] = 'emulated'; - $this->supported['indexes'] = true; - $this->supported['affected_rows'] = true; - $this->supported['transactions'] = false; - $this->supported['savepoints'] = false; - $this->supported['summary_functions'] = true; - $this->supported['order_by_text'] = true; - $this->supported['current_id'] = 'emulated'; - $this->supported['limit_queries'] = true; - $this->supported['LOBs'] = true; - $this->supported['replace'] = true; - $this->supported['sub_selects'] = 'emulated'; - $this->supported['triggers'] = false; - $this->supported['auto_increment'] = true; - $this->supported['primary_key'] = true; - $this->supported['result_introspection'] = true; - $this->supported['prepared_statements'] = 'emulated'; - $this->supported['identifier_quoting'] = true; - $this->supported['pattern_escaping'] = true; - $this->supported['new_link'] = true; - - $this->options['DBA_username'] = false; - $this->options['DBA_password'] = false; - $this->options['default_table_type'] = ''; - $this->options['max_identifiers_length'] = 64; - - $this->_reCheckSupportedOptions(); - } - - // }}} - // {{{ _reCheckSupportedOptions() - - /** - * If the user changes certain options, other capabilities may depend - * on the new settings, so we need to check them (again). - * - * @access private - */ - function _reCheckSupportedOptions() - { - $this->supported['transactions'] = $this->options['use_transactions']; - $this->supported['savepoints'] = $this->options['use_transactions']; - if ($this->options['default_table_type']) { - switch (strtoupper($this->options['default_table_type'])) { - case 'BLACKHOLE': - case 'MEMORY': - case 'ARCHIVE': - case 'CSV': - case 'HEAP': - case 'ISAM': - case 'MERGE': - case 'MRG_ISAM': - case 'ISAM': - case 'MRG_MYISAM': - case 'MYISAM': - $this->supported['savepoints'] = false; - $this->supported['transactions'] = false; - $this->warnings[] = $this->options['default_table_type'] . - ' is not a supported default table type'; - break; - } - } - } - - // }}} - // {{{ function setOption($option, $value) - - /** - * set the option for the db class - * - * @param string option name - * @param mixed value for the option - * - * @return mixed MDB2_OK or MDB2 Error Object - * - * @access public - */ - function setOption($option, $value) - { - $res = parent::setOption($option, $value); - $this->_reCheckSupportedOptions(); - } - - // }}} - // {{{ errorInfo() - - /** - * This method is used to collect information about an error - * - * @param integer $error - * @return array - * @access public - */ - function errorInfo($error = null) - { - if ($this->connection) { - $native_code = @mysql_errno($this->connection); - $native_msg = @mysql_error($this->connection); - } else { - $native_code = @mysql_errno(); - $native_msg = @mysql_error(); - } - if (is_null($error)) { - static $ecode_map; - if (empty($ecode_map)) { - $ecode_map = array( - 1000 => MDB2_ERROR_INVALID, //hashchk - 1001 => MDB2_ERROR_INVALID, //isamchk - 1004 => MDB2_ERROR_CANNOT_CREATE, - 1005 => MDB2_ERROR_CANNOT_CREATE, - 1006 => MDB2_ERROR_CANNOT_CREATE, - 1007 => MDB2_ERROR_ALREADY_EXISTS, - 1008 => MDB2_ERROR_CANNOT_DROP, - 1009 => MDB2_ERROR_CANNOT_DROP, - 1010 => MDB2_ERROR_CANNOT_DROP, - 1011 => MDB2_ERROR_CANNOT_DELETE, - 1022 => MDB2_ERROR_ALREADY_EXISTS, - 1029 => MDB2_ERROR_NOT_FOUND, - 1032 => MDB2_ERROR_NOT_FOUND, - 1044 => MDB2_ERROR_ACCESS_VIOLATION, - 1045 => MDB2_ERROR_ACCESS_VIOLATION, - 1046 => MDB2_ERROR_NODBSELECTED, - 1048 => MDB2_ERROR_CONSTRAINT, - 1049 => MDB2_ERROR_NOSUCHDB, - 1050 => MDB2_ERROR_ALREADY_EXISTS, - 1051 => MDB2_ERROR_NOSUCHTABLE, - 1054 => MDB2_ERROR_NOSUCHFIELD, - 1060 => MDB2_ERROR_ALREADY_EXISTS, - 1061 => MDB2_ERROR_ALREADY_EXISTS, - 1062 => MDB2_ERROR_ALREADY_EXISTS, - 1064 => MDB2_ERROR_SYNTAX, - 1067 => MDB2_ERROR_INVALID, - 1072 => MDB2_ERROR_NOT_FOUND, - 1086 => MDB2_ERROR_ALREADY_EXISTS, - 1091 => MDB2_ERROR_NOT_FOUND, - 1100 => MDB2_ERROR_NOT_LOCKED, - 1109 => MDB2_ERROR_NOT_FOUND, - 1125 => MDB2_ERROR_ALREADY_EXISTS, - 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW, - 1138 => MDB2_ERROR_INVALID, - 1142 => MDB2_ERROR_ACCESS_VIOLATION, - 1143 => MDB2_ERROR_ACCESS_VIOLATION, - 1146 => MDB2_ERROR_NOSUCHTABLE, - 1149 => MDB2_ERROR_SYNTAX, - 1169 => MDB2_ERROR_CONSTRAINT, - 1176 => MDB2_ERROR_NOT_FOUND, - 1177 => MDB2_ERROR_NOSUCHTABLE, - 1213 => MDB2_ERROR_DEADLOCK, - 1216 => MDB2_ERROR_CONSTRAINT, - 1217 => MDB2_ERROR_CONSTRAINT, - 1227 => MDB2_ERROR_ACCESS_VIOLATION, - 1235 => MDB2_ERROR_CANNOT_CREATE, - 1299 => MDB2_ERROR_INVALID_DATE, - 1300 => MDB2_ERROR_INVALID, - 1304 => MDB2_ERROR_ALREADY_EXISTS, - 1305 => MDB2_ERROR_NOT_FOUND, - 1306 => MDB2_ERROR_CANNOT_DROP, - 1307 => MDB2_ERROR_CANNOT_CREATE, - 1334 => MDB2_ERROR_CANNOT_ALTER, - 1339 => MDB2_ERROR_NOT_FOUND, - 1356 => MDB2_ERROR_INVALID, - 1359 => MDB2_ERROR_ALREADY_EXISTS, - 1360 => MDB2_ERROR_NOT_FOUND, - 1363 => MDB2_ERROR_NOT_FOUND, - 1365 => MDB2_ERROR_DIVZERO, - 1451 => MDB2_ERROR_CONSTRAINT, - 1452 => MDB2_ERROR_CONSTRAINT, - 1542 => MDB2_ERROR_CANNOT_DROP, - 1546 => MDB2_ERROR_CONSTRAINT, - 1582 => MDB2_ERROR_CONSTRAINT, - 2003 => MDB2_ERROR_CONNECT_FAILED, - 2019 => MDB2_ERROR_INVALID, - ); - } - if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) { - $ecode_map[1022] = MDB2_ERROR_CONSTRAINT; - $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL; - $ecode_map[1062] = MDB2_ERROR_CONSTRAINT; - } else { - // Doing this in case mode changes during runtime. - $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS; - $ecode_map[1048] = MDB2_ERROR_CONSTRAINT; - $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS; - } - if (isset($ecode_map[$native_code])) { - $error = $ecode_map[$native_code]; - } - } - return array($error, $native_code, $native_msg); - } - - // }}} - // {{{ escape() - - /** - * Quotes a string so it can be safely used in a query. It will quote - * the text so it can safely be used within a query. - * - * @param string the input string to quote - * @param bool escape wildcards - * - * @return string quoted string - * - * @access public - */ - function escape($text, $escape_wildcards = false) - { - if ($escape_wildcards) { - $text = $this->escapePattern($text); - } - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - $text = @mysql_real_escape_string($text, $connection); - return $text; - } - - // }}} - // {{{ beginTransaction() - - /** - * Start a transaction or set a savepoint. - * - * @param string name of a savepoint to set - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function beginTransaction($savepoint = null) - { - $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - $this->_getServerCapabilities(); - if (!is_null($savepoint)) { - if (!$this->supports('savepoints')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'savepoint cannot be released when changes are auto committed', __FUNCTION__); - } - $query = 'SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } elseif ($this->in_transaction) { - return MDB2_OK; //nothing to do - } - if (!$this->destructor_registered && $this->opened_persistent) { - $this->destructor_registered = true; - register_shutdown_function('MDB2_closeOpenTransactions'); - } - $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0'; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = true; - return MDB2_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the database changes done during a transaction that is in - * progress or release a savepoint. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after committing the pending changes. - * - * @param string name of a savepoint to release - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function commit($savepoint = null) - { - $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__); - } - if (!is_null($savepoint)) { - if (!$this->supports('savepoints')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - $server_info = $this->getServerVersion(); - if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) { - return MDB2_OK; - } - $query = 'RELEASE SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } - - if (!$this->supports('transactions')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'transactions are not supported', __FUNCTION__); - } - - $result =& $this->_doQuery('COMMIT', true); - if (PEAR::isError($result)) { - return $result; - } - if (!$this->start_transaction) { - $query = 'SET AUTOCOMMIT = 1'; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - } - $this->in_transaction = false; - return MDB2_OK; - } - - // }}} - // {{{ rollback() - - /** - * Cancel any database changes done during a transaction or since a specific - * savepoint that is in progress. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after canceling the pending changes. - * - * @param string name of a savepoint to rollback to - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function rollback($savepoint = null) - { - $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'rollback cannot be done changes are auto committed', __FUNCTION__); - } - if (!is_null($savepoint)) { - if (!$this->supports('savepoints')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } - - $query = 'ROLLBACK'; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - if (!$this->start_transaction) { - $query = 'SET AUTOCOMMIT = 1'; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - } - $this->in_transaction = false; - return MDB2_OK; - } - - // }}} - // {{{ function setTransactionIsolation() - - /** - * Set the transacton isolation level. - * - * @param string standard isolation level - * READ UNCOMMITTED (allows dirty reads) - * READ COMMITTED (prevents dirty reads) - * REPEATABLE READ (prevents nonrepeatable reads) - * SERIALIZABLE (prevents phantom reads) - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - * @since 2.1.1 - */ - static function setTransactionIsolation($isolation, $options = array()) - { - $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true)); - if (!$this->supports('transactions')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'transactions are not supported', __FUNCTION__); - } - switch ($isolation) { - case 'READ UNCOMMITTED': - case 'READ COMMITTED': - case 'REPEATABLE READ': - case 'SERIALIZABLE': - break; - default: - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'isolation level is not supported: '.$isolation, __FUNCTION__); - } - - $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation"; - return $this->_doQuery($query, true); - } - - // }}} - // {{{ _doConnect() - - /** - * do the grunt work of the connect - * - * @return connection on success or MDB2 Error Object on failure - * @access protected - */ - function _doConnect($username, $password, $persistent = false) - { - if (!PEAR::loadExtension($this->phptype)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__); - } - - $params = array(); - if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') { - $params[0] = ':' . $this->dsn['socket']; - } else { - $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec'] - : 'localhost'; - if ($this->dsn['port']) { - $params[0].= ':' . $this->dsn['port']; - } - } - $params[] = $username ? $username : null; - $params[] = $password ? $password : null; - if (!$persistent) { - if ($this->_isNewLinkSet()) { - $params[] = true; - } else { - $params[] = false; - } - } - if (version_compare(phpversion(), '4.3.0', '>=')) { - $params[] = isset($this->dsn['client_flags']) - ? $this->dsn['client_flags'] : null; - } - $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect'; - - $connection = @call_user_func_array($connect_function, $params); - if (!$connection) { - if (($err = @mysql_error()) != '') { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - $err, __FUNCTION__); - } else { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - 'unable to establish a connection', __FUNCTION__); - } - } - - if (!empty($this->dsn['charset'])) { - $result = $this->setCharset($this->dsn['charset'], $connection); - if (PEAR::isError($result)) { - $this->disconnect(false); - return $result; - } - } - - return $connection; - } - - // }}} - // {{{ connect() - - /** - * Connect to the database - * - * @return MDB2_OK on success, MDB2 Error Object on failure - * @access public - */ - function connect() - { - if (is_resource($this->connection)) { - //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0 - if (MDB2::areEquals($this->connected_dsn, $this->dsn) - && $this->opened_persistent == $this->options['persistent'] - ) { - return MDB2_OK; - } - $this->disconnect(false); - } - - $connection = $this->_doConnect( - $this->dsn['username'], - $this->dsn['password'], - $this->options['persistent'] - ); - if (PEAR::isError($connection)) { - return $connection; - } - - $this->connection = $connection; - $this->connected_dsn = $this->dsn; - $this->connected_database_name = ''; - $this->opened_persistent = $this->options['persistent']; - $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype; - - if ($this->database_name) { - if ($this->database_name != $this->connected_database_name) { - if (!@mysql_select_db($this->database_name, $connection)) { - $err = $this->raiseError(null, null, null, - 'Could not select the database: '.$this->database_name, __FUNCTION__); - return $err; - } - $this->connected_database_name = $this->database_name; - } - } - - $this->_getServerCapabilities(); - - return MDB2_OK; - } - - // }}} - // {{{ setCharset() - - /** - * Set the charset on the current connection - * - * @param string charset (or array(charset, collation)) - * @param resource connection handle - * - * @return true on success, MDB2 Error Object on failure - */ - function setCharset($charset, $connection = null) - { - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - $collation = null; - if (is_array($charset) && 2 == count($charset)) { - $collation = array_pop($charset); - $charset = array_pop($charset); - } - $client_info = mysql_get_client_info(); - if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) { - if (!$result = mysql_set_charset($charset, $connection)) { - $err =& $this->raiseError(null, null, null, - 'Could not set client character set', __FUNCTION__); - return $err; - } - return $result; - } - $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'"; - if (!is_null($collation)) { - $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'"; - } - return $this->_doQuery($query, true, $connection); - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - $connection = $this->_doConnect($this->dsn['username'], - $this->dsn['password'], - $this->options['persistent']); - if (PEAR::isError($connection)) { - return $connection; - } - - $result = @mysql_select_db($name, $connection); - @mysql_close($connection); - - return $result; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @param boolean $force if the disconnect should be forced even if the - * connection is opened persistently - * @return mixed true on success, false if not connected and error - * object on error - * @access public - */ - function disconnect($force = true) - { - if (is_resource($this->connection)) { - if ($this->in_transaction) { - $dsn = $this->dsn; - $database_name = $this->database_name; - $persistent = $this->options['persistent']; - $this->dsn = $this->connected_dsn; - $this->database_name = $this->connected_database_name; - $this->options['persistent'] = $this->opened_persistent; - $this->rollback(); - $this->dsn = $dsn; - $this->database_name = $database_name; - $this->options['persistent'] = $persistent; - } - - if (!$this->opened_persistent || $force) { - $ok = @mysql_close($this->connection); - if (!$ok) { - return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED, - null, null, null, __FUNCTION__); - } - } - } else { - return false; - } - return parent::disconnect($force); - } - - // }}} - // {{{ standaloneQuery() - - /** - * execute a query as DBA - * - * @param string $query the SQL query - * @param mixed $types array that contains the types of the columns in - * the result set - * @param boolean $is_manip if the query is a manipulation query - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function &standaloneQuery($query, $types = null, $is_manip = false) - { - $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username']; - $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password']; - $connection = $this->_doConnect($user, $pass, $this->options['persistent']); - if (PEAR::isError($connection)) { - return $connection; - } - - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $query = $this->_modifyQuery($query, $is_manip, $limit, $offset); - - $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name); - if (!PEAR::isError($result)) { - $result = $this->_affectedRows($connection, $result); - } - - @mysql_close($connection); - return $result; - } - - // }}} - // {{{ _doQuery() - - /** - * Execute a query - * @param string $query query - * @param boolean $is_manip if the query is a manipulation query - * @param resource $connection - * @param string $database_name - * @return result or error object - * @access protected - */ - function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null) - { - $this->last_query = $query; - $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre')); - if ($result) { - if (PEAR::isError($result)) { - return $result; - } - $query = $result; - } - if ($this->options['disable_query']) { - $result = $is_manip ? 0 : null; - return $result; - } - - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - if (is_null($database_name)) { - $database_name = $this->database_name; - } - - if ($database_name) { - if ($database_name != $this->connected_database_name) { - if (!@mysql_select_db($database_name, $connection)) { - $err = $this->raiseError(null, null, null, - 'Could not select the database: '.$database_name, __FUNCTION__); - return $err; - } - $this->connected_database_name = $database_name; - } - } - - $function = $this->options['result_buffering'] - ? 'mysql_query' : 'mysql_unbuffered_query'; - $result = @$function($query, $connection); - if (!$result) { - $err =& $this->raiseError(null, null, null, - 'Could not execute statement', __FUNCTION__); - return $err; - } - - $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result)); - return $result; - } - - // }}} - // {{{ _affectedRows() - - /** - * Returns the number of rows affected - * - * @param resource $result - * @param resource $connection - * @return mixed MDB2 Error Object or the number of rows affected - * @access private - */ - function _affectedRows($connection, $result = null) - { - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - return @mysql_affected_rows($connection); - } - - // }}} - // {{{ _modifyQuery() - - /** - * Changes a query string for various DBMS specific reasons - * - * @param string $query query to modify - * @param boolean $is_manip if it is a DML query - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string modified query - * @access protected - */ - function _modifyQuery($query, $is_manip, $limit, $offset) - { - if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) { - // "DELETE FROM table" gives 0 affected rows in MySQL. - // This little hack lets you know how many rows were deleted. - if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) { - $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/', - 'DELETE FROM \1 WHERE 1=1', $query); - } - } - if ($limit > 0 - && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query) - ) { - $query = rtrim($query); - if (substr($query, -1) == ';') { - $query = substr($query, 0, -1); - } - - // LIMIT doesn't always come last in the query - // @see http://dev.mysql.com/doc/refman/5.0/en/select.html - $after = ''; - if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) { - $after = $matches[0]; - $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query); - } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) { - $after = $matches[0]; - $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query); - } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) { - $after = $matches[0]; - $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query); - } - - if ($is_manip) { - return $query . " LIMIT $limit" . $after; - } else { - return $query . " LIMIT $offset, $limit" . $after; - } - } - return $query; - } - - // }}} - // {{{ getServerVersion() - - /** - * return version information about the server - * - * @param bool $native determines if the raw version string should be returned - * @return mixed array/string with version information or MDB2 error object - * @access public - */ - function getServerVersion($native = false) - { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - if ($this->connected_server_info) { - $server_info = $this->connected_server_info; - } else { - $server_info = @mysql_get_server_info($connection); - } - if (!$server_info) { - return $this->raiseError(null, null, null, - 'Could not get server information', __FUNCTION__); - } - // cache server_info - $this->connected_server_info = $server_info; - if (!$native) { - $tmp = explode('.', $server_info, 3); - if (isset($tmp[2]) && strpos($tmp[2], '-')) { - $tmp2 = explode('-', @$tmp[2], 2); - } else { - $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null; - $tmp2[1] = null; - } - $server_info = array( - 'major' => isset($tmp[0]) ? $tmp[0] : null, - 'minor' => isset($tmp[1]) ? $tmp[1] : null, - 'patch' => $tmp2[0], - 'extra' => $tmp2[1], - 'native' => $server_info, - ); - } - return $server_info; - } - - // }}} - // {{{ _getServerCapabilities() - - /** - * Fetch some information about the server capabilities - * (transactions, subselects, prepared statements, etc). - * - * @access private - */ - function _getServerCapabilities() - { - if (!$this->server_capabilities_checked) { - $this->server_capabilities_checked = true; - - //set defaults - $this->supported['sub_selects'] = 'emulated'; - $this->supported['prepared_statements'] = 'emulated'; - $this->supported['triggers'] = false; - $this->start_transaction = false; - $this->varchar_max_length = 255; - - $server_info = $this->getServerVersion(); - if (is_array($server_info)) { - $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']; - - if (!version_compare($server_version, '4.1.0', '<')) { - $this->supported['sub_selects'] = true; - $this->supported['prepared_statements'] = true; - } - - // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB) - if (version_compare($server_version, '4.1.0', '>=')) { - if (version_compare($server_version, '4.1.1', '<')) { - $this->supported['savepoints'] = false; - } - } elseif (version_compare($server_version, '4.0.14', '<')) { - $this->supported['savepoints'] = false; - } - - if (!version_compare($server_version, '4.0.11', '<')) { - $this->start_transaction = true; - } - - if (!version_compare($server_version, '5.0.3', '<')) { - $this->varchar_max_length = 65532; - } - - if (!version_compare($server_version, '5.0.2', '<')) { - $this->supported['triggers'] = true; - } - } - } - } - - // }}} - // {{{ function _skipUserDefinedVariable($query, $position) - - /** - * Utility method, used by prepare() to avoid misinterpreting MySQL user - * defined variables (SELECT @x:=5) for placeholders. - * Check if the placeholder is a false positive, i.e. if it is an user defined - * variable instead. If so, skip it and advance the position, otherwise - * return the current position, which is valid - * - * @param string $query - * @param integer $position current string cursor position - * @return integer $new_position - * @access protected - */ - function _skipUserDefinedVariable($query, $position) - { - $found = strpos(strrev(substr($query, 0, $position)), '@'); - if ($found === false) { - return $position; - } - $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1; - $substring = substr($query, $pos, $position - $pos + 2); - if (preg_match('/^@\w+\s*:=$/', $substring)) { - return $position + 1; //found an user defined variable: skip it - } - return $position; - } - - // }}} - // {{{ prepare() - - /** - * Prepares a query for multiple execution with execute(). - * With some database backends, this is emulated. - * prepare() requires a generic query as string like - * 'INSERT INTO numbers VALUES(?,?)' or - * 'INSERT INTO numbers VALUES(:foo,:bar)'. - * The ? and :name and are placeholders which can be set using - * bindParam() and the query can be sent off using the execute() method. - * The allowed format for :name can be set with the 'bindname_format' option. - * - * @param string $query the query to prepare - * @param mixed $types array that contains the types of the placeholders - * @param mixed $result_types array that contains the types of the columns in - * the result set or MDB2_PREPARE_RESULT, if set to - * MDB2_PREPARE_MANIP the query is handled as a manipulation query - * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders - * @return mixed resource handle for the prepared query on success, a MDB2 - * error on failure - * @access public - * @see bindParam, execute - */ - function &prepare($query, $types = null, $result_types = null, $lobs = array()) - { - if ($this->options['emulate_prepared'] - || $this->supported['prepared_statements'] !== true - ) { - $obj =& parent::prepare($query, $types, $result_types, $lobs); - return $obj; - } - $is_manip = ($result_types === MDB2_PREPARE_MANIP); - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $query = $this->_modifyQuery($query, $is_manip, $limit, $offset); - $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre')); - if ($result) { - if (PEAR::isError($result)) { - return $result; - } - $query = $result; - } - $placeholder_type_guess = $placeholder_type = null; - $question = '?'; - $colon = ':'; - $positions = array(); - $position = 0; - while ($position < strlen($query)) { - $q_position = strpos($query, $question, $position); - $c_position = strpos($query, $colon, $position); - if ($q_position && $c_position) { - $p_position = min($q_position, $c_position); - } elseif ($q_position) { - $p_position = $q_position; - } elseif ($c_position) { - $p_position = $c_position; - } else { - break; - } - if (is_null($placeholder_type)) { - $placeholder_type_guess = $query[$p_position]; - } - - $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position); - if (PEAR::isError($new_pos)) { - return $new_pos; - } - if ($new_pos != $position) { - $position = $new_pos; - continue; //evaluate again starting from the new position - } - - //make sure this is not part of an user defined variable - $new_pos = $this->_skipUserDefinedVariable($query, $position); - if ($new_pos != $position) { - $position = $new_pos; - continue; //evaluate again starting from the new position - } - - if ($query[$position] == $placeholder_type_guess) { - if (is_null($placeholder_type)) { - $placeholder_type = $query[$p_position]; - $question = $colon = $placeholder_type; - } - if ($placeholder_type == ':') { - $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s'; - $parameter = preg_replace($regexp, '\\1', $query); - if ($parameter === '') { - $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null, - 'named parameter name must match "bindname_format" option', __FUNCTION__); - return $err; - } - $positions[$p_position] = $parameter; - $query = substr_replace($query, '?', $position, strlen($parameter)+1); - } else { - $positions[$p_position] = count($positions); - } - $position = $p_position + 1; - } else { - $position = $p_position; - } - } - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - static $prep_statement_counter = 1; - $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand())); - $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']); - $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text'); - $statement =& $this->_doQuery($query, true, $connection); - if (PEAR::isError($statement)) { - return $statement; - } - - $class_name = 'MDB2_Statement_'.$this->phptype; - $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset); - $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj)); - return $obj; - } - - // }}} - // {{{ replace() - - /** - * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT - * query, except that if there is already a row in the table with the same - * key field values, the old row is deleted before the new row is inserted. - * - * The REPLACE type of query does not make part of the SQL standards. Since - * practically only MySQL implements it natively, this type of query is - * emulated through this method for other DBMS using standard types of - * queries inside a transaction to assure the atomicity of the operation. - * - * @access public - * - * @param string $table name of the table on which the REPLACE query will - * be executed. - * @param array $fields associative array that describes the fields and the - * values that will be inserted or updated in the specified table. The - * indexes of the array are the names of all the fields of the table. The - * values of the array are also associative arrays that describe the - * values and other properties of the table fields. - * - * Here follows a list of field properties that need to be specified: - * - * value: - * Value to be assigned to the specified field. This value may be - * of specified in database independent type format as this - * function can perform the necessary datatype conversions. - * - * Default: - * this property is required unless the Null property - * is set to 1. - * - * type - * Name of the type of the field. Currently, all types Metabase - * are supported except for clob and blob. - * - * Default: no type conversion - * - * null - * Boolean property that indicates that the value for this field - * should be set to null. - * - * The default value for fields missing in INSERT queries may be - * specified the definition of a table. Often, the default value - * is already null, but since the REPLACE may be emulated using - * an UPDATE query, make sure that all fields of the table are - * listed in this function argument array. - * - * Default: 0 - * - * key - * Boolean property that indicates that this field should be - * handled as a primary key or at least as part of the compound - * unique index of the table that will determine the row that will - * updated if it exists or inserted a new row otherwise. - * - * This function will fail if no key field is specified or if the - * value of a key field is set to null because fields that are - * part of unique index they may not be null. - * - * Default: 0 - * - * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html - * @return mixed MDB2_OK on success, a MDB2 error on failure - */ - function replace($table, $fields) - { - $count = count($fields); - $query = $values = ''; - $keys = $colnum = 0; - for (reset($fields); $colnum < $count; next($fields), $colnum++) { - $name = key($fields); - if ($colnum > 0) { - $query .= ','; - $values.= ','; - } - $query.= $this->quoteIdentifier($name, true); - if (isset($fields[$name]['null']) && $fields[$name]['null']) { - $value = 'NULL'; - } else { - $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null; - $value = $this->quote($fields[$name]['value'], $type); - if (PEAR::isError($value)) { - return $value; - } - } - $values.= $value; - if (isset($fields[$name]['key']) && $fields[$name]['key']) { - if ($value === 'NULL') { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'key value '.$name.' may not be NULL', __FUNCTION__); - } - $keys++; - } - } - if ($keys == 0) { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'not specified which fields are keys', __FUNCTION__); - } - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $table = $this->quoteIdentifier($table, true); - $query = "REPLACE INTO $table ($query) VALUES ($values)"; - $result =& $this->_doQuery($query, true, $connection); - if (PEAR::isError($result)) { - return $result; - } - return $this->_affectedRows($connection, $result); - } - - // }}} - // {{{ nextID() - - /** - * Returns the next free id of a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true the sequence is - * automatic created, if it - * not exists - * - * @return mixed MDB2 Error Object or id - * @access public - */ - function nextID($seq_name, $ondemand = true) - { - $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true); - $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true); - $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)"; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $this->expectError(MDB2_ERROR_NOSUCHTABLE); - $result =& $this->_doQuery($query, true); - $this->popExpect(); - $this->popErrorHandling(); - if (PEAR::isError($result)) { - if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) { - $this->loadModule('Manager', null, true); - $result = $this->manager->createSequence($seq_name); - if (PEAR::isError($result)) { - return $this->raiseError($result, null, null, - 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__); - } else { - return $this->nextID($seq_name, false); - } - } - return $result; - } - $value = $this->lastInsertID(); - if (is_numeric($value)) { - $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value"; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name; - } - } - return $value; - } - - // }}} - // {{{ lastInsertID() - - /** - * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) - * - * @param string $table name of the table into which a new row was inserted - * @param string $field name of the field into which a new row was inserted - * @return mixed MDB2 Error Object or id - * @access public - */ - function lastInsertID($table = null, $field = null) - { - // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051 - return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer'); - } - - // }}} - // {{{ currID() - - /** - * Returns the current id of a sequence - * - * @param string $seq_name name of the sequence - * @return mixed MDB2 Error Object or id - * @access public - */ - function currID($seq_name) - { - $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true); - $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true); - $query = "SELECT MAX($seqcol_name) FROM $sequence_name"; - return $this->queryOne($query, 'integer'); - } -} - -/** - * MDB2 MySQL result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Result_mysql extends MDB2_Result_Common -{ - // }}} - // {{{ fetchRow() - - /** - * Fetch a row and insert the data into an existing array. - * - * @param int $fetchmode how the array data should be indexed - * @param int $rownum number of the row where the data can be found - * @return int data array on success, a MDB2 error on failure - * @access public - */ - function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null) - { - if (!is_null($rownum)) { - $seek = $this->seek($rownum); - if (PEAR::isError($seek)) { - return $seek; - } - } - if ($fetchmode == MDB2_FETCHMODE_DEFAULT) { - $fetchmode = $this->db->fetchmode; - } - if ($fetchmode & MDB2_FETCHMODE_ASSOC) { - $row = @mysql_fetch_assoc($this->result); - if (is_array($row) - && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE - ) { - $row = array_change_key_case($row, $this->db->options['field_case']); - } - } else { - $row = @mysql_fetch_row($this->result); - } - - if (!$row) { - if ($this->result === false) { - $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - return $err; - } - $null = null; - return $null; - } - $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL; - $rtrim = false; - if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) { - if (empty($this->types)) { - $mode += MDB2_PORTABILITY_RTRIM; - } else { - $rtrim = true; - } - } - if ($mode) { - $this->db->_fixResultArrayValues($row, $mode); - } - if (!empty($this->types)) { - $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim); - } - if (!empty($this->values)) { - $this->_assignBindColumns($row); - } - if ($fetchmode === MDB2_FETCHMODE_OBJECT) { - $object_class = $this->db->options['fetch_class']; - if ($object_class == 'stdClass') { - $row = (object) $row; - } else { - $row = new $object_class($row); - } - } - ++$this->rownum; - return $row; - } - - // }}} - // {{{ _getColumnNames() - - /** - * Retrieve the names of columns returned by the DBMS in a query result. - * - * @return mixed Array variable that holds the names of columns as keys - * or an MDB2 error on failure. - * Some DBMS may not return any columns when the result set - * does not contain any rows. - * @access private - */ - function _getColumnNames() - { - $columns = array(); - $numcols = $this->numCols(); - if (PEAR::isError($numcols)) { - return $numcols; - } - for ($column = 0; $column < $numcols; $column++) { - $column_name = @mysql_field_name($this->result, $column); - $columns[$column_name] = $column; - } - if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $columns = array_change_key_case($columns, $this->db->options['field_case']); - } - return $columns; - } - - // }}} - // {{{ numCols() - - /** - * Count the number of columns returned by the DBMS in a query result. - * - * @return mixed integer value with the number of columns, a MDB2 error - * on failure - * @access public - */ - function numCols() - { - $cols = @mysql_num_fields($this->result); - if (is_null($cols)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return count($this->types); - } - return $this->db->raiseError(null, null, null, - 'Could not get column count', __FUNCTION__); - } - return $cols; - } - - // }}} - // {{{ free() - - /** - * Free the internal resources associated with result. - * - * @return boolean true on success, false if result is invalid - * @access public - */ - function free() - { - if (is_resource($this->result) && $this->db->connection) { - $free = @mysql_free_result($this->result); - if ($free === false) { - return $this->db->raiseError(null, null, null, - 'Could not free result', __FUNCTION__); - } - } - $this->result = false; - return MDB2_OK; - } -} - -/** - * MDB2 MySQL buffered result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_BufferedResult_mysql extends MDB2_Result_mysql -{ - // }}} - // {{{ seek() - - /** - * Seek to a specific row in a result set - * - * @param int $rownum number of the row where the data can be found - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function seek($rownum = 0) - { - if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return MDB2_OK; - } - return $this->db->raiseError(MDB2_ERROR_INVALID, null, null, - 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__); - } - $this->rownum = $rownum - 1; - return MDB2_OK; - } - - // }}} - // {{{ valid() - - /** - * Check if the end of the result set has been reached - * - * @return mixed true or false on sucess, a MDB2 error on failure - * @access public - */ - function valid() - { - $numrows = $this->numRows(); - if (PEAR::isError($numrows)) { - return $numrows; - } - return $this->rownum < ($numrows - 1); - } - - // }}} - // {{{ numRows() - - /** - * Returns the number of rows in a result object - * - * @return mixed MDB2 Error Object or the number of rows - * @access public - */ - function numRows() - { - $rows = @mysql_num_rows($this->result); - if (false === $rows) { - if (false === $this->result) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return 0; - } - return $this->db->raiseError(null, null, null, - 'Could not get row count', __FUNCTION__); - } - return $rows; - } -} - -/** - * MDB2 MySQL statement driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Statement_mysql extends MDB2_Statement_Common -{ - // {{{ _execute() - - /** - * Execute a prepared query statement helper method. - * - * @param mixed $result_class string which specifies which result class to use - * @param mixed $result_wrap_class string which specifies which class to wrap results in - * - * @return mixed MDB2_Result or integer (affected rows) on success, - * a MDB2 error on failure - * @access private - */ - function &_execute($result_class = true, $result_wrap_class = false) - { - if (is_null($this->statement)) { - $result =& parent::_execute($result_class, $result_wrap_class); - return $result; - } - $this->db->last_query = $this->query; - $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values)); - if ($this->db->getOption('disable_query')) { - $result = $this->is_manip ? 0 : null; - return $result; - } - - $connection = $this->db->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $query = 'EXECUTE '.$this->statement; - if (!empty($this->positions)) { - $parameters = array(); - foreach ($this->positions as $parameter) { - if (!array_key_exists($parameter, $this->values)) { - return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__); - } - $value = $this->values[$parameter]; - $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null; - if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) { - if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) { - if ($match[1] == 'file://') { - $value = $match[2]; - } - $value = @fopen($value, 'r'); - $close = true; - } - if (is_resource($value)) { - $data = ''; - while (!@feof($value)) { - $data.= @fread($value, $this->db->options['lob_buffer_length']); - } - if ($close) { - @fclose($value); - } - $value = $data; - } - } - $quoted = $this->db->quote($value, $type); - if (PEAR::isError($quoted)) { - return $quoted; - } - $param_query = 'SET @'.$parameter.' = '.$quoted; - $result = $this->db->_doQuery($param_query, true, $connection); - if (PEAR::isError($result)) { - return $result; - } - } - $query.= ' USING @'.implode(', @', array_values($this->positions)); - } - - $result = $this->db->_doQuery($query, $this->is_manip, $connection); - if (PEAR::isError($result)) { - return $result; - } - - if ($this->is_manip) { - $affected_rows = $this->db->_affectedRows($connection, $result); - return $affected_rows; - } - - $result =& $this->db->_wrapResult($result, $this->result_types, - $result_class, $result_wrap_class, $this->limit, $this->offset); - $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result)); - return $result; - } - - // }}} - // {{{ free() - - /** - * Release resources allocated for the specified prepared query. - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function free() - { - if (is_null($this->positions)) { - return $this->db->raiseError(MDB2_ERROR, null, null, - 'Prepared statement has already been freed', __FUNCTION__); - } - $result = MDB2_OK; - - if (!is_null($this->statement)) { - $connection = $this->db->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - $query = 'DEALLOCATE PREPARE '.$this->statement; - $result = $this->db->_doQuery($query, true, $connection); - } - - parent::free(); - return $result; - } -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/pgsql.php b/3rdparty/MDB2/Driver/pgsql.php deleted file mode 100644 index 13fea69068..0000000000 --- a/3rdparty/MDB2/Driver/pgsql.php +++ /dev/null @@ -1,1519 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php,v 1.203 2008/11/29 14:04:46 afz Exp $ - -/** - * MDB2 PostGreSQL driver - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -class MDB2_Driver_pgsql extends MDB2_Driver_Common -{ - // {{{ properties - var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\'); - - var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"'); - // }}} - // {{{ constructor - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - - $this->phptype = 'pgsql'; - $this->dbsyntax = 'pgsql'; - - $this->supported['sequences'] = true; - $this->supported['indexes'] = true; - $this->supported['affected_rows'] = true; - $this->supported['summary_functions'] = true; - $this->supported['order_by_text'] = true; - $this->supported['transactions'] = true; - $this->supported['savepoints'] = true; - $this->supported['current_id'] = true; - $this->supported['limit_queries'] = true; - $this->supported['LOBs'] = true; - $this->supported['replace'] = 'emulated'; - $this->supported['sub_selects'] = true; - $this->supported['triggers'] = true; - $this->supported['auto_increment'] = 'emulated'; - $this->supported['primary_key'] = true; - $this->supported['result_introspection'] = true; - $this->supported['prepared_statements'] = true; - $this->supported['identifier_quoting'] = true; - $this->supported['pattern_escaping'] = true; - $this->supported['new_link'] = true; - - $this->options['DBA_username'] = false; - $this->options['DBA_password'] = false; - $this->options['multi_query'] = false; - $this->options['disable_smart_seqname'] = true; - $this->options['max_identifiers_length'] = 63; - } - - // }}} - // {{{ errorInfo() - - /** - * This method is used to collect information about an error - * - * @param integer $error - * @return array - * @access public - */ - function errorInfo($error = null) - { - // Fall back to MDB2_ERROR if there was no mapping. - $error_code = MDB2_ERROR; - - $native_msg = ''; - if (is_resource($error)) { - $native_msg = @pg_result_error($error); - } elseif ($this->connection) { - $native_msg = @pg_last_error($this->connection); - if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) { - $native_msg = 'Database connection has been lost.'; - $error_code = MDB2_ERROR_CONNECT_FAILED; - } - } else { - $native_msg = @pg_last_error(); - } - - static $error_regexps; - if (empty($error_regexps)) { - $error_regexps = array( - '/column .* (of relation .*)?does not exist/i' - => MDB2_ERROR_NOSUCHFIELD, - '/(relation|sequence|table).*does not exist|class .* not found/i' - => MDB2_ERROR_NOSUCHTABLE, - '/database .* does not exist/' - => MDB2_ERROR_NOT_FOUND, - '/constraint .* does not exist/' - => MDB2_ERROR_NOT_FOUND, - '/index .* does not exist/' - => MDB2_ERROR_NOT_FOUND, - '/database .* already exists/i' - => MDB2_ERROR_ALREADY_EXISTS, - '/relation .* already exists/i' - => MDB2_ERROR_ALREADY_EXISTS, - '/(divide|division) by zero$/i' - => MDB2_ERROR_DIVZERO, - '/pg_atoi: error in .*: can\'t parse /i' - => MDB2_ERROR_INVALID_NUMBER, - '/invalid input syntax for( type)? (integer|numeric)/i' - => MDB2_ERROR_INVALID_NUMBER, - '/value .* is out of range for type \w*int/i' - => MDB2_ERROR_INVALID_NUMBER, - '/integer out of range/i' - => MDB2_ERROR_INVALID_NUMBER, - '/value too long for type character/i' - => MDB2_ERROR_INVALID, - '/attribute .* not found|relation .* does not have attribute/i' - => MDB2_ERROR_NOSUCHFIELD, - '/column .* specified in USING clause does not exist in (left|right) table/i' - => MDB2_ERROR_NOSUCHFIELD, - '/parser: parse error at or near/i' - => MDB2_ERROR_SYNTAX, - '/syntax error at/' - => MDB2_ERROR_SYNTAX, - '/column reference .* is ambiguous/i' - => MDB2_ERROR_SYNTAX, - '/permission denied/' - => MDB2_ERROR_ACCESS_VIOLATION, - '/violates not-null constraint/' - => MDB2_ERROR_CONSTRAINT_NOT_NULL, - '/violates [\w ]+ constraint/' - => MDB2_ERROR_CONSTRAINT, - '/referential integrity violation/' - => MDB2_ERROR_CONSTRAINT, - '/more expressions than target columns/i' - => MDB2_ERROR_VALUE_COUNT_ON_ROW, - ); - } - if (is_numeric($error) && $error < 0) { - $error_code = $error; - } else { - foreach ($error_regexps as $regexp => $code) { - if (preg_match($regexp, $native_msg)) { - $error_code = $code; - break; - } - } - } - return array($error_code, null, $native_msg); - } - - // }}} - // {{{ escape() - - /** - * Quotes a string so it can be safely used in a query. It will quote - * the text so it can safely be used within a query. - * - * @param string the input string to quote - * @param bool escape wildcards - * - * @return string quoted string - * - * @access public - */ - function escape($text, $escape_wildcards = false) - { - if ($escape_wildcards) { - $text = $this->escapePattern($text); - } - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) { - $text = @pg_escape_string($connection, $text); - } else { - $text = @pg_escape_string($text); - } - return $text; - } - - // }}} - // {{{ beginTransaction() - - /** - * Start a transaction or set a savepoint. - * - * @param string name of a savepoint to set - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function beginTransaction($savepoint = null) - { - $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!is_null($savepoint)) { - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'savepoint cannot be released when changes are auto committed', __FUNCTION__); - } - $query = 'SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } elseif ($this->in_transaction) { - return MDB2_OK; //nothing to do - } - if (!$this->destructor_registered && $this->opened_persistent) { - $this->destructor_registered = true; - register_shutdown_function('MDB2_closeOpenTransactions'); - } - $result =& $this->_doQuery('BEGIN', true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = true; - return MDB2_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the database changes done during a transaction that is in - * progress or release a savepoint. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after committing the pending changes. - * - * @param string name of a savepoint to release - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function commit($savepoint = null) - { - $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__); - } - if (!is_null($savepoint)) { - $query = 'RELEASE SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } - - $result =& $this->_doQuery('COMMIT', true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = false; - return MDB2_OK; - } - - // }}} - // {{{ rollback() - - /** - * Cancel any database changes done during a transaction or since a specific - * savepoint that is in progress. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after canceling the pending changes. - * - * @param string name of a savepoint to rollback to - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function rollback($savepoint = null) - { - $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'rollback cannot be done changes are auto committed', __FUNCTION__); - } - if (!is_null($savepoint)) { - $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } - - $query = 'ROLLBACK'; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = false; - return MDB2_OK; - } - - // }}} - // {{{ function setTransactionIsolation() - - /** - * Set the transacton isolation level. - * - * @param string standard isolation level - * READ UNCOMMITTED (allows dirty reads) - * READ COMMITTED (prevents dirty reads) - * REPEATABLE READ (prevents nonrepeatable reads) - * SERIALIZABLE (prevents phantom reads) - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - * @since 2.1.1 - */ - static function setTransactionIsolation($isolation, $options = array()) - { - $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true)); - switch ($isolation) { - case 'READ UNCOMMITTED': - case 'READ COMMITTED': - case 'REPEATABLE READ': - case 'SERIALIZABLE': - break; - default: - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'isolation level is not supported: '.$isolation, __FUNCTION__); - } - - $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation"; - return $this->_doQuery($query, true); - } - - // }}} - // {{{ _doConnect() - - /** - * Do the grunt work of connecting to the database - * - * @return mixed connection resource on success, MDB2 Error Object on failure - * @access protected - */ - function _doConnect($username, $password, $database_name, $persistent = false) - { - if (!PEAR::loadExtension($this->phptype)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__); - } - - if ($database_name == '') { - $database_name = 'template1'; - } - - $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp'; - - $params = array(''); - if ($protocol == 'tcp') { - if ($this->dsn['hostspec']) { - $params[0].= 'host=' . $this->dsn['hostspec']; - } - if ($this->dsn['port']) { - $params[0].= ' port=' . $this->dsn['port']; - } - } elseif ($protocol == 'unix') { - // Allow for pg socket in non-standard locations. - if ($this->dsn['socket']) { - $params[0].= 'host=' . $this->dsn['socket']; - } - if ($this->dsn['port']) { - $params[0].= ' port=' . $this->dsn['port']; - } - } - if ($database_name) { - $params[0].= ' dbname=\'' . addslashes($database_name) . '\''; - } - if ($username) { - $params[0].= ' user=\'' . addslashes($username) . '\''; - } - if ($password) { - $params[0].= ' password=\'' . addslashes($password) . '\''; - } - if (!empty($this->dsn['options'])) { - $params[0].= ' options=' . $this->dsn['options']; - } - if (!empty($this->dsn['tty'])) { - $params[0].= ' tty=' . $this->dsn['tty']; - } - if (!empty($this->dsn['connect_timeout'])) { - $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout']; - } - if (!empty($this->dsn['sslmode'])) { - $params[0].= ' sslmode=' . $this->dsn['sslmode']; - } - if (!empty($this->dsn['service'])) { - $params[0].= ' service=' . $this->dsn['service']; - } - - if ($this->_isNewLinkSet()) { - if (version_compare(phpversion(), '4.3.0', '>=')) { - $params[] = PGSQL_CONNECT_FORCE_NEW; - } - } - - $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect'; - $connection = @call_user_func_array($connect_function, $params); - if (!$connection) { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - 'unable to establish a connection', __FUNCTION__); - } - - if (empty($this->dsn['disable_iso_date'])) { - if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) { - return $this->raiseError(null, null, null, - 'Unable to set date style to iso', __FUNCTION__); - } - } - - if (!empty($this->dsn['charset'])) { - $result = $this->setCharset($this->dsn['charset'], $connection); - if (PEAR::isError($result)) { - return $result; - } - } - - return $connection; - } - - // }}} - // {{{ connect() - - /** - * Connect to the database - * - * @return true on success, MDB2 Error Object on failure - * @access public - */ - function connect() - { - if (is_resource($this->connection)) { - //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0 - if (MDB2::areEquals($this->connected_dsn, $this->dsn) - && $this->connected_database_name == $this->database_name - && ($this->opened_persistent == $this->options['persistent']) - ) { - return MDB2_OK; - } - $this->disconnect(false); - } - - if ($this->database_name) { - $connection = $this->_doConnect($this->dsn['username'], - $this->dsn['password'], - $this->database_name, - $this->options['persistent']); - if (PEAR::isError($connection)) { - return $connection; - } - - $this->connection = $connection; - $this->connected_dsn = $this->dsn; - $this->connected_database_name = $this->database_name; - $this->opened_persistent = $this->options['persistent']; - $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype; - } - - return MDB2_OK; - } - - // }}} - // {{{ setCharset() - - /** - * Set the charset on the current connection - * - * @param string charset - * @param resource connection handle - * - * @return true on success, MDB2 Error Object on failure - */ - function setCharset($charset, $connection = null) - { - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - if (is_array($charset)) { - $charset = array_shift($charset); - $this->warnings[] = 'postgresql does not support setting client collation'; - } - $result = @pg_set_client_encoding($connection, $charset); - if ($result == -1) { - return $this->raiseError(null, null, null, - 'Unable to set client charset: '.$charset, __FUNCTION__); - } - return MDB2_OK; - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - $res = $this->_doConnect($this->dsn['username'], - $this->dsn['password'], - $this->escape($name), - $this->options['persistent']); - if (!PEAR::isError($res)) { - return true; - } - - return false; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @param boolean $force if the disconnect should be forced even if the - * connection is opened persistently - * @return mixed true on success, false if not connected and error - * object on error - * @access public - */ - function disconnect($force = true) - { - if (is_resource($this->connection)) { - if ($this->in_transaction) { - $dsn = $this->dsn; - $database_name = $this->database_name; - $persistent = $this->options['persistent']; - $this->dsn = $this->connected_dsn; - $this->database_name = $this->connected_database_name; - $this->options['persistent'] = $this->opened_persistent; - $this->rollback(); - $this->dsn = $dsn; - $this->database_name = $database_name; - $this->options['persistent'] = $persistent; - } - - if (!$this->opened_persistent || $force) { - $ok = @pg_close($this->connection); - if (!$ok) { - return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED, - null, null, null, __FUNCTION__); - } - } - } else { - return false; - } - return parent::disconnect($force); - } - - // }}} - // {{{ standaloneQuery() - - /** - * execute a query as DBA - * - * @param string $query the SQL query - * @param mixed $types array that contains the types of the columns in - * the result set - * @param boolean $is_manip if the query is a manipulation query - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function &standaloneQuery($query, $types = null, $is_manip = false) - { - $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username']; - $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password']; - $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']); - if (PEAR::isError($connection)) { - return $connection; - } - - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $query = $this->_modifyQuery($query, $is_manip, $limit, $offset); - - $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name); - if (!PEAR::isError($result)) { - if ($is_manip) { - $result = $this->_affectedRows($connection, $result); - } else { - $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset); - } - } - - @pg_close($connection); - return $result; - } - - // }}} - // {{{ _doQuery() - - /** - * Execute a query - * @param string $query query - * @param boolean $is_manip if the query is a manipulation query - * @param resource $connection - * @param string $database_name - * @return result or error object - * @access protected - */ - function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null) - { - $this->last_query = $query; - $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre')); - if ($result) { - if (PEAR::isError($result)) { - return $result; - } - $query = $result; - } - if ($this->options['disable_query']) { - $result = $is_manip ? 0 : null; - return $result; - } - - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - - $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query'; - $result = @$function($connection, $query); - if (!$result) { - $err =& $this->raiseError(null, null, null, - 'Could not execute statement', __FUNCTION__); - return $err; - } elseif ($this->options['multi_query']) { - if (!($result = @pg_get_result($connection))) { - $err =& $this->raiseError(null, null, null, - 'Could not get the first result from a multi query', __FUNCTION__); - return $err; - } - } - - $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result)); - return $result; - } - - // }}} - // {{{ _affectedRows() - - /** - * Returns the number of rows affected - * - * @param resource $result - * @param resource $connection - * @return mixed MDB2 Error Object or the number of rows affected - * @access private - */ - function _affectedRows($connection, $result = null) - { - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - return @pg_affected_rows($result); - } - - // }}} - // {{{ _modifyQuery() - - /** - * Changes a query string for various DBMS specific reasons - * - * @param string $query query to modify - * @param boolean $is_manip if it is a DML query - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string modified query - * @access protected - */ - function _modifyQuery($query, $is_manip, $limit, $offset) - { - if ($limit > 0 - && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query) - ) { - $query = rtrim($query); - if (substr($query, -1) == ';') { - $query = substr($query, 0, -1); - } - if ($is_manip) { - $query = $this->_modifyManipQuery($query, $limit); - } else { - $query.= " LIMIT $limit OFFSET $offset"; - } - } - return $query; - } - - // }}} - // {{{ _modifyManipQuery() - - /** - * Changes a manip query string for various DBMS specific reasons - * - * @param string $query query to modify - * @param integer $limit limit the number of rows - * @return string modified query - * @access protected - */ - function _modifyManipQuery($query, $limit) - { - $pos = strpos(strtolower($query), 'where'); - $where = $pos ? substr($query, $pos) : ''; - - $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)'; - $from_clause = '([\w\.]+)'; - $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)'; - $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i'; - $matches = preg_match($pattern, $query, $match); - if ($matches) { - $manip = $match[1]; - $from = $match[2]; - $what = (count($matches) == 6) ? $match[5] : $match[3]; - return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')'; - } - //return error? - return $query; - } - - // }}} - // {{{ getServerVersion() - - /** - * return version information about the server - * - * @param bool $native determines if the raw version string should be returned - * @return mixed array/string with version information or MDB2 error object - * @access public - */ - function getServerVersion($native = false) - { - $query = 'SHOW SERVER_VERSION'; - if ($this->connected_server_info) { - $server_info = $this->connected_server_info; - } else { - $server_info = $this->queryOne($query, 'text'); - if (PEAR::isError($server_info)) { - return $server_info; - } - } - // cache server_info - $this->connected_server_info = $server_info; - if (!$native && !PEAR::isError($server_info)) { - $tmp = explode('.', $server_info, 3); - if (empty($tmp[2]) - && isset($tmp[1]) - && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2) - ) { - $server_info = array( - 'major' => $tmp[0], - 'minor' => $tmp2[1], - 'patch' => null, - 'extra' => $tmp2[2], - 'native' => $server_info, - ); - } else { - $server_info = array( - 'major' => isset($tmp[0]) ? $tmp[0] : null, - 'minor' => isset($tmp[1]) ? $tmp[1] : null, - 'patch' => isset($tmp[2]) ? $tmp[2] : null, - 'extra' => null, - 'native' => $server_info, - ); - } - } - return $server_info; - } - - // }}} - // {{{ prepare() - - /** - * Prepares a query for multiple execution with execute(). - * With some database backends, this is emulated. - * prepare() requires a generic query as string like - * 'INSERT INTO numbers VALUES(?,?)' or - * 'INSERT INTO numbers VALUES(:foo,:bar)'. - * The ? and :name and are placeholders which can be set using - * bindParam() and the query can be sent off using the execute() method. - * The allowed format for :name can be set with the 'bindname_format' option. - * - * @param string $query the query to prepare - * @param mixed $types array that contains the types of the placeholders - * @param mixed $result_types array that contains the types of the columns in - * the result set or MDB2_PREPARE_RESULT, if set to - * MDB2_PREPARE_MANIP the query is handled as a manipulation query - * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders - * @return mixed resource handle for the prepared query on success, a MDB2 - * error on failure - * @access public - * @see bindParam, execute - */ - function &prepare($query, $types = null, $result_types = null, $lobs = array()) - { - if ($this->options['emulate_prepared']) { - $obj =& parent::prepare($query, $types, $result_types, $lobs); - return $obj; - } - $is_manip = ($result_types === MDB2_PREPARE_MANIP); - $offset = $this->offset; - $limit = $this->limit; - $this->offset = $this->limit = 0; - $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre')); - if ($result) { - if (PEAR::isError($result)) { - return $result; - } - $query = $result; - } - $pgtypes = function_exists('pg_prepare') ? false : array(); - if ($pgtypes !== false && !empty($types)) { - $this->loadModule('Datatype', null, true); - } - $query = $this->_modifyQuery($query, $is_manip, $limit, $offset); - $placeholder_type_guess = $placeholder_type = null; - $question = '?'; - $colon = ':'; - $positions = array(); - $position = $parameter = 0; - while ($position < strlen($query)) { - $q_position = strpos($query, $question, $position); - $c_position = strpos($query, $colon, $position); - //skip "::type" cast ("select id::varchar(20) from sometable where name=?") - $doublecolon_position = strpos($query, '::', $position); - if ($doublecolon_position !== false && $doublecolon_position == $c_position) { - $c_position = strpos($query, $colon, $position+2); - } - if ($q_position && $c_position) { - $p_position = min($q_position, $c_position); - } elseif ($q_position) { - $p_position = $q_position; - } elseif ($c_position) { - $p_position = $c_position; - } else { - break; - } - if (is_null($placeholder_type)) { - $placeholder_type_guess = $query[$p_position]; - } - - $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position); - if (PEAR::isError($new_pos)) { - return $new_pos; - } - if ($new_pos != $position) { - $position = $new_pos; - continue; //evaluate again starting from the new position - } - - if ($query[$position] == $placeholder_type_guess) { - if (is_null($placeholder_type)) { - $placeholder_type = $query[$p_position]; - $question = $colon = $placeholder_type; - if (!empty($types) && is_array($types)) { - if ($placeholder_type == ':') { - } else { - $types = array_values($types); - } - } - } - if ($placeholder_type_guess == '?') { - $length = 1; - $name = $parameter; - } else { - $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s'; - $param = preg_replace($regexp, '\\1', $query); - if ($param === '') { - $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null, - 'named parameter name must match "bindname_format" option', __FUNCTION__); - return $err; - } - $length = strlen($param) + 1; - $name = $param; - } - if ($pgtypes !== false) { - if (is_array($types) && array_key_exists($name, $types)) { - $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]); - } elseif (is_array($types) && array_key_exists($parameter, $types)) { - $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]); - } else { - $pgtypes[] = 'text'; - } - } - if (($key_parameter = array_search($name, $positions))) { - $next_parameter = 1; - foreach ($positions as $key => $value) { - if ($key_parameter == $key) { - break; - } - ++$next_parameter; - } - } else { - ++$parameter; - $next_parameter = $parameter; - $positions[] = $name; - } - $query = substr_replace($query, '$'.$parameter, $position, $length); - $position = $p_position + strlen($parameter); - } else { - $position = $p_position; - } - } - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - static $prep_statement_counter = 1; - $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand())); - $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']); - if ($pgtypes === false) { - $result = @pg_prepare($connection, $statement_name, $query); - if (!$result) { - $err =& $this->raiseError(null, null, null, - 'Unable to create prepared statement handle', __FUNCTION__); - return $err; - } - } else { - $types_string = ''; - if ($pgtypes) { - $types_string = ' ('.implode(', ', $pgtypes).') '; - } - $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query; - $statement =& $this->_doQuery($query, true, $connection); - if (PEAR::isError($statement)) { - return $statement; - } - } - - $class_name = 'MDB2_Statement_'.$this->phptype; - $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset); - $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj)); - return $obj; - } - - // }}} - // {{{ function getSequenceName($sqn) - - /** - * adds sequence name formatting to a sequence name - * - * @param string name of the sequence - * - * @return string formatted sequence name - * - * @access public - */ - function getSequenceName($sqn) - { - if (false === $this->options['disable_smart_seqname']) { - if (strpos($sqn, '_') !== false) { - list($table, $field) = explode('_', $sqn, 2); - } - $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')"); - if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) { - $order_by = ' a.attnum'; - $schema_clause = ' AND n.nspname=current_schema()'; - } else { - $schemas = explode(',', $schema_list); - $schema_clause = ' AND n.nspname IN ('.$schema_list.')'; - $counter = 1; - $order_by = ' CASE '; - foreach ($schemas as $schema) { - $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++; - } - $order_by .= ' ELSE '.$counter.' END, a.attnum'; - } - - $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128) - FROM pg_attrdef d - WHERE d.adrelid = a.attrelid - AND d.adnum = a.attnum - AND a.atthasdef - ) FROM 'nextval[^'']*''([^'']*)') - FROM pg_attribute a - LEFT JOIN pg_class c ON c.oid = a.attrelid - LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef - LEFT JOIN pg_namespace n ON c.relnamespace = n.oid - WHERE (c.relname = ".$this->quote($sqn, 'text'); - if (!empty($field)) { - $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")"; - } - $query .= " )" - .$schema_clause." - AND NOT a.attisdropped - AND a.attnum > 0 - AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%' - ORDER BY ".$order_by; - $seqname = $this->queryOne($query); - if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) { - return $seqname; - } - } - - return parent::getSequenceName($sqn); - } - - // }}} - // {{{ nextID() - - /** - * Returns the next free id of a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true the sequence is - * automatic created, if it - * not exists - * @return mixed MDB2 Error Object or id - * @access public - */ - function nextID($seq_name, $ondemand = true) - { - $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true); - $query = "SELECT NEXTVAL('$sequence_name')"; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $this->expectError(MDB2_ERROR_NOSUCHTABLE); - $result = $this->queryOne($query, 'integer'); - $this->popExpect(); - $this->popErrorHandling(); - if (PEAR::isError($result)) { - if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) { - $this->loadModule('Manager', null, true); - $result = $this->manager->createSequence($seq_name); - if (PEAR::isError($result)) { - return $this->raiseError($result, null, null, - 'on demand sequence could not be created', __FUNCTION__); - } - return $this->nextId($seq_name, false); - } - } - return $result; - } - - // }}} - // {{{ lastInsertID() - - /** - * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) - * - * @param string $table name of the table into which a new row was inserted - * @param string $field name of the field into which a new row was inserted - * @return mixed MDB2 Error Object or id - * @access public - */ - function lastInsertID($table = null, $field = null) - { - if (empty($table) && empty($field)) { - return $this->queryOne('SELECT lastval()', 'integer'); - } - $seq = $table.(empty($field) ? '' : '_'.$field); - $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true); - return $this->queryOne("SELECT currval('$sequence_name')", 'integer'); - } - - // }}} - // {{{ currID() - - /** - * Returns the current id of a sequence - * - * @param string $seq_name name of the sequence - * @return mixed MDB2 Error Object or id - * @access public - */ - function currID($seq_name) - { - $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true); - return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer'); - } -} - -/** - * MDB2 PostGreSQL result driver - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -class MDB2_Result_pgsql extends MDB2_Result_Common -{ - // }}} - // {{{ fetchRow() - - /** - * Fetch a row and insert the data into an existing array. - * - * @param int $fetchmode how the array data should be indexed - * @param int $rownum number of the row where the data can be found - * @return int data array on success, a MDB2 error on failure - * @access public - */ - function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null) - { - if (!is_null($rownum)) { - $seek = $this->seek($rownum); - if (PEAR::isError($seek)) { - return $seek; - } - } - if ($fetchmode == MDB2_FETCHMODE_DEFAULT) { - $fetchmode = $this->db->fetchmode; - } - if ($fetchmode & MDB2_FETCHMODE_ASSOC) { - $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC); - if (is_array($row) - && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE - ) { - $row = array_change_key_case($row, $this->db->options['field_case']); - } - } else { - $row = @pg_fetch_row($this->result); - } - if (!$row) { - if ($this->result === false) { - $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - return $err; - } - $null = null; - return $null; - } - $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL; - $rtrim = false; - if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) { - if (empty($this->types)) { - $mode += MDB2_PORTABILITY_RTRIM; - } else { - $rtrim = true; - } - } - if ($mode) { - $this->db->_fixResultArrayValues($row, $mode); - } - if (!empty($this->types)) { - $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim); - } - if (!empty($this->values)) { - $this->_assignBindColumns($row); - } - if ($fetchmode === MDB2_FETCHMODE_OBJECT) { - $object_class = $this->db->options['fetch_class']; - if ($object_class == 'stdClass') { - $row = (object) $row; - } else { - $row = new $object_class($row); - } - } - ++$this->rownum; - return $row; - } - - // }}} - // {{{ _getColumnNames() - - /** - * Retrieve the names of columns returned by the DBMS in a query result. - * - * @return mixed Array variable that holds the names of columns as keys - * or an MDB2 error on failure. - * Some DBMS may not return any columns when the result set - * does not contain any rows. - * @access private - */ - function _getColumnNames() - { - $columns = array(); - $numcols = $this->numCols(); - if (PEAR::isError($numcols)) { - return $numcols; - } - for ($column = 0; $column < $numcols; $column++) { - $column_name = @pg_field_name($this->result, $column); - $columns[$column_name] = $column; - } - if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $columns = array_change_key_case($columns, $this->db->options['field_case']); - } - return $columns; - } - - // }}} - // {{{ numCols() - - /** - * Count the number of columns returned by the DBMS in a query result. - * - * @access public - * @return mixed integer value with the number of columns, a MDB2 error - * on failure - */ - function numCols() - { - $cols = @pg_num_fields($this->result); - if (is_null($cols)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return count($this->types); - } - return $this->db->raiseError(null, null, null, - 'Could not get column count', __FUNCTION__); - } - return $cols; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal result pointer to the next available result - * - * @return true on success, false if there is no more result set or an error object on failure - * @access public - */ - function nextResult() - { - $connection = $this->db->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - if (!($this->result = @pg_get_result($connection))) { - return false; - } - return MDB2_OK; - } - - // }}} - // {{{ free() - - /** - * Free the internal resources associated with result. - * - * @return boolean true on success, false if result is invalid - * @access public - */ - function free() - { - if (is_resource($this->result) && $this->db->connection) { - $free = @pg_free_result($this->result); - if ($free === false) { - return $this->db->raiseError(null, null, null, - 'Could not free result', __FUNCTION__); - } - } - $this->result = false; - return MDB2_OK; - } -} - -/** - * MDB2 PostGreSQL buffered result driver - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql -{ - // {{{ seek() - - /** - * Seek to a specific row in a result set - * - * @param int $rownum number of the row where the data can be found - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function seek($rownum = 0) - { - if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return MDB2_OK; - } - return $this->db->raiseError(MDB2_ERROR_INVALID, null, null, - 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__); - } - $this->rownum = $rownum - 1; - return MDB2_OK; - } - - // }}} - // {{{ valid() - - /** - * Check if the end of the result set has been reached - * - * @return mixed true or false on sucess, a MDB2 error on failure - * @access public - */ - function valid() - { - $numrows = $this->numRows(); - if (PEAR::isError($numrows)) { - return $numrows; - } - return $this->rownum < ($numrows - 1); - } - - // }}} - // {{{ numRows() - - /** - * Returns the number of rows in a result object - * - * @return mixed MDB2 Error Object or the number of rows - * @access public - */ - function numRows() - { - $rows = @pg_num_rows($this->result); - if (is_null($rows)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return 0; - } - return $this->db->raiseError(null, null, null, - 'Could not get row count', __FUNCTION__); - } - return $rows; - } -} - -/** - * MDB2 PostGreSQL statement driver - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -class MDB2_Statement_pgsql extends MDB2_Statement_Common -{ - // {{{ _execute() - - /** - * Execute a prepared query statement helper method. - * - * @param mixed $result_class string which specifies which result class to use - * @param mixed $result_wrap_class string which specifies which class to wrap results in - * - * @return mixed MDB2_Result or integer (affected rows) on success, - * a MDB2 error on failure - * @access private - */ - function &_execute($result_class = true, $result_wrap_class = false) - { - if (is_null($this->statement)) { - $result =& parent::_execute($result_class, $result_wrap_class); - return $result; - } - $this->db->last_query = $this->query; - $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values)); - if ($this->db->getOption('disable_query')) { - $result = $this->is_manip ? 0 : null; - return $result; - } - - $connection = $this->db->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $query = false; - $parameters = array(); - // todo: disabled until pg_execute() bytea issues are cleared up - if (true || !function_exists('pg_execute')) { - $query = 'EXECUTE '.$this->statement; - } - if (!empty($this->positions)) { - foreach ($this->positions as $parameter) { - if (!array_key_exists($parameter, $this->values)) { - return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__); - } - $value = $this->values[$parameter]; - $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null; - if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) { - if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) { - if ($match[1] == 'file://') { - $value = $match[2]; - } - $value = @fopen($value, 'r'); - $close = true; - } - if (is_resource($value)) { - $data = ''; - while (!@feof($value)) { - $data.= @fread($value, $this->db->options['lob_buffer_length']); - } - if ($close) { - @fclose($value); - } - $value = $data; - } - } - $quoted = $this->db->quote($value, $type, $query); - if (PEAR::isError($quoted)) { - return $quoted; - } - $parameters[] = $quoted; - } - if ($query) { - $query.= ' ('.implode(', ', $parameters).')'; - } - } - - if (!$query) { - $result = @pg_execute($connection, $this->statement, $parameters); - if (!$result) { - $err =& $this->db->raiseError(null, null, null, - 'Unable to execute statement', __FUNCTION__); - return $err; - } - } else { - $result = $this->db->_doQuery($query, $this->is_manip, $connection); - if (PEAR::isError($result)) { - return $result; - } - } - - if ($this->is_manip) { - $affected_rows = $this->db->_affectedRows($connection, $result); - return $affected_rows; - } - - $result =& $this->db->_wrapResult($result, $this->result_types, - $result_class, $result_wrap_class, $this->limit, $this->offset); - $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result)); - return $result; - } - - // }}} - // {{{ free() - - /** - * Release resources allocated for the specified prepared query. - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function free() - { - if (is_null($this->positions)) { - return $this->db->raiseError(MDB2_ERROR, null, null, - 'Prepared statement has already been freed', __FUNCTION__); - } - $result = MDB2_OK; - - if (!is_null($this->statement)) { - $connection = $this->db->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - $query = 'DEALLOCATE PREPARE '.$this->statement; - $result = $this->db->_doQuery($query, true, $connection); - } - - parent::free(); - return $result; - } -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/sqlite.php b/3rdparty/MDB2/Driver/sqlite.php deleted file mode 100644 index 5d2ad27d01..0000000000 --- a/3rdparty/MDB2/Driver/sqlite.php +++ /dev/null @@ -1,1088 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.165 2008/11/30 14:28:01 afz Exp $ -// - -/** - * MDB2 SQLite driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_sqlite extends MDB2_Driver_Common -{ - // {{{ properties - var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false); - - var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"'); - - var $_lasterror = ''; - - var $fix_assoc_fields_names = false; - - // }}} - // {{{ constructor - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - - $this->phptype = 'sqlite'; - $this->dbsyntax = 'sqlite'; - - $this->supported['sequences'] = 'emulated'; - $this->supported['indexes'] = true; - $this->supported['affected_rows'] = true; - $this->supported['summary_functions'] = true; - $this->supported['order_by_text'] = true; - $this->supported['current_id'] = 'emulated'; - $this->supported['limit_queries'] = true; - $this->supported['LOBs'] = true; - $this->supported['replace'] = true; - $this->supported['transactions'] = true; - $this->supported['savepoints'] = false; - $this->supported['sub_selects'] = true; - $this->supported['triggers'] = true; - $this->supported['auto_increment'] = true; - $this->supported['primary_key'] = false; // requires alter table implementation - $this->supported['result_introspection'] = false; // not implemented - $this->supported['prepared_statements'] = 'emulated'; - $this->supported['identifier_quoting'] = true; - $this->supported['pattern_escaping'] = false; - $this->supported['new_link'] = false; - - $this->options['DBA_username'] = false; - $this->options['DBA_password'] = false; - $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off'; - $this->options['fixed_float'] = 0; - $this->options['database_path'] = ''; - $this->options['database_extension'] = ''; - $this->options['server_version'] = ''; - $this->options['max_identifiers_length'] = 128; //no real limit - } - - // }}} - // {{{ errorInfo() - - /** - * This method is used to collect information about an error - * - * @param integer $error - * @return array - * @access public - */ - function errorInfo($error = null) - { - $native_code = null; - if ($this->connection) { - $native_code = @sqlite_last_error($this->connection); - } - $native_msg = $this->_lasterror - ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code); - - // PHP 5.2+ prepends the function name to $php_errormsg, so we need - // this hack to work around it, per bug #9599. - $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg); - - if (is_null($error)) { - static $error_regexps; - if (empty($error_regexps)) { - $error_regexps = array( - '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE, - '/^no such index:/' => MDB2_ERROR_NOT_FOUND, - '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS, - '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT, - '/is not unique/' => MDB2_ERROR_CONSTRAINT, - '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT, - '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT, - '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL, - '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD, - '/no column named/' => MDB2_ERROR_NOSUCHFIELD, - '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD, - '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX, - '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW, - ); - } - foreach ($error_regexps as $regexp => $code) { - if (preg_match($regexp, $native_msg)) { - $error = $code; - break; - } - } - } - return array($error, $native_code, $native_msg); - } - - // }}} - // {{{ escape() - - /** - * Quotes a string so it can be safely used in a query. It will quote - * the text so it can safely be used within a query. - * - * @param string the input string to quote - * @param bool escape wildcards - * - * @return string quoted string - * - * @access public - */ - function escape($text, $escape_wildcards = false) - { - $text = @sqlite_escape_string($text); - return $text; - } - - // }}} - // {{{ beginTransaction() - - /** - * Start a transaction or set a savepoint. - * - * @param string name of a savepoint to set - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function beginTransaction($savepoint = null) - { - $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!is_null($savepoint)) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } elseif ($this->in_transaction) { - return MDB2_OK; //nothing to do - } - if (!$this->destructor_registered && $this->opened_persistent) { - $this->destructor_registered = true; - register_shutdown_function('MDB2_closeOpenTransactions'); - } - $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name']; - $result =$this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = true; - return MDB2_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the database changes done during a transaction that is in - * progress or release a savepoint. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after committing the pending changes. - * - * @param string name of a savepoint to release - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function commit($savepoint = null) - { - $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__); - } - if (!is_null($savepoint)) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - - $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name']; - $result =$this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = false; - return MDB2_OK; - } - - // }}} - // {{{ - - /** - * Cancel any database changes done during a transaction or since a specific - * savepoint that is in progress. This function may only be called when - * auto-committing is disabled, otherwise it will fail. Therefore, a new - * transaction is implicitly started after canceling the pending changes. - * - * @param string name of a savepoint to rollback to - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - */ - function rollback($savepoint = null) - { - $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint)); - if (!$this->in_transaction) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'rollback cannot be done changes are auto committed', __FUNCTION__); - } - if (!is_null($savepoint)) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - - $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name']; - $result =$this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = false; - return MDB2_OK; - } - - // }}} - // {{{ function setTransactionIsolation() - - /** - * Set the transacton isolation level. - * - * @param string standard isolation level - * READ UNCOMMITTED (allows dirty reads) - * READ COMMITTED (prevents dirty reads) - * REPEATABLE READ (prevents nonrepeatable reads) - * SERIALIZABLE (prevents phantom reads) - * @return mixed MDB2_OK on success, a MDB2 error on failure - * - * @access public - * @since 2.1.1 - */ - static function setTransactionIsolation($isolation,$options=array()) - { - $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true)); - switch ($isolation) { - case 'READ UNCOMMITTED': - $isolation = 0; - break; - case 'READ COMMITTED': - case 'REPEATABLE READ': - case 'SERIALIZABLE': - $isolation = 1; - break; - default: - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'isolation level is not supported: '.$isolation, __FUNCTION__); - } - - $query = "PRAGMA read_uncommitted=$isolation"; - return $this->_doQuery($query, true); - } - - // }}} - // {{{ getDatabaseFile() - - /** - * Builds the string with path+dbname+extension - * - * @return string full database path+file - * @access protected - */ - function _getDatabaseFile($database_name) - { - if ($database_name === '' || $database_name === ':memory:') { - return $database_name; - } - return $this->options['database_path'].$database_name.$this->options['database_extension']; - } - - // }}} - // {{{ connect() - - /** - * Connect to the database - * - * @return true on success, MDB2 Error Object on failure - **/ - function connect() - { - $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); - $database_file = $this->_getDatabaseFile($this->database_name); - if (is_resource($this->connection)) { - //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0 - if (MDB2::areEquals($this->connected_dsn, $this->dsn) - && $this->connected_database_name == $database_file - && $this->opened_persistent == $this->options['persistent'] - ) { - return MDB2_OK; - } - $this->disconnect(false); - } - - if (!PEAR::loadExtension($this->phptype)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__); - } - - if (empty($this->database_name)) { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - 'unable to establish a connection', __FUNCTION__); - } - - if ($database_file !== ':memory:') { - if(!strpos($database_file,'.db')){ - $database_file="$datadir/$database_file.db"; - } - if (!file_exists($database_file)) { - if (!touch($database_file)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Could not create database file', __FUNCTION__); - } - if (!isset($this->dsn['mode']) - || !is_numeric($this->dsn['mode']) - ) { - $mode = 0644; - } else { - $mode = octdec($this->dsn['mode']); - } - if (!chmod($database_file, $mode)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Could not be chmodded database file', __FUNCTION__); - } - if (!file_exists($database_file)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Could not be found database file', __FUNCTION__); - } - } - if (!is_file($database_file)) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'Database is a directory name', __FUNCTION__); - } - if (!is_readable($database_file)) { - return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null, - 'Could not read database file', __FUNCTION__); - } - } - - $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open'); - $php_errormsg = ''; - if (version_compare('5.1.0', PHP_VERSION, '>')) { - @ini_set('track_errors', true); - echo 1; - $connection = @$connect_function($database_file); - echo 2; - @ini_restore('track_errors'); - } else { - $connection = @$connect_function($database_file, 0666, $php_errormsg); - } - $this->_lasterror = $php_errormsg; - if (!$connection) { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - 'unable to establish a connection', __FUNCTION__); - } - - if ($this->fix_assoc_fields_names || - $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES) - { - @sqlite_query("PRAGMA short_column_names = 1", $connection); - $this->fix_assoc_fields_names = true; - } - - $this->connection = $connection; - $this->connected_dsn = $this->dsn; - $this->connected_database_name = $database_file; - $this->opened_persistent = $this->getoption('persistent'); - $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype; - - return MDB2_OK; - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - $database_file = $this->_getDatabaseFile($name); - $result = file_exists($database_file); - return $result; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @param boolean $force if the disconnect should be forced even if the - * connection is opened persistently - * @return mixed true on success, false if not connected and error - * object on error - * @access public - */ - function disconnect($force = true) - { - if (is_resource($this->connection)) { - if ($this->in_transaction) { - $dsn = $this->dsn; - $database_name = $this->database_name; - $persistent = $this->options['persistent']; - $this->dsn = $this->connected_dsn; - $this->database_name = $this->connected_database_name; - $this->options['persistent'] = $this->opened_persistent; - $this->rollback(); - $this->dsn = $dsn; - $this->database_name = $database_name; - $this->options['persistent'] = $persistent; - } - - if (!$this->opened_persistent || $force) { - @sqlite_close($this->connection); - } - } else { - return false; - } - return parent::disconnect($force); - } - - // }}} - // {{{ _doQuery() - - /** - * Execute a query - * @param string $query query - * @param boolean $is_manip if the query is a manipulation query - * @param resource $connection - * @param string $database_name - * @return result or error object - * @access protected - */ - function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null) - { - $this->last_query = $query; - $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre')); - if ($result) { - if (PEAR::isError($result)) { - return $result; - } - $query = $result; - } - if ($this->options['disable_query']) { - $result = $is_manip ? 0 : null; - return $result; - } - - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - - $function = $this->options['result_buffering'] - ? 'sqlite_query' : 'sqlite_unbuffered_query'; - $php_errormsg = ''; - if (version_compare('5.1.0', PHP_VERSION, '>')) { - @ini_set('track_errors', true); - do { - $result = @$function($query.';', $connection); - } while (sqlite_last_error($connection) == SQLITE_SCHEMA); - @ini_restore('track_errors'); - } else { - do { - $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg); - } while (sqlite_last_error($connection) == SQLITE_SCHEMA); - } - $this->_lasterror = $php_errormsg; - - if (!$result) { - $err =$this->raiseError(null, null, null, - 'Could not execute statement', __FUNCTION__); - return $err; - } - - $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result)); - return $result; - } - - // }}} - // {{{ _affectedRows() - - /** - * Returns the number of rows affected - * - * @param resource $result - * @param resource $connection - * @return mixed MDB2 Error Object or the number of rows affected - * @access private - */ - function _affectedRows($connection, $result = null) - { - if (is_null($connection)) { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - } - return @sqlite_changes($connection); - } - - // }}} - // {{{ _modifyQuery() - - /** - * Changes a query string for various DBMS specific reasons - * - * @param string $query query to modify - * @param boolean $is_manip if it is a DML query - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string modified query - * @access protected - */ - function _modifyQuery($query, $is_manip, $limit, $offset) - { - if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) { - if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) { - $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/', - 'DELETE FROM \1 WHERE 1=1', $query); - } - } - if ($limit > 0 - && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query) - ) { - $query = rtrim($query); - if (substr($query, -1) == ';') { - $query = substr($query, 0, -1); - } - if ($is_manip) { - $query.= " LIMIT $limit"; - } else { - $query.= " LIMIT $offset,$limit"; - } - } - return $query; - } - - // }}} - // {{{ getServerVersion() - - /** - * return version information about the server - * - * @param bool $native determines if the raw version string should be returned - * @return mixed array/string with version information or MDB2 error object - * @access public - */ - function getServerVersion($native = false) - { - $server_info = false; - if ($this->connected_server_info) { - $server_info = $this->connected_server_info; - } elseif ($this->options['server_version']) { - $server_info = $this->options['server_version']; - } elseif (function_exists('sqlite_libversion')) { - $server_info = @sqlite_libversion(); - } - if (!$server_info) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__); - } - // cache server_info - $this->connected_server_info = $server_info; - if (!$native) { - $tmp = explode('.', $server_info, 3); - $server_info = array( - 'major' => isset($tmp[0]) ? $tmp[0] : null, - 'minor' => isset($tmp[1]) ? $tmp[1] : null, - 'patch' => isset($tmp[2]) ? $tmp[2] : null, - 'extra' => null, - 'native' => $server_info, - ); - } - return $server_info; - } - - // }}} - // {{{ replace() - - /** - * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT - * query, except that if there is already a row in the table with the same - * key field values, the old row is deleted before the new row is inserted. - * - * The REPLACE type of query does not make part of the SQL standards. Since - * practically only SQLite implements it natively, this type of query is - * emulated through this method for other DBMS using standard types of - * queries inside a transaction to assure the atomicity of the operation. - * - * @access public - * - * @param string $table name of the table on which the REPLACE query will - * be executed. - * @param array $fields associative array that describes the fields and the - * values that will be inserted or updated in the specified table. The - * indexes of the array are the names of all the fields of the table. The - * values of the array are also associative arrays that describe the - * values and other properties of the table fields. - * - * Here follows a list of field properties that need to be specified: - * - * value: - * Value to be assigned to the specified field. This value may be - * of specified in database independent type format as this - * function can perform the necessary datatype conversions. - * - * Default: - * this property is required unless the Null property - * is set to 1. - * - * type - * Name of the type of the field. Currently, all types Metabase - * are supported except for clob and blob. - * - * Default: no type conversion - * - * null - * Boolean property that indicates that the value for this field - * should be set to null. - * - * The default value for fields missing in INSERT queries may be - * specified the definition of a table. Often, the default value - * is already null, but since the REPLACE may be emulated using - * an UPDATE query, make sure that all fields of the table are - * listed in this function argument array. - * - * Default: 0 - * - * key - * Boolean property that indicates that this field should be - * handled as a primary key or at least as part of the compound - * unique index of the table that will determine the row that will - * updated if it exists or inserted a new row otherwise. - * - * This function will fail if no key field is specified or if the - * value of a key field is set to null because fields that are - * part of unique index they may not be null. - * - * Default: 0 - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - */ - function replace($table, $fields) - { - $count = count($fields); - $query = $values = ''; - $keys = $colnum = 0; - for (reset($fields); $colnum < $count; next($fields), $colnum++) { - $name = key($fields); - if ($colnum > 0) { - $query .= ','; - $values.= ','; - } - $query.= $this->quoteIdentifier($name, true); - if (isset($fields[$name]['null']) && $fields[$name]['null']) { - $value = 'NULL'; - } else { - $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null; - $value = $this->quote($fields[$name]['value'], $type); - if (PEAR::isError($value)) { - return $value; - } - } - $values.= $value; - if (isset($fields[$name]['key']) && $fields[$name]['key']) { - if ($value === 'NULL') { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'key value '.$name.' may not be NULL', __FUNCTION__); - } - $keys++; - } - } - if ($keys == 0) { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'not specified which fields are keys', __FUNCTION__); - } - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $table = $this->quoteIdentifier($table, true); - $query = "REPLACE INTO $table ($query) VALUES ($values)"; - $result =$this->_doQuery($query, true, $connection); - if (PEAR::isError($result)) { - return $result; - } - return $this->_affectedRows($connection, $result); - } - - // }}} - // {{{ nextID() - - /** - * Returns the next free id of a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true the sequence is - * automatic created, if it - * not exists - * - * @return mixed MDB2 Error Object or id - * @access public - */ - function nextID($seq_name, $ondemand = true) - { - $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true); - $seqcol_name = $this->options['seqcol_name']; - $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)"; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $this->expectError(MDB2_ERROR_NOSUCHTABLE); - $result =$this->_doQuery($query, true); - $this->popExpect(); - $this->popErrorHandling(); - if (PEAR::isError($result)) { - if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) { - $this->loadModule('Manager', null, true); - $result = $this->manager->createSequence($seq_name); - if (PEAR::isError($result)) { - return $this->raiseError($result, null, null, - 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__); - } else { - return $this->nextID($seq_name, false); - } - } - return $result; - } - $value = $this->lastInsertID(); - if (is_numeric($value)) { - $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value"; - $result =$this->_doQuery($query, true); - if (PEAR::isError($result)) { - $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name; - } - } - return $value; - } - - // }}} - // {{{ lastInsertID() - - /** - * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) - * - * @param string $table name of the table into which a new row was inserted - * @param string $field name of the field into which a new row was inserted - * @return mixed MDB2 Error Object or id - * @access public - */ - function lastInsertID($table = null, $field = null) - { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - $value = @sqlite_last_insert_rowid($connection); - if (!$value) { - return $this->raiseError(null, null, null, - 'Could not get last insert ID', __FUNCTION__); - } - return $value; - } - - // }}} - // {{{ currID() - - /** - * Returns the current id of a sequence - * - * @param string $seq_name name of the sequence - * @return mixed MDB2 Error Object or id - * @access public - */ - function currID($seq_name) - { - $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true); - $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true); - $query = "SELECT MAX($seqcol_name) FROM $sequence_name"; - return $this->queryOne($query, 'integer'); - } -} - -/** - * MDB2 SQLite result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Result_sqlite extends MDB2_Result_Common -{ - // }}} - // {{{ fetchRow() - - /** - * Fetch a row and insert the data into an existing array. - * - * @param int $fetchmode how the array data should be indexed - * @param int $rownum number of the row where the data can be found - * @return int data array on success, a MDB2 error on failure - * @access public - */ - function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null) - { - if (!is_null($rownum)) { - $seek = $this->seek($rownum); - if (PEAR::isError($seek)) { - return $seek; - } - } - if ($fetchmode == MDB2_FETCHMODE_DEFAULT) { - $fetchmode = $this->db->fetchmode; - } - if ($fetchmode & MDB2_FETCHMODE_ASSOC) { - $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC); - if (is_array($row) - && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE - ) { - $row = array_change_key_case($row, $this->db->options['field_case']); - } - } else { - $row = @sqlite_fetch_array($this->result, SQLITE_NUM); - } - if (!$row) { - if ($this->result === false) { - $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - return $err; - } - $null = null; - return $null; - } - $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL; - $rtrim = false; - if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) { - if (empty($this->types)) { - $mode += MDB2_PORTABILITY_RTRIM; - } else { - $rtrim = true; - } - } - if ($mode) { - $this->db->_fixResultArrayValues($row, $mode); - } - if (!empty($this->types)) { - $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim); - } - if (!empty($this->values)) { - $this->_assignBindColumns($row); - } - if ($fetchmode === MDB2_FETCHMODE_OBJECT) { - $object_class = $this->db->options['fetch_class']; - if ($object_class == 'stdClass') { - $row = (object) $row; - } else { - $row = new $object_class($row); - } - } - ++$this->rownum; - return $row; - } - - // }}} - // {{{ _getColumnNames() - - /** - * Retrieve the names of columns returned by the DBMS in a query result. - * - * @return mixed Array variable that holds the names of columns as keys - * or an MDB2 error on failure. - * Some DBMS may not return any columns when the result set - * does not contain any rows. - * @access private - */ - function _getColumnNames() - { - $columns = array(); - $numcols = $this->numCols(); - if (PEAR::isError($numcols)) { - return $numcols; - } - for ($column = 0; $column < $numcols; $column++) { - $column_name = @sqlite_field_name($this->result, $column); - $columns[$column_name] = $column; - } - if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $columns = array_change_key_case($columns, $this->db->options['field_case']); - } - return $columns; - } - - // }}} - // {{{ numCols() - - /** - * Count the number of columns returned by the DBMS in a query result. - * - * @access public - * @return mixed integer value with the number of columns, a MDB2 error - * on failure - */ - function numCols() - { - $cols = @sqlite_num_fields($this->result); - if (is_null($cols)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return count($this->types); - } - return $this->db->raiseError(null, null, null, - 'Could not get column count', __FUNCTION__); - } - return $cols; - } -} - -/** - * MDB2 SQLite buffered result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite -{ - // {{{ seek() - - /** - * Seek to a specific row in a result set - * - * @param int $rownum number of the row where the data can be found - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function seek($rownum = 0) - { - if (!@sqlite_seek($this->result, $rownum)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return MDB2_OK; - } - return $this->db->raiseError(MDB2_ERROR_INVALID, null, null, - 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__); - } - $this->rownum = $rownum - 1; - return MDB2_OK; - } - - // }}} - // {{{ valid() - - /** - * Check if the end of the result set has been reached - * - * @return mixed true or false on sucess, a MDB2 error on failure - * @access public - */ - function valid() - { - $numrows = $this->numRows(); - if (PEAR::isError($numrows)) { - return $numrows; - } - return $this->rownum < ($numrows - 1); - } - - // }}} - // {{{ numRows() - - /** - * Returns the number of rows in a result object - * - * @return mixed MDB2 Error Object or the number of rows - * @access public - */ - function numRows() - { - $rows = @sqlite_num_rows($this->result); - if (is_null($rows)) { - if ($this->result === false) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } elseif (is_null($this->result)) { - return 0; - } - return $this->db->raiseError(null, null, null, - 'Could not get row count', __FUNCTION__); - } - return $rows; - } -} - -/** - * MDB2 SQLite statement driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Statement_sqlite extends MDB2_Statement_Common -{ - -} - -?> diff --git a/3rdparty/MDB2/Extended.php b/3rdparty/MDB2/Extended.php deleted file mode 100644 index 864ab92354..0000000000 --- a/3rdparty/MDB2/Extended.php +++ /dev/null @@ -1,721 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Extended.php,v 1.60 2007/11/28 19:49:34 quipo Exp $ - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * Used by autoPrepare() - */ -define('MDB2_AUTOQUERY_INSERT', 1); -define('MDB2_AUTOQUERY_UPDATE', 2); -define('MDB2_AUTOQUERY_DELETE', 3); -define('MDB2_AUTOQUERY_SELECT', 4); - -/** - * MDB2_Extended: class which adds several high level methods to MDB2 - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Extended extends MDB2_Module_Common -{ - // {{{ autoPrepare() - - /** - * Generate an insert, update or delete query and call prepare() on it - * - * @param string table - * @param array the fields names - * @param int type of query to build - * MDB2_AUTOQUERY_INSERT - * MDB2_AUTOQUERY_UPDATE - * MDB2_AUTOQUERY_DELETE - * MDB2_AUTOQUERY_SELECT - * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement) - * @param array that contains the types of the placeholders - * @param mixed array that contains the types of the columns in - * the result set or MDB2_PREPARE_RESULT, if set to - * MDB2_PREPARE_MANIP the query is handled as a manipulation query - * - * @return resource handle for the query - * @see buildManipSQL - * @access public - */ - function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT, - $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP) - { - $query = $this->buildManipSQL($table, $table_fields, $mode, $where); - if (PEAR::isError($query)) { - return $query; - } - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $lobs = array(); - foreach ((array)$types as $param => $type) { - if (($type == 'clob') || ($type == 'blob')) { - $lobs[$param] = $table_fields[$param]; - } - } - return $db->prepare($query, $types, $result_types, $lobs); - } - - // }}} - // {{{ autoExecute() - - /** - * Generate an insert, update or delete query and call prepare() and execute() on it - * - * @param string name of the table - * @param array assoc ($key=>$value) where $key is a field name and $value its value - * @param int type of query to build - * MDB2_AUTOQUERY_INSERT - * MDB2_AUTOQUERY_UPDATE - * MDB2_AUTOQUERY_DELETE - * MDB2_AUTOQUERY_SELECT - * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement) - * @param array that contains the types of the placeholders - * @param string which specifies which result class to use - * @param mixed array that contains the types of the columns in - * the result set or MDB2_PREPARE_RESULT, if set to - * MDB2_PREPARE_MANIP the query is handled as a manipulation query - * - * @return bool|MDB2_Error true on success, a MDB2 error on failure - * @see buildManipSQL - * @see autoPrepare - * @access public - */ - function &autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT, - $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP) - { - $fields_values = (array)$fields_values; - if ($mode == MDB2_AUTOQUERY_SELECT) { - if (is_array($result_types)) { - $keys = array_keys($result_types); - } elseif (!empty($fields_values)) { - $keys = $fields_values; - } else { - $keys = array(); - } - } else { - $keys = array_keys($fields_values); - } - $params = array_values($fields_values); - if (empty($params)) { - $query = $this->buildManipSQL($table, $keys, $mode, $where); - - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if ($mode == MDB2_AUTOQUERY_SELECT) { - $result =& $db->query($query, $result_types, $result_class); - } else { - $result = $db->exec($query); - } - } else { - $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types); - if (PEAR::isError($stmt)) { - return $stmt; - } - $result =& $stmt->execute($params, $result_class); - $stmt->free(); - } - return $result; - } - - // }}} - // {{{ buildManipSQL() - - /** - * Make automaticaly an sql query for prepare() - * - * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT) - * will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?) - * NB : - This belongs more to a SQL Builder class, but this is a simple facility - * - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all - * the records of the table will be updated/deleted ! - * - * @param string name of the table - * @param ordered array containing the fields names - * @param int type of query to build - * MDB2_AUTOQUERY_INSERT - * MDB2_AUTOQUERY_UPDATE - * MDB2_AUTOQUERY_DELETE - * MDB2_AUTOQUERY_SELECT - * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement) - * - * @return string sql query for prepare() - * @access public - */ - function buildManipSQL($table, $table_fields, $mode, $where = false) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if ($db->options['quote_identifier']) { - $table = $db->quoteIdentifier($table); - } - - if (!empty($table_fields) && $db->options['quote_identifier']) { - foreach ($table_fields as $key => $field) { - $table_fields[$key] = $db->quoteIdentifier($field); - } - } - - if ($where !== false && !is_null($where)) { - if (is_array($where)) { - $where = implode(' AND ', $where); - } - $where = ' WHERE '.$where; - } - - switch ($mode) { - case MDB2_AUTOQUERY_INSERT: - if (empty($table_fields)) { - return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'Insert requires table fields', __FUNCTION__); - } - $cols = implode(', ', $table_fields); - $values = '?'.str_repeat(', ?', (count($table_fields) - 1)); - return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')'; - break; - case MDB2_AUTOQUERY_UPDATE: - if (empty($table_fields)) { - return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'Update requires table fields', __FUNCTION__); - } - $set = implode(' = ?, ', $table_fields).' = ?'; - $sql = 'UPDATE '.$table.' SET '.$set.$where; - return $sql; - break; - case MDB2_AUTOQUERY_DELETE: - $sql = 'DELETE FROM '.$table.$where; - return $sql; - break; - case MDB2_AUTOQUERY_SELECT: - $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*'; - $sql = 'SELECT '.$cols.' FROM '.$table.$where; - return $sql; - break; - } - return $db->raiseError(MDB2_ERROR_SYNTAX, null, null, - 'Non existant mode', __FUNCTION__); - } - - // }}} - // {{{ limitQuery() - - /** - * Generates a limited query - * - * @param string query - * @param array that contains the types of the columns in the result set - * @param integer the numbers of rows to fetch - * @param integer the row to start to fetching - * @param string which specifies which result class to use - * @param mixed string which specifies which class to wrap results in - * - * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure - * @access public - */ - function &limitQuery($query, $types, $limit, $offset = 0, $result_class = true, - $result_wrap_class = false) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $result = $db->setLimit($limit, $offset); - if (PEAR::isError($result)) { - return $result; - } - $result =& $db->query($query, $types, $result_class, $result_wrap_class); - return $result; - } - - // }}} - // {{{ execParam() - - /** - * Execute a parameterized DML statement. - * - * @param string the SQL query - * @param array if supplied, prepare/execute will be used - * with this array as execute parameters - * @param array that contains the types of the values defined in $params - * - * @return int|MDB2_Error affected rows on success, a MDB2 error on failure - * @access public - */ - function execParam($query, $params = array(), $param_types = null) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - settype($params, 'array'); - if (empty($params)) { - return $db->exec($query); - } - - $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP); - if (PEAR::isError($stmt)) { - return $stmt; - } - - $result = $stmt->execute($params); - if (PEAR::isError($result)) { - return $result; - } - - $stmt->free(); - return $result; - } - - // }}} - // {{{ getOne() - - /** - * Fetch the first column of the first row of data returned from a query. - * Takes care of doing the query and freeing the results when finished. - * - * @param string the SQL query - * @param string that contains the type of the column in the result set - * @param array if supplied, prepare/execute will be used - * with this array as execute parameters - * @param array that contains the types of the values defined in $params - * @param int|string which column to return - * - * @return scalar|MDB2_Error data on success, a MDB2 error on failure - * @access public - */ - function getOne($query, $type = null, $params = array(), - $param_types = null, $colnum = 0) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - settype($params, 'array'); - settype($type, 'array'); - if (empty($params)) { - return $db->queryOne($query, $type, $colnum); - } - - $stmt = $db->prepare($query, $param_types, $type); - if (PEAR::isError($stmt)) { - return $stmt; - } - - $result = $stmt->execute($params); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $one = $result->fetchOne($colnum); - $stmt->free(); - $result->free(); - return $one; - } - - // }}} - // {{{ getRow() - - /** - * Fetch the first row of data returned from a query. Takes care - * of doing the query and freeing the results when finished. - * - * @param string the SQL query - * @param array that contains the types of the columns in the result set - * @param array if supplied, prepare/execute will be used - * with this array as execute parameters - * @param array that contains the types of the values defined in $params - * @param int the fetch mode to use - * - * @return array|MDB2_Error data on success, a MDB2 error on failure - * @access public - */ - function getRow($query, $types = null, $params = array(), - $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - settype($params, 'array'); - if (empty($params)) { - return $db->queryRow($query, $types, $fetchmode); - } - - $stmt = $db->prepare($query, $param_types, $types); - if (PEAR::isError($stmt)) { - return $stmt; - } - - $result = $stmt->execute($params); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $row = $result->fetchRow($fetchmode); - $stmt->free(); - $result->free(); - return $row; - } - - // }}} - // {{{ getCol() - - /** - * Fetch a single column from a result set and return it as an - * indexed array. - * - * @param string the SQL query - * @param string that contains the type of the column in the result set - * @param array if supplied, prepare/execute will be used - * with this array as execute parameters - * @param array that contains the types of the values defined in $params - * @param int|string which column to return - * - * @return array|MDB2_Error data on success, a MDB2 error on failure - * @access public - */ - function getCol($query, $type = null, $params = array(), - $param_types = null, $colnum = 0) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - settype($params, 'array'); - settype($type, 'array'); - if (empty($params)) { - return $db->queryCol($query, $type, $colnum); - } - - $stmt = $db->prepare($query, $param_types, $type); - if (PEAR::isError($stmt)) { - return $stmt; - } - - $result = $stmt->execute($params); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $col = $result->fetchCol($colnum); - $stmt->free(); - $result->free(); - return $col; - } - - // }}} - // {{{ getAll() - - /** - * Fetch all the rows returned from a query. - * - * @param string the SQL query - * @param array that contains the types of the columns in the result set - * @param array if supplied, prepare/execute will be used - * with this array as execute parameters - * @param array that contains the types of the values defined in $params - * @param int the fetch mode to use - * @param bool if set to true, the $all will have the first - * column as its first dimension - * @param bool $force_array used only when the query returns exactly - * two columns. If true, the values of the returned array will be - * one-element arrays instead of scalars. - * @param bool $group if true, the values of the returned array is - * wrapped in another array. If the same key value (in the first - * column) repeats itself, the values will be appended to this array - * instead of overwriting the existing values. - * - * @return array|MDB2_Error data on success, a MDB2 error on failure - * @access public - */ - function getAll($query, $types = null, $params = array(), - $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, - $rekey = false, $force_array = false, $group = false) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - settype($params, 'array'); - if (empty($params)) { - return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group); - } - - $stmt = $db->prepare($query, $param_types, $types); - if (PEAR::isError($stmt)) { - return $stmt; - } - - $result = $stmt->execute($params); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group); - $stmt->free(); - $result->free(); - return $all; - } - - // }}} - // {{{ getAssoc() - - /** - * Fetch the entire result set of a query and return it as an - * associative array using the first column as the key. - * - * If the result set contains more than two columns, the value - * will be an array of the values from column 2-n. If the result - * set contains only two columns, the returned value will be a - * scalar with the value of the second column (unless forced to an - * array with the $force_array parameter). A MDB2 error code is - * returned on errors. If the result set contains fewer than two - * columns, a MDB2_ERROR_TRUNCATED error is returned. - * - * For example, if the table 'mytable' contains: - *
-     *   ID      TEXT       DATE
-     * --------------------------------
-     *   1       'one'      944679408
-     *   2       'two'      944679408
-     *   3       'three'    944679408
-     * 
- * Then the call getAssoc('SELECT id,text FROM mytable') returns: - *
-     *    array(
-     *      '1' => 'one',
-     *      '2' => 'two',
-     *      '3' => 'three',
-     *    )
-     * 
- * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns: - *
-     *    array(
-     *      '1' => array('one', '944679408'),
-     *      '2' => array('two', '944679408'),
-     *      '3' => array('three', '944679408')
-     *    )
-     * 
- * - * If the more than one row occurs with the same value in the - * first column, the last row overwrites all previous ones by - * default. Use the $group parameter if you don't want to - * overwrite like this. Example: - *
-     * getAssoc('SELECT category,id,name FROM mytable', null, null
-     *           MDB2_FETCHMODE_ASSOC, false, true) returns:
-     *    array(
-     *      '1' => array(array('id' => '4', 'name' => 'number four'),
-     *                   array('id' => '6', 'name' => 'number six')
-     *             ),
-     *      '9' => array(array('id' => '4', 'name' => 'number four'),
-     *                   array('id' => '6', 'name' => 'number six')
-     *             )
-     *    )
-     * 
- * - * Keep in mind that database functions in PHP usually return string - * values for results regardless of the database's internal type. - * - * @param string the SQL query - * @param array that contains the types of the columns in the result set - * @param array if supplied, prepare/execute will be used - * with this array as execute parameters - * @param array that contains the types of the values defined in $params - * @param bool $force_array used only when the query returns - * exactly two columns. If TRUE, the values of the returned array - * will be one-element arrays instead of scalars. - * @param bool $group if TRUE, the values of the returned array - * is wrapped in another array. If the same key value (in the first - * column) repeats itself, the values will be appended to this array - * instead of overwriting the existing values. - * - * @return array|MDB2_Error data on success, a MDB2 error on failure - * @access public - */ - function getAssoc($query, $types = null, $params = array(), $param_types = null, - $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - settype($params, 'array'); - if (empty($params)) { - return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group); - } - - $stmt = $db->prepare($query, $param_types, $types); - if (PEAR::isError($stmt)) { - return $stmt; - } - - $result = $stmt->execute($params); - if (!MDB2::isResultCommon($result)) { - return $result; - } - - $all = $result->fetchAll($fetchmode, true, $force_array, $group); - $stmt->free(); - $result->free(); - return $all; - } - - // }}} - // {{{ executeMultiple() - - /** - * This function does several execute() calls on the same statement handle. - * $params must be an array indexed numerically from 0, one execute call is - * done for every 'row' in the array. - * - * If an error occurs during execute(), executeMultiple() does not execute - * the unfinished rows, but rather returns that error. - * - * @param resource query handle from prepare() - * @param array numeric array containing the data to insert into the query - * - * @return bool|MDB2_Error true on success, a MDB2 error on failure - * @access public - * @see prepare(), execute() - */ - function executeMultiple(&$stmt, $params = null) - { - for ($i = 0, $j = count($params); $i < $j; $i++) { - $result = $stmt->execute($params[$i]); - if (PEAR::isError($result)) { - return $result; - } - } - return MDB2_OK; - } - - // }}} - // {{{ getBeforeID() - - /** - * Returns the next free id of a sequence if the RDBMS - * does not support auto increment - * - * @param string name of the table into which a new row was inserted - * @param string name of the field into which a new row was inserted - * @param bool when true the sequence is automatic created, if it not exists - * @param bool if the returned value should be quoted - * - * @return int|MDB2_Error id on success, a MDB2 error on failure - * @access public - */ - function getBeforeID($table, $field = null, $ondemand = true, $quote = true) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if ($db->supports('auto_increment') !== true) { - $seq = $table.(empty($field) ? '' : '_'.$field); - $id = $db->nextID($seq, $ondemand); - if (!$quote || PEAR::isError($id)) { - return $id; - } - return $db->quote($id, 'integer'); - } elseif (!$quote) { - return null; - } - return 'NULL'; - } - - // }}} - // {{{ getAfterID() - - /** - * Returns the autoincrement ID if supported or $id - * - * @param mixed value as returned by getBeforeId() - * @param string name of the table into which a new row was inserted - * @param string name of the field into which a new row was inserted - * - * @return int|MDB2_Error id on success, a MDB2 error on failure - * @access public - */ - function getAfterID($id, $table, $field = null) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if ($db->supports('auto_increment') !== true) { - return $id; - } - return $db->lastInsertID($table, $field); - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Iterator.php b/3rdparty/MDB2/Iterator.php deleted file mode 100644 index ca5e7b69c2..0000000000 --- a/3rdparty/MDB2/Iterator.php +++ /dev/null @@ -1,259 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Iterator.php,v 1.22 2006/05/06 14:03:41 lsmith Exp $ - -/** - * PHP5 Iterator - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Iterator implements Iterator -{ - protected $fetchmode; - protected $result; - protected $row; - - // {{{ constructor - - /** - * Constructor - */ - public function __construct($result, $fetchmode = MDB2_FETCHMODE_DEFAULT) - { - $this->result = $result; - $this->fetchmode = $fetchmode; - } - // }}} - - // {{{ seek() - - /** - * Seek forward to a specific row in a result set - * - * @param int number of the row where the data can be found - * - * @return void - * @access public - */ - public function seek($rownum) - { - $this->row = null; - if ($this->result) { - $this->result->seek($rownum); - } - } - // }}} - - // {{{ next() - - /** - * Fetch next row of data - * - * @return void - * @access public - */ - public function next() - { - $this->row = null; - } - // }}} - - // {{{ current() - - /** - * return a row of data - * - * @return void - * @access public - */ - public function current() - { - if (is_null($this->row)) { - $row = $this->result->fetchRow($this->fetchmode); - if (PEAR::isError($row)) { - $row = false; - } - $this->row = $row; - } - return $this->row; - } - // }}} - - // {{{ valid() - - /** - * Check if the end of the result set has been reached - * - * @return bool true/false, false is also returned on failure - * @access public - */ - public function valid() - { - return (bool)$this->current(); - } - // }}} - - // {{{ free() - - /** - * Free the internal resources associated with result. - * - * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid - * @access public - */ - public function free() - { - if ($this->result) { - return $this->result->free(); - } - $this->result = false; - $this->row = null; - return false; - } - // }}} - - // {{{ key() - - /** - * Returns the row number - * - * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid - * @access public - */ - public function key() - { - if ($this->result) { - return $this->result->rowCount(); - } - return false; - } - // }}} - - // {{{ rewind() - - /** - * Seek to the first row in a result set - * - * @return void - * @access public - */ - public function rewind() - { - } - // }}} - - // {{{ destructor - - /** - * Destructor - */ - public function __destruct() - { - $this->free(); - } - // }}} -} - -/** - * PHP5 buffered Iterator - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator -{ - // {{{ valid() - - /** - * Check if the end of the result set has been reached - * - * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid - * @access public - */ - public function valid() - { - if ($this->result) { - return $this->result->valid(); - } - return false; - } - // }}} - - // {{{count() - - /** - * Returns the number of rows in a result object - * - * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid - * @access public - */ - public function count() - { - if ($this->result) { - return $this->result->numRows(); - } - return false; - } - // }}} - - // {{{ rewind() - - /** - * Seek to the first row in a result set - * - * @return void - * @access public - */ - public function rewind() - { - $this->seek(0); - } - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/LOB.php b/3rdparty/MDB2/LOB.php deleted file mode 100644 index ae67224020..0000000000 --- a/3rdparty/MDB2/LOB.php +++ /dev/null @@ -1,264 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: LOB.php,v 1.34 2006/10/25 11:52:21 lsmith Exp $ - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -require_once('MDB2.php'); - -/** - * MDB2_LOB: user land stream wrapper implementation for LOB support - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_LOB -{ - /** - * contains the key to the global MDB2 instance array of the associated - * MDB2 instance - * - * @var integer - * @access protected - */ - var $db_index; - - /** - * contains the key to the global MDB2_LOB instance array of the associated - * MDB2_LOB instance - * - * @var integer - * @access protected - */ - var $lob_index; - - // {{{ stream_open() - - /** - * open stream - * - * @param string specifies the URL that was passed to fopen() - * @param string the mode used to open the file - * @param int holds additional flags set by the streams API - * @param string not used - * - * @return bool - * @access public - */ - function stream_open($path, $mode, $options, &$opened_path) - { - if (!preg_match('/^rb?\+?$/', $mode)) { - return false; - } - $url = parse_url($path); - if (empty($url['host'])) { - return false; - } - $this->db_index = (int)$url['host']; - if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) { - return false; - } - $db =& $GLOBALS['_MDB2_databases'][$this->db_index]; - $this->lob_index = (int)$url['user']; - if (!isset($db->datatype->lobs[$this->lob_index])) { - return false; - } - return true; - } - // }}} - - // {{{ stream_read() - - /** - * read stream - * - * @param int number of bytes to read - * - * @return string - * @access public - */ - function stream_read($count) - { - if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) { - $db =& $GLOBALS['_MDB2_databases'][$this->db_index]; - $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]); - - $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count); - $length = strlen($data); - if ($length == 0) { - $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true; - } - $db->datatype->lobs[$this->lob_index]['position'] += $length; - return $data; - } - } - // }}} - - // {{{ stream_write() - - /** - * write stream, note implemented - * - * @param string data - * - * @return int - * @access public - */ - function stream_write($data) - { - return 0; - } - // }}} - - // {{{ stream_tell() - - /** - * return the current position - * - * @return int current position - * @access public - */ - function stream_tell() - { - if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) { - $db =& $GLOBALS['_MDB2_databases'][$this->db_index]; - return $db->datatype->lobs[$this->lob_index]['position']; - } - } - // }}} - - // {{{ stream_eof() - - /** - * Check if stream reaches EOF - * - * @return bool - * @access public - */ - function stream_eof() - { - if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) { - return true; - } - - $db =& $GLOBALS['_MDB2_databases'][$this->db_index]; - $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]); - if (version_compare(phpversion(), "5.0", ">=") - && version_compare(phpversion(), "5.1", "<") - ) { - return !$result; - } - return $result; - } - // }}} - - // {{{ stream_seek() - - /** - * Seek stream, not implemented - * - * @param int offset - * @param int whence - * - * @return bool - * @access public - */ - function stream_seek($offset, $whence) - { - return false; - } - // }}} - - // {{{ stream_stat() - - /** - * return information about stream - * - * @access public - */ - function stream_stat() - { - if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) { - $db =& $GLOBALS['_MDB2_databases'][$this->db_index]; - return array( - 'db_index' => $this->db_index, - 'lob_index' => $this->lob_index, - ); - } - } - // }}} - - // {{{ stream_close() - - /** - * close stream - * - * @access public - */ - function stream_close() - { - if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) { - $db =& $GLOBALS['_MDB2_databases'][$this->db_index]; - if (isset($db->datatype->lobs[$this->lob_index])) { - $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]); - unset($db->datatype->lobs[$this->lob_index]); - } - } - } - // }}} -} - -// register streams wrapper -if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) { - MDB2::raiseError(); - return false; -} - -?> diff --git a/3rdparty/MDB2/Schema.php b/3rdparty/MDB2/Schema.php deleted file mode 100644 index 25818460a6..0000000000 --- a/3rdparty/MDB2/Schema.php +++ /dev/null @@ -1,2763 +0,0 @@ - - * Author: Igor Feghali - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith - * @author Igor Feghali - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Schema.php,v 1.132 2009/02/22 21:43:22 ifeghali Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -// require_once('MDB2.php'); - -define('MDB2_SCHEMA_DUMP_ALL', 0); -define('MDB2_SCHEMA_DUMP_STRUCTURE', 1); -define('MDB2_SCHEMA_DUMP_CONTENT', 2); - -/** - * If you add an error code here, make sure you also add a textual - * version of it in MDB2_Schema::errorMessage(). - */ - -define('MDB2_SCHEMA_ERROR', -1); -define('MDB2_SCHEMA_ERROR_PARSE', -2); -define('MDB2_SCHEMA_ERROR_VALIDATE', -3); -define('MDB2_SCHEMA_ERROR_UNSUPPORTED', -4); // Driver does not support this function -define('MDB2_SCHEMA_ERROR_INVALID', -5); // Invalid attribute value -define('MDB2_SCHEMA_ERROR_WRITER', -6); - -/** - * The database manager is a class that provides a set of database - * management services like installing, altering and dumping the data - * structures of databases. - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema extends PEAR -{ - // {{{ properties - - var $db; - - var $warnings = array(); - - var $options = array( - 'fail_on_invalid_names' => true, - 'dtd_file' => false, - 'valid_types' => array(), - 'force_defaults' => true, - 'parser' => 'MDB2_Schema_Parser', - 'writer' => 'MDB2_Schema_Writer', - 'validate' => 'MDB2_Schema_Validate', - 'drop_missing_tables' => false - ); - - // }}} - // {{{ apiVersion() - - /** - * Return the MDB2 API version - * - * @return string the MDB2 API version number - * @access public - */ - function apiVersion() - { - return '0.4.3'; - } - - // }}} - // {{{ arrayMergeClobber() - - /** - * Clobbers two arrays together - * - * @param array $a1 array that should be clobbered - * @param array $a2 array that should be clobbered - * - * @return array|false array on success and false on error - * - * @access public - * @author kc@hireability.com - */ - function arrayMergeClobber($a1, $a2) - { - if (!is_array($a1) || !is_array($a2)) { - return false; - } - foreach ($a2 as $key => $val) { - if (is_array($val) && array_key_exists($key, $a1) && is_array($a1[$key])) { - $a1[$key] = MDB2_Schema::arrayMergeClobber($a1[$key], $val); - } else { - $a1[$key] = $val; - } - } - return $a1; - } - - // }}} - // {{{ resetWarnings() - - /** - * reset the warning array - * - * @access public - * @return void - */ - function resetWarnings() - { - $this->warnings = array(); - } - - // }}} - // {{{ getWarnings() - - /** - * Get all warnings in reverse order - * - * This means that the last warning is the first element in the array - * - * @return array with warnings - * @access public - * @see resetWarnings() - */ - function getWarnings() - { - return array_reverse($this->warnings); - } - - // }}} - // {{{ setOption() - - /** - * Sets the option for the db class - * - * @param string $option option name - * @param mixed $value value for the option - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function setOption($option, $value) - { - if (isset($this->options[$option])) { - if (is_null($value)) { - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'may not set an option to value null'); - } - $this->options[$option] = $value; - return MDB2_OK; - } - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - "unknown option $option"); - } - - // }}} - // {{{ getOption() - - /** - * returns the value of an option - * - * @param string $option option name - * - * @return mixed the option value or error object - * @access public - */ - function getOption($option) - { - if (isset($this->options[$option])) { - return $this->options[$option]; - } - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, - null, null, "unknown option $option"); - } - - // }}} - // {{{ factory() - - /** - * Create a new MDB2 object for the specified database type - * type - * - * @param string|array|MDB2_Driver_Common &$db 'data source name', see the - * MDB2::parseDSN method for a description of the dsn format. - * Can also be specified as an array of the - * format returned by @see MDB2::parseDSN. - * Finally you can also pass an existing db object to be used. - * @param array $options An associative array of option names and their values. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - * @see MDB2::parseDSN - */ - static function factory(&$db, $options = array()) - { - $obj =new MDB2_Schema(); - $result = $obj->connect($db, $options); - if (PEAR::isError($result)) { - return $result; - } - return $obj; - } - - // }}} - // {{{ connect() - - /** - * Create a new MDB2 connection object and connect to the specified - * database - * - * @param string|array|MDB2_Driver_Common &$db 'data source name', see the - * MDB2::parseDSN method for a description of the dsn format. - * Can also be specified as an array of the - * format returned by MDB2::parseDSN. - * Finally you can also pass an existing db object to be used. - * @param array $options An associative array of option names and their values. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - * @see MDB2::parseDSN - */ - function connect(&$db, $options = array()) - { - $db_options = array(); - if (is_array($options)) { - foreach ($options as $option => $value) { - if (array_key_exists($option, $this->options)) { - $result = $this->setOption($option, $value); - if (PEAR::isError($result)) { - return $result; - } - } else { - $db_options[$option] = $value; - } - } - } - $this->disconnect(); - if (!MDB2::isConnection($db)) { - $db =MDB2::factory($db, $db_options); - } - - if (PEAR::isError($db)) { - return $db; - } - $this->db =& $db; - $this->db->loadModule('Datatype'); - $this->db->loadModule('Manager'); - $this->db->loadModule('Reverse'); - $this->db->loadModule('Function'); - if (empty($this->options['valid_types'])) { - $this->options['valid_types'] = $this->db->datatype->getValidTypes(); - } - - return MDB2_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @access public - * @return void - */ - function disconnect() - { - if (MDB2::isConnection($this->db)) { - $this->db->disconnect(); - unset($this->db); - } - } - - // }}} - // {{{ parseDatabaseDefinition() - - /** - * Parse a database definition from a file or an array - * - * @param string|array $schema the database schema array or file name - * @param bool $skip_unreadable if non readable files should be skipped - * @param array $variables associative array that the defines the text string values - * that are meant to be used to replace the variables that are - * used in the schema description. - * @param bool $fail_on_invalid_names make function fail on invalid names - * @param array $structure database structure definition - * - * @access public - * @return array - */ - function parseDatabaseDefinition($schema, $skip_unreadable = false, $variables = array(), - $fail_on_invalid_names = true, $structure = false) - { - $database_definition = false; - if (is_string($schema)) { - // if $schema is not readable then we just skip it - // and simply copy the $current_schema file to that file name - if (is_readable($schema)) { - $database_definition = $this->parseDatabaseDefinitionFile($schema, $variables, $fail_on_invalid_names, $structure); - } - } elseif (is_array($schema)) { - $database_definition = $schema; - } - if (!$database_definition && !$skip_unreadable) { - $database_definition = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'invalid data type of schema or unreadable data source'); - } - return $database_definition; - } - - // }}} - // {{{ parseDatabaseDefinitionFile() - - /** - * Parse a database definition file by creating a schema format - * parser object and passing the file contents as parser input data stream. - * - * @param string $input_file the database schema file. - * @param array $variables associative array that the defines the text string values - * that are meant to be used to replace the variables that are - * used in the schema description. - * @param bool $fail_on_invalid_names make function fail on invalid names - * @param array $structure database structure definition - * - * @access public - * @return array - */ - function parseDatabaseDefinitionFile($input_file, $variables = array(), - $fail_on_invalid_names = true, $structure = false) - { - $dtd_file = $this->options['dtd_file']; - if ($dtd_file) { - include_once 'XML/DTD/XmlValidator.php'; - $dtd =new XML_DTD_XmlValidator; - if (!$dtd->isValid($dtd_file, $input_file)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage()); - } - } - - $class_name = $this->options['parser']; - - $result = MDB2::loadClass($class_name, $this->db->getOption('debug')); - if (PEAR::isError($result)) { - return $result; - } - - $parser =new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']); - $result = $parser->setInputFile($input_file); - if (PEAR::isError($result)) { - return $result; - } - - $result = $parser->parse(); - if (PEAR::isError($result)) { - return $result; - } - if (PEAR::isError($parser->error)) { - return $parser->error; - } - - return $parser->database_definition; - } - - // }}} - // {{{ getDefinitionFromDatabase() - - /** - * Attempt to reverse engineer a schema structure from an existing MDB2 - * This method can be used if no xml schema file exists yet. - * The resulting xml schema file may need some manual adjustments. - * - * @return array|MDB2_Error array with definition or error object - * @access public - */ - function getDefinitionFromDatabase() - { - $database = $this->db->database_name; - if (empty($database)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was not specified a valid database name'); - } - $class_name = $this->options['validate']; - - $result = MDB2::loadClass($class_name, $this->db->getOption('debug')); - if (PEAR::isError($result)) { - return $result; - } - - $val =new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']); - - $database_definition = array( - 'name' => $database, - 'create' => true, - 'overwrite' => false, - 'charset' => 'utf8', - 'description' => '', - 'comments' => '', - 'tables' => array(), - 'sequences' => array(), - ); - - $tables = $this->db->manager->listTables(); - if (PEAR::isError($tables)) { - return $tables; - } - - foreach ($tables as $table_name) { - $fields = $this->db->manager->listTableFields($table_name); - if (PEAR::isError($fields)) { - return $fields; - } - - $database_definition['tables'][$table_name] = array( - 'was' => '', - 'description' => '', - 'comments' => '', - 'fields' => array(), - 'indexes' => array(), - 'constraints' => array(), - 'initialization' => array() - ); - - $table_definition =& $database_definition['tables'][$table_name]; - foreach ($fields as $field_name) { - $definition = $this->db->reverse->getTableFieldDefinition($table_name, $field_name); - if (PEAR::isError($definition)) { - return $definition; - } - - if (!empty($definition[0]['autoincrement'])) { - $definition[0]['default'] = '0'; - } - - $table_definition['fields'][$field_name] = $definition[0]; - - $field_choices = count($definition); - if ($field_choices > 1) { - $warning = "There are $field_choices type choices in the table $table_name field $field_name (#1 is the default): "; - - $field_choice_cnt = 1; - - $table_definition['fields'][$field_name]['choices'] = array(); - foreach ($definition as $field_choice) { - $table_definition['fields'][$field_name]['choices'][] = $field_choice; - - $warning .= 'choice #'.($field_choice_cnt).': '.serialize($field_choice); - $field_choice_cnt++; - } - $this->warnings[] = $warning; - } - - /** - * The first parameter is used to verify if there are duplicated - * fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateField(array(), $table_definition['fields'][$field_name], $field_name); - if (PEAR::isError($result)) { - return $result; - } - } - - $keys = array(); - - $indexes = $this->db->manager->listTableIndexes($table_name); - if (PEAR::isError($indexes)) { - return $indexes; - } - - if (is_array($indexes)) { - foreach ($indexes as $index_name) { - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - $definition = $this->db->reverse->getTableIndexDefinition($table_name, $index_name); - $this->db->popExpect(); - if (PEAR::isError($definition)) { - if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) { - continue; - } - return $definition; - } - - $keys[$index_name] = $definition; - } - } - - $constraints = $this->db->manager->listTableConstraints($table_name); - if (PEAR::isError($constraints)) { - return $constraints; - } - - if (is_array($constraints)) { - foreach ($constraints as $constraint_name) { - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - $definition = $this->db->reverse->getTableConstraintDefinition($table_name, $constraint_name); - $this->db->popExpect(); - if (PEAR::isError($definition)) { - if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) { - continue; - } - return $definition; - } - - $keys[$constraint_name] = $definition; - } - } - - foreach ($keys as $key_name => $definition) { - if (array_key_exists('foreign', $definition) - && $definition['foreign'] - ) { - /** - * The first parameter is used to verify if there are duplicated - * foreign keys which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateConstraint(array(), $definition, $key_name); - if (PEAR::isError($result)) { - return $result; - } - - foreach ($definition['fields'] as $field_name => $field) { - /** - * The first parameter is used to verify if there are duplicated - * referencing fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateConstraintField(array(), $field_name); - if (PEAR::isError($result)) { - return $result; - } - - $definition['fields'][$field_name] = ''; - } - - foreach ($definition['references']['fields'] as $field_name => $field) { - /** - * The first parameter is used to verify if there are duplicated - * referenced fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateConstraintReferencedField(array(), $field_name); - if (PEAR::isError($result)) { - return $result; - } - - $definition['references']['fields'][$field_name] = ''; - } - - $table_definition['constraints'][$key_name] = $definition; - } else { - /** - * The first parameter is used to verify if there are duplicated - * indices which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateIndex(array(), $definition, $key_name); - if (PEAR::isError($result)) { - return $result; - } - - foreach ($definition['fields'] as $field_name => $field) { - /** - * The first parameter is used to verify if there are duplicated - * index fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateIndexField(array(), $field, $field_name); - if (PEAR::isError($result)) { - return $result; - } - - $definition['fields'][$field_name] = $field; - } - - $table_definition['indexes'][$key_name] = $definition; - } - } - - /** - * The first parameter is used to verify if there are duplicated - * tables which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateTable(array(), $table_definition, $table_name); - if (PEAR::isError($result)) { - return $result; - } - - } - - $sequences = $this->db->manager->listSequences(); - if (PEAR::isError($sequences)) { - return $sequences; - } - - if (is_array($sequences)) { - foreach ($sequences as $sequence_name) { - $definition = $this->db->reverse->getSequenceDefinition($sequence_name); - if (PEAR::isError($definition)) { - return $definition; - } - if (isset($database_definition['tables'][$sequence_name]) - && isset($database_definition['tables'][$sequence_name]['indexes']) - ) { - foreach ($database_definition['tables'][$sequence_name]['indexes'] as $index) { - if (isset($index['primary']) && $index['primary'] - && count($index['fields'] == 1) - ) { - $definition['on'] = array( - 'table' => $sequence_name, - 'field' => key($index['fields']), - ); - break; - } - } - } - - /** - * The first parameter is used to verify if there are duplicated - * sequences which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateSequence(array(), $definition, $sequence_name); - if (PEAR::isError($result)) { - return $result; - } - - $database_definition['sequences'][$sequence_name] = $definition; - } - } - - $result = $val->validateDatabase($database_definition); - if (PEAR::isError($result)) { - return $result; - } - - return $database_definition; - } - - // }}} - // {{{ createTableIndexes() - - /** - * A method to create indexes for an existing table - * - * @param string $table_name Name of the table - * @param array $indexes An array of indexes to be created - * @param boolean $overwrite If the table/index should be overwritten if it already exists - * - * @return mixed MDB2_Error if there is an error creating an index, MDB2_OK otherwise - * @access public - */ - function createTableIndexes($table_name, $indexes, $overwrite = false) - { - if (!$this->db->supports('indexes')) { - $this->db->debug('Indexes are not supported', __FUNCTION__); - return MDB2_OK; - } - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - foreach ($indexes as $index_name => $index) { - - // Does the index already exist, and if so, should it be overwritten? - $create_index = true; - $this->db->expectError($errorcodes); - if (!empty($index['primary']) || !empty($index['unique'])) { - $current_indexes = $this->db->manager->listTableConstraints($table_name); - } else { - $current_indexes = $this->db->manager->listTableIndexes($table_name); - } - - $this->db->popExpect(); - if (PEAR::isError($current_indexes)) { - if (!MDB2::isError($current_indexes, $errorcodes)) { - return $current_indexes; - } - } elseif (is_array($current_indexes) && in_array($index_name, $current_indexes)) { - if (!$overwrite) { - $this->db->debug('Index already exists: '.$index_name, __FUNCTION__); - $create_index = false; - } else { - $this->db->debug('Preparing to overwrite index: '.$index_name, __FUNCTION__); - - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->dropConstraint($table_name, $index_name); - } else { - $result = $this->db->manager->dropIndex($table_name, $index_name); - } - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) { - return $result; - } - } - } - - // Check if primary is being used and if it's supported - if (!empty($index['primary']) && !$this->db->supports('primary_key')) { - - // Primary not supported so we fallback to UNIQUE and making the field NOT NULL - $index['unique'] = true; - - $changes = array(); - - foreach ($index['fields'] as $field => $empty) { - $field_info = $this->db->reverse->getTableFieldDefinition($table_name, $field); - if (PEAR::isError($field_info)) { - return $field_info; - } - if (!$field_info[0]['notnull']) { - $changes['change'][$field] = $field_info[0]; - - $changes['change'][$field]['notnull'] = true; - } - } - if (!empty($changes)) { - $this->db->manager->alterTable($table_name, $changes, false); - } - } - - // Should the index be created? - if ($create_index) { - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->createConstraint($table_name, $index_name, $index); - } else { - $result = $this->db->manager->createIndex($table_name, $index_name, $index); - } - if (PEAR::isError($result)) { - return $result; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ createTableConstraints() - - /** - * A method to create foreign keys for an existing table - * - * @param string $table_name Name of the table - * @param array $constraints An array of foreign keys to be created - * @param boolean $overwrite If the foreign key should be overwritten if it already exists - * - * @return mixed MDB2_Error if there is an error creating a foreign key, MDB2_OK otherwise - * @access public - */ - function createTableConstraints($table_name, $constraints, $overwrite = false) - { - if (!$this->db->supports('indexes')) { - $this->db->debug('Indexes are not supported', __FUNCTION__); - return MDB2_OK; - } - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - foreach ($constraints as $constraint_name => $constraint) { - - // Does the foreign key already exist, and if so, should it be overwritten? - $create_constraint = true; - $this->db->expectError($errorcodes); - $current_constraints = $this->db->manager->listTableConstraints($table_name); - $this->db->popExpect(); - if (PEAR::isError($current_constraints)) { - if (!MDB2::isError($current_constraints, $errorcodes)) { - return $current_constraints; - } - } elseif (is_array($current_constraints) && in_array($constraint_name, $current_constraints)) { - if (!$overwrite) { - $this->db->debug('Foreign key already exists: '.$constraint_name, __FUNCTION__); - $create_constraint = false; - } else { - $this->db->debug('Preparing to overwrite foreign key: '.$constraint_name, __FUNCTION__); - $result = $this->db->manager->dropConstraint($table_name, $constraint_name); - if (PEAR::isError($result)) { - return $result; - } - } - } - - // Should the foreign key be created? - if ($create_constraint) { - $result = $this->db->manager->createConstraint($table_name, $constraint_name, $constraint); - if (PEAR::isError($result)) { - return $result; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ createTable() - - /** - * Create a table and inititialize the table if data is available - * - * @param string $table_name name of the table to be created - * @param array $table multi dimensional array that contains the - * structure and optional data of the table - * @param bool $overwrite if the table/index should be overwritten if it already exists - * @param array $options an array of options to be passed to the database specific driver - * version of MDB2_Driver_Manager_Common::createTable(). - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function createTable($table_name, $table, $overwrite = false, $options = array()) - { - $create = true; - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - - $this->db->expectError($errorcodes); - - $tables = $this->db->manager->listTables(); - - $this->db->popExpect(); - if (PEAR::isError($tables)) { - if (!MDB2::isError($tables, $errorcodes)) { - return $tables; - } - } elseif (is_array($tables) && in_array($table_name, $tables)) { - if (!$overwrite) { - $create = false; - $this->db->debug('Table already exists: '.$table_name, __FUNCTION__); - } else { - $result = $this->db->manager->dropTable($table_name); - if (PEAR::isError($result)) { - return $result; - } - $this->db->debug('Overwritting table: '.$table_name, __FUNCTION__); - } - } - - if ($create) { - $result = $this->db->manager->createTable($table_name, $table['fields'], $options); - if (PEAR::isError($result)) { - return $result; - } - } - - if (!empty($table['initialization']) && is_array($table['initialization'])) { - $result = $this->initializeTable($table_name, $table); - if (PEAR::isError($result)) { - return $result; - } - } - - if (!empty($table['indexes']) && is_array($table['indexes'])) { - $result = $this->createTableIndexes($table_name, $table['indexes'], $overwrite); - if (PEAR::isError($result)) { - return $result; - } - } - - if (!empty($table['constraints']) && is_array($table['constraints'])) { - $result = $this->createTableConstraints($table_name, $table['constraints'], $overwrite); - if (PEAR::isError($result)) { - return $result; - } - } - - return MDB2_OK; - } - - // }}} - // {{{ initializeTable() - - /** - * Inititialize the table with data - * - * @param string $table_name name of the table - * @param array $table multi dimensional array that contains the - * structure and optional data of the table - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function initializeTable($table_name, $table) - { - $query_insertselect = 'INSERT INTO %s (%s) (SELECT %s FROM %s %s)'; - - $query_insert = 'INSERT INTO %s (%s) VALUES (%s)'; - $query_update = 'UPDATE %s SET %s %s'; - $query_delete = 'DELETE FROM %s %s'; - - $table_name = $this->db->quoteIdentifier($table_name, true); - - $result = MDB2_OK; - - $support_transactions = $this->db->supports('transactions'); - - foreach ($table['initialization'] as $instruction) { - $query = ''; - switch ($instruction['type']) { - case 'insert': - if (!isset($instruction['data']['select'])) { - $data = $this->getInstructionFields($instruction['data'], $table['fields']); - if (!empty($data)) { - $fields = implode(', ', array_keys($data)); - $values = implode(', ', array_values($data)); - - $query = sprintf($query_insert, $table_name, $fields, $values); - } - } else { - $data = $this->getInstructionFields($instruction['data']['select'], $table['fields']); - $where = $this->getInstructionWhere($instruction['data']['select'], $table['fields']); - - $select_table_name = $this->db->quoteIdentifier($instruction['data']['select']['table'], true); - if (!empty($data)) { - $fields = implode(', ', array_keys($data)); - $values = implode(', ', array_values($data)); - - $query = sprintf($query_insertselect, $table_name, $fields, $values, $select_table_name, $where); - } - } - break; - case 'update': - $data = $this->getInstructionFields($instruction['data'], $table['fields']); - $where = $this->getInstructionWhere($instruction['data'], $table['fields']); - if (!empty($data)) { - array_walk($data, array($this, 'buildFieldValue')); - $fields_values = implode(', ', $data); - - $query = sprintf($query_update, $table_name, $fields_values, $where); - } - break; - case 'delete': - $where = $this->getInstructionWhere($instruction['data'], $table['fields']); - $query = sprintf($query_delete, $table_name, $where); - break; - } - if ($query) { - if ($support_transactions && PEAR::isError($res = $this->db->beginNestedTransaction())) { - return $res; - } - - $result = $this->db->exec($query); - if (PEAR::isError($result)) { - return $result; - } - - if ($support_transactions && PEAR::isError($res = $this->db->completeNestedTransaction())) { - return $res; - } - } - } - return $result; - } - - // }}} - // {{{ buildFieldValue() - - /** - * Appends the contents of second argument + '=' to the beginning of first - * argument. - * - * Used with array_walk() in initializeTable() for UPDATEs. - * - * @param string &$element value of array's element - * @param string $key key of array's element - * - * @return void - * - * @access public - * @see MDB2_Schema::initializeTable() - */ - function buildFieldValue(&$element, $key) - { - $element = $key."=$element"; - } - - // }}} - // {{{ getExpression() - - /** - * Generates a string that represents a value that would be associated - * with a column in a DML instruction. - * - * @param array $element multi dimensional array that contains the - * structure of the current DML instruction. - * @param array $fields_definition multi dimensional array that contains the - * definition for current table's fields - * @param string $type type of given field - * - * @return string - * - * @access public - * @see MDB2_Schema::getInstructionFields(), MDB2_Schema::getInstructionWhere() - */ - function getExpression($element, $fields_definition = array(), $type = null) - { - $str = ''; - switch ($element['type']) { - case 'null': - $str .= 'NULL'; - break; - case 'value': - $str .= $this->db->quote($element['data'], $type); - break; - case 'column': - $str .= $this->db->quoteIdentifier($element['data'], true); - break; - case 'function': - $arguments = array(); - if (!empty($element['data']['arguments']) - && is_array($element['data']['arguments']) - ) { - foreach ($element['data']['arguments'] as $v) { - $arguments[] = $this->getExpression($v, $fields_definition); - } - } - if (method_exists($this->db->function, $element['data']['name'])) { - $user_func = array(&$this->db->function, $element['data']['name']); - - $str .= call_user_func_array($user_func, $arguments); - } else { - $str .= $element['data']['name'].'('; - $str .= implode(', ', $arguments); - $str .= ')'; - } - break; - case 'expression': - $type0 = $type1 = null; - if ($element['data']['operants'][0]['type'] == 'column' - && array_key_exists($element['data']['operants'][0]['data'], $fields_definition) - ) { - $type0 = $fields_definition[$element['data']['operants'][0]['data']]['type']; - } - - if ($element['data']['operants'][1]['type'] == 'column' - && array_key_exists($element['data']['operants'][1]['data'], $fields_definition) - ) { - $type1 = $fields_definition[$element['data']['operants'][1]['data']]['type']; - } - - $str .= '('; - $str .= $this->getExpression($element['data']['operants'][0], $fields_definition, $type1); - $str .= $this->getOperator($element['data']['operator']); - $str .= $this->getExpression($element['data']['operants'][1], $fields_definition, $type0); - $str .= ')'; - break; - } - - return $str; - } - - // }}} - // {{{ getOperator() - - /** - * Returns the matching SQL operator - * - * @param string $op parsed descriptive operator - * - * @return string matching SQL operator - * - * @access public - * @static - * @see MDB2_Schema::getExpression() - */ - function getOperator($op) - { - switch ($op) { - case 'PLUS': - return ' + '; - case 'MINUS': - return ' - '; - case 'TIMES': - return ' * '; - case 'DIVIDED': - return ' / '; - case 'EQUAL': - return ' = '; - case 'NOT EQUAL': - return ' != '; - case 'LESS THAN': - return ' < '; - case 'GREATER THAN': - return ' > '; - case 'LESS THAN OR EQUAL': - return ' <= '; - case 'GREATER THAN OR EQUAL': - return ' >= '; - default: - return ' '.$op.' '; - } - } - - // }}} - // {{{ getInstructionFields() - - /** - * Walks the parsed DML instruction array, field by field, - * storing them and their processed values inside a new array. - * - * @param array $instruction multi dimensional array that contains the - * structure of the current DML instruction. - * @param array $fields_definition multi dimensional array that contains the - * definition for current table's fields - * - * @return array array of strings in the form 'field_name' => 'value' - * - * @access public - * @static - * @see MDB2_Schema::initializeTable() - */ - function getInstructionFields($instruction, $fields_definition = array()) - { - $fields = array(); - if (!empty($instruction['field']) && is_array($instruction['field'])) { - foreach ($instruction['field'] as $field) { - $field_name = $this->db->quoteIdentifier($field['name'], true); - - $fields[$field_name] = $this->getExpression($field['group'], $fields_definition); - } - } - return $fields; - } - - // }}} - // {{{ getInstructionWhere() - - /** - * Translates the parsed WHERE expression of a DML instruction - * (array structure) to a SQL WHERE clause (string). - * - * @param array $instruction multi dimensional array that contains the - * structure of the current DML instruction. - * @param array $fields_definition multi dimensional array that contains the - * definition for current table's fields. - * - * @return string SQL WHERE clause - * - * @access public - * @static - * @see MDB2_Schema::initializeTable() - */ - function getInstructionWhere($instruction, $fields_definition = array()) - { - $where = ''; - if (!empty($instruction['where'])) { - $where = 'WHERE '.$this->getExpression($instruction['where'], $fields_definition); - } - return $where; - } - - // }}} - // {{{ createSequence() - - /** - * Create a sequence - * - * @param string $sequence_name name of the sequence to be created - * @param array $sequence multi dimensional array that contains the - * structure and optional data of the table - * @param bool $overwrite if the sequence should be overwritten if it already exists - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function createSequence($sequence_name, $sequence, $overwrite = false) - { - if (!$this->db->supports('sequences')) { - $this->db->debug('Sequences are not supported', __FUNCTION__); - return MDB2_OK; - } - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - $this->db->expectError($errorcodes); - $sequences = $this->db->manager->listSequences(); - $this->db->popExpect(); - if (PEAR::isError($sequences)) { - if (!MDB2::isError($sequences, $errorcodes)) { - return $sequences; - } - } elseif (is_array($sequence) && in_array($sequence_name, $sequences)) { - if (!$overwrite) { - $this->db->debug('Sequence already exists: '.$sequence_name, __FUNCTION__); - return MDB2_OK; - } - - $result = $this->db->manager->dropSequence($sequence_name); - if (PEAR::isError($result)) { - return $result; - } - $this->db->debug('Overwritting sequence: '.$sequence_name, __FUNCTION__); - } - - $start = 1; - $field = ''; - if (!empty($sequence['on'])) { - $table = $sequence['on']['table']; - $field = $sequence['on']['field']; - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - $this->db->expectError($errorcodes); - $tables = $this->db->manager->listTables(); - $this->db->popExpect(); - if (PEAR::isError($tables) && !MDB2::isError($tables, $errorcodes)) { - return $tables; - } - - if (!PEAR::isError($tables) && is_array($tables) && in_array($table, $tables)) { - if ($this->db->supports('summary_functions')) { - $query = "SELECT MAX($field) FROM ".$this->db->quoteIdentifier($table, true); - } else { - $query = "SELECT $field FROM ".$this->db->quoteIdentifier($table, true)." ORDER BY $field DESC"; - } - $start = $this->db->queryOne($query, 'integer'); - if (PEAR::isError($start)) { - return $start; - } - ++$start; - } else { - $this->warnings[] = 'Could not sync sequence: '.$sequence_name; - } - } elseif (!empty($sequence['start']) && is_numeric($sequence['start'])) { - $start = $sequence['start']; - $table = ''; - } - - $result = $this->db->manager->createSequence($sequence_name, $start); - if (PEAR::isError($result)) { - return $result; - } - - return MDB2_OK; - } - - // }}} - // {{{ createDatabase() - - /** - * Create a database space within which may be created database objects - * like tables, indexes and sequences. The implementation of this function - * is highly DBMS specific and may require special permissions to run - * successfully. Consult the documentation or the DBMS drivers that you - * use to be aware of eventual configuration requirements. - * - * @param array $database_definition multi dimensional array that contains the current definition - * @param array $options an array of options to be passed to the - * database specific driver version of - * MDB2_Driver_Manager_Common::createTable(). - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function createDatabase($database_definition, $options = array()) - { - if (!isset($database_definition['name']) || !$database_definition['name']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'no valid database name specified'); - } - - $create = (isset($database_definition['create']) && $database_definition['create']); - $overwrite = (isset($database_definition['overwrite']) && $database_definition['overwrite']); - - /** - * - * We need to clean up database name before any query to prevent - * database driver from using a inexistent database - * - */ - $previous_database_name = $this->db->setDatabase(''); - - // Lower / Upper case the db name if the portability deems so. - if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $func = $this->db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'; - - $db_name = $func($database_definition['name']); - } else { - $db_name = $database_definition['name']; - } - - if ($create) { - - $dbExists = $this->db->databaseExists($db_name); - if (PEAR::isError($dbExists)) { - return $dbExists; - } - - if ($dbExists && $overwrite) { - $this->db->expectError(MDB2_ERROR_CANNOT_DROP); - $result = $this->db->manager->dropDatabase($db_name); - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_CANNOT_DROP)) { - return $result; - } - $dbExists = false; - $this->db->debug('Overwritting database: ' . $db_name, __FUNCTION__); - } - - $dbOptions = array(); - if (array_key_exists('charset', $database_definition) - && !empty($database_definition['charset'])) { - $dbOptions['charset'] = $database_definition['charset']; - } - - if ($dbExists) { - $this->db->debug('Database already exists: ' . $db_name, __FUNCTION__); -// if (!empty($dbOptions)) { -// $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION); -// $this->db->expectError($errorcodes); -// $result = $this->db->manager->alterDatabase($db_name, $dbOptions); -// $this->db->popExpect(); -// if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) { -// return $result; -// } -// } - $create = false; - } else { - $this->db->expectError(MDB2_ERROR_UNSUPPORTED); - $result = $this->db->manager->createDatabase($db_name, $dbOptions); - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_UNSUPPORTED)) { - return $result; - } - $this->db->debug('Creating database: ' . $db_name, __FUNCTION__); - } - } - - $this->db->setDatabase($db_name); - if (($support_transactions = $this->db->supports('transactions')) - && PEAR::isError($result = $this->db->beginNestedTransaction()) - ) { - return $result; - } - - $created_objects = 0; - if (isset($database_definition['tables']) - && is_array($database_definition['tables']) - ) { - foreach ($database_definition['tables'] as $table_name => $table) { - $result = $this->createTable($table_name, $table, $overwrite, $options); - if (PEAR::isError($result)) { - break; - } - $created_objects++; - } - } - if (!PEAR::isError($result) - && isset($database_definition['sequences']) - && is_array($database_definition['sequences']) - ) { - foreach ($database_definition['sequences'] as $sequence_name => $sequence) { - $result = $this->createSequence($sequence_name, $sequence, false, $overwrite); - - if (PEAR::isError($result)) { - break; - } - $created_objects++; - } - } - - if ($support_transactions) { - $res = $this->db->completeNestedTransaction(); - if (PEAR::isError($res)) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not end transaction ('. - $res->getMessage().' ('.$res->getUserinfo().'))'); - } - } elseif (PEAR::isError($result) && $created_objects) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'the database was only partially created ('. - $result->getMessage().' ('.$result->getUserinfo().'))'); - } - - $this->db->setDatabase($previous_database_name); - - if (PEAR::isError($result) && $create - && PEAR::isError($result2 = $this->db->manager->dropDatabase($db_name)) - ) { - if (!MDB2::isError($result2, MDB2_ERROR_UNSUPPORTED)) { - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not drop the created database after unsuccessful creation attempt ('. - $result2->getMessage().' ('.$result2->getUserinfo().'))'); - } - } - - return $result; - } - - // }}} - // {{{ compareDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareDefinitions($current_definition, $previous_definition) - { - $changes = array(); - - if (!empty($current_definition['tables']) && is_array($current_definition['tables'])) { - $changes['tables'] = $defined_tables = array(); - foreach ($current_definition['tables'] as $table_name => $table) { - $previous_tables = array(); - if (!empty($previous_definition) && is_array($previous_definition)) { - $previous_tables = $previous_definition['tables']; - } - $change = $this->compareTableDefinitions($table_name, $table, $previous_tables, $defined_tables); - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['tables'] = MDB2_Schema::arrayMergeClobber($changes['tables'], $change); - } - } - - if (!empty($previous_definition['tables']) - && is_array($previous_definition['tables'])) { - foreach ($previous_definition['tables'] as $table_name => $table) { - if (empty($defined_tables[$table_name])) { - $changes['tables']['remove'][$table_name] = true; - } - } - } - } - if (!empty($current_definition['sequences']) && is_array($current_definition['sequences'])) { - $changes['sequences'] = $defined_sequences = array(); - foreach ($current_definition['sequences'] as $sequence_name => $sequence) { - $previous_sequences = array(); - if (!empty($previous_definition) && is_array($previous_definition)) { - $previous_sequences = $previous_definition['sequences']; - } - - $change = $this->compareSequenceDefinitions($sequence_name, - $sequence, - $previous_sequences, - $defined_sequences); - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['sequences'] = MDB2_Schema::arrayMergeClobber($changes['sequences'], $change); - } - } - if (!empty($previous_definition['sequences']) && is_array($previous_definition['sequences'])) { - foreach ($previous_definition['sequences'] as $sequence_name => $sequence) { - if (empty($defined_sequences[$sequence_name])) { - $changes['sequences']['remove'][$sequence_name] = true; - } - } - } - } - return $changes; - } - - // }}} - // {{{ compareTableFieldsDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $table_name name of the table - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareTableFieldsDefinitions($table_name, $current_definition, - $previous_definition) - { - $changes = $defined_fields = array(); - - if (is_array($current_definition)) { - foreach ($current_definition as $field_name => $field) { - $was_field_name = $field['was']; - if (!empty($previous_definition[$field_name]) - && ( - (isset($previous_definition[$field_name]['was']) - && $previous_definition[$field_name]['was'] == $was_field_name) - || !isset($previous_definition[$was_field_name]) - )) { - $was_field_name = $field_name; - } - - if (!empty($previous_definition[$was_field_name])) { - if ($was_field_name != $field_name) { - $changes['rename'][$was_field_name] = array('name' => $field_name, 'definition' => $field); - } - - if (!empty($defined_fields[$was_field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the field "'.$was_field_name. - '" was specified for more than one field of table'); - } - - $defined_fields[$was_field_name] = true; - - $change = $this->db->compareDefinition($field, $previous_definition[$was_field_name]); - if (PEAR::isError($change)) { - return $change; - } - - if (!empty($change)) { - if (array_key_exists('default', $change) - && $change['default'] - && !array_key_exists('default', $field)) { - $field['default'] = null; - } - - $change['definition'] = $field; - - $changes['change'][$field_name] = $change; - } - } else { - if ($field_name != $was_field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous field name ("'. - $was_field_name.'") for field "'.$field_name.'" of table "'. - $table_name.'" that does not exist'); - } - - $changes['add'][$field_name] = $field; - } - } - } - - if (isset($previous_definition) && is_array($previous_definition)) { - foreach ($previous_definition as $field_previous_name => $field_previous) { - if (empty($defined_fields[$field_previous_name])) { - $changes['remove'][$field_previous_name] = true; - } - } - } - - return $changes; - } - - // }}} - // {{{ compareTableIndexesDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $table_name name of the table - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareTableIndexesDefinitions($table_name, $current_definition, - $previous_definition) - { - $changes = $defined_indexes = array(); - - if (is_array($current_definition)) { - foreach ($current_definition as $index_name => $index) { - $was_index_name = $index['was']; - if (!empty($previous_definition[$index_name]) - && isset($previous_definition[$index_name]['was']) - && $previous_definition[$index_name]['was'] == $was_index_name - ) { - $was_index_name = $index_name; - } - if (!empty($previous_definition[$was_index_name])) { - $change = array(); - if ($was_index_name != $index_name) { - $change['name'] = $was_index_name; - } - - if (!empty($defined_indexes[$was_index_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the index "'.$was_index_name.'" was specified for'. - ' more than one index of table "'.$table_name.'"'); - } - $defined_indexes[$was_index_name] = true; - - $previous_unique = array_key_exists('unique', $previous_definition[$was_index_name]) - ? $previous_definition[$was_index_name]['unique'] : false; - - $unique = array_key_exists('unique', $index) ? $index['unique'] : false; - if ($previous_unique != $unique) { - $change['unique'] = $unique; - } - - $previous_primary = array_key_exists('primary', $previous_definition[$was_index_name]) - ? $previous_definition[$was_index_name]['primary'] : false; - - $primary = array_key_exists('primary', $index) ? $index['primary'] : false; - if ($previous_primary != $primary) { - $change['primary'] = $primary; - } - - $defined_fields = array(); - $previous_fields = $previous_definition[$was_index_name]['fields']; - if (!empty($index['fields']) && is_array($index['fields'])) { - foreach ($index['fields'] as $field_name => $field) { - if (!empty($previous_fields[$field_name])) { - $defined_fields[$field_name] = true; - - $previous_sorting = array_key_exists('sorting', $previous_fields[$field_name]) - ? $previous_fields[$field_name]['sorting'] : ''; - - $sorting = array_key_exists('sorting', $field) ? $field['sorting'] : ''; - if ($previous_sorting != $sorting) { - $change['change'] = true; - } - } else { - $change['change'] = true; - } - } - } - if (isset($previous_fields) && is_array($previous_fields)) { - foreach ($previous_fields as $field_name => $field) { - if (empty($defined_fields[$field_name])) { - $change['change'] = true; - } - } - } - if (!empty($change)) { - $changes['change'][$index_name] = $current_definition[$index_name]; - } - } else { - if ($index_name != $was_index_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous index name ("'.$was_index_name. - ') for index "'.$index_name.'" of table "'.$table_name.'" that does not exist'); - } - $changes['add'][$index_name] = $current_definition[$index_name]; - } - } - } - foreach ($previous_definition as $index_previous_name => $index_previous) { - if (empty($defined_indexes[$index_previous_name])) { - $changes['remove'][$index_previous_name] = $index_previous; - } - } - return $changes; - } - - // }}} - // {{{ compareTableDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $table_name name of the table - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array &$defined_tables table names in the schema - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareTableDefinitions($table_name, $current_definition, - $previous_definition, &$defined_tables) - { - $changes = array(); - - if (is_array($current_definition)) { - $was_table_name = $table_name; - if (!empty($current_definition['was'])) { - $was_table_name = $current_definition['was']; - } - if (!empty($previous_definition[$was_table_name])) { - $changes['change'][$was_table_name] = array(); - if ($was_table_name != $table_name) { - $changes['change'][$was_table_name] = array('name' => $table_name); - } - if (!empty($defined_tables[$was_table_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the table "'.$was_table_name. - '" was specified for more than one table of the database'); - } - $defined_tables[$was_table_name] = true; - if (!empty($current_definition['fields']) && is_array($current_definition['fields'])) { - $previous_fields = array(); - if (isset($previous_definition[$was_table_name]['fields']) - && is_array($previous_definition[$was_table_name]['fields'])) { - $previous_fields = $previous_definition[$was_table_name]['fields']; - } - - $change = $this->compareTableFieldsDefinitions($table_name, - $current_definition['fields'], - $previous_fields); - - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['change'][$was_table_name] = - MDB2_Schema::arrayMergeClobber($changes['change'][$was_table_name], $change); - } - } - if (!empty($current_definition['indexes']) && is_array($current_definition['indexes'])) { - $previous_indexes = array(); - if (isset($previous_definition[$was_table_name]['indexes']) - && is_array($previous_definition[$was_table_name]['indexes'])) { - $previous_indexes = $previous_definition[$was_table_name]['indexes']; - } - $change = $this->compareTableIndexesDefinitions($table_name, - $current_definition['indexes'], - $previous_indexes); - - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['change'][$was_table_name]['indexes'] = $change; - } - } - if (empty($changes['change'][$was_table_name])) { - unset($changes['change'][$was_table_name]); - } - if (empty($changes['change'])) { - unset($changes['change']); - } - } else { - if ($table_name != $was_table_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous table name ("'.$was_table_name. - '") for table "'.$table_name.'" that does not exist'); - } - $changes['add'][$table_name] = true; - } - } - - return $changes; - } - - // }}} - // {{{ compareSequenceDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $sequence_name name of the sequence - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array &$defined_sequences names in the schema - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareSequenceDefinitions($sequence_name, $current_definition, - $previous_definition, &$defined_sequences) - { - $changes = array(); - - if (is_array($current_definition)) { - $was_sequence_name = $sequence_name; - if (!empty($previous_definition[$sequence_name]) - && isset($previous_definition[$sequence_name]['was']) - && $previous_definition[$sequence_name]['was'] == $was_sequence_name - ) { - $was_sequence_name = $sequence_name; - } elseif (!empty($current_definition['was'])) { - $was_sequence_name = $current_definition['was']; - } - if (!empty($previous_definition[$was_sequence_name])) { - if ($was_sequence_name != $sequence_name) { - $changes['change'][$was_sequence_name]['name'] = $sequence_name; - } - - if (!empty($defined_sequences[$was_sequence_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the sequence "'.$was_sequence_name.'" was specified as base'. - ' of more than of sequence of the database'); - } - - $defined_sequences[$was_sequence_name] = true; - - $change = array(); - if (!empty($current_definition['start']) - && isset($previous_definition[$was_sequence_name]['start']) - && $current_definition['start'] != $previous_definition[$was_sequence_name]['start'] - ) { - $change['start'] = $previous_definition[$sequence_name]['start']; - } - if (isset($current_definition['on']['table']) - && isset($previous_definition[$was_sequence_name]['on']['table']) - && $current_definition['on']['table'] != $previous_definition[$was_sequence_name]['on']['table'] - && isset($current_definition['on']['field']) - && isset($previous_definition[$was_sequence_name]['on']['field']) - && $current_definition['on']['field'] != $previous_definition[$was_sequence_name]['on']['field'] - ) { - $change['on'] = $current_definition['on']; - } - if (!empty($change)) { - $changes['change'][$was_sequence_name][$sequence_name] = $change; - } - } else { - if ($sequence_name != $was_sequence_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous sequence name ("'.$was_sequence_name. - '") for sequence "'.$sequence_name.'" that does not exist'); - } - $changes['add'][$sequence_name] = true; - } - } - return $changes; - } - // }}} - // {{{ verifyAlterDatabase() - - /** - * Verify that the changes requested are supported - * - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function verifyAlterDatabase($changes) - { - if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) { - foreach ($changes['tables']['change'] as $table_name => $table) { - if (!empty($table['indexes']) && is_array($table['indexes'])) { - if (!$this->db->supports('indexes')) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'indexes are not supported'); - } - $table_changes = count($table['indexes']); - if (!empty($table['indexes']['add'])) { - $table_changes--; - } - if (!empty($table['indexes']['remove'])) { - $table_changes--; - } - if (!empty($table['indexes']['change'])) { - $table_changes--; - } - if ($table_changes) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'index alteration not yet supported: '.implode(', ', array_keys($table['indexes']))); - } - } - unset($table['indexes']); - $result = $this->db->manager->alterTable($table_name, $table, true); - if (PEAR::isError($result)) { - return $result; - } - } - } - if (!empty($changes['sequences']) && is_array($changes['sequences'])) { - if (!$this->db->supports('sequences')) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'sequences are not supported'); - } - $sequence_changes = count($changes['sequences']); - if (!empty($changes['sequences']['add'])) { - $sequence_changes--; - } - if (!empty($changes['sequences']['remove'])) { - $sequence_changes--; - } - if (!empty($changes['sequences']['change'])) { - $sequence_changes--; - } - if ($sequence_changes) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'sequence alteration not yet supported: '.implode(', ', array_keys($changes['sequences']))); - } - } - return MDB2_OK; - } - - // }}} - // {{{ alterDatabaseIndexes() - - /** - * Execute the necessary actions to implement the requested changes - * in the indexes inside a database structure. - * - * @param string $table_name name of the table - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabaseIndexes($table_name, $changes) - { - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - if (!empty($changes['remove']) && is_array($changes['remove'])) { - foreach ($changes['remove'] as $index_name => $index) { - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->dropConstraint($table_name, $index_name, !empty($index['primary'])); - } else { - $result = $this->db->manager->dropIndex($table_name, $index_name); - } - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) { - return $result; - } - $alterations++; - } - } - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $index_name => $index) { - /** - * Drop existing index/constraint first. - * Since $changes doesn't tell us whether it's an index or a constraint before the change, - * we have to find out and call the appropriate method. - */ - if (in_array($index_name, $this->db->manager->listTableIndexes($table_name))) { - $result = $this->db->manager->dropIndex($table_name, $index_name); - } elseif (in_array($index_name, $this->db->manager->listTableConstraints($table_name))) { - $result = $this->db->manager->dropConstraint($table_name, $index_name); - } - if (!empty($result) && PEAR::isError($result)) { - return $result; - } - - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->createConstraint($table_name, $index_name, $index); - } else { - $result = $this->db->manager->createIndex($table_name, $index_name, $index); - } - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $index_name => $index) { - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->createConstraint($table_name, $index_name, $index); - } else { - $result = $this->db->manager->createIndex($table_name, $index_name, $index); - } - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - return $alterations; - } - - // }}} - // {{{ alterDatabaseTables() - - /** - * Execute the necessary actions to implement the requested changes - * in the tables inside a database structure. - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabaseTables($current_definition, $previous_definition, $changes) - { - /* FIXME: tables marked to be added are initialized by createTable(), others don't */ - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $table_name => $table) { - $result = $this->createTable($table_name, $current_definition[$table_name]); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if ($this->options['drop_missing_tables'] - && !empty($changes['remove']) - && is_array($changes['remove'])) { - foreach ($changes['remove'] as $table_name => $table) { - $result = $this->db->manager->dropTable($table_name); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $table_name => $table) { - $indexes = array(); - if (!empty($table['indexes'])) { - $indexes = $table['indexes']; - unset($table['indexes']); - } - if (!empty($indexes['remove'])) { - $result = $this->alterDatabaseIndexes($table_name, array('remove' => $indexes['remove'])); - if (PEAR::isError($result)) { - return $result; - } - unset($indexes['remove']); - $alterations += $result; - } - $result = $this->db->manager->alterTable($table_name, $table, false); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - - // table may be renamed at this point - if (!empty($table['name'])) { - $table_name = $table['name']; - } - - if (!empty($indexes)) { - $result = $this->alterDatabaseIndexes($table_name, $indexes); - if (PEAR::isError($result)) { - return $result; - } - $alterations += $result; - } - } - } - - return $alterations; - } - - // }}} - // {{{ alterDatabaseSequences() - - /** - * Execute the necessary actions to implement the requested changes - * in the sequences inside a database structure. - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabaseSequences($current_definition, $previous_definition, $changes) - { - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $sequence_name => $sequence) { - $result = $this->createSequence($sequence_name, $current_definition[$sequence_name]); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if (!empty($changes['remove']) && is_array($changes['remove'])) { - foreach ($changes['remove'] as $sequence_name => $sequence) { - $result = $this->db->manager->dropSequence($sequence_name); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $sequence_name => $sequence) { - $result = $this->db->manager->dropSequence($previous_definition[$sequence_name]['was']); - if (PEAR::isError($result)) { - return $result; - } - $result = $this->createSequence($sequence_name, $sequence); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - return $alterations; - } - - // }}} - // {{{ alterDatabase() - - /** - * Execute the necessary actions to implement the requested changes - * in a database structure. - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabase($current_definition, $previous_definition, $changes) - { - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - $result = $this->verifyAlterDatabase($changes); - if (PEAR::isError($result)) { - return $result; - } - - if (!empty($current_definition['name'])) { - $previous_database_name = $this->db->setDatabase($current_definition['name']); - } - - if (($support_transactions = $this->db->supports('transactions')) - && PEAR::isError($result = $this->db->beginNestedTransaction()) - ) { - return $result; - } - - if (!empty($changes['tables']) && !empty($current_definition['tables'])) { - $current_tables = isset($current_definition['tables']) ? $current_definition['tables'] : array(); - $previous_tables = isset($previous_definition['tables']) ? $previous_definition['tables'] : array(); - - $result = $this->alterDatabaseTables($current_tables, $previous_tables, $changes['tables']); - if (is_numeric($result)) { - $alterations += $result; - } - } - - if (!PEAR::isError($result) && !empty($changes['sequences'])) { - $current_sequences = isset($current_definition['sequences']) ? $current_definition['sequences'] : array(); - $previous_sequences = isset($previous_definition['sequences']) ? $previous_definition['sequences'] : array(); - - $result = $this->alterDatabaseSequences($current_sequences, $previous_sequences, $changes['sequences']); - if (is_numeric($result)) { - $alterations += $result; - } - } - - if ($support_transactions) { - $res = $this->db->completeNestedTransaction(); - if (PEAR::isError($res)) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not end transaction ('. - $res->getMessage().' ('.$res->getUserinfo().'))'); - } - } elseif (PEAR::isError($result) && $alterations) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'the requested database alterations were only partially implemented ('. - $result->getMessage().' ('.$result->getUserinfo().'))'); - } - - if (isset($previous_database_name)) { - $this->db->setDatabase($previous_database_name); - } - return $result; - } - - // }}} - // {{{ dumpDatabaseChanges() - - /** - * Dump the changes between two database definitions. - * - * @param array $changes associative array that specifies the list of database - * definitions changes as returned by the _compareDefinitions - * manager class function. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function dumpDatabaseChanges($changes) - { - if (!empty($changes['tables'])) { - if (!empty($changes['tables']['add']) && is_array($changes['tables']['add'])) { - foreach ($changes['tables']['add'] as $table_name => $table) { - $this->db->debug("$table_name:", __FUNCTION__); - $this->db->debug("\tAdded table '$table_name'", __FUNCTION__); - } - } - - if (!empty($changes['tables']['remove']) && is_array($changes['tables']['remove'])) { - if ($this->options['drop_missing_tables']) { - foreach ($changes['tables']['remove'] as $table_name => $table) { - $this->db->debug("$table_name:", __FUNCTION__); - $this->db->debug("\tRemoved table '$table_name'", __FUNCTION__); - } - } else { - foreach ($changes['tables']['remove'] as $table_name => $table) { - $this->db->debug("\tObsolete table '$table_name' left as is", __FUNCTION__); - } - } - } - - if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) { - foreach ($changes['tables']['change'] as $table_name => $table) { - if (array_key_exists('name', $table)) { - $this->db->debug("\tRenamed table '$table_name' to '".$table['name']."'", __FUNCTION__); - } - if (!empty($table['add']) && is_array($table['add'])) { - foreach ($table['add'] as $field_name => $field) { - $this->db->debug("\tAdded field '".$field_name."'", __FUNCTION__); - } - } - if (!empty($table['remove']) && is_array($table['remove'])) { - foreach ($table['remove'] as $field_name => $field) { - $this->db->debug("\tRemoved field '".$field_name."'", __FUNCTION__); - } - } - if (!empty($table['rename']) && is_array($table['rename'])) { - foreach ($table['rename'] as $field_name => $field) { - $this->db->debug("\tRenamed field '".$field_name."' to '".$field['name']."'", __FUNCTION__); - } - } - if (!empty($table['change']) && is_array($table['change'])) { - foreach ($table['change'] as $field_name => $field) { - $field = $field['definition']; - if (array_key_exists('type', $field)) { - $this->db->debug("\tChanged field '$field_name' type to '".$field['type']."'", __FUNCTION__); - } - - if (array_key_exists('unsigned', $field)) { - $this->db->debug("\tChanged field '$field_name' type to '". - (!empty($field['unsigned']) && $field['unsigned'] ? '' : 'not ')."unsigned'", - __FUNCTION__); - } - - if (array_key_exists('length', $field)) { - $this->db->debug("\tChanged field '$field_name' length to '". - (!empty($field['length']) ? $field['length']: 'no length')."'", __FUNCTION__); - } - if (array_key_exists('default', $field)) { - $this->db->debug("\tChanged field '$field_name' default to ". - (isset($field['default']) ? "'".$field['default']."'" : 'NULL'), __FUNCTION__); - } - - if (array_key_exists('notnull', $field)) { - $this->db->debug("\tChanged field '$field_name' notnull to ". - (!empty($field['notnull']) && $field['notnull'] ? 'true' : 'false'), - __FUNCTION__); - } - } - } - if (!empty($table['indexes']) && is_array($table['indexes'])) { - if (!empty($table['indexes']['add']) && is_array($table['indexes']['add'])) { - foreach ($table['indexes']['add'] as $index_name => $index) { - $this->db->debug("\tAdded index '".$index_name. - "' of table '$table_name'", __FUNCTION__); - } - } - if (!empty($table['indexes']['remove']) && is_array($table['indexes']['remove'])) { - foreach ($table['indexes']['remove'] as $index_name => $index) { - $this->db->debug("\tRemoved index '".$index_name. - "' of table '$table_name'", __FUNCTION__); - } - } - if (!empty($table['indexes']['change']) && is_array($table['indexes']['change'])) { - foreach ($table['indexes']['change'] as $index_name => $index) { - if (array_key_exists('name', $index)) { - $this->db->debug("\tRenamed index '".$index_name."' to '".$index['name']. - "' on table '$table_name'", __FUNCTION__); - } - if (array_key_exists('unique', $index)) { - $this->db->debug("\tChanged index '".$index_name."' unique to '". - !empty($index['unique'])."' on table '$table_name'", __FUNCTION__); - } - if (array_key_exists('primary', $index)) { - $this->db->debug("\tChanged index '".$index_name."' primary to '". - !empty($index['primary'])."' on table '$table_name'", __FUNCTION__); - } - if (array_key_exists('change', $index)) { - $this->db->debug("\tChanged index '".$index_name. - "' on table '$table_name'", __FUNCTION__); - } - } - } - } - } - } - } - if (!empty($changes['sequences'])) { - if (!empty($changes['sequences']['add']) && is_array($changes['sequences']['add'])) { - foreach ($changes['sequences']['add'] as $sequence_name => $sequence) { - $this->db->debug("$sequence_name:", __FUNCTION__); - $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__); - } - } - if (!empty($changes['sequences']['remove']) && is_array($changes['sequences']['remove'])) { - foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) { - $this->db->debug("$sequence_name:", __FUNCTION__); - $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__); - } - } - if (!empty($changes['sequences']['change']) && is_array($changes['sequences']['change'])) { - foreach ($changes['sequences']['change'] as $sequence_name => $sequence) { - if (array_key_exists('name', $sequence)) { - $this->db->debug("\tRenamed sequence '$sequence_name' to '". - $sequence['name']."'", __FUNCTION__); - } - if (!empty($sequence['change']) && is_array($sequence['change'])) { - foreach ($sequence['change'] as $sequence_name => $sequence) { - if (array_key_exists('start', $sequence)) { - $this->db->debug("\tChanged sequence '$sequence_name' start to '". - $sequence['start']."'", __FUNCTION__); - } - } - } - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ dumpDatabase() - - /** - * Dump a previously parsed database structure in the Metabase schema - * XML based format suitable for the Metabase parser. This function - * may optionally dump the database definition with initialization - * commands that specify the data that is currently present in the tables. - * - * @param array $database_definition multi dimensional array that contains the current definition - * @param array $arguments associative array that takes pairs of tag - * names and values that define dump options. - *
array (
-     *                     'output_mode'    =>    String
-     *                         'file' :   dump into a file
-     *                         default:   dump using a function
-     *                     'output'        =>    String
-     *                         depending on the 'Output_Mode'
-     *                                  name of the file
-     *                                  name of the function
-     *                     'end_of_line'        =>    String
-     *                         end of line delimiter that should be used
-     *                         default: "\n"
-     *                 );
- * @param int $dump Int that determines what data to dump - * + MDB2_SCHEMA_DUMP_ALL : the entire db - * + MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db - * + MDB2_SCHEMA_DUMP_CONTENT : only the content of the db - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL) - { - $class_name = $this->options['writer']; - - $result = MDB2::loadClass($class_name, $this->db->getOption('debug')); - if (PEAR::isError($result)) { - return $result; - } - - // get initialization data - if (isset($database_definition['tables']) && is_array($database_definition['tables']) - && $dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT - ) { - foreach ($database_definition['tables'] as $table_name => $table) { - $fields = array(); - $fieldsq = array(); - foreach ($table['fields'] as $field_name => $field) { - $fields[$field_name] = $field['type']; - - $fieldsq[] = $this->db->quoteIdentifier($field_name, true); - } - - $query = 'SELECT '.implode(', ', $fieldsq).' FROM '; - $query .= $this->db->quoteIdentifier($table_name, true); - - $data = $this->db->queryAll($query, $fields, MDB2_FETCHMODE_ASSOC); - - if (PEAR::isError($data)) { - return $data; - } - - if (!empty($data)) { - $initialization = array(); - $lob_buffer_length = $this->db->getOption('lob_buffer_length'); - foreach ($data as $row) { - $rows = array(); - foreach ($row as $key => $lob) { - if (is_resource($lob)) { - $value = ''; - while (!feof($lob)) { - $value .= fread($lob, $lob_buffer_length); - } - $row[$key] = $value; - } - $rows[] = array('name' => $key, 'group' => array('type' => 'value', 'data' => $row[$key])); - } - $initialization[] = array('type' => 'insert', 'data' => array('field' => $rows)); - } - $database_definition['tables'][$table_name]['initialization'] = $initialization; - } - } - } - - $writer = new $class_name($this->options['valid_types']); - return $writer->dumpDatabase($database_definition, $arguments, $dump); - } - - // }}} - // {{{ writeInitialization() - - /** - * Write initialization and sequences - * - * @param string|array $data data file or data array - * @param string|array $structure structure file or array - * @param array $variables associative array that is passed to the argument - * of the same name to the parseDatabaseDefinitionFile function. (there third - * param) - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function writeInitialization($data, $structure = false, $variables = array()) - { - if ($structure) { - $structure = $this->parseDatabaseDefinition($structure, false, $variables); - if (PEAR::isError($structure)) { - return $structure; - } - } - - $data = $this->parseDatabaseDefinition($data, false, $variables, false, $structure); - if (PEAR::isError($data)) { - return $data; - } - - $previous_database_name = null; - if (!empty($data['name'])) { - $previous_database_name = $this->db->setDatabase($data['name']); - } elseif (!empty($structure['name'])) { - $previous_database_name = $this->db->setDatabase($structure['name']); - } - - if (!empty($data['tables']) && is_array($data['tables'])) { - foreach ($data['tables'] as $table_name => $table) { - if (empty($table['initialization'])) { - continue; - } - $result = $this->initializeTable($table_name, $table); - if (PEAR::isError($result)) { - return $result; - } - } - } - - if (!empty($structure['sequences']) && is_array($structure['sequences'])) { - foreach ($structure['sequences'] as $sequence_name => $sequence) { - if (isset($data['sequences'][$sequence_name]) - || !isset($sequence['on']['table']) - || !isset($data['tables'][$sequence['on']['table']]) - ) { - continue; - } - $result = $this->createSequence($sequence_name, $sequence, true); - if (PEAR::isError($result)) { - return $result; - } - } - } - if (!empty($data['sequences']) && is_array($data['sequences'])) { - foreach ($data['sequences'] as $sequence_name => $sequence) { - $result = $this->createSequence($sequence_name, $sequence, true); - if (PEAR::isError($result)) { - return $result; - } - } - } - - if (isset($previous_database_name)) { - $this->db->setDatabase($previous_database_name); - } - - return MDB2_OK; - } - - // }}} - // {{{ updateDatabase() - - /** - * Compare the correspondent files of two versions of a database schema - * definition: the previously installed and the one that defines the schema - * that is meant to update the database. - * If the specified previous definition file does not exist, this function - * will create the database from the definition specified in the current - * schema file. - * If both files exist, the function assumes that the database was previously - * installed based on the previous schema file and will update it by just - * applying the changes. - * If this function succeeds, the contents of the current schema file are - * copied to replace the previous schema file contents. Any subsequent schema - * changes should only be done on the file specified by the $current_schema_file - * to let this function make a consistent evaluation of the exact changes that - * need to be applied. - * - * @param string|array $current_schema filename or array of the updated database schema definition. - * @param string|array $previous_schema filename or array of the previously installed database schema definition. - * @param array $variables associative array that is passed to the argument of the same - * name to the parseDatabaseDefinitionFile function. (there third param) - * @param bool $disable_query determines if the disable_query option should be set to true - * for the alterDatabase() or createDatabase() call - * @param bool $overwrite_old_schema_file Overwrite? - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function updateDatabase($current_schema, $previous_schema = false, - $variables = array(), $disable_query = false, - $overwrite_old_schema_file = false) - { - $current_definition = $this->parseDatabaseDefinition($current_schema, false, $variables, - $this->options['fail_on_invalid_names']); - - if (PEAR::isError($current_definition)) { - return $current_definition; - } - - $previous_definition = false; - if ($previous_schema) { - $previous_definition = $this->parseDatabaseDefinition($previous_schema, true, $variables, - $this->options['fail_on_invalid_names']); - if (PEAR::isError($previous_definition)) { - return $previous_definition; - } - } - - if ($previous_definition) { - $dbExists = $this->db->databaseExists($current_definition['name']); - if (PEAR::isError($dbExists)) { - return $dbExists; - } - - if (!$dbExists) { - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'database to update does not exist: '.$current_definition['name']); - } - - $changes = $this->compareDefinitions($current_definition, $previous_definition); - if (PEAR::isError($changes)) { - return $changes; - } - - if (is_array($changes)) { - $this->db->setOption('disable_query', $disable_query); - $result = $this->alterDatabase($current_definition, $previous_definition, $changes); - $this->db->setOption('disable_query', false); - if (PEAR::isError($result)) { - return $result; - } - $copy = true; - if ($this->db->options['debug']) { - $result = $this->dumpDatabaseChanges($changes); - if (PEAR::isError($result)) { - return $result; - } - } - } - } else { - $this->db->setOption('disable_query', $disable_query); - $result = $this->createDatabase($current_definition); - $this->db->setOption('disable_query', false); - if (PEAR::isError($result)) { - return $result; - } - } - - if ($overwrite_old_schema_file - && !$disable_query - && is_string($previous_schema) && is_string($current_schema) - && !copy($current_schema, $previous_schema)) { - - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not copy the new database definition file to the current file'); - } - - return MDB2_OK; - } - // }}} - // {{{ errorMessage() - - /** - * Return a textual error message for a MDB2 error code - * - * @param int|array $value integer error code, null to get the - * current error code-message map, - * or an array with a new error code-message map - * - * @return string error message, or false if the error code was not recognized - * @access public - */ - function errorMessage($value = null) - { - static $errorMessages; - if (is_array($value)) { - $errorMessages = $value; - return MDB2_OK; - } elseif (!isset($errorMessages)) { - $errorMessages = array( - MDB2_SCHEMA_ERROR => 'unknown error', - MDB2_SCHEMA_ERROR_PARSE => 'schema parse error', - MDB2_SCHEMA_ERROR_VALIDATE => 'schema validation error', - MDB2_SCHEMA_ERROR_INVALID => 'invalid', - MDB2_SCHEMA_ERROR_UNSUPPORTED => 'not supported', - MDB2_SCHEMA_ERROR_WRITER => 'schema writer error', - ); - } - - if (is_null($value)) { - return $errorMessages; - } - - if (PEAR::isError($value)) { - $value = $value->getCode(); - } - - return !empty($errorMessages[$value]) ? - $errorMessages[$value] : $errorMessages[MDB2_SCHEMA_ERROR]; - } - - // }}} - // {{{ raiseError() - - /** - * This method is used to communicate an error and invoke error - * callbacks etc. Basically a wrapper for PEAR::raiseError - * without the message string. - * - * @param int|PEAR_Error $code integer error code or and PEAR_Error instance - * @param int $mode error mode, see PEAR_Error docs - * error level (E_USER_NOTICE etc). If error mode is - * PEAR_ERROR_CALLBACK, this is the callback function, - * either as a function name, or as an array of an - * object and method name. For other error modes this - * parameter is ignored. - * @param array $options Options, depending on the mode, @see PEAR::setErrorHandling - * @param string $userinfo Extra debug information. Defaults to the last - * query and native error code. - * - * @return object a PEAR error object - * @access public - * @see PEAR_Error - */ - function raiseError($code = null, $mode = null, $options = null, $userinfo = null,$a=null,$b=null,$c=null) - { - $err =PEAR::raiseError(null, $code, $mode, $options, - $userinfo, 'MDB2_Schema_Error', true); - return $err; - } - - // }}} - // {{{ isError() - - /** - * Tell whether a value is an MDB2_Schema error. - * - * @param mixed $data the value to test - * @param int $code if $data is an error object, return true only if $code is - * a string and $db->getMessage() == $code or - * $code is an integer and $db->getCode() == $code - * - * @return bool true if parameter is an error - * @access public - */ - static function isError($data, $code = null) - { - if (is_a($data, 'MDB2_Schema_Error')) { - if (is_null($code)) { - return true; - } elseif (is_string($code)) { - return $data->getMessage() === $code; - } else { - $code = (array)$code; - return in_array($data->getCode(), $code); - } - } - return false; - } - - // }}} -} - -/** - * MDB2_Schema_Error implements a class for reporting portable database error - * messages. - * - * @category Database - * @package MDB2_Schema - * @author Stig Bakken - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Error extends PEAR_Error -{ - /** - * MDB2_Schema_Error constructor. - * - * @param mixed $code error code, or string with error message. - * @param int $mode what 'error mode' to operate in - * @param int $level what error level to use for $mode & PEAR_ERROR_TRIGGER - * @param mixed $debuginfo additional debug info, such as the last query - * - * @access public - */ - function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR, $mode = PEAR_ERROR_RETURN, - $level = E_USER_NOTICE, $debuginfo = null) - { - $this->PEAR_Error('MDB2_Schema Error: ' . MDB2_Schema::errorMessage($code), $code, - $mode, $level, $debuginfo); - } -} -?> diff --git a/3rdparty/MDB2/Schema/Parser.php b/3rdparty/MDB2/Schema/Parser.php deleted file mode 100644 index b740ef55fa..0000000000 --- a/3rdparty/MDB2/Schema/Parser.php +++ /dev/null @@ -1,812 +0,0 @@ - - * Author: Igor Feghali - * - * $Id: Parser.php,v 1.68 2008/11/30 03:34:00 clockwerx Exp $ - * - * @category Database - * @package MDB2_Schema - * @author Christian Dickmann - * @author Igor Feghali - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Parser.php,v 1.68 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - - -require_once('XML/Parser.php'); -require_once('MDB2/Schema/Validate.php'); - -/** - * Parses an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Christian Dickmann - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Parser extends XML_Parser -{ - var $database_definition = array(); - - var $elements = array(); - - var $element = ''; - - var $count = 0; - - var $table = array(); - - var $table_name = ''; - - var $field = array(); - - var $field_name = ''; - - var $init = array(); - - var $init_function = array(); - - var $init_expression = array(); - - var $init_field = array(); - - var $index = array(); - - var $index_name = ''; - - var $constraint = array(); - - var $constraint_name = ''; - - var $var_mode = false; - - var $variables = array(); - - var $sequence = array(); - - var $sequence_name = ''; - - var $error; - - var $structure = false; - - var $val; - - function __construct($variables, $fail_on_invalid_names = true, - $structure = false, $valid_types = array(), - $force_defaults = true) - { - // force ISO-8859-1 due to different defaults for PHP4 and PHP5 - // todo: this probably needs to be investigated some more andcleaned up - parent::__construct('ISO-8859-1'); - - $this->variables = $variables; - $this->structure = $structure; - $this->val =new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults); - } - - function startHandler($xp, $element, $attribs) - { - if (strtolower($element) == 'variable') { - $this->var_mode = true; - return; - } - - $this->elements[$this->count++] = strtolower($element); - - $this->element = implode('-', $this->elements); - - switch ($this->element) { - /* Initialization */ - case 'database-table-initialization': - $this->table['initialization'] = array(); - break; - - /* Insert */ - /* insert: field+ */ - case 'database-table-initialization-insert': - $this->init = array('type' => 'insert', 'data' => array('field' => array())); - break; - /* insert-select: field+, table, where? */ - case 'database-table-initialization-insert-select': - $this->init['data']['table'] = ''; - break; - - /* Update */ - /* update: field+, where? */ - case 'database-table-initialization-update': - $this->init = array('type' => 'update', 'data' => array('field' => array())); - break; - - /* Delete */ - /* delete: where */ - case 'database-table-initialization-delete': - $this->init = array('type' => 'delete', 'data' => array('where' => array())); - break; - - /* Insert and Update */ - case 'database-table-initialization-insert-field': - case 'database-table-initialization-insert-select-field': - case 'database-table-initialization-update-field': - $this->init_field = array('name' => '', 'group' => array()); - break; - case 'database-table-initialization-insert-field-value': - case 'database-table-initialization-insert-select-field-value': - case 'database-table-initialization-update-field-value': - /* if value tag is empty cdataHandler is not called so we must force value element creation here */ - $this->init_field['group'] = array('type' => 'value', 'data' => ''); - break; - case 'database-table-initialization-insert-field-null': - case 'database-table-initialization-insert-select-field-null': - case 'database-table-initialization-update-field-null': - $this->init_field['group'] = array('type' => 'null'); - break; - case 'database-table-initialization-insert-field-function': - case 'database-table-initialization-insert-select-field-function': - case 'database-table-initialization-update-field-function': - $this->init_function = array('name' => ''); - break; - case 'database-table-initialization-insert-field-expression': - case 'database-table-initialization-insert-select-field-expression': - case 'database-table-initialization-update-field-expression': - $this->init_expression = array(); - break; - - /* All */ - case 'database-table-initialization-insert-select-where': - case 'database-table-initialization-update-where': - case 'database-table-initialization-delete-where': - $this->init['data']['where'] = array('type' => '', 'data' => array()); - break; - case 'database-table-initialization-insert-select-where-expression': - case 'database-table-initialization-update-where-expression': - case 'database-table-initialization-delete-where-expression': - $this->init_expression = array(); - break; - - /* One level simulation of expression-function recursion */ - case 'database-table-initialization-insert-field-expression-function': - case 'database-table-initialization-insert-select-field-expression-function': - case 'database-table-initialization-insert-select-where-expression-function': - case 'database-table-initialization-update-field-expression-function': - case 'database-table-initialization-update-where-expression-function': - case 'database-table-initialization-delete-where-expression-function': - $this->init_function = array('name' => ''); - break; - - /* One level simulation of function-expression recursion */ - case 'database-table-initialization-insert-field-function-expression': - case 'database-table-initialization-insert-select-field-function-expression': - case 'database-table-initialization-insert-select-where-function-expression': - case 'database-table-initialization-update-field-function-expression': - case 'database-table-initialization-update-where-function-expression': - case 'database-table-initialization-delete-where-function-expression': - $this->init_expression = array(); - break; - - /* Definition */ - case 'database': - $this->database_definition = array( - 'name' => '', - 'create' => '', - 'overwrite' => '', - 'charset' => '', - 'description' => '', - 'comments' => '', - 'tables' => array(), - 'sequences' => array() - ); - break; - case 'database-table': - $this->table_name = ''; - - $this->table = array( - 'was' => '', - 'description' => '', - 'comments' => '', - 'fields' => array(), - 'indexes' => array(), - 'constraints' => array(), - 'initialization' => array() - ); - break; - case 'database-table-declaration-field': - case 'database-table-declaration-foreign-field': - case 'database-table-declaration-foreign-references-field': - $this->field_name = ''; - - $this->field = array(); - break; - case 'database-table-declaration-index-field': - $this->field_name = ''; - - $this->field = array('sorting' => '', 'length' => ''); - break; - /* force field attributes to be initialized when the tag is empty in the XML */ - case 'database-table-declaration-field-was': - $this->field['was'] = ''; - break; - case 'database-table-declaration-field-type': - $this->field['type'] = ''; - break; - case 'database-table-declaration-field-fixed': - $this->field['fixed'] = ''; - break; - case 'database-table-declaration-field-default': - $this->field['default'] = ''; - break; - case 'database-table-declaration-field-notnull': - $this->field['notnull'] = ''; - break; - case 'database-table-declaration-field-autoincrement': - $this->field['autoincrement'] = ''; - break; - case 'database-table-declaration-field-unsigned': - $this->field['unsigned'] = ''; - break; - case 'database-table-declaration-field-length': - $this->field['length'] = ''; - break; - case 'database-table-declaration-field-description': - $this->field['description'] = ''; - break; - case 'database-table-declaration-field-comments': - $this->field['comments'] = ''; - break; - case 'database-table-declaration-index': - $this->index_name = ''; - - $this->index = array( - 'was' => '', - 'unique' =>'', - 'primary' => '', - 'fields' => array() - ); - break; - case 'database-table-declaration-foreign': - $this->constraint_name = ''; - - $this->constraint = array( - 'was' => '', - 'match' => '', - 'ondelete' => '', - 'onupdate' => '', - 'deferrable' => '', - 'initiallydeferred' => '', - 'foreign' => true, - 'fields' => array(), - 'references' => array('table' => '', 'fields' => array()) - ); - break; - case 'database-sequence': - $this->sequence_name = ''; - - $this->sequence = array( - 'was' => '', - 'start' => '', - 'description' => '', - 'comments' => '', - 'on' => array('table' => '', 'field' => '') - ); - break; - } - } - - function endHandler($xp, $element) - { - if (strtolower($element) == 'variable') { - $this->var_mode = false; - return; - } - - switch ($this->element) { - /* Initialization */ - - /* Insert */ - case 'database-table-initialization-insert-select': - $this->init['data'] = array('select' => $this->init['data']); - break; - - /* Insert and Delete */ - case 'database-table-initialization-insert-field': - case 'database-table-initialization-insert-select-field': - case 'database-table-initialization-update-field': - $result = $this->val->validateDataField($this->table['fields'], $this->init['data']['field'], $this->init_field); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->init['data']['field'][] = $this->init_field; - } - break; - case 'database-table-initialization-insert-field-function': - case 'database-table-initialization-insert-select-field-function': - case 'database-table-initialization-update-field-function': - $this->init_field['group'] = array('type' => 'function', 'data' => $this->init_function); - break; - case 'database-table-initialization-insert-field-expression': - case 'database-table-initialization-insert-select-field-expression': - case 'database-table-initialization-update-field-expression': - $this->init_field['group'] = array('type' => 'expression', 'data' => $this->init_expression); - break; - - /* All */ - case 'database-table-initialization-insert-select-where-expression': - case 'database-table-initialization-update-where-expression': - case 'database-table-initialization-delete-where-expression': - $this->init['data']['where']['type'] = 'expression'; - $this->init['data']['where']['data'] = $this->init_expression; - break; - case 'database-table-initialization-insert': - case 'database-table-initialization-delete': - case 'database-table-initialization-update': - $this->table['initialization'][] = $this->init; - break; - - /* One level simulation of expression-function recursion */ - case 'database-table-initialization-insert-field-expression-function': - case 'database-table-initialization-insert-select-field-expression-function': - case 'database-table-initialization-insert-select-where-expression-function': - case 'database-table-initialization-update-field-expression-function': - case 'database-table-initialization-update-where-expression-function': - case 'database-table-initialization-delete-where-expression-function': - $this->init_expression['operants'][] = array('type' => 'function', 'data' => $this->init_function); - break; - - /* One level simulation of function-expression recursion */ - case 'database-table-initialization-insert-field-function-expression': - case 'database-table-initialization-insert-select-field-function-expression': - case 'database-table-initialization-insert-select-where-function-expression': - case 'database-table-initialization-update-field-function-expression': - case 'database-table-initialization-update-where-function-expression': - case 'database-table-initialization-delete-where-function-expression': - $this->init_function['arguments'][] = array('type' => 'expression', 'data' => $this->init_expression); - break; - - /* Table definition */ - case 'database-table': - $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->database_definition['tables'][$this->table_name] = $this->table; - } - break; - case 'database-table-name': - if (isset($this->structure['tables'][$this->table_name])) { - $this->table = $this->structure['tables'][$this->table_name]; - } - break; - - /* Field declaration */ - case 'database-table-declaration-field': - $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->table['fields'][$this->field_name] = $this->field; - } - break; - - /* Index declaration */ - case 'database-table-declaration-index': - $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->table['indexes'][$this->index_name] = $this->index; - } - break; - case 'database-table-declaration-index-field': - $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->index['fields'][$this->field_name] = $this->field; - } - break; - - /* Foreign Key declaration */ - case 'database-table-declaration-foreign': - $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->table['constraints'][$this->constraint_name] = $this->constraint; - } - break; - case 'database-table-declaration-foreign-field': - $result = $this->val->validateConstraintField($this->constraint['fields'], $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->constraint['fields'][$this->field_name] = ''; - } - break; - case 'database-table-declaration-foreign-references-field': - $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->constraint['references']['fields'][$this->field_name] = ''; - } - break; - - /* Sequence declaration */ - case 'database-sequence': - $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->database_definition['sequences'][$this->sequence_name] = $this->sequence; - } - break; - - /* End of File */ - case 'database': - $result = $this->val->validateDatabase($this->database_definition); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } - break; - } - - unset($this->elements[--$this->count]); - $this->element = implode('-', $this->elements); - } - - function raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE,$a=null,$b=null,$c=null) - { - if (is_null($this->error)) { - $error = ''; - if (is_resource($msg)) { - $error .= 'Parser error: '.xml_error_string(xml_get_error_code($msg)); - $xp = $msg; - } else { - $error .= 'Parser error: '.$msg; - if (!is_resource($xp)) { - $xp = $this->parser; - } - } - - if ($error_string = xml_error_string($xmlecode)) { - $error .= ' - '.$error_string; - } - - if (is_resource($xp)) { - $byte = @xml_get_current_byte_index($xp); - $line = @xml_get_current_line_number($xp); - $column = @xml_get_current_column_number($xp); - $error .= " - Byte: $byte; Line: $line; Col: $column"; - } - - $error .= "\n"; - - $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error); - } - return $this->error; - } - - function cdataHandler($xp, $data) - { - if ($this->var_mode == true) { - if (!isset($this->variables[$data])) { - $this->raiseError('variable "'.$data.'" not found', null, $xp); - return; - } - $data = $this->variables[$data]; - } - - switch ($this->element) { - /* Initialization */ - - /* Insert */ - case 'database-table-initialization-insert-select-table': - $this->init['data']['table'] = $data; - break; - - /* Insert and Update */ - case 'database-table-initialization-insert-field-name': - case 'database-table-initialization-insert-select-field-name': - case 'database-table-initialization-update-field-name': - $this->init_field['name'] .= $data; - break; - case 'database-table-initialization-insert-field-value': - case 'database-table-initialization-insert-select-field-value': - case 'database-table-initialization-update-field-value': - $this->init_field['group']['data'] .= $data; - break; - case 'database-table-initialization-insert-field-function-name': - case 'database-table-initialization-insert-select-field-function-name': - case 'database-table-initialization-update-field-function-name': - $this->init_function['name'] .= $data; - break; - case 'database-table-initialization-insert-field-function-value': - case 'database-table-initialization-insert-select-field-function-value': - case 'database-table-initialization-update-field-function-value': - $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-function-column': - case 'database-table-initialization-insert-select-field-function-column': - case 'database-table-initialization-update-field-function-column': - $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data); - break; - case 'database-table-initialization-insert-field-column': - case 'database-table-initialization-insert-select-field-column': - case 'database-table-initialization-update-field-column': - $this->init_field['group'] = array('type' => 'column', 'data' => $data); - break; - - /* All */ - case 'database-table-initialization-insert-field-expression-operator': - case 'database-table-initialization-insert-select-field-expression-operator': - case 'database-table-initialization-insert-select-where-expression-operator': - case 'database-table-initialization-update-field-expression-operator': - case 'database-table-initialization-update-where-expression-operator': - case 'database-table-initialization-delete-where-expression-operator': - $this->init_expression['operator'] = $data; - break; - case 'database-table-initialization-insert-field-expression-value': - case 'database-table-initialization-insert-select-field-expression-value': - case 'database-table-initialization-insert-select-where-expression-value': - case 'database-table-initialization-update-field-expression-value': - case 'database-table-initialization-update-where-expression-value': - case 'database-table-initialization-delete-where-expression-value': - $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-expression-column': - case 'database-table-initialization-insert-select-field-expression-column': - case 'database-table-initialization-insert-select-where-expression-column': - case 'database-table-initialization-update-field-expression-column': - case 'database-table-initialization-update-where-expression-column': - case 'database-table-initialization-delete-where-expression-column': - $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data); - break; - - case 'database-table-initialization-insert-field-function-function': - case 'database-table-initialization-insert-field-function-expression': - case 'database-table-initialization-insert-field-expression-expression': - case 'database-table-initialization-update-field-function-function': - case 'database-table-initialization-update-field-function-expression': - case 'database-table-initialization-update-field-expression-expression': - case 'database-table-initialization-update-where-expression-expression': - case 'database-table-initialization-delete-where-expression-expression': - /* Recursion to be implemented yet */ - break; - - /* One level simulation of expression-function recursion */ - case 'database-table-initialization-insert-field-expression-function-name': - case 'database-table-initialization-insert-select-field-expression-function-name': - case 'database-table-initialization-insert-select-where-expression-function-name': - case 'database-table-initialization-update-field-expression-function-name': - case 'database-table-initialization-update-where-expression-function-name': - case 'database-table-initialization-delete-where-expression-function-name': - $this->init_function['name'] .= $data; - break; - case 'database-table-initialization-insert-field-expression-function-value': - case 'database-table-initialization-insert-select-field-expression-function-value': - case 'database-table-initialization-insert-select-where-expression-function-value': - case 'database-table-initialization-update-field-expression-function-value': - case 'database-table-initialization-update-where-expression-function-value': - case 'database-table-initialization-delete-where-expression-function-value': - $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-expression-function-column': - case 'database-table-initialization-insert-select-field-expression-function-column': - case 'database-table-initialization-insert-select-where-expression-function-column': - case 'database-table-initialization-update-field-expression-function-column': - case 'database-table-initialization-update-where-expression-function-column': - case 'database-table-initialization-delete-where-expression-function-column': - $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data); - break; - - /* One level simulation of function-expression recursion */ - case 'database-table-initialization-insert-field-function-expression-operator': - case 'database-table-initialization-insert-select-field-function-expression-operator': - case 'database-table-initialization-update-field-function-expression-operator': - $this->init_expression['operator'] = $data; - break; - case 'database-table-initialization-insert-field-function-expression-value': - case 'database-table-initialization-insert-select-field-function-expression-value': - case 'database-table-initialization-update-field-function-expression-value': - $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-function-expression-column': - case 'database-table-initialization-insert-select-field-function-expression-column': - case 'database-table-initialization-update-field-function-expression-column': - $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data); - break; - - /* Database */ - case 'database-name': - $this->database_definition['name'] .= $data; - break; - case 'database-create': - $this->database_definition['create'] .= $data; - break; - case 'database-overwrite': - $this->database_definition['overwrite'] .= $data; - break; - case 'database-charset': - $this->database_definition['charset'] .= $data; - break; - case 'database-description': - $this->database_definition['description'] .= $data; - break; - case 'database-comments': - $this->database_definition['comments'] .= $data; - break; - - /* Table declaration */ - case 'database-table-name': - $this->table_name .= $data; - break; - case 'database-table-was': - $this->table['was'] .= $data; - break; - case 'database-table-description': - $this->table['description'] .= $data; - break; - case 'database-table-comments': - $this->table['comments'] .= $data; - break; - - /* Field declaration */ - case 'database-table-declaration-field-name': - $this->field_name .= $data; - break; - case 'database-table-declaration-field-was': - $this->field['was'] .= $data; - break; - case 'database-table-declaration-field-type': - $this->field['type'] .= $data; - break; - case 'database-table-declaration-field-fixed': - $this->field['fixed'] .= $data; - break; - case 'database-table-declaration-field-default': - $this->field['default'] .= $data; - break; - case 'database-table-declaration-field-notnull': - $this->field['notnull'] .= $data; - break; - case 'database-table-declaration-field-autoincrement': - $this->field['autoincrement'] .= $data; - break; - case 'database-table-declaration-field-unsigned': - $this->field['unsigned'] .= $data; - break; - case 'database-table-declaration-field-length': - $this->field['length'] .= $data; - break; - case 'database-table-declaration-field-description': - $this->field['description'] .= $data; - break; - case 'database-table-declaration-field-comments': - $this->field['comments'] .= $data; - break; - - /* Index declaration */ - case 'database-table-declaration-index-name': - $this->index_name .= $data; - break; - case 'database-table-declaration-index-was': - $this->index['was'] .= $data; - break; - case 'database-table-declaration-index-unique': - $this->index['unique'] .= $data; - break; - case 'database-table-declaration-index-primary': - $this->index['primary'] .= $data; - break; - case 'database-table-declaration-index-field-name': - $this->field_name .= $data; - break; - case 'database-table-declaration-index-field-sorting': - $this->field['sorting'] .= $data; - break; - /* Add by Leoncx */ - case 'database-table-declaration-index-field-length': - $this->field['length'] .= $data; - break; - - /* Foreign Key declaration */ - case 'database-table-declaration-foreign-name': - $this->constraint_name .= $data; - break; - case 'database-table-declaration-foreign-was': - $this->constraint['was'] .= $data; - break; - case 'database-table-declaration-foreign-match': - $this->constraint['match'] .= $data; - break; - case 'database-table-declaration-foreign-ondelete': - $this->constraint['ondelete'] .= $data; - break; - case 'database-table-declaration-foreign-onupdate': - $this->constraint['onupdate'] .= $data; - break; - case 'database-table-declaration-foreign-deferrable': - $this->constraint['deferrable'] .= $data; - break; - case 'database-table-declaration-foreign-initiallydeferred': - $this->constraint['initiallydeferred'] .= $data; - break; - case 'database-table-declaration-foreign-field': - $this->field_name .= $data; - break; - case 'database-table-declaration-foreign-references-table': - $this->constraint['references']['table'] .= $data; - break; - case 'database-table-declaration-foreign-references-field': - $this->field_name .= $data; - break; - - /* Sequence declaration */ - case 'database-sequence-name': - $this->sequence_name .= $data; - break; - case 'database-sequence-was': - $this->sequence['was'] .= $data; - break; - case 'database-sequence-start': - $this->sequence['start'] .= $data; - break; - case 'database-sequence-description': - $this->sequence['description'] .= $data; - break; - case 'database-sequence-comments': - $this->sequence['comments'] .= $data; - break; - case 'database-sequence-on-table': - $this->sequence['on']['table'] .= $data; - break; - case 'database-sequence-on-field': - $this->sequence['on']['field'] .= $data; - break; - } - } -} - -?> diff --git a/3rdparty/MDB2/Schema/Parser2.php b/3rdparty/MDB2/Schema/Parser2.php deleted file mode 100644 index 01318473fd..0000000000 --- a/3rdparty/MDB2/Schema/Parser2.php +++ /dev/null @@ -1,624 +0,0 @@ - - * - * @category Database - * @package MDB2_Schema - * @author Igor Feghali - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Parser2.php,v 1.12 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -require_once 'XML/Unserializer.php'; -require_once 'MDB2/Schema/Validate.php'; - -/** - * Parses an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith - * @author Igor Feghali - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Parser2 extends XML_Unserializer -{ - var $database_definition = array(); - - var $database_loaded = array(); - - var $variables = array(); - - var $error; - - var $structure = false; - - var $val; - - var $options = array(); - - var $table = array(); - - var $table_name = ''; - - var $field = array(); - - var $field_name = ''; - - var $index = array(); - - var $index_name = ''; - - var $constraint = array(); - - var $constraint_name = ''; - - var $sequence = array(); - - var $sequence_name = ''; - - var $init = array(); - - function __construct($variables, $fail_on_invalid_names = true, $structure = false, $valid_types = array(), $force_defaults = true) - { - // force ISO-8859-1 due to different defaults for PHP4 and PHP5 - // todo: this probably needs to be investigated some more and cleaned up - $this->options['encoding'] = 'ISO-8859-1'; - - $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE'] = true; - $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY'] = false; - - $this->options['forceEnum'] = array('table', 'field', 'index', 'foreign', 'insert', 'update', 'delete', 'sequence'); - - /* - * todo: find a way to force the following items not to be parsed as arrays - * as it cause problems in functions with multiple arguments - */ - //$this->options['forceNEnum'] = array('value', 'column'); - $this->variables = $variables; - $this->structure = $structure; - - $this->val =& new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults); - parent::XML_Unserializer($this->options); - } - - function MDB2_Schema_Parser2($variables, $fail_on_invalid_names = true, $structure = false, $valid_types = array(), $force_defaults = true) - { - $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults); - } - - function parse() - { - $result = $this->unserialize($this->filename, true); - - if (PEAR::isError($result)) { - return $result; - } else { - $this->database_loaded = $this->getUnserializedData(); - return $this->fixDatabaseKeys($this->database_loaded); - } - } - - function setInputFile($filename) - { - $this->filename = $filename; - return MDB2_OK; - } - - function renameKey(&$arr, $oKey, $nKey) - { - $arr[$nKey] = &$arr[$oKey]; - unset($arr[$oKey]); - } - - function fixDatabaseKeys($database) - { - $this->database_definition = array( - 'name' => '', - 'create' => '', - 'overwrite' => '', - 'charset' => '', - 'description' => '', - 'comments' => '', - 'tables' => array(), - 'sequences' => array() - ); - - if (!empty($database['name'])) { - $this->database_definition['name'] = $database['name']; - } - if (!empty($database['create'])) { - $this->database_definition['create'] = $database['create']; - } - if (!empty($database['overwrite'])) { - $this->database_definition['overwrite'] = $database['overwrite']; - } - if (!empty($database['charset'])) { - $this->database_definition['charset'] = $database['charset']; - } - if (!empty($database['description'])) { - $this->database_definition['description'] = $database['description']; - } - if (!empty($database['comments'])) { - $this->database_definition['comments'] = $database['comments']; - } - - if (!empty($database['table']) && is_array($database['table'])) { - foreach ($database['table'] as $table) { - $this->fixTableKeys($table); - } - } - - if (!empty($database['sequence']) && is_array($database['sequence'])) { - foreach ($database['sequence'] as $sequence) { - $this->fixSequenceKeys($sequence); - } - } - - $result = $this->val->validateDatabase($this->database_definition); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - return MDB2_OK; - } - - function fixTableKeys($table) - { - $this->table = array( - 'was' => '', - 'description' => '', - 'comments' => '', - 'fields' => array(), - 'indexes' => array(), - 'constraints' => array(), - 'initialization' => array() - ); - - if (!empty($table['name'])) { - $this->table_name = $table['name']; - } else { - $this->table_name = ''; - } - if (!empty($table['was'])) { - $this->table['was'] = $table['was']; - } - if (!empty($table['description'])) { - $this->table['description'] = $table['description']; - } - if (!empty($table['comments'])) { - $this->table['comments'] = $table['comments']; - } - - if (!empty($table['declaration']) && is_array($table['declaration'])) { - if (!empty($table['declaration']['field']) && is_array($table['declaration']['field'])) { - foreach ($table['declaration']['field'] as $field) { - $this->fixTableFieldKeys($field); - } - } - - if (!empty($table['declaration']['index']) && is_array($table['declaration']['index'])) { - foreach ($table['declaration']['index'] as $index) { - $this->fixTableIndexKeys($index); - } - } - - if (!empty($table['declaration']['foreign']) && is_array($table['declaration']['foreign'])) { - foreach ($table['declaration']['foreign'] as $constraint) { - $this->fixTableConstraintKeys($constraint); - } - } - } - - if (!empty($table['initialization']) && is_array($table['initialization'])) { - if (!empty($table['initialization']['insert']) && is_array($table['initialization']['insert'])) { - foreach ($table['initialization']['insert'] as $init) { - $this->fixTableInitializationKeys($init, 'insert'); - } - } - if (!empty($table['initialization']['update']) && is_array($table['initialization']['update'])) { - foreach ($table['initialization']['update'] as $init) { - $this->fixTableInitializationKeys($init, 'update'); - } - } - if (!empty($table['initialization']['delete']) && is_array($table['initialization']['delete'])) { - foreach ($table['initialization']['delete'] as $init) { - $this->fixTableInitializationKeys($init, 'delete'); - } - } - } - - $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->database_definition['tables'][$this->table_name] = $this->table; - } - - return MDB2_OK; - } - - function fixTableFieldKeys($field) - { - $this->field = array(); - if (!empty($field['name'])) { - $this->field_name = $field['name']; - } else { - $this->field_name = ''; - } - if (!empty($field['was'])) { - $this->field['was'] = $field['was']; - } - if (!empty($field['type'])) { - $this->field['type'] = $field['type']; - } - if (!empty($field['fixed'])) { - $this->field['fixed'] = $field['fixed']; - } - if (isset($field['default'])) { - $this->field['default'] = $field['default']; - } - if (!empty($field['notnull'])) { - $this->field['notnull'] = $field['notnull']; - } - if (!empty($field['autoincrement'])) { - $this->field['autoincrement'] = $field['autoincrement']; - } - if (!empty($field['unsigned'])) { - $this->field['unsigned'] = $field['unsigned']; - } - if (!empty($field['length'])) { - $this->field['length'] = $field['length']; - } - if (!empty($field['description'])) { - $this->field['description'] = $field['description']; - } - if (!empty($field['comments'])) { - $this->field['comments'] = $field['comments']; - } - - $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->table['fields'][$this->field_name] = $this->field; - } - - return MDB2_OK; - } - - function fixTableIndexKeys($index) - { - $this->index = array( - 'was' => '', - 'unique' =>'', - 'primary' => '', - 'fields' => array() - ); - - if (!empty($index['name'])) { - $this->index_name = $index['name']; - } else { - $this->index_name = ''; - } - if (!empty($index['was'])) { - $this->index['was'] = $index['was']; - } - if (!empty($index['unique'])) { - $this->index['unique'] = $index['unique']; - } - if (!empty($index['primary'])) { - $this->index['primary'] = $index['primary']; - } - if (!empty($index['field'])) { - foreach ($index['field'] as $field) { - if (!empty($field['name'])) { - $this->field_name = $field['name']; - } else { - $this->field_name = ''; - } - $this->field = array( - 'sorting' => '', - 'length' => '' - ); - - if (!empty($field['sorting'])) { - $this->field['sorting'] = $field['sorting']; - } - if (!empty($field['length'])) { - $this->field['length'] = $field['length']; - } - - $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - $this->index['fields'][$this->field_name] = $this->field; - } - } - - $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->table['indexes'][$this->index_name] = $this->index; - } - - return MDB2_OK; - } - - function fixTableConstraintKeys($constraint) - { - $this->constraint = array( - 'was' => '', - 'match' => '', - 'ondelete' => '', - 'onupdate' => '', - 'deferrable' => '', - 'initiallydeferred' => '', - 'foreign' => true, - 'fields' => array(), - 'references' => array('table' => '', 'fields' => array()) - ); - - if (!empty($constraint['name'])) { - $this->constraint_name = $constraint['name']; - } else { - $this->constraint_name = ''; - } - if (!empty($constraint['was'])) { - $this->constraint['was'] = $constraint['was']; - } - if (!empty($constraint['match'])) { - $this->constraint['match'] = $constraint['match']; - } - if (!empty($constraint['ondelete'])) { - $this->constraint['ondelete'] = $constraint['ondelete']; - } - if (!empty($constraint['onupdate'])) { - $this->constraint['onupdate'] = $constraint['onupdate']; - } - if (!empty($constraint['deferrable'])) { - $this->constraint['deferrable'] = $constraint['deferrable']; - } - if (!empty($constraint['initiallydeferred'])) { - $this->constraint['initiallydeferred'] = $constraint['initiallydeferred']; - } - if (!empty($constraint['field']) && is_array($constraint['field'])) { - foreach ($constraint['field'] as $field) { - $result = $this->val->validateConstraintField($this->constraint['fields'], $field); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - $this->constraint['fields'][$field] = ''; - } - } - - if (!empty($constraint['references']) && is_array($constraint['references'])) { - /** - * As we forced 'table' to be enumerated - * we have to fix it on the foreign-references-table context - */ - if (!empty($constraint['references']['table']) && is_array($constraint['references']['table'])) { - $this->constraint['references']['table'] = $constraint['references']['table'][0]; - } - - if (!empty($constraint['references']['field']) && is_array($constraint['references']['field'])) { - foreach ($constraint['references']['field'] as $field) { - $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $field); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - $this->constraint['references']['fields'][$field] = ''; - } - } - } - - $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->table['constraints'][$this->constraint_name] = $this->constraint; - } - - return MDB2_OK; - } - - function fixTableInitializationKeys($element, $type = '') - { - if (!empty($element['select']) && is_array($element['select'])) { - $this->fixTableInitializationDataKeys($element['select']); - $this->init = array( 'select' => $this->init ); - } else { - $this->fixTableInitializationDataKeys($element); - } - - $this->table['initialization'][] = array( 'type' => $type, 'data' => $this->init ); - } - - function fixTableInitializationDataKeys($element) - { - $this->init = array(); - if (!empty($element['field']) && is_array($element['field'])) { - foreach ($element['field'] as $field) { - $name = $field['name']; - unset($field['name']); - - $this->setExpression($field); - $this->init['field'][] = array( 'name' => $name, 'group' => $field ); - } - } - /** - * As we forced 'table' to be enumerated - * we have to fix it on the insert-select context - */ - if (!empty($element['table']) && is_array($element['table'])) { - $this->init['table'] = $element['table'][0]; - } - if (!empty($element['where']) && is_array($element['where'])) { - $this->init['where'] = $element['where']; - $this->setExpression($this->init['where']); - } - } - - function setExpression(&$arr) - { - $element = each($arr); - - $arr = array( 'type' => $element['key'] ); - - $element = $element['value']; - - switch ($arr['type']) { - case 'null': - break; - case 'value': - case 'column': - $arr['data'] = $element; - break; - case 'function': - if (!empty($element) - && is_array($element) - ) { - $arr['data'] = array( 'name' => $element['name'] ); - unset($element['name']); - - foreach ($element as $type => $value) { - if (!empty($value)) { - if (is_array($value)) { - foreach ($value as $argument) { - $argument = array( $type => $argument ); - $this->setExpression($argument); - $arr['data']['arguments'][] = $argument; - } - } else { - $arr['data']['arguments'][] = array( 'type' => $type, 'data' => $value ); - } - } - } - } - break; - case 'expression': - $arr['data'] = array( 'operants' => array(), 'operator' => $element['operator'] ); - unset($element['operator']); - - foreach ($element as $k => $v) { - $argument = array( $k => $v ); - $this->setExpression($argument); - $arr['data']['operants'][] = $argument; - } - break; - } - } - - function fixSequenceKeys($sequence) - { - $this->sequence = array( - 'was' => '', - 'start' => '', - 'description' => '', - 'comments' => '', - 'on' => array('table' => '', 'field' => '') - ); - - if (!empty($sequence['name'])) { - $this->sequence_name = $sequence['name']; - } else { - $this->sequence_name = ''; - } - if (!empty($sequence['was'])) { - $this->sequence['was'] = $sequence['was']; - } - if (!empty($sequence['start'])) { - $this->sequence['start'] = $sequence['start']; - } - if (!empty($sequence['description'])) { - $this->sequence['description'] = $sequence['description']; - } - if (!empty($sequence['comments'])) { - $this->sequence['comments'] = $sequence['comments']; - } - if (!empty($sequence['on']) && is_array($sequence['on'])) { - /** - * As we forced 'table' to be enumerated - * we have to fix it on the sequence-on-table context - */ - if (!empty($sequence['on']['table']) && is_array($sequence['on']['table'])) { - $this->sequence['on']['table'] = $sequence['on']['table'][0]; - } - - /** - * As we forced 'field' to be enumerated - * we have to fix it on the sequence-on-field context - */ - if (!empty($sequence['on']['field']) && is_array($sequence['on']['field'])) { - $this->sequence['on']['field'] = $sequence['on']['field'][0]; - } - } - - $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->database_definition['sequences'][$this->sequence_name] = $this->sequence; - } - - return MDB2_OK; - } - - function &raiseError($msg = null, $ecode = MDB2_SCHEMA_ERROR_PARSE) - { - if (is_null($this->error)) { - $error = 'Parser error: '.$msg."\n"; - - $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error); - } - return $this->error; - } -} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/ibase.php b/3rdparty/MDB2/Schema/Reserved/ibase.php deleted file mode 100644 index b208abc83a..0000000000 --- a/3rdparty/MDB2/Schema/Reserved/ibase.php +++ /dev/null @@ -1,436 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['ibase'] -/** - * Has a list of reserved words of Interbase/Firebird - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author Lorenzo Alberton - */ -$GLOBALS['_MDB2_Schema_Reserved']['ibase'] = array( - 'ABS', - 'ABSOLUTE', - 'ACTION', - 'ACTIVE', - 'ADD', - 'ADMIN', - 'AFTER', - 'ALL', - 'ALLOCATE', - 'ALTER', - 'AND', - 'ANY', - 'ARE', - 'AS', - 'ASC', - 'ASCENDING', - 'ASSERTION', - 'AT', - 'AUTHORIZATION', - 'AUTO', - 'AUTODDL', - 'AVG', - 'BACKUP', - 'BASE_NAME', - 'BASED', - 'BASENAME', - 'BEFORE', - 'BEGIN', - 'BETWEEN', - 'BIGINT', - 'BIT', - 'BIT_LENGTH', - 'BLOB', - 'BLOCK', - 'BLOBEDIT', - 'BOOLEAN', - 'BOTH', - 'BOTH', - 'BREAK', - 'BUFFER', - 'BY', - 'CACHE', - 'CASCADE', - 'CASCADED', - 'CASE', - 'CASE', - 'CAST', - 'CATALOG', - 'CHAR', - 'CHAR_LENGTH', - 'CHARACTER', - 'CHARACTER_LENGTH', - 'CHECK', - 'CHECK_POINT_LEN', - 'CHECK_POINT_LENGTH', - 'CLOSE', - 'COALESCE', - 'COLLATE', - 'COLLATION', - 'COLUMN', - 'COMMENT', - 'COMMIT', - 'COMMITTED', - 'COMPILETIME', - 'COMPUTED', - 'CONDITIONAL', - 'CONNECT', - 'CONNECTION', - 'CONSTRAINT', - 'CONSTRAINTS', - 'CONTAINING', - 'CONTINUE', - 'CONVERT', - 'CORRESPONDING', - 'COUNT', - 'CREATE', - 'CROSS', - 'CSTRING', - 'CURRENT', - 'CURRENT_CONNECTION', - 'CURRENT_DATE', - 'CURRENT_ROLE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_TRANSACTION', - 'CURRENT_USER', - 'DATABASE', - 'DATE', - 'DAY', - 'DB_KEY', - 'DEALLOCATE', - 'DEBUG', - 'DEC', - 'DECIMAL', - 'DECLARE', - 'DEFAULT', - 'DEFERRABLE', - 'DEFERRED', - 'DELETE', - 'DELETING', - 'DESC', - 'DESCENDING', - 'DESCRIBE', - 'DESCRIPTOR', - 'DIAGNOSTICS', - 'DIFFERENCE', - 'DISCONNECT', - 'DISPLAY', - 'DISTINCT', - 'DO', - 'DOMAIN', - 'DOUBLE', - 'DROP', - 'ECHO', - 'EDIT', - 'ELSE', - 'END', - 'END-EXEC', - 'ENTRY_POINT', - 'ESCAPE', - 'EVENT', - 'EXCEPT', - 'EXCEPTION', - 'EXEC', - 'EXECUTE', - 'EXISTS', - 'EXIT', - 'EXTERN', - 'EXTERNAL', - 'EXTRACT', - 'FALSE', - 'FETCH', - 'FILE', - 'FILTER', - 'FIRST', - 'FLOAT', - 'FOR', - 'FOREIGN', - 'FOUND', - 'FREE_IT', - 'FROM', - 'FULL', - 'FUNCTION', - 'GDSCODE', - 'GEN_ID', - 'GENERATOR', - 'GET', - 'GLOBAL', - 'GO', - 'GOTO', - 'GRANT', - 'GROUP', - 'GROUP_COMMIT_WAIT', - 'GROUP_COMMIT_WAIT_TIME', - 'HAVING', - 'HELP', - 'HOUR', - 'IDENTITY', - 'IF', - 'IIF', - 'IMMEDIATE', - 'IN', - 'INACTIVE', - 'INDEX', - 'INDICATOR', - 'INIT', - 'INITIALLY', - 'INNER', - 'INPUT', - 'INPUT_TYPE', - 'INSENSITIVE', - 'INSERT', - 'INSERTING', - 'INT', - 'INTEGER', - 'INTERSECT', - 'INTERVAL', - 'INTO', - 'IS', - 'ISOLATION', - 'ISQL', - 'JOIN', - 'KEY', - 'LANGUAGE', - 'LAST', - 'LC_MESSAGES', - 'LC_TYPE', - 'LEADING', - 'LEADING', - 'LEADING', - 'LEAVE', - 'LEFT', - 'LENGTH', - 'LEV', - 'LEVEL', - 'LIKE', - 'LOCAL', - 'LOCK', - 'LOG_BUF_SIZE', - 'LOG_BUFFER_SIZE', - 'LOGFILE', - 'LONG', - 'LOWER', - 'MANUAL', - 'MATCH', - 'MAX', - 'MAX_SEGMENT', - 'MAXIMUM', - 'MAXIMUM_SEGMENT', - 'MERGE', - 'MESSAGE', - 'MIN', - 'MINIMUM', - 'MINUTE', - 'MODULE', - 'MODULE_NAME', - 'MONTH', - 'NAMES', - 'NATIONAL', - 'NATURAL', - 'NCHAR', - 'NEXT', - 'NO', - 'NOAUTO', - 'NOT', - 'NULL', - 'NULLIF', - 'NULLS', - 'NUM_LOG_BUFFERS', - 'NUM_LOG_BUFS', - 'NUMERIC', - 'OCTET_LENGTH', - 'OF', - 'ON', - 'ONLY', - 'OPEN', - 'OPTION', - 'OR', - 'ORDER', - 'OUTER', - 'OUTPUT', - 'OUTPUT_TYPE', - 'OVERFLOW', - 'OVERLAPS', - 'PAD', - 'PAGE', - 'PAGE_SIZE', - 'PAGELENGTH', - 'PAGES', - 'PARAMETER', - 'PARTIAL', - 'PASSWORD', - 'PERCENT', - 'PLAN', - 'POSITION', - 'POST_EVENT', - 'PRECISION', - 'PREPARE', - 'PRESERVE', - 'PRIMARY', - 'PRIOR', - 'PRIVILEGES', - 'PROCEDURE', - 'PUBLIC', - 'QUIT', - 'RAW_PARTITIONS', - 'RDB$DB_KEY', - 'READ', - 'REAL', - 'RECORD_VERSION', - 'RECREATE', - 'RECREATE ROW_COUNT', - 'REFERENCES', - 'RELATIVE', - 'RELEASE', - 'RESERV', - 'RESERVING', - 'RESTART', - 'RESTRICT', - 'RETAIN', - 'RETURN', - 'RETURNING', - 'RETURNING_VALUES', - 'RETURNS', - 'REVOKE', - 'RIGHT', - 'ROLE', - 'ROLLBACK', - 'ROW_COUNT', - 'ROWS', - 'RUNTIME', - 'SAVEPOINT', - 'SCALAR_ARRAY', - 'SCHEMA', - 'SCROLL', - 'SECOND', - 'SECTION', - 'SELECT', - 'SEQUENCE', - 'SESSION', - 'SESSION_USER', - 'SET', - 'SHADOW', - 'SHARED', - 'SHELL', - 'SHOW', - 'SINGULAR', - 'SIZE', - 'SKIP', - 'SMALLINT', - 'SNAPSHOT', - 'SOME', - 'SORT', - 'SPACE', - 'SQL', - 'SQLCODE', - 'SQLERROR', - 'SQLSTATE', - 'SQLWARNING', - 'STABILITY', - 'STARTING', - 'STARTS', - 'STATEMENT', - 'STATIC', - 'STATISTICS', - 'SUB_TYPE', - 'SUBSTRING', - 'SUM', - 'SUSPEND', - 'SYSTEM_USER', - 'TABLE', - 'TEMPORARY', - 'TERMINATOR', - 'THEN', - 'TIES', - 'TIME', - 'TIMESTAMP', - 'TIMEZONE_HOUR', - 'TIMEZONE_MINUTE', - 'TO', - 'TRAILING', - 'TRANSACTION', - 'TRANSLATE', - 'TRANSLATION', - 'TRIGGER', - 'TRIM', - 'TRUE', - 'TYPE', - 'UNCOMMITTED', - 'UNION', - 'UNIQUE', - 'UNKNOWN', - 'UPDATE', - 'UPDATING', - 'UPPER', - 'USAGE', - 'USER', - 'USING', - 'VALUE', - 'VALUES', - 'VARCHAR', - 'VARIABLE', - 'VARYING', - 'VERSION', - 'VIEW', - 'WAIT', - 'WEEKDAY', - 'WHEN', - 'WHENEVER', - 'WHERE', - 'WHILE', - 'WITH', - 'WORK', - 'WRITE', - 'YEAR', - 'YEARDAY', - 'ZONE', -); -// }}} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Schema/Reserved/mssql.php b/3rdparty/MDB2/Schema/Reserved/mssql.php deleted file mode 100644 index 74ac688578..0000000000 --- a/3rdparty/MDB2/Schema/Reserved/mssql.php +++ /dev/null @@ -1,258 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mssql'] -/** - * Has a list of all the reserved words for mssql. - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author David Coallier - */ -$GLOBALS['_MDB2_Schema_Reserved']['mssql'] = array( - 'ADD', - 'CURRENT_TIMESTAMP', - 'GROUP', - 'OPENQUERY', - 'SERIALIZABLE', - 'ALL', - 'CURRENT_USER', - 'HAVING', - 'OPENROWSET', - 'SESSION_USER', - 'ALTER', - 'CURSOR', - 'HOLDLOCK', - 'OPTION', - 'SET', - 'AND', - 'DATABASE', - 'IDENTITY', - 'OR', - 'SETUSER', - 'ANY', - 'DBCC', - 'IDENTITYCOL', - 'ORDER', - 'SHUTDOWN', - 'AS', - 'DEALLOCATE', - 'IDENTITY_INSERT', - 'OUTER', - 'SOME', - 'ASC', - 'DECLARE', - 'IF', - 'OVER', - 'STATISTICS', - 'AUTHORIZATION', - 'DEFAULT', - 'IN', - 'PERCENT', - 'SUM', - 'AVG', - 'DELETE', - 'INDEX', - 'PERM', - 'SYSTEM_USER', - 'BACKUP', - 'DENY', - 'INNER', - 'PERMANENT', - 'TABLE', - 'BEGIN', - 'DESC', - 'INSERT', - 'PIPE', - 'TAPE', - 'BETWEEN', - 'DISK', - 'INTERSECT', - 'PLAN', - 'TEMP', - 'BREAK', - 'DISTINCT', - 'INTO', - 'PRECISION', - 'TEMPORARY', - 'BROWSE', - 'DISTRIBUTED', - 'IS', - 'PREPARE', - 'TEXTSIZE', - 'BULK', - 'DOUBLE', - 'ISOLATION', - 'PRIMARY', - 'THEN', - 'BY', - 'DROP', - 'JOIN', - 'PRINT', - 'TO', - 'CASCADE', - 'DUMMY', - 'KEY', - 'PRIVILEGES', - 'TOP', - 'CASE', - 'DUMP', - 'KILL', - 'PROC', - 'TRAN', - 'CHECK', - 'ELSE', - 'LEFT', - 'PROCEDURE', - 'TRANSACTION', - 'CHECKPOINT', - 'END', - 'LEVEL', - 'PROCESSEXIT', - 'TRIGGER', - 'CLOSE', - 'ERRLVL', - 'LIKE', - 'PUBLIC', - 'TRUNCATE', - 'CLUSTERED', - 'ERROREXIT', - 'LINENO', - 'RAISERROR', - 'TSEQUAL', - 'COALESCE', - 'ESCAPE', - 'LOAD', - 'READ', - 'UNCOMMITTED', - 'COLUMN', - 'EXCEPT', - 'MAX', - 'READTEXT', - 'UNION', - 'COMMIT', - 'EXEC', - 'MIN', - 'RECONFIGURE', - 'UNIQUE', - 'COMMITTED', - 'EXECUTE', - 'MIRROREXIT', - 'REFERENCES', - 'UPDATE', - 'COMPUTE', - 'EXISTS', - 'NATIONAL', - 'REPEATABLE', - 'UPDATETEXT', - 'CONFIRM', - 'EXIT', - 'NOCHECK', - 'REPLICATION', - 'USE', - 'CONSTRAINT', - 'FETCH', - 'NONCLUSTERED', - 'RESTORE', - 'USER', - 'CONTAINS', - 'FILE', - 'NOT', - 'RESTRICT', - 'VALUES', - 'CONTAINSTABLE', - 'FILLFACTOR', - 'NULL', - 'RETURN', - 'VARYING', - 'CONTINUE', - 'FLOPPY', - 'NULLIF', - 'REVOKE', - 'VIEW', - 'CONTROLROW', - 'FOR', - 'OF', - 'RIGHT', - 'WAITFOR', - 'CONVERT', - 'FOREIGN', - 'OFF', - 'ROLLBACK', - 'WHEN', - 'COUNT', - 'FREETEXT', - 'OFFSETS', - 'ROWCOUNT', - 'WHERE', - 'CREATE', - 'FREETEXTTABLE', - 'ON', - 'ROWGUIDCOL', - 'WHILE', - 'CROSS', - 'FROM', - 'ONCE', - 'RULE', - 'WITH', - 'CURRENT', - 'FULL', - 'ONLY', - 'SAVE', - 'WORK', - 'CURRENT_DATE', - 'GOTO', - 'OPEN', - 'SCHEMA', - 'WRITETEXT', - 'CURRENT_TIME', - 'GRANT', - 'OPENDATASOURCE', - 'SELECT', -); -//}}} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/mysql.php b/3rdparty/MDB2/Schema/Reserved/mysql.php deleted file mode 100644 index 4f0575e0bb..0000000000 --- a/3rdparty/MDB2/Schema/Reserved/mysql.php +++ /dev/null @@ -1,284 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.3 2006/03/01 12:16:40 lsmith Exp $ -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mysql'] -/** - * Has a list of reserved words of mysql - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author David Coalier - */ -$GLOBALS['_MDB2_Schema_Reserved']['mysql'] = array( - 'ADD', - 'ALL', - 'ALTER', - 'ANALYZE', - 'AND', - 'AS', - 'ASC', - 'ASENSITIVE', - 'BEFORE', - 'BETWEEN', - 'BIGINT', - 'BINARY', - 'BLOB', - 'BOTH', - 'BY', - 'CALL', - 'CASCADE', - 'CASE', - 'CHANGE', - 'CHAR', - 'CHARACTER', - 'CHECK', - 'COLLATE', - 'COLUMN', - 'CONDITION', - 'CONNECTION', - 'CONSTRAINT', - 'CONTINUE', - 'CONVERT', - 'CREATE', - 'CROSS', - 'CURRENT_DATE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_USER', - 'CURSOR', - 'DATABASE', - 'DATABASES', - 'DAY_HOUR', - 'DAY_MICROSECOND', - 'DAY_MINUTE', - 'DAY_SECOND', - 'DEC', - 'DECIMAL', - 'DECLARE', - 'DEFAULT', - 'DELAYED', - 'DELETE', - 'DESC', - 'DESCRIBE', - 'DETERMINISTIC', - 'DISTINCT', - 'DISTINCTROW', - 'DIV', - 'DOUBLE', - 'DROP', - 'DUAL', - 'EACH', - 'ELSE', - 'ELSEIF', - 'ENCLOSED', - 'ESCAPED', - 'EXISTS', - 'EXIT', - 'EXPLAIN', - 'FALSE', - 'FETCH', - 'FLOAT', - 'FLOAT4', - 'FLOAT8', - 'FOR', - 'FORCE', - 'FOREIGN', - 'FROM', - 'FULLTEXT', - 'GOTO', - 'GRANT', - 'GROUP', - 'HAVING', - 'HIGH_PRIORITY', - 'HOUR_MICROSECOND', - 'HOUR_MINUTE', - 'HOUR_SECOND', - 'IF', - 'IGNORE', - 'IN', - 'INDEX', - 'INFILE', - 'INNER', - 'INOUT', - 'INSENSITIVE', - 'INSERT', - 'INT', - 'INT1', - 'INT2', - 'INT3', - 'INT4', - 'INT8', - 'INTEGER', - 'INTERVAL', - 'INTO', - 'IS', - 'ITERATE', - 'JOIN', - 'KEY', - 'KEYS', - 'KILL', - 'LABEL', - 'LEADING', - 'LEAVE', - 'LEFT', - 'LIKE', - 'LIMIT', - 'LINES', - 'LOAD', - 'LOCALTIME', - 'LOCALTIMESTAMP', - 'LOCK', - 'LONG', - 'LONGBLOB', - 'LONGTEXT', - 'LOOP', - 'LOW_PRIORITY', - 'MATCH', - 'MEDIUMBLOB', - 'MEDIUMINT', - 'MEDIUMTEXT', - 'MIDDLEINT', - 'MINUTE_MICROSECOND', - 'MINUTE_SECOND', - 'MOD', - 'MODIFIES', - 'NATURAL', - 'NOT', - 'NO_WRITE_TO_BINLOG', - 'NULL', - 'NUMERIC', - 'ON', - 'OPTIMIZE', - 'OPTION', - 'OPTIONALLY', - 'OR', - 'ORDER', - 'OUT', - 'OUTER', - 'OUTFILE', - 'PRECISION', - 'PRIMARY', - 'PROCEDURE', - 'PURGE', - 'RAID0', - 'READ', - 'READS', - 'REAL', - 'REFERENCES', - 'REGEXP', - 'RELEASE', - 'RENAME', - 'REPEAT', - 'REPLACE', - 'REQUIRE', - 'RESTRICT', - 'RETURN', - 'REVOKE', - 'RIGHT', - 'RLIKE', - 'SCHEMA', - 'SCHEMAS', - 'SECOND_MICROSECOND', - 'SELECT', - 'SENSITIVE', - 'SEPARATOR', - 'SET', - 'SHOW', - 'SMALLINT', - 'SONAME', - 'SPATIAL', - 'SPECIFIC', - 'SQL', - 'SQLEXCEPTION', - 'SQLSTATE', - 'SQLWARNING', - 'SQL_BIG_RESULT', - 'SQL_CALC_FOUND_ROWS', - 'SQL_SMALL_RESULT', - 'SSL', - 'STARTING', - 'STRAIGHT_JOIN', - 'TABLE', - 'TERMINATED', - 'THEN', - 'TINYBLOB', - 'TINYINT', - 'TINYTEXT', - 'TO', - 'TRAILING', - 'TRIGGER', - 'TRUE', - 'UNDO', - 'UNION', - 'UNIQUE', - 'UNLOCK', - 'UNSIGNED', - 'UPDATE', - 'USAGE', - 'USE', - 'USING', - 'UTC_DATE', - 'UTC_TIME', - 'UTC_TIMESTAMP', - 'VALUES', - 'VARBINARY', - 'VARCHAR', - 'VARCHARACTER', - 'VARYING', - 'WHEN', - 'WHERE', - 'WHILE', - 'WITH', - 'WRITE', - 'X509', - 'XOR', - 'YEAR_MONTH', - 'ZEROFILL', - ); - // }}} -?> diff --git a/3rdparty/MDB2/Schema/Reserved/oci8.php b/3rdparty/MDB2/Schema/Reserved/oci8.php deleted file mode 100644 index 57fe12ddca..0000000000 --- a/3rdparty/MDB2/Schema/Reserved/oci8.php +++ /dev/null @@ -1,171 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['oci8'] -/** - * Has a list of all the reserved words for oracle. - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author David Coallier - */ -$GLOBALS['_MDB2_Schema_Reserved']['oci8'] = array( - 'ACCESS', - 'ELSE', - 'MODIFY', - 'START', - 'ADD', - 'EXCLUSIVE', - 'NOAUDIT', - 'SELECT', - 'ALL', - 'EXISTS', - 'NOCOMPRESS', - 'SESSION', - 'ALTER', - 'FILE', - 'NOT', - 'SET', - 'AND', - 'FLOAT', - 'NOTFOUND ', - 'SHARE', - 'ANY', - 'FOR', - 'NOWAIT', - 'SIZE', - 'ARRAYLEN', - 'FROM', - 'NULL', - 'SMALLINT', - 'AS', - 'GRANT', - 'NUMBER', - 'SQLBUF', - 'ASC', - 'GROUP', - 'OF', - 'SUCCESSFUL', - 'AUDIT', - 'HAVING', - 'OFFLINE ', - 'SYNONYM', - 'BETWEEN', - 'IDENTIFIED', - 'ON', - 'SYSDATE', - 'BY', - 'IMMEDIATE', - 'ONLINE', - 'TABLE', - 'CHAR', - 'IN', - 'OPTION', - 'THEN', - 'CHECK', - 'INCREMENT', - 'OR', - 'TO', - 'CLUSTER', - 'INDEX', - 'ORDER', - 'TRIGGER', - 'COLUMN', - 'INITIAL', - 'PCTFREE', - 'UID', - 'COMMENT', - 'INSERT', - 'PRIOR', - 'UNION', - 'COMPRESS', - 'INTEGER', - 'PRIVILEGES', - 'UNIQUE', - 'CONNECT', - 'INTERSECT', - 'PUBLIC', - 'UPDATE', - 'CREATE', - 'INTO', - 'RAW', - 'USER', - 'CURRENT', - 'IS', - 'RENAME', - 'VALIDATE', - 'DATE', - 'LEVEL', - 'RESOURCE', - 'VALUES', - 'DECIMAL', - 'LIKE', - 'REVOKE', - 'VARCHAR', - 'DEFAULT', - 'LOCK', - 'ROW', - 'VARCHAR2', - 'DELETE', - 'LONG', - 'ROWID', - 'VIEW', - 'DESC', - 'MAXEXTENTS', - 'ROWLABEL', - 'WHENEVER', - 'DISTINCT', - 'MINUS', - 'ROWNUM', - 'WHERE', - 'DROP', - 'MODE', - 'ROWS', - 'WITH', -); -// }}} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/pgsql.php b/3rdparty/MDB2/Schema/Reserved/pgsql.php deleted file mode 100644 index d358e9c12f..0000000000 --- a/3rdparty/MDB2/Schema/Reserved/pgsql.php +++ /dev/null @@ -1,147 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['pgsql'] -/** - * Has a list of reserved words of pgsql - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author Marcelo Santos Araujo - */ -$GLOBALS['_MDB2_Schema_Reserved']['pgsql'] = array( - 'ALL', - 'ANALYSE', - 'ANALYZE', - 'AND', - 'ANY', - 'AS', - 'ASC', - 'AUTHORIZATION', - 'BETWEEN', - 'BINARY', - 'BOTH', - 'CASE', - 'CAST', - 'CHECK', - 'COLLATE', - 'COLUMN', - 'CONSTRAINT', - 'CREATE', - 'CURRENT_DATE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_USER', - 'DEFAULT', - 'DEFERRABLE', - 'DESC', - 'DISTINCT', - 'DO', - 'ELSE', - 'END', - 'EXCEPT', - 'FALSE', - 'FOR', - 'FOREIGN', - 'FREEZE', - 'FROM', - 'FULL', - 'GRANT', - 'GROUP', - 'HAVING', - 'ILIKE', - 'IN', - 'INITIALLY', - 'INNER', - 'INTERSECT', - 'INTO', - 'IS', - 'ISNULL', - 'JOIN', - 'LEADING', - 'LEFT', - 'LIKE', - 'LIMIT', - 'LOCALTIME', - 'LOCALTIMESTAMP', - 'NATURAL', - 'NEW', - 'NOT', - 'NOTNULL', - 'NULL', - 'OFF', - 'OFFSET', - 'OLD', - 'ON', - 'ONLY', - 'OR', - 'ORDER', - 'OUTER', - 'OVERLAPS', - 'PLACING', - 'PRIMARY', - 'REFERENCES', - 'SELECT', - 'SESSION_USER', - 'SIMILAR', - 'SOME', - 'TABLE', - 'THEN', - 'TO', - 'TRAILING', - 'TRUE', - 'UNION', - 'UNIQUE', - 'USER', - 'USING', - 'VERBOSE', - 'WHEN', - 'WHERE' -); -// }}} -?> - diff --git a/3rdparty/MDB2/Schema/Tool.php b/3rdparty/MDB2/Schema/Tool.php deleted file mode 100644 index 9689a0f6d7..0000000000 --- a/3rdparty/MDB2/Schema/Tool.php +++ /dev/null @@ -1,560 +0,0 @@ - - * $Id: Tool.php,v 1.6 2008/12/13 00:26:07 clockwerx Exp $ - * - * @category Database - * @package MDB2_Schema - * @author Christian Weiske - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Tool.php,v 1.6 2008/12/13 00:26:07 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -require_once 'MDB2/Schema.php'; -require_once 'MDB2/Schema/Tool/ParameterException.php'; - -/** -* Command line tool to work with database schemas -* -* Functionality: -* - dump a database schema to stdout -* - import schema into database -* - create a diff between two schemas -* - apply diff to database -* - * @category Database - * @package MDB2_Schema - * @author Christian Weiske - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Tool -{ - /** - * Run the schema tool - * - * @param array $args Array of command line arguments - */ - public function __construct($args) - { - $strAction = $this->getAction($args); - try { - $this->{'do' . ucfirst($strAction)}($args); - } catch (MDB2_Schema_Tool_ParameterException $e) { - $this->{'doHelp' . ucfirst($strAction)}($e->getMessage()); - } - }//public function __construct($args) - - - - /** - * Runs the tool with command line arguments - * - * @return void - */ - public static function run() - { - $args = $GLOBALS['argv']; - array_shift($args); - - try { - $tool = new MDB2_Schema_Tool($args); - } catch (Exception $e) { - self::toStdErr($e->getMessage() . "\n"); - } - }//public static function run() - - - - /** - * Reads the first parameter from the argument array and - * returns the action. - * - * @param array &$args Command line parameters - * - * @return string Action to execute - */ - protected function getAction(&$args) - { - if (count($args) == 0) { - return 'help'; - } - $arg = array_shift($args); - switch ($arg) { - case 'h': - case 'help': - case '-h': - case '--help': - return 'help'; - case 'd': - case 'dump': - case '-d': - case '--dump': - return 'dump'; - case 'l': - case 'load': - case '-l': - case '--load': - return 'load'; - case 'i': - case 'diff': - case '-i': - case '--diff': - return 'diff'; - case 'a': - case 'apply': - case '-a': - case '--apply': - return 'apply'; - case 'n': - case 'init': - case '-i': - case '--init': - return 'init'; - default: - throw new MDB2_Schema_Tool_ParameterException("Unknown mode \"$arg\""); - } - }//protected function getAction(&$args) - - - - /** - * Writes the message to stderr - * - * @param string $msg Message to print - * - * @return void - */ - protected static function toStdErr($msg) - { - file_put_contents('php://stderr', $msg); - }//protected static function toStdErr($msg) - - - - /** - * Displays generic help to stdout - * - * @return void - */ - protected function doHelp() - { - self::toStdErr(<< '
', - 'idxname_format' => '%s', - 'debug' => true, - 'quote_identifier' => true, - 'force_defaults' => false, - 'portability' => true, - 'use_transactions' => false, - ); - return $options; - }//protected function getSchemaOptions() - - - - /** - * Checks if the passed parameter is a PEAR_Error object - * and throws an exception in that case. - * - * @param mixed $object Some variable to check - * @param string $location Where the error occured - * - * @return void - */ - protected function throwExceptionOnError($object, $location = '') - { - if (PEAR::isError($object)) { - //FIXME: exception class - //debug_print_backtrace(); - throw new Exception('Error ' . $location - . "\n" . $object->getMessage() - . "\n" . $object->getUserInfo() - ); - } - }//protected function throwExceptionOnError($object, $location = '') - - - - /** - * Loads a file or a dsn from the arguments - * - * @param array &$args Array of arguments to the program - * - * @return array Array of ('file'|'dsn', $value) - */ - protected function getFileOrDsn(&$args) - { - if (count($args) == 0) { - throw new MDB2_Schema_Tool_ParameterException('File or DSN expected'); - } - - $arg = array_shift($args); - if ($arg == '-p') { - $bAskPassword = true; - $arg = array_shift($args); - } else { - $bAskPassword = false; - } - - if (strpos($arg, '://') === false) { - if (file_exists($arg)) { - //File - return array('file', $arg); - } else { - throw new Exception('Schema file does not exist'); - } - } - - //read password if necessary - if ($bAskPassword) { - $password = $this->readPasswordFromStdin($arg); - $arg = self::setPasswordIntoDsn($arg, $password); - self::toStdErr($arg); - } - return array('dsn', $arg); - }//protected function getFileOrDsn(&$args) - - - - /** - * Takes a DSN data source name and integrates the given - * password into it. - * - * @param string $dsn Data source name - * @param string $password Password - * - * @return string DSN with password - */ - protected function setPasswordIntoDsn($dsn, $password) - { - //simple try to integrate password - if (strpos($dsn, '@') === false) { - //no @ -> no user and no password - return str_replace('://', '://:' . $password . '@', $dsn); - } else if (preg_match('|://[^:]+@|', $dsn)) { - //user only, no password - return str_replace('@', ':' . $password . '@', $dsn); - } else if (strpos($dsn, ':@') !== false) { - //abstract version - return str_replace(':@', ':' . $password . '@', $dsn); - } - - return $dsn; - }//protected function setPasswordIntoDsn($dsn, $password) - - - - /** - * Reads a password from stdin - * - * @param string $dsn DSN name to put into the message - * - * @return string Password - */ - protected function readPasswordFromStdin($dsn) - { - $stdin = fopen('php://stdin', 'r'); - self::toStdErr('Please insert password for ' . $dsn . "\n"); - $password = ''; - $breakme = false; - while (false !== ($char = fgetc($stdin))) { - if (ord($char) == 10 || $char == "\n" || $char == "\r") { - break; - } - $password .= $char; - } - fclose($stdin); - - return trim($password); - }//protected function readPasswordFromStdin() - - - - /** - * Creates a database schema dump and sends it to stdout - * - * @param array $args Command line arguments - * - * @return void - */ - protected function doDump($args) - { - $dump_what = MDB2_SCHEMA_DUMP_STRUCTURE; - $arg = ''; - if (count($args)) { - $arg = $args[0]; - } - - switch (strtolower($arg)) { - case 'all': - $dump_what = MDB2_SCHEMA_DUMP_ALL; - array_shift($args); - break; - case 'data': - $dump_what = MDB2_SCHEMA_DUMP_CONTENT; - array_shift($args); - break; - case 'schema': - array_shift($args); - } - - list($type, $dsn) = $this->getFileOrDsn($args); - if ($type == 'file') { - throw new MDB2_Schema_Tool_ParameterException( - 'Dumping a schema file as a schema file does not make much sense' - ); - } - - $schema = MDB2_Schema::factory($dsn, $this->getSchemaOptions()); - $this->throwExceptionOnError($schema); - - $definition = $schema->getDefinitionFromDatabase(); - $this->throwExceptionOnError($definition); - - - $dump_options = array( - 'output_mode' => 'file', - 'output' => 'php://stdout', - 'end_of_line' => "\r\n" - ); - $op = $schema->dumpDatabase( - $definition, $dump_options, $dump_what - ); - $this->throwExceptionOnError($op); - - $schema->disconnect(); - }//protected function doDump($args) - - - - /** - * Loads a database schema - * - * @param array $args Command line arguments - * - * @return void - */ - protected function doLoad($args) - { - list($typeSource, $dsnSource) = $this->getFileOrDsn($args); - list($typeDest, $dsnDest) = $this->getFileOrDsn($args); - - if ($typeDest == 'file') { - throw new MDB2_Schema_Tool_ParameterException( - 'A schema can only be loaded into a database, not a file' - ); - } - - - $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaDest); - - //load definition - if ($typeSource == 'file') { - $definition = $schemaDest->parseDatabaseDefinitionFile($dsnSource); - $where = 'loading schema file'; - } else { - $schemaSource = MDB2_Schema::factory($dsnSource, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaSource, 'connecting to source database'); - - $definition = $schemaSource->getDefinitionFromDatabase(); - $where = 'loading definition from database'; - } - $this->throwExceptionOnError($definition, $where); - - - //create destination database from definition - $simulate = false; - $op = $schemaDest->createDatabase($definition, array(), $simulate); - $this->throwExceptionOnError($op, 'creating the database'); - }//protected function doLoad($args) - - - - /** - * Initializes a database with data - * - * @param array $args Command line arguments - * - * @return void - */ - protected function doInit($args) - { - list($typeSource, $dsnSource) = $this->getFileOrDsn($args); - list($typeDest, $dsnDest) = $this->getFileOrDsn($args); - - if ($typeSource != 'file') { - throw new MDB2_Schema_Tool_ParameterException( - 'Data must come from a source file' - ); - } - - if ($typeDest != 'dsn') { - throw new MDB2_Schema_Tool_ParameterException( - 'A schema can only be loaded into a database, not a file' - ); - } - - $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaDest, 'connecting to destination database'); - - $definition = $schemaDest->getDefinitionFromDatabase(); - $this->throwExceptionOnError($definition, 'loading definition from database'); - - $op = $schemaDest->writeInitialization($dsnSource, $definition); - $this->throwExceptionOnError($op, 'initializing database'); - }//protected function doInit($args) - - -}//class MDB2_Schema_Tool - -?> diff --git a/3rdparty/MDB2/Schema/Tool/ParameterException.php b/3rdparty/MDB2/Schema/Tool/ParameterException.php deleted file mode 100644 index fab1e03e25..0000000000 --- a/3rdparty/MDB2/Schema/Tool/ParameterException.php +++ /dev/null @@ -1,6 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/MDB2/Schema/Validate.php b/3rdparty/MDB2/Schema/Validate.php deleted file mode 100644 index 217cf51b95..0000000000 --- a/3rdparty/MDB2/Schema/Validate.php +++ /dev/null @@ -1,917 +0,0 @@ - - * Author: Igor Feghali - * - * @category Database - * @package MDB2_Schema - * @author Christian Dickmann - * @author Igor Feghali - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Validate.php,v 1.42 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -/** - * Validates an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Igor Feghali - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Validate -{ - // {{{ properties - - var $fail_on_invalid_names = true; - - var $valid_types = array(); - - var $force_defaults = true; - - // }}} - // {{{ constructor - - function __construct($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true) - { - if (empty($GLOBALS['_MDB2_Schema_Reserved'])) { - $GLOBALS['_MDB2_Schema_Reserved'] = array(); - } - - if (is_array($fail_on_invalid_names)) { - $this->fail_on_invalid_names = array_intersect($fail_on_invalid_names, - array_keys($GLOBALS['_MDB2_Schema_Reserved'])); - } elseif ($fail_on_invalid_names === true) { - $this->fail_on_invalid_names = array_keys($GLOBALS['_MDB2_Schema_Reserved']); - } else { - $this->fail_on_invalid_names = array(); - } - $this->valid_types = $valid_types; - $this->force_defaults = $force_defaults; - } - - // }}} - // {{{ raiseError() - - function &raiseError($ecode, $msg = null) - { - $error =& MDB2_Schema::raiseError($ecode, null, null, $msg); - return $error; - } - - // }}} - // {{{ isBoolean() - - /** - * Verifies if a given value can be considered boolean. If yes, set value - * to true or false according to its actual contents and return true. If - * not, keep its contents untouched and return false. - * - * @param mixed &$value value to be checked - * - * @return bool - * - * @access public - * @static - */ - function isBoolean(&$value) - { - if (is_bool($value)) { - return true; - } - - if ($value === 0 || $value === 1 || $value === '') { - $value = (bool)$value; - return true; - } - - if (!is_string($value)) { - return false; - } - - switch ($value) { - case '0': - case 'N': - case 'n': - case 'no': - case 'false': - $value = false; - break; - case '1': - case 'Y': - case 'y': - case 'yes': - case 'true': - $value = true; - break; - default: - return false; - } - return true; - } - - // }}} - // {{{ validateTable() - - /* Definition */ - /** - * Checks whether the definition of a parsed table is valid. Modify table - * definition when necessary. - * - * @param array $tables multi dimensional array that contains the - * tables of current database. - * @param array &$table multi dimensional array that contains the - * structure and optional data of the table. - * @param string $table_name name of the parsed table - * - * @return bool|error object - * - * @access public - */ - function validateTable($tables, &$table, $table_name) - { - /* Have we got a name? */ - if (!$table_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a table has to have a name'); - } - - /* Table name duplicated? */ - if (is_array($tables) && isset($tables[$table_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'table "'.$table_name.'" already exists'); - } - - /* Table name reserved? */ - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($table_name); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'table name "'.$table_name.'" is a reserved word in: '.$rdbms); - } - } - } - - /* Was */ - if (empty($table['was'])) { - $table['was'] = $table_name; - } - - /* Have we got fields? */ - if (empty($table['fields']) || !is_array($table['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'tables need one or more fields'); - } - - /* Autoincrement */ - $autoinc = $primary = false; - foreach ($table['fields'] as $field_name => $field) { - if (!empty($field['autoincrement'])) { - if ($autoinc) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'there was already an autoincrement field in "'.$table_name.'" before "'.$field_name.'"'); - } - $autoinc = $field_name; - } - } - - /* - * Checking Indexes - * this have to be done here otherwise we can't - * guarantee that all table fields were already - * defined in the moment we are parsing indexes - */ - if (!empty($table['indexes']) && is_array($table['indexes'])) { - foreach ($table['indexes'] as $name => $index) { - $skip_index = false; - if (!empty($index['primary'])) { - /* - * Lets see if we should skip this index since there is - * already an auto increment on this field this implying - * a primary key index. - */ - if (count($index['fields']) == '1' - && $autoinc - && array_key_exists($autoinc, $index['fields'])) { - $skip_index = true; - } elseif ($autoinc || $primary) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'there was already an primary index or autoincrement field in "'.$table_name.'" before "'.$name.'"'); - } else { - $primary = true; - } - } - - if (!$skip_index && is_array($index['fields'])) { - foreach ($index['fields'] as $field_name => $field) { - if (!isset($table['fields'][$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'index field "'.$field_name.'" does not exist'); - } - if (!empty($index['primary']) - && !$table['fields'][$field_name]['notnull'] - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'all primary key fields must be defined notnull in "'.$table_name.'"'); - } - } - } else { - unset($table['indexes'][$name]); - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ validateField() - - /** - * Checks whether the definition of a parsed field is valid. Modify field - * definition when necessary. - * - * @param array $fields multi dimensional array that contains the - * fields of current table. - * @param array &$field multi dimensional array that contains the - * structure of the parsed field. - * @param string $field_name name of the parsed field - * - * @return bool|error object - * - * @access public - */ - function validateField($fields, &$field, $field_name) - { - /* Have we got a name? */ - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field name missing'); - } - - /* Field name duplicated? */ - if (is_array($fields) && isset($fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "'.$field_name.'" already exists'); - } - - /* Field name reserverd? */ - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($field_name); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field name "'.$field_name.'" is a reserved word in: '.$rdbms); - } - } - } - - /* Type check */ - if (empty($field['type'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'no field type specified'); - } - if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'no valid field type ("'.$field['type'].'") specified'); - } - - /* Unsigned */ - if (array_key_exists('unsigned', $field) && !$this->isBoolean($field['unsigned'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'unsigned has to be a boolean value'); - } - - /* Fixed */ - if (array_key_exists('fixed', $field) && !$this->isBoolean($field['fixed'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'fixed has to be a boolean value'); - } - - /* Length */ - if (array_key_exists('length', $field) && $field['length'] <= 0) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'length has to be an integer greater 0'); - } - - // if it's a DECIMAL datatype, check if a 'scale' value is provided: - // 8,4 should be translated to DECIMAL(8,4) - if (is_float($this->valid_types[$field['type']]) - && !empty($field['length']) - && strpos($field['length'], ',') !== false - ) { - list($field['length'], $field['scale']) = explode(',', $field['length']); - } - - /* Was */ - if (empty($field['was'])) { - $field['was'] = $field_name; - } - - /* Notnull */ - if (empty($field['notnull'])) { - $field['notnull'] = false; - } - if (!$this->isBoolean($field['notnull'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "notnull" has to be a boolean value'); - } - - /* Default */ - if ($this->force_defaults - && !array_key_exists('default', $field) - && $field['type'] != 'clob' && $field['type'] != 'blob' - ) { - $field['default'] = $this->valid_types[$field['type']]; - } - if (array_key_exists('default', $field)) { - if ($field['type'] == 'clob' || $field['type'] == 'blob') { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field['type'].'"-fields are not allowed to have a default value'); - } - if ($field['default'] === '' && !$field['notnull']) { - $field['default'] = null; - } - } - if (isset($field['default']) - && PEAR::isError($result = $this->validateDataFieldValue($field, $field['default'], $field_name)) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'default value of "'.$field_name.'" is incorrect: '.$result->getUserinfo()); - } - - /* Autoincrement */ - if (!empty($field['autoincrement'])) { - if (!$field['notnull']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'all autoincrement fields must be defined notnull'); - } - - if (empty($field['default'])) { - $field['default'] = '0'; - } elseif ($field['default'] !== '0' && $field['default'] !== 0) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'all autoincrement fields must be defined default "0"'); - } - } - return MDB2_OK; - } - - // }}} - // {{{ validateIndex() - - /** - * Checks whether a parsed index is valid. Modify index definition when - * necessary. - * - * @param array $table_indexes multi dimensional array that contains the - * indexes of current table. - * @param array &$index multi dimensional array that contains the - * structure of the parsed index. - * @param string $index_name name of the parsed index - * - * @return bool|error object - * - * @access public - */ - function validateIndex($table_indexes, &$index, $index_name) - { - if (!$index_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'an index has to have a name'); - } - if (is_array($table_indexes) && isset($table_indexes[$index_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'index "'.$index_name.'" already exists'); - } - if (array_key_exists('unique', $index) && !$this->isBoolean($index['unique'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "unique" has to be a boolean value'); - } - if (array_key_exists('primary', $index) && !$this->isBoolean($index['primary'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "primary" has to be a boolean value'); - } - - /* Have we got fields? */ - if (empty($index['fields']) || !is_array($index['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'indexes need one or more fields'); - } - - if (empty($index['was'])) { - $index['was'] = $index_name; - } - return MDB2_OK; - } - - // }}} - // {{{ validateIndexField() - - /** - * Checks whether a parsed index-field is valid. Modify its definition when - * necessary. - * - * @param array $index_fields multi dimensional array that contains the - * fields of current index. - * @param array &$field multi dimensional array that contains the - * structure of the parsed index-field. - * @param string $field_name name of the parsed index-field - * - * @return bool|error object - * - * @access public - */ - function validateIndexField($index_fields, &$field, $field_name) - { - if (is_array($index_fields) && isset($index_fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'index field "'.$field_name.'" already exists'); - } - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'the index-field-name is required'); - } - if (empty($field['sorting'])) { - $field['sorting'] = 'ascending'; - } elseif ($field['sorting'] !== 'ascending' && $field['sorting'] !== 'descending') { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sorting type unknown'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateConstraint() - - /** - * Checks whether a parsed foreign key is valid. Modify its definition when - * necessary. - * - * @param array $table_constraints multi dimensional array that contains the - * constraints of current table. - * @param array &$constraint multi dimensional array that contains the - * structure of the parsed foreign key. - * @param string $constraint_name name of the parsed foreign key - * - * @return bool|error object - * - * @access public - */ - function validateConstraint($table_constraints, &$constraint, $constraint_name) - { - if (!$constraint_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a foreign key has to have a name'); - } - if (is_array($table_constraints) && isset($table_constraints[$constraint_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" already exists'); - } - - /* Have we got fields? */ - if (empty($constraint['fields']) || !is_array($constraint['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" need one or more fields'); - } - - /* Have we got referenced fields? */ - if (empty($constraint['references']) || !is_array($constraint['references'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" need to reference one or more fields'); - } - - /* Have we got referenced table? */ - if (empty($constraint['references']['table'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" need to reference a table'); - } - - if (empty($constraint['was'])) { - $constraint['was'] = $constraint_name; - } - return MDB2_OK; - } - - // }}} - // {{{ validateConstraintField() - - /** - * Checks whether a foreign-field is valid. - * - * @param array $constraint_fields multi dimensional array that contains the - * fields of current foreign key. - * @param string $field_name name of the parsed foreign-field - * - * @return bool|error object - * - * @access public - */ - function validateConstraintField($constraint_fields, $field_name) - { - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'empty value for foreign-field'); - } - if (is_array($constraint_fields) && isset($constraint_fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign field "'.$field_name.'" already exists'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateConstraintReferencedField() - - /** - * Checks whether a foreign-referenced field is valid. - * - * @param array $referenced_fields multi dimensional array that contains the - * fields of current foreign key. - * @param string $field_name name of the parsed foreign-field - * - * @return bool|error object - * - * @access public - */ - function validateConstraintReferencedField($referenced_fields, $field_name) - { - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'empty value for referenced foreign-field'); - } - if (is_array($referenced_fields) && isset($referenced_fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign field "'.$field_name.'" already referenced'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateSequence() - - /** - * Checks whether the definition of a parsed sequence is valid. Modify - * sequence definition when necessary. - * - * @param array $sequences multi dimensional array that contains the - * sequences of current database. - * @param array &$sequence multi dimensional array that contains the - * structure of the parsed sequence. - * @param string $sequence_name name of the parsed sequence - * - * @return bool|error object - * - * @access public - */ - function validateSequence($sequences, &$sequence, $sequence_name) - { - if (!$sequence_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a sequence has to have a name'); - } - - if (is_array($sequences) && isset($sequences[$sequence_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence "'.$sequence_name.'" already exists'); - } - - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($sequence_name); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence name "'.$sequence_name.'" is a reserved word in: '.$rdbms); - } - } - } - - if (empty($sequence['was'])) { - $sequence['was'] = $sequence_name; - } - - if (!empty($sequence['on']) - && (empty($sequence['on']['table']) || empty($sequence['on']['field'])) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence "'.$sequence_name.'" on a table was not properly defined'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateDatabase() - - /** - * Checks whether a parsed database is valid. Modify its structure and - * data when necessary. - * - * @param array &$database multi dimensional array that contains the - * structure and optional data of the database. - * - * @return bool|error object - * - * @access public - */ - function validateDatabase(&$database) - { - /* Have we got a name? */ - if (!is_array($database) || !isset($database['name']) || !$database['name']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a database has to have a name'); - } - - /* Database name reserved? */ - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($database['name']); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'database name "'.$database['name'].'" is a reserved word in: '.$rdbms); - } - } - } - - /* Create */ - if (isset($database['create']) - && !$this->isBoolean($database['create']) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "create" has to be a boolean value'); - } - - /* Overwrite */ - if (isset($database['overwrite']) - && $database['overwrite'] !== '' - && !$this->isBoolean($database['overwrite']) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "overwrite" has to be a boolean value'); - } - - /* - * This have to be done here otherwise we can't guarantee that all - * tables were already defined in the moment we are parsing constraints - */ - if (isset($database['tables'])) { - foreach ($database['tables'] as $table_name => $table) { - if (!empty($table['constraints'])) { - foreach ($table['constraints'] as $constraint_name => $constraint) { - $referenced_table_name = $constraint['references']['table']; - - if (!isset($database['tables'][$referenced_table_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'referenced table "'.$referenced_table_name.'" of foreign key "'.$constraint_name.'" of table "'.$table_name.'" does not exist'); - } - - if (empty($constraint['references']['fields'])) { - $referenced_table = $database['tables'][$referenced_table_name]; - - $primary = false; - - if (!empty($referenced_table['indexes'])) { - foreach ($referenced_table['indexes'] as $index_name => $index) { - if (array_key_exists('primary', $index) - && $index['primary'] - ) { - $primary = array(); - foreach ($index['fields'] as $field_name => $field) { - $primary[$field_name] = ''; - } - break; - } - } - } - - if (!$primary) { - foreach ($referenced_table['fields'] as $field_name => $field) { - if (array_key_exists('autoincrement', $field) - && $field['autoincrement'] - ) { - $primary = array( $field_name => '' ); - break; - } - } - } - - if (!$primary) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'referenced table "'.$referenced_table_name.'" has no primary key and no referenced field was specified for foreign key "'.$constraint_name.'" of table "'.$table_name.'"'); - } - - $constraint['references']['fields'] = $primary; - } - - /* the same number of referencing and referenced fields ? */ - if (count($constraint['fields']) != count($constraint['references']['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'The number of fields in the referenced key must match those of the foreign key "'.$constraint_name.'"'); - } - - $database['tables'][$table_name]['constraints'][$constraint_name]['references']['fields'] = $constraint['references']['fields']; - } - } - } - } - - /* - * This have to be done here otherwise we can't guarantee that all - * tables were already defined in the moment we are parsing sequences - */ - if (isset($database['sequences'])) { - foreach ($database['sequences'] as $seq_name => $seq) { - if (!empty($seq['on']) - && empty($database['tables'][$seq['on']['table']]['fields'][$seq['on']['field']]) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence "'.$seq_name.'" was assigned on unexisting field/table'); - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ validateDataField() - - /* Data Manipulation */ - /** - * Checks whether a parsed DML-field is valid. Modify its structure when - * necessary. This is called when validating INSERT and - * UPDATE. - * - * @param array $table_fields multi dimensional array that contains the - * definition for current table's fields. - * @param array $instruction_fields multi dimensional array that contains the - * parsed fields of the current DML instruction. - * @param string &$field array that contains the parsed instruction field - * - * @return bool|error object - * - * @access public - */ - function validateDataField($table_fields, $instruction_fields, &$field) - { - if (!$field['name']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field-name has to be specified'); - } - - if (is_array($instruction_fields) && isset($instruction_fields[$field['name']])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "'.$field['name'].'" already initialized'); - } - - if (is_array($table_fields) && !isset($table_fields[$field['name']])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field['name'].'" is not defined'); - } - - if (!isset($field['group']['type'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field['name'].'" has no initial value'); - } - - if (isset($field['group']['data']) - && $field['group']['type'] == 'value' - && $field['group']['data'] !== '' - && PEAR::isError($result = $this->validateDataFieldValue($table_fields[$field['name']], $field['group']['data'], $field['name'])) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'value of "'.$field['name'].'" is incorrect: '.$result->getUserinfo()); - } - - return MDB2_OK; - } - - // }}} - // {{{ validateDataFieldValue() - - /** - * Checks whether a given value is compatible with a table field. This is - * done when parsing a field for a INSERT or UPDATE instruction. - * - * @param array $field_def multi dimensional array that contains the - * definition for current table's fields. - * @param string &$field_value value to fill the parsed field - * @param string $field_name name of the parsed field - * - * @return bool|error object - * - * @access public - * @see MDB2_Schema_Validate::validateInsertField() - */ - function validateDataFieldValue($field_def, &$field_value, $field_name) - { - switch ($field_def['type']) { - case 'text': - case 'clob': - if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is larger than "'.$field_def['length'].'"'); - } - break; - case 'blob': - $field_value = pack('H*', $field_value); - if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is larger than "'.$field_def['type'].'"'); - } - break; - case 'integer': - if ($field_value != ((int)$field_value)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - //$field_value = (int)$field_value; - if (!empty($field_def['unsigned']) && $field_def['unsigned'] && $field_value < 0) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" signed instead of unsigned'); - } - break; - case 'boolean': - if (!$this->isBoolean($field_value)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'date': - if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/', $field_value) - && $field_value !== 'CURRENT_DATE' - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'timestamp': - if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $field_value) - && strcasecmp($field_value, 'now()') != 0 - && $field_value !== 'CURRENT_TIMESTAMP' - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'time': - if (!preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2})/", $field_value) - && $field_value !== 'CURRENT_TIME' - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'float': - case 'double': - if ($field_value != (double)$field_value) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - //$field_value = (double)$field_value; - break; - } - return MDB2_OK; - } -} - -?> diff --git a/3rdparty/MDB2/Schema/Writer.php b/3rdparty/MDB2/Schema/Writer.php deleted file mode 100644 index 5ae4918dc1..0000000000 --- a/3rdparty/MDB2/Schema/Writer.php +++ /dev/null @@ -1,581 +0,0 @@ - - * Author: Igor Feghali - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith - * @author Igor Feghali - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Writer.php,v 1.40 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -/** - * Writes an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Writer -{ - // {{{ properties - - var $valid_types = array(); - - // }}} - // {{{ constructor - - function __construct($valid_types = array()) - { - $this->valid_types = $valid_types; - } - - function MDB2_Schema_Writer($valid_types = array()) - { - $this->__construct($valid_types); - } - - // }}} - // {{{ raiseError() - - /** - * This method is used to communicate an error and invoke error - * callbacks etc. Basically a wrapper for PEAR::raiseError - * without the message string. - * - * @param int|PEAR_Error $code integer error code or and PEAR_Error instance - * @param int $mode error mode, see PEAR_Error docs - * error level (E_USER_NOTICE etc). If error mode is - * PEAR_ERROR_CALLBACK, this is the callback function, - * either as a function name, or as an array of an - * object and method name. For other error modes this - * parameter is ignored. - * @param string $options Extra debug information. Defaults to the last - * query and native error code. - * - * @return object a PEAR error object - * @access public - * @see PEAR_Error - */ - function &raiseError($code = null, $mode = null, $options = null, $userinfo = null) - { - $error =& MDB2_Schema::raiseError($code, $mode, $options, $userinfo); - return $error; - } - - // }}} - // {{{ _escapeSpecialChars() - - /** - * add escapecharacters to all special characters in a string - * - * @param string $string string that should be escaped - * - * @return string escaped string - * @access protected - */ - function _escapeSpecialChars($string) - { - if (!is_string($string)) { - $string = strval($string); - } - - $escaped = ''; - for ($char = 0, $count = strlen($string); $char < $count; $char++) { - switch ($string[$char]) { - case '&': - $escaped .= '&'; - break; - case '>': - $escaped .= '>'; - break; - case '<': - $escaped .= '<'; - break; - case '"': - $escaped .= '"'; - break; - case '\'': - $escaped .= '''; - break; - default: - $code = ord($string[$char]); - if ($code < 32 || $code > 127) { - $escaped .= "&#$code;"; - } else { - $escaped .= $string[$char]; - } - break; - } - } - return $escaped; - } - - // }}} - // {{{ _dumpBoolean() - - /** - * dump the structure of a sequence - * - * @param string $boolean boolean value or variable definition - * - * @return string with xml boolea definition - * @access private - */ - function _dumpBoolean($boolean) - { - if (is_string($boolean)) { - if ($boolean !== 'true' || $boolean !== 'false' - || preg_match('/.*/', $boolean) - ) { - return $boolean; - } - } - return $boolean ? 'true' : 'false'; - } - - // }}} - // {{{ dumpSequence() - - /** - * dump the structure of a sequence - * - * @param string $sequence_definition sequence definition - * @param string $sequence_name sequence name - * @param string $eol end of line characters - * @param integer $dump determines what data to dump - * MDB2_SCHEMA_DUMP_ALL : the entire db - * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db - * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db - * - * @return mixed string xml sequence definition on success, or a error object - * @access public - */ - function dumpSequence($sequence_definition, $sequence_name, $eol, $dump = MDB2_SCHEMA_DUMP_ALL) - { - $buffer = "$eol $eol $sequence_name$eol"; - if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) { - if (!empty($sequence_definition['start'])) { - $start = $sequence_definition['start']; - $buffer .= " $start$eol"; - } - } - - if (!empty($sequence_definition['on'])) { - $buffer .= " $eol"; - $buffer .= " ".$sequence_definition['on']['table']; - $buffer .= "
$eol ".$sequence_definition['on']['field']; - $buffer .= "$eol
$eol"; - } - $buffer .= "
$eol"; - - return $buffer; - } - - // }}} - // {{{ dumpDatabase() - - /** - * Dump a previously parsed database structure in the Metabase schema - * XML based format suitable for the Metabase parser. This function - * may optionally dump the database definition with initialization - * commands that specify the data that is currently present in the tables. - * - * @param array $database_definition unknown - * @param array $arguments associative array that takes pairs of tag - * names and values that define dump options. - * array ( - * 'output_mode' => String - * 'file' : dump into a file - * default: dump using a function - * 'output' => String - * depending on the 'Output_Mode' - * name of the file - * name of the function - * 'end_of_line' => String - * end of line delimiter that should be used - * default: "\n" - * ); - * @param integer $dump determines what data to dump - * MDB2_SCHEMA_DUMP_ALL : the entire db - * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db - * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db - * - * @return mixed MDB2_OK on success, or a error object - * @access public - */ - function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL) - { - if (!empty($arguments['output'])) { - if (!empty($arguments['output_mode']) && $arguments['output_mode'] == 'file') { - $fp = fopen($arguments['output'], 'w'); - if ($fp === false) { - return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null, - 'it was not possible to open output file'); - } - - $output = false; - } elseif (is_callable($arguments['output'])) { - $output = $arguments['output']; - } else { - return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null, - 'no valid output function specified'); - } - } else { - return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null, - 'no output method specified'); - } - - $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n"; - - $sequences = array(); - if (!empty($database_definition['sequences']) - && is_array($database_definition['sequences']) - ) { - foreach ($database_definition['sequences'] as $sequence_name => $sequence) { - $table = !empty($sequence['on']) ? $sequence['on']['table'] :''; - - $sequences[$table][] = $sequence_name; - } - } - - $buffer = ''.$eol; - $buffer .= "$eol$eol ".$database_definition['name'].""; - $buffer .= "$eol ".$this->_dumpBoolean($database_definition['create']).""; - $buffer .= "$eol ".$this->_dumpBoolean($database_definition['overwrite'])."$eol"; - $buffer .= "$eol ".$database_definition['charset']."$eol"; - - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - } - - if (!empty($database_definition['tables']) && is_array($database_definition['tables'])) { - foreach ($database_definition['tables'] as $table_name => $table) { - $buffer = "$eol $eol$eol $table_name$eol"; - if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_STRUCTURE) { - $buffer .= "$eol $eol"; - if (!empty($table['fields']) && is_array($table['fields'])) { - foreach ($table['fields'] as $field_name => $field) { - if (empty($field['type'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null, - 'it was not specified the type of the field "'. - $field_name.'" of the table "'.$table_name.'"'); - } - if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'type "'.$field['type'].'" is not yet supported'); - } - $buffer .= "$eol $eol $field_name$eol "; - $buffer .= $field['type']."$eol"; - if (!empty($field['fixed']) && $field['type'] === 'text') { - $buffer .= " ".$this->_dumpBoolean($field['fixed'])."$eol"; - } - if (array_key_exists('default', $field) - && $field['type'] !== 'clob' && $field['type'] !== 'blob' - ) { - $buffer .= ' '.$this->_escapeSpecialChars($field['default'])."$eol"; - } - if (!empty($field['notnull'])) { - $buffer .= " ".$this->_dumpBoolean($field['notnull'])."$eol"; - } else { - $buffer .= " false$eol"; - } - if (!empty($field['autoincrement'])) { - $buffer .= " " . $field['autoincrement'] ."$eol"; - } - if (!empty($field['unsigned'])) { - $buffer .= " ".$this->_dumpBoolean($field['unsigned'])."$eol"; - } - if (!empty($field['length'])) { - $buffer .= ' '.$field['length']."$eol"; - } - $buffer .= " $eol"; - } - } - - if (!empty($table['indexes']) && is_array($table['indexes'])) { - foreach ($table['indexes'] as $index_name => $index) { - if (strtolower($index_name) === 'primary') { - $index_name = $table_name . '_pKey'; - } - $buffer .= "$eol $eol $index_name$eol"; - if (!empty($index['unique'])) { - $buffer .= " ".$this->_dumpBoolean($index['unique'])."$eol"; - } - - if (!empty($index['primary'])) { - $buffer .= " ".$this->_dumpBoolean($index['primary'])."$eol"; - } - - foreach ($index['fields'] as $field_name => $field) { - $buffer .= " $eol $field_name$eol"; - if (!empty($field) && is_array($field)) { - $buffer .= ' '.$field['sorting']."$eol"; - } - $buffer .= " $eol"; - } - $buffer .= " $eol"; - } - } - - if (!empty($table['constraints']) && is_array($table['constraints'])) { - foreach ($table['constraints'] as $constraint_name => $constraint) { - $buffer .= "$eol $eol $constraint_name$eol"; - if (empty($constraint['fields']) || !is_array($constraint['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null, - 'it was not specified a field for the foreign key "'. - $constraint_name.'" of the table "'.$table_name.'"'); - } - if (!is_array($constraint['references']) || empty($constraint['references']['table'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null, - 'it was not specified the referenced table of the foreign key "'. - $constraint_name.'" of the table "'.$table_name.'"'); - } - if (!empty($constraint['match'])) { - $buffer .= " ".$constraint['match']."$eol"; - } - if (!empty($constraint['ondelete'])) { - $buffer .= " ".$constraint['ondelete']."$eol"; - } - if (!empty($constraint['onupdate'])) { - $buffer .= " ".$constraint['onupdate']."$eol"; - } - if (!empty($constraint['deferrable'])) { - $buffer .= " ".$constraint['deferrable']."$eol"; - } - if (!empty($constraint['initiallydeferred'])) { - $buffer .= " ".$constraint['initiallydeferred']."$eol"; - } - foreach ($constraint['fields'] as $field_name => $field) { - $buffer .= " $field_name$eol"; - } - $buffer .= " $eol
".$constraint['references']['table']."
$eol"; - foreach ($constraint['references']['fields'] as $field_name => $field) { - $buffer .= " $field_name$eol"; - } - $buffer .= " $eol"; - - $buffer .= " $eol"; - } - } - - $buffer .= "$eol $eol"; - } - - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - } - - $buffer = ''; - if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) { - if (!empty($table['initialization']) && is_array($table['initialization'])) { - $buffer = "$eol $eol"; - foreach ($table['initialization'] as $instruction) { - switch ($instruction['type']) { - case 'insert': - $buffer .= "$eol $eol"; - foreach ($instruction['data']['field'] as $field) { - $field_name = $field['name']; - - $buffer .= "$eol $eol $field_name$eol"; - $buffer .= $this->writeExpression($field['group'], 5, $arguments); - $buffer .= " $eol"; - } - $buffer .= "$eol $eol"; - break; - case 'update': - $buffer .= "$eol $eol"; - foreach ($instruction['data']['field'] as $field) { - $field_name = $field['name']; - - $buffer .= "$eol $eol $field_name$eol"; - $buffer .= $this->writeExpression($field['group'], 5, $arguments); - $buffer .= " $eol"; - } - - if (!empty($instruction['data']['where']) - && is_array($instruction['data']['where']) - ) { - $buffer .= " $eol"; - $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments); - $buffer .= " $eol"; - } - - $buffer .= "$eol $eol"; - break; - case 'delete': - $buffer .= "$eol $eol$eol"; - if (!empty($instruction['data']['where']) - && is_array($instruction['data']['where']) - ) { - $buffer .= " $eol"; - $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments); - $buffer .= " $eol"; - } - $buffer .= "$eol $eol"; - break; - } - } - $buffer .= "$eol $eol"; - } - } - $buffer .= "$eol $eol"; - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - } - - if (isset($sequences[$table_name])) { - foreach ($sequences[$table_name] as $sequence) { - $result = $this->dumpSequence($database_definition['sequences'][$sequence], - $sequence, $eol, $dump); - if (PEAR::isError($result)) { - return $result; - } - - if ($output) { - call_user_func($output, $result); - } else { - fwrite($fp, $result); - } - } - } - } - } - - if (isset($sequences[''])) { - foreach ($sequences[''] as $sequence) { - $result = $this->dumpSequence($database_definition['sequences'][$sequence], - $sequence, $eol, $dump); - if (PEAR::isError($result)) { - return $result; - } - - if ($output) { - call_user_func($output, $result); - } else { - fwrite($fp, $result); - } - } - } - - $buffer = "$eol
$eol"; - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - fclose($fp); - } - - return MDB2_OK; - } - - // }}} - // {{{ writeExpression() - - /** - * Dumps the structure of an element. Elements can be value, column, - * function or expression. - * - * @param array $element multi dimensional array that represents the parsed element - * of a DML instruction. - * @param integer $offset base indentation width - * @param array $arguments associative array that takes pairs of tag - * names and values that define dump options. - * - * @return string - * - * @access public - * @see MDB2_Schema_Writer::dumpDatabase() - */ - function writeExpression($element, $offset = 0, $arguments = null) - { - $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n"; - $str = ''; - - $indent = str_repeat(' ', $offset); - $noffset = $offset + 1; - - switch ($element['type']) { - case 'value': - $str .= "$indent".$this->_escapeSpecialChars($element['data'])."$eol"; - break; - case 'column': - $str .= "$indent".$this->_escapeSpecialChars($element['data'])."$eol"; - break; - case 'function': - $str .= "$indent$eol$indent ".$this->_escapeSpecialChars($element['data']['name'])."$eol"; - - if (!empty($element['data']['arguments']) - && is_array($element['data']['arguments']) - ) { - foreach ($element['data']['arguments'] as $v) { - $str .= $this->writeExpression($v, $noffset, $arguments); - } - } - - $str .= "$indent$eol"; - break; - case 'expression': - $str .= "$indent$eol"; - $str .= $this->writeExpression($element['data']['operants'][0], $noffset, $arguments); - $str .= "$indent ".$element['data']['operator']."$eol"; - $str .= $this->writeExpression($element['data']['operants'][1], $noffset, $arguments); - $str .= "$indent$eol"; - break; - } - return $str; - } - - // }}} -} -?> diff --git a/3rdparty/PEAR.php b/3rdparty/PEAR.php deleted file mode 100644 index f832c0d491..0000000000 --- a/3rdparty/PEAR.php +++ /dev/null @@ -1,1055 +0,0 @@ - | -// | Stig Bakken | -// | Tomas V.V.Cox | -// +--------------------------------------------------------------------+ -// -// $Id: PEAR.php,v 1.82.2.6 2005/01/01 05:24:51 cellog Exp $ -// - -define('PEAR_ERROR_RETURN', 1); -define('PEAR_ERROR_PRINT', 2); -define('PEAR_ERROR_TRIGGER', 4); -define('PEAR_ERROR_DIE', 8); -define('PEAR_ERROR_CALLBACK', 16); -/** - * WARNING: obsolete - * @deprecated - */ -define('PEAR_ERROR_EXCEPTION', 32); -define('PEAR_ZE2', (function_exists('version_compare') && - version_compare(zend_version(), "2-dev", "ge"))); - -if (substr(PHP_OS, 0, 3) == 'WIN') { - define('OS_WINDOWS', true); - define('OS_UNIX', false); - define('PEAR_OS', 'Windows'); -} else { - define('OS_WINDOWS', false); - define('OS_UNIX', true); - define('PEAR_OS', 'Unix'); // blatant assumption -} - -// instant backwards compatibility -if (!defined('PATH_SEPARATOR')) { - if (OS_WINDOWS) { - define('PATH_SEPARATOR', ';'); - } else { - define('PATH_SEPARATOR', ':'); - } -} - -$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN; -$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE; -$GLOBALS['_PEAR_destructor_object_list'] = array(); -$GLOBALS['_PEAR_shutdown_funcs'] = array(); -$GLOBALS['_PEAR_error_handler_stack'] = array(); - -@ini_set('track_errors', true); - -/** - * Base class for other PEAR classes. Provides rudimentary - * emulation of destructors. - * - * If you want a destructor in your class, inherit PEAR and make a - * destructor method called _yourclassname (same name as the - * constructor, but with a "_" prefix). Also, in your constructor you - * have to call the PEAR constructor: $this->PEAR();. - * The destructor method will be called without parameters. Note that - * at in some SAPI implementations (such as Apache), any output during - * the request shutdown (in which destructors are called) seems to be - * discarded. If you need to get any debug information from your - * destructor, use error_log(), syslog() or something similar. - * - * IMPORTANT! To use the emulated destructors you need to create the - * objects by reference: $obj =& new PEAR_child; - * - * @since PHP 4.0.2 - * @author Stig Bakken - * @see http://pear.php.net/manual/ - */ -class PEAR -{ - // {{{ properties - - /** - * Whether to enable internal debug messages. - * - * @var bool - * @access private - */ - var $_debug = false; - - /** - * Default error mode for this object. - * - * @var int - * @access private - */ - var $_default_error_mode = null; - - /** - * Default error options used for this object when error mode - * is PEAR_ERROR_TRIGGER. - * - * @var int - * @access private - */ - var $_default_error_options = null; - - /** - * Default error handler (callback) for this object, if error mode is - * PEAR_ERROR_CALLBACK. - * - * @var string - * @access private - */ - var $_default_error_handler = ''; - - /** - * Which class to use for error objects. - * - * @var string - * @access private - */ - var $_error_class = 'PEAR_Error'; - - /** - * An array of expected errors. - * - * @var array - * @access private - */ - var $_expected_errors = array(); - - // }}} - - // {{{ constructor - - /** - * Constructor. Registers this object in - * $_PEAR_destructor_object_list for destructor emulation if a - * destructor object exists. - * - * @param string $error_class (optional) which class to use for - * error objects, defaults to PEAR_Error. - * @access public - * @return void - */ - function PEAR($error_class = null) - { - $classname = strtolower(get_class($this)); - if ($this->_debug) { - print "PEAR constructor called, class=$classname\n"; - } - if ($error_class !== null) { - $this->_error_class = $error_class; - } - while ($classname && strcasecmp($classname, "pear")) { - $destructor = "_$classname"; - if (method_exists($this, $destructor)) { - global $_PEAR_destructor_object_list; - $_PEAR_destructor_object_list[] = &$this; - if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) { - register_shutdown_function("_PEAR_call_destructors"); - $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true; - } - break; - } else { - $classname = get_parent_class($classname); - } - } - } - - // }}} - // {{{ destructor - - /** - * Destructor (the emulated type of...). Does nothing right now, - * but is included for forward compatibility, so subclass - * destructors should always call it. - * - * See the note in the class desciption about output from - * destructors. - * - * @access public - * @return void - */ - function _PEAR() { - if ($this->_debug) { - printf("PEAR destructor called, class=%s\n", strtolower(get_class($this))); - } - } - - // }}} - // {{{ getStaticProperty() - - /** - * If you have a class that's mostly/entirely static, and you need static - * properties, you can use this method to simulate them. Eg. in your method(s) - * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar'); - * You MUST use a reference, or they will not persist! - * - * @access public - * @param string $class The calling classname, to prevent clashes - * @param string $var The variable to retrieve. - * @return mixed A reference to the variable. If not set it will be - * auto initialised to NULL. - */ - function &getStaticProperty($class, $var) - { - static $properties; - return $properties[$class][$var]; - } - - // }}} - // {{{ registerShutdownFunc() - - /** - * Use this function to register a shutdown method for static - * classes. - * - * @access public - * @param mixed $func The function name (or array of class/method) to call - * @param mixed $args The arguments to pass to the function - * @return void - */ - function registerShutdownFunc($func, $args = array()) - { - $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args); - } - - // }}} - // {{{ isError() - - /** - * Tell whether a value is a PEAR error. - * - * @param mixed $data the value to test - * @param int $code if $data is an error object, return true - * only if $code is a string and - * $obj->getMessage() == $code or - * $code is an integer and $obj->getCode() == $code - * @access public - * @return bool true if parameter is an error - */ - static function isError($data, $code = null) - { - if ($data instanceof PEAR_Error) { - if (is_null($code)) { - return true; - } elseif (is_string($code)) { - return $data->getMessage() == $code; - } else { - return $data->getCode() == $code; - } - } - return false; - } - - // }}} - // {{{ setErrorHandling() - - /** - * Sets how errors generated by this object should be handled. - * Can be invoked both in objects and statically. If called - * statically, setErrorHandling sets the default behaviour for all - * PEAR objects. If called in an object, setErrorHandling sets - * the default behaviour for that object. - * - * @param int $mode - * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, - * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, - * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION. - * - * @param mixed $options - * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one - * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). - * - * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected - * to be the callback function or method. A callback - * function is a string with the name of the function, a - * callback method is an array of two elements: the element - * at index 0 is the object, and the element at index 1 is - * the name of the method to call in the object. - * - * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is - * a printf format string used when printing the error - * message. - * - * @access public - * @return void - * @see PEAR_ERROR_RETURN - * @see PEAR_ERROR_PRINT - * @see PEAR_ERROR_TRIGGER - * @see PEAR_ERROR_DIE - * @see PEAR_ERROR_CALLBACK - * @see PEAR_ERROR_EXCEPTION - * - * @since PHP 4.0.5 - */ - - function setErrorHandling($mode = null, $options = null) - { - if (isset($this) && $this instanceof PEAR) { - $setmode = &$this->_default_error_mode; - $setoptions = &$this->_default_error_options; - } else { - $setmode = &$GLOBALS['_PEAR_default_error_mode']; - $setoptions = &$GLOBALS['_PEAR_default_error_options']; - } - - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $setmode = $mode; - $setoptions = $options; - break; - - case PEAR_ERROR_CALLBACK: - $setmode = $mode; - // class/object method callback - if (is_callable($options)) { - $setoptions = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - } - - // }}} - // {{{ expectError() - - /** - * This method is used to tell which errors you expect to get. - * Expected errors are always returned with error mode - * PEAR_ERROR_RETURN. Expected error codes are stored in a stack, - * and this method pushes a new element onto it. The list of - * expected errors are in effect until they are popped off the - * stack with the popExpect() method. - * - * Note that this method can not be called statically - * - * @param mixed $code a single error code or an array of error codes to expect - * - * @return int the new depth of the "expected errors" stack - * @access public - */ - function expectError($code = '*') - { - if (is_array($code)) { - array_push($this->_expected_errors, $code); - } else { - array_push($this->_expected_errors, array($code)); - } - return sizeof($this->_expected_errors); - } - - // }}} - // {{{ popExpect() - - /** - * This method pops one element off the expected error codes - * stack. - * - * @return array the list of error codes that were popped - */ - function popExpect() - { - return array_pop($this->_expected_errors); - } - - // }}} - // {{{ _checkDelExpect() - - /** - * This method checks unsets an error code if available - * - * @param mixed error code - * @return bool true if the error code was unset, false otherwise - * @access private - * @since PHP 4.3.0 - */ - function _checkDelExpect($error_code) - { - $deleted = false; - - foreach ($this->_expected_errors AS $key => $error_array) { - if (in_array($error_code, $error_array)) { - unset($this->_expected_errors[$key][array_search($error_code, $error_array)]); - $deleted = true; - } - - // clean up empty arrays - if (0 == count($this->_expected_errors[$key])) { - unset($this->_expected_errors[$key]); - } - } - return $deleted; - } - - // }}} - // {{{ delExpect() - - /** - * This method deletes all occurences of the specified element from - * the expected error codes stack. - * - * @param mixed $error_code error code that should be deleted - * @return mixed list of error codes that were deleted or error - * @access public - * @since PHP 4.3.0 - */ - function delExpect($error_code) - { - $deleted = false; - - if ((is_array($error_code) && (0 != count($error_code)))) { - // $error_code is a non-empty array here; - // we walk through it trying to unset all - // values - foreach($error_code as $key => $error) { - if ($this->_checkDelExpect($error)) { - $deleted = true; - } else { - $deleted = false; - } - } - return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME - } elseif (!empty($error_code)) { - // $error_code comes alone, trying to unset it - if ($this->_checkDelExpect($error_code)) { - return true; - } else { - return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME - } - } else { - // $error_code is empty - return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME - } - } - - // }}} - // {{{ raiseError() - - /** - * This method is a wrapper that returns an instance of the - * configured error class with this object's default error - * handling applied. If the $mode and $options parameters are not - * specified, the object's defaults are used. - * - * @param mixed $message a text error message or a PEAR error object - * - * @param int $code a numeric error code (it is up to your class - * to define these if you want to use codes) - * - * @param int $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, - * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, - * PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION. - * - * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter - * specifies the PHP-internal error level (one of - * E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). - * If $mode is PEAR_ERROR_CALLBACK, this - * parameter specifies the callback function or - * method. In other error modes this parameter - * is ignored. - * - * @param string $userinfo If you need to pass along for example debug - * information, this parameter is meant for that. - * - * @param string $error_class The returned error object will be - * instantiated from this class, if specified. - * - * @param bool $skipmsg If true, raiseError will only pass error codes, - * the error message parameter will be dropped. - * - * @access public - * @return object a PEAR error object - * @see PEAR::setErrorHandling - * @since PHP 4.0.5 - */ - function raiseError($message = null, - $code = null, - $mode = null, - $options = null, - $userinfo = null, - $error_class = null, - $skipmsg = false) - { - // The error is yet a PEAR error object - if (is_object($message)) { - $code = $message->getCode(); - $userinfo = $message->getUserInfo(); - $error_class = $message->getType(); - $message->error_message_prefix = ''; - $message = $message->getMessage(); - } - - if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) { - if ($exp[0] == "*" || - (is_int(reset($exp)) && in_array($code, $exp)) || - (is_string(reset($exp)) && in_array($message, $exp))) { - $mode = PEAR_ERROR_RETURN; - } - } - // No mode given, try global ones - if ($mode === null) { - // Class error handler - if (isset($this) && isset($this->_default_error_mode)) { - $mode = $this->_default_error_mode; - $options = $this->_default_error_options; - // Global error handler - } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) { - $mode = $GLOBALS['_PEAR_default_error_mode']; - $options = $GLOBALS['_PEAR_default_error_options']; - } - } - - if ($error_class !== null) { - $ec = $error_class; - } elseif (isset($this) && isset($this->_error_class)) { - $ec = $this->_error_class; - } else { - $ec = 'PEAR_Error'; - } - if ($skipmsg) { - return new $ec($code, $mode, $options, $userinfo); - } else { - return new $ec($message, $code, $mode, $options, $userinfo); - } - } - - // }}} - // {{{ throwError() - - /** - * Simpler form of raiseError with fewer options. In most cases - * message, code and userinfo are enough. - * - * @param string $message - * - */ - function throwError($message = null, - $code = null, - $userinfo = null) - { - if (isset($this) && $this instanceof PEAR) { - return $this->raiseError($message, $code, null, null, $userinfo); - } else { - return PEAR::raiseError($message, $code, null, null, $userinfo); - } - } - - // }}} - function staticPushErrorHandling($mode, $options = null) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $def_mode = &$GLOBALS['_PEAR_default_error_mode']; - $def_options = &$GLOBALS['_PEAR_default_error_options']; - $stack[] = array($def_mode, $def_options); - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $def_mode = $mode; - $def_options = $options; - break; - - case PEAR_ERROR_CALLBACK: - $def_mode = $mode; - // class/object method callback - if (is_callable($options)) { - $def_options = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - $stack[] = array($mode, $options); - return true; - } - - function staticPopErrorHandling() - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $setmode = &$GLOBALS['_PEAR_default_error_mode']; - $setoptions = &$GLOBALS['_PEAR_default_error_options']; - array_pop($stack); - list($mode, $options) = $stack[sizeof($stack) - 1]; - array_pop($stack); - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $setmode = $mode; - $setoptions = $options; - break; - - case PEAR_ERROR_CALLBACK: - $setmode = $mode; - // class/object method callback - if (is_callable($options)) { - $setoptions = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - return true; - } - - // {{{ pushErrorHandling() - - /** - * Push a new error handler on top of the error handler options stack. With this - * you can easily override the actual error handler for some code and restore - * it later with popErrorHandling. - * - * @param mixed $mode (same as setErrorHandling) - * @param mixed $options (same as setErrorHandling) - * - * @return bool Always true - * - * @see PEAR::setErrorHandling - */ - function pushErrorHandling($mode, $options = null) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - if (isset($this) && $this instanceof PEAR) { - $def_mode = &$this->_default_error_mode; - $def_options = &$this->_default_error_options; - } else { - $def_mode = &$GLOBALS['_PEAR_default_error_mode']; - $def_options = &$GLOBALS['_PEAR_default_error_options']; - } - $stack[] = array($def_mode, $def_options); - - if (isset($this) && $this instanceof PEAR) { - $this->setErrorHandling($mode, $options); - } else { - PEAR::setErrorHandling($mode, $options); - } - $stack[] = array($mode, $options); - return true; - } - - // }}} - // {{{ popErrorHandling() - - /** - * Pop the last error handler used - * - * @return bool Always true - * - * @see PEAR::pushErrorHandling - */ - function popErrorHandling() - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - array_pop($stack); - list($mode, $options) = $stack[sizeof($stack) - 1]; - array_pop($stack); - if (isset($this) && $this instanceof PEAR) { - $this->setErrorHandling($mode, $options); - } else { - PEAR::setErrorHandling($mode, $options); - } - return true; - } - - // }}} - // {{{ loadExtension() - - /** - * OS independant PHP extension load. Remember to take care - * on the correct extension name for case sensitive OSes. - * - * @param string $ext The extension name - * @return bool Success or not on the dl() call - */ - function loadExtension($ext) - { - if (!extension_loaded($ext)) { - // if either returns true dl() will produce a FATAL error, stop that - if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) { - return false; - } - if (OS_WINDOWS) { - $suffix = '.dll'; - } elseif (PHP_OS == 'HP-UX') { - $suffix = '.sl'; - } elseif (PHP_OS == 'AIX') { - $suffix = '.a'; - } elseif (PHP_OS == 'OSX') { - $suffix = '.bundle'; - } else { - $suffix = '.so'; - } - return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix); - } - return true; - } - - // }}} -} - -// {{{ _PEAR_call_destructors() - -function _PEAR_call_destructors() -{ - global $_PEAR_destructor_object_list; - if (is_array($_PEAR_destructor_object_list) && - sizeof($_PEAR_destructor_object_list)) - { - reset($_PEAR_destructor_object_list); - if (@PEAR::getStaticProperty('PEAR', 'destructlifo')) { - $_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list); - } - while (list($k, $objref) = each($_PEAR_destructor_object_list)) { - $classname = get_class($objref); - while ($classname) { - $destructor = "_$classname"; - if (method_exists($objref, $destructor)) { - $objref->$destructor(); - break; - } else { - $classname = get_parent_class($classname); - } - } - } - // Empty the object list to ensure that destructors are - // not called more than once. - $_PEAR_destructor_object_list = array(); - } - - // Now call the shutdown functions - if (is_array($GLOBALS['_PEAR_shutdown_funcs']) AND !empty($GLOBALS['_PEAR_shutdown_funcs'])) { - foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) { - call_user_func_array($value[0], $value[1]); - } - } -} - -// }}} - -class PEAR_Error -{ - // {{{ properties - - var $error_message_prefix = ''; - var $mode = PEAR_ERROR_RETURN; - var $level = E_USER_NOTICE; - var $code = -1; - var $message = ''; - var $userinfo = ''; - var $backtrace = null; - - // }}} - // {{{ constructor - - /** - * PEAR_Error constructor - * - * @param string $message message - * - * @param int $code (optional) error code - * - * @param int $mode (optional) error mode, one of: PEAR_ERROR_RETURN, - * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER, - * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION - * - * @param mixed $options (optional) error level, _OR_ in the case of - * PEAR_ERROR_CALLBACK, the callback function or object/method - * tuple. - * - * @param string $userinfo (optional) additional user/debug info - * - * @access public - * - */ - function PEAR_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - if ($mode === null) { - $mode = PEAR_ERROR_RETURN; - } - $this->message = $message; - $this->code = $code; - $this->mode = $mode; - $this->userinfo = $userinfo; - if (function_exists("debug_backtrace")) { - if (@!PEAR::getStaticProperty('PEAR_Error', 'skiptrace')) { - $this->backtrace = debug_backtrace(); - } - } - if ($mode & PEAR_ERROR_CALLBACK) { - $this->level = E_USER_NOTICE; - $this->callback = $options; - } else { - if ($options === null) { - $options = E_USER_NOTICE; - } - $this->level = $options; - $this->callback = null; - } - if ($this->mode & PEAR_ERROR_PRINT) { - if (is_null($options) || is_int($options)) { - $format = "%s"; - } else { - $format = $options; - } - printf($format, $this->getMessage()); - } - if ($this->mode & PEAR_ERROR_TRIGGER) { - trigger_error($this->getMessage(), $this->level); - } - if ($this->mode & PEAR_ERROR_DIE) { - $msg = $this->getMessage(); - if (is_null($options) || is_int($options)) { - $format = "%s"; - if (substr($msg, -1) != "\n") { - $msg .= "\n"; - } - } else { - $format = $options; - } - die(sprintf($format, $msg)); - } - if ($this->mode & PEAR_ERROR_CALLBACK) { - if (is_callable($this->callback)) { - call_user_func($this->callback, $this); - } - } - if ($this->mode & PEAR_ERROR_EXCEPTION) { - trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_ErrorStack for exceptions", E_USER_WARNING); - eval('$e = new Exception($this->message, $this->code);$e->PEAR_Error = $this;throw($e);'); - } - } - - // }}} - // {{{ getMode() - - /** - * Get the error mode from an error object. - * - * @return int error mode - * @access public - */ - function getMode() { - return $this->mode; - } - - // }}} - // {{{ getCallback() - - /** - * Get the callback function/method from an error object. - * - * @return mixed callback function or object/method array - * @access public - */ - function getCallback() { - return $this->callback; - } - - // }}} - // {{{ getMessage() - - - /** - * Get the error message from an error object. - * - * @return string full error message - * @access public - */ - function getMessage() - { - return ($this->error_message_prefix . $this->message); - } - - - // }}} - // {{{ getCode() - - /** - * Get error code from an error object - * - * @return int error code - * @access public - */ - function getCode() - { - return $this->code; - } - - // }}} - // {{{ getType() - - /** - * Get the name of this error/exception. - * - * @return string error/exception name (type) - * @access public - */ - function getType() - { - return get_class($this); - } - - // }}} - // {{{ getUserInfo() - - /** - * Get additional user-supplied information. - * - * @return string user-supplied information - * @access public - */ - function getUserInfo() - { - return $this->userinfo; - } - - // }}} - // {{{ getDebugInfo() - - /** - * Get additional debug information supplied by the application. - * - * @return string debug information - * @access public - */ - function getDebugInfo() - { - return $this->getUserInfo(); - } - - // }}} - // {{{ getBacktrace() - - /** - * Get the call backtrace from where the error was generated. - * Supported with PHP 4.3.0 or newer. - * - * @param int $frame (optional) what frame to fetch - * @return array Backtrace, or NULL if not available. - * @access public - */ - function getBacktrace($frame = null) - { - if ($frame === null) { - return $this->backtrace; - } - return $this->backtrace[$frame]; - } - - // }}} - // {{{ addUserInfo() - - function addUserInfo($info) - { - if (empty($this->userinfo)) { - $this->userinfo = $info; - } else { - $this->userinfo .= " ** $info"; - } - } - - // }}} - // {{{ toString() - - /** - * Make a string representation of this object. - * - * @return string a string with an object summary - * @access public - */ - function toString() { - $modes = array(); - $levels = array(E_USER_NOTICE => 'notice', - E_USER_WARNING => 'warning', - E_USER_ERROR => 'error'); - if ($this->mode & PEAR_ERROR_CALLBACK) { - if (is_array($this->callback)) { - $callback = (is_object($this->callback[0]) ? - strtolower(get_class($this->callback[0])) : - $this->callback[0]) . '::' . - $this->callback[1]; - } else { - $callback = $this->callback; - } - return sprintf('[%s: message="%s" code=%d mode=callback '. - 'callback=%s prefix="%s" info="%s"]', - strtolower(get_class($this)), $this->message, $this->code, - $callback, $this->error_message_prefix, - $this->userinfo); - } - if ($this->mode & PEAR_ERROR_PRINT) { - $modes[] = 'print'; - } - if ($this->mode & PEAR_ERROR_TRIGGER) { - $modes[] = 'trigger'; - } - if ($this->mode & PEAR_ERROR_DIE) { - $modes[] = 'die'; - } - if ($this->mode & PEAR_ERROR_RETURN) { - $modes[] = 'return'; - } - return sprintf('[%s: message="%s" code=%d mode=%s level=%s '. - 'prefix="%s" info="%s"]', - strtolower(get_class($this)), $this->message, $this->code, - implode("|", $modes), $levels[$this->level], - $this->error_message_prefix, - $this->userinfo); - } - - // }}} -} - -/* - * Local Variables: - * mode: php - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ -?> diff --git a/3rdparty/PEAR/Autoloader.php b/3rdparty/PEAR/Autoloader.php deleted file mode 100644 index de0278d619..0000000000 --- a/3rdparty/PEAR/Autoloader.php +++ /dev/null @@ -1,208 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Autoloader.php,v 1.11 2004/02/27 02:21:29 cellog Exp $ - -if (!extension_loaded("overload")) { - // die hard without ext/overload - die("Rebuild PHP with the `overload' extension to use PEAR_Autoloader"); -} - -require_once "PEAR.php"; - -/** - * This class is for objects where you want to separate the code for - * some methods into separate classes. This is useful if you have a - * class with not-frequently-used methods that contain lots of code - * that you would like to avoid always parsing. - * - * The PEAR_Autoloader class provides autoloading and aggregation. - * The autoloading lets you set up in which classes the separated - * methods are found. Aggregation is the technique used to import new - * methods, an instance of each class providing separated methods is - * stored and called every time the aggregated method is called. - * - * @author Stig Sther Bakken - */ -class PEAR_Autoloader extends PEAR -{ - // {{{ properties - - /** - * Map of methods and classes where they are defined - * - * @var array - * - * @access private - */ - var $_autoload_map = array(); - - /** - * Map of methods and aggregate objects - * - * @var array - * - * @access private - */ - var $_method_map = array(); - - // }}} - // {{{ addAutoload() - - /** - * Add one or more autoload entries. - * - * @param string $method which method to autoload - * - * @param string $classname (optional) which class to find the method in. - * If the $method parameter is an array, this - * parameter may be omitted (and will be ignored - * if not), and the $method parameter will be - * treated as an associative array with method - * names as keys and class names as values. - * - * @return void - * - * @access public - */ - function addAutoload($method, $classname = null) - { - if (is_array($method)) { - array_walk($method, create_function('$a,&$b', '$b = strtolower($b);')); - $this->_autoload_map = array_merge($this->_autoload_map, $method); - } else { - $this->_autoload_map[strtolower($method)] = $classname; - } - } - - // }}} - // {{{ removeAutoload() - - /** - * Remove an autoload entry. - * - * @param string $method which method to remove the autoload entry for - * - * @return bool TRUE if an entry was removed, FALSE if not - * - * @access public - */ - function removeAutoload($method) - { - $method = strtolower($method); - $ok = isset($this->_autoload_map[$method]); - unset($this->_autoload_map[$method]); - return $ok; - } - - // }}} - // {{{ addAggregateObject() - - /** - * Add an aggregate object to this object. If the specified class - * is not defined, loading it will be attempted following PEAR's - * file naming scheme. All the methods in the class will be - * aggregated, except private ones (name starting with an - * underscore) and constructors. - * - * @param string $classname what class to instantiate for the object. - * - * @return void - * - * @access public - */ - function addAggregateObject($classname) - { - $classname = strtolower($classname); - if (!class_exists($classname)) { - $include_file = preg_replace('/[^a-z0-9]/i', '_', $classname); - include_once $include_file; - } - $obj =& new $classname; - $methods = get_class_methods($classname); - foreach ($methods as $method) { - // don't import priviate methods and constructors - if ($method{0} != '_' && $method != $classname) { - $this->_method_map[$method] = $obj; - } - } - } - - // }}} - // {{{ removeAggregateObject() - - /** - * Remove an aggregate object. - * - * @param string $classname the class of the object to remove - * - * @return bool TRUE if an object was removed, FALSE if not - * - * @access public - */ - function removeAggregateObject($classname) - { - $ok = false; - $classname = strtolower($classname); - reset($this->_method_map); - while (list($method, $obj) = each($this->_method_map)) { - if (is_a($obj, $classname)) { - unset($this->_method_map[$method]); - $ok = true; - } - } - return $ok; - } - - // }}} - // {{{ __call() - - /** - * Overloaded object call handler, called each time an - * undefined/aggregated method is invoked. This method repeats - * the call in the right aggregate object and passes on the return - * value. - * - * @param string $method which method that was called - * - * @param string $args An array of the parameters passed in the - * original call - * - * @return mixed The return value from the aggregated method, or a PEAR - * error if the called method was unknown. - */ - function __call($method, $args, &$retval) - { - $method = strtolower($method); - if (empty($this->_method_map[$method]) && isset($this->_autoload_map[$method])) { - $this->addAggregateObject($this->_autoload_map[$method]); - } - if (isset($this->_method_map[$method])) { - $retval = call_user_func_array(array($this->_method_map[$method], $method), $args); - return true; - } - return false; - } - - // }}} -} - -overload("PEAR_Autoloader"); - -?> diff --git a/3rdparty/PEAR/Builder.php b/3rdparty/PEAR/Builder.php deleted file mode 100644 index 4f6cc135d1..0000000000 --- a/3rdparty/PEAR/Builder.php +++ /dev/null @@ -1,426 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Builder.php,v 1.16.2.3 2005/02/17 17:55:01 cellog Exp $ - -require_once 'PEAR/Common.php'; - -/** - * Class to handle building (compiling) extensions. - * - * @author Stig Sther Bakken - */ -class PEAR_Builder extends PEAR_Common -{ - // {{{ properties - - var $php_api_version = 0; - var $zend_module_api_no = 0; - var $zend_extension_api_no = 0; - - var $extensions_built = array(); - - var $current_callback = null; - - // used for msdev builds - var $_lastline = null; - var $_firstline = null; - // }}} - // {{{ constructor - - /** - * PEAR_Builder constructor. - * - * @param object $ui user interface object (instance of PEAR_Frontend_*) - * - * @access public - */ - function PEAR_Builder(&$ui) - { - parent::PEAR_Common(); - $this->setFrontendObject($ui); - } - - // }}} - - // {{{ _build_win32() - - /** - * Build an extension from source on windows. - * requires msdev - */ - function _build_win32($descfile, $callback = null) - { - if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) { - return $info; - } - $dir = dirname($descfile); - $old_cwd = getcwd(); - - if (!@chdir($dir)) { - return $this->raiseError("could not chdir to $dir"); - } - $this->log(2, "building in $dir"); - - $dsp = $info['package'].'.dsp'; - if (!@is_file("$dir/$dsp")) { - return $this->raiseError("The DSP $dsp does not exist."); - } - // XXX TODO: make release build type configurable - $command = 'msdev '.$dsp.' /MAKE "'.$info['package']. ' - Release"'; - - $this->current_callback = $callback; - $err = $this->_runCommand($command, array(&$this, 'msdevCallback')); - if (PEAR::isError($err)) { - return $err; - } - - // figure out the build platform and type - $platform = 'Win32'; - $buildtype = 'Release'; - if (preg_match('/.*?'.$info['package'].'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) { - $platform = $matches[1]; - $buildtype = $matches[2]; - } - - if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/',$this->_lastline,$matches)) { - if ($matches[2]) { - // there were errors in the build - return $this->raiseError("There were errors during compilation."); - } - $out = $matches[1]; - } else { - return $this->raiseError("Did not understand the completion status returned from msdev.exe."); - } - - // msdev doesn't tell us the output directory :/ - // open the dsp, find /out and use that directory - $dsptext = join(file($dsp),''); - - // this regex depends on the build platform and type having been - // correctly identified above. - $regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'. - $info['package'].'\s-\s'. - $platform.'\s'. - $buildtype.'").*?'. - '\/out:"(.*?)"/is'; - - if ($dsptext && preg_match($regex,$dsptext,$matches)) { - // what we get back is a relative path to the output file itself. - $outfile = realpath($matches[2]); - } else { - return $this->raiseError("Could not retrieve output information from $dsp."); - } - if (@copy($outfile, "$dir/$out")) { - $outfile = "$dir/$out"; - } - - $built_files[] = array( - 'file' => "$outfile", - 'php_api' => $this->php_api_version, - 'zend_mod_api' => $this->zend_module_api_no, - 'zend_ext_api' => $this->zend_extension_api_no, - ); - - return $built_files; - } - // }}} - - // {{{ msdevCallback() - function msdevCallback($what, $data) - { - if (!$this->_firstline) - $this->_firstline = $data; - $this->_lastline = $data; - } - // }}} - - // {{{ _harventInstDir - /** - * @param string - * @param string - * @param array - * @access private - */ - function _harvestInstDir($dest_prefix, $dirname, &$built_files) - { - $d = opendir($dirname); - if (!$d) - return false; - - $ret = true; - while (($ent = readdir($d)) !== false) { - if ($ent{0} == '.') - continue; - - $full = $dirname . DIRECTORY_SEPARATOR . $ent; - if (is_dir($full)) { - if (!$this->_harvestInstDir( - $dest_prefix . DIRECTORY_SEPARATOR . $ent, - $full, $built_files)) { - $ret = false; - break; - } - } else { - $dest = $dest_prefix . DIRECTORY_SEPARATOR . $ent; - $built_files[] = array( - 'file' => $full, - 'dest' => $dest, - 'php_api' => $this->php_api_version, - 'zend_mod_api' => $this->zend_module_api_no, - 'zend_ext_api' => $this->zend_extension_api_no, - ); - } - } - closedir($d); - return $ret; - } - - // }}} - - // {{{ build() - - /** - * Build an extension from source. Runs "phpize" in the source - * directory, but compiles in a temporary directory - * (/var/tmp/pear-build-USER/PACKAGE-VERSION). - * - * @param string $descfile path to XML package description file - * - * @param mixed $callback callback function used to report output, - * see PEAR_Builder::_runCommand for details - * - * @return array an array of associative arrays with built files, - * format: - * array( array( 'file' => '/path/to/ext.so', - * 'php_api' => YYYYMMDD, - * 'zend_mod_api' => YYYYMMDD, - * 'zend_ext_api' => YYYYMMDD ), - * ... ) - * - * @access public - * - * @see PEAR_Builder::_runCommand - * @see PEAR_Common::infoFromDescriptionFile - */ - function build($descfile, $callback = null) - { - if (PEAR_OS == "Windows") { - return $this->_build_win32($descfile,$callback); - } - if (PEAR_OS != 'Unix') { - return $this->raiseError("building extensions not supported on this platform"); - } - if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) { - return $info; - } - $dir = dirname($descfile); - $old_cwd = getcwd(); - if (!@chdir($dir)) { - return $this->raiseError("could not chdir to $dir"); - } - $vdir = "$info[package]-$info[version]"; - if (is_dir($vdir)) { - chdir($vdir); - } - $dir = getcwd(); - $this->log(2, "building in $dir"); - $this->current_callback = $callback; - putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH')); - $err = $this->_runCommand("phpize", array(&$this, 'phpizeCallback')); - if (PEAR::isError($err)) { - return $err; - } - if (!$err) { - return $this->raiseError("`phpize' failed"); - } - - // {{{ start of interactive part - $configure_command = "$dir/configure"; - if (isset($info['configure_options'])) { - foreach ($info['configure_options'] as $o) { - list($r) = $this->ui->userDialog('build', - array($o['prompt']), - array('text'), - array(@$o['default'])); - if (substr($o['name'], 0, 5) == 'with-' && - ($r == 'yes' || $r == 'autodetect')) { - $configure_command .= " --$o[name]"; - } else { - $configure_command .= " --$o[name]=".trim($r); - } - } - } - // }}} end of interactive part - - // FIXME make configurable - if(!$user=getenv('USER')){ - $user='defaultuser'; - } - $build_basedir = "/var/tmp/pear-build-$user"; - $build_dir = "$build_basedir/$info[package]-$info[version]"; - $inst_dir = "$build_basedir/install-$info[package]-$info[version]"; - $this->log(1, "building in $build_dir"); - if (is_dir($build_dir)) { - System::rm('-rf', $build_dir); - } - if (!System::mkDir(array('-p', $build_dir))) { - return $this->raiseError("could not create build dir: $build_dir"); - } - $this->addTempFile($build_dir); - if (!System::mkDir(array('-p', $inst_dir))) { - return $this->raiseError("could not create temporary install dir: $inst_dir"); - } - $this->addTempFile($inst_dir); - - if (getenv('MAKE')) { - $make_command = getenv('MAKE'); - } else { - $make_command = 'make'; - } - $to_run = array( - $configure_command, - $make_command, - "$make_command INSTALL_ROOT=\"$inst_dir\" install", - "find \"$inst_dir\" -ls" - ); - if (!@chdir($build_dir)) { - return $this->raiseError("could not chdir to $build_dir"); - } - putenv('PHP_PEAR_VERSION=@PEAR-VER@'); - foreach ($to_run as $cmd) { - $err = $this->_runCommand($cmd, $callback); - if (PEAR::isError($err)) { - chdir($old_cwd); - return $err; - } - if (!$err) { - chdir($old_cwd); - return $this->raiseError("`$cmd' failed"); - } - } - if (!($dp = opendir("modules"))) { - chdir($old_cwd); - return $this->raiseError("no `modules' directory found"); - } - $built_files = array(); - $prefix = exec("php-config --prefix"); - $this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files); - chdir($old_cwd); - return $built_files; - } - - // }}} - // {{{ phpizeCallback() - - /** - * Message callback function used when running the "phpize" - * program. Extracts the API numbers used. Ignores other message - * types than "cmdoutput". - * - * @param string $what the type of message - * @param mixed $data the message - * - * @return void - * - * @access public - */ - function phpizeCallback($what, $data) - { - if ($what != 'cmdoutput') { - return; - } - $this->log(1, rtrim($data)); - if (preg_match('/You should update your .aclocal.m4/', $data)) { - return; - } - $matches = array(); - if (preg_match('/^\s+(\S[^:]+):\s+(\d{8})/', $data, $matches)) { - $member = preg_replace('/[^a-z]/', '_', strtolower($matches[1])); - $apino = (int)$matches[2]; - if (isset($this->$member)) { - $this->$member = $apino; - //$msg = sprintf("%-22s : %d", $matches[1], $apino); - //$this->log(1, $msg); - } - } - } - - // }}} - // {{{ _runCommand() - - /** - * Run an external command, using a message callback to report - * output. The command will be run through popen and output is - * reported for every line with a "cmdoutput" message with the - * line string, including newlines, as payload. - * - * @param string $command the command to run - * - * @param mixed $callback (optional) function to use as message - * callback - * - * @return bool whether the command was successful (exit code 0 - * means success, any other means failure) - * - * @access private - */ - function _runCommand($command, $callback = null) - { - $this->log(1, "running: $command"); - $pp = @popen("$command 2>&1", "r"); - if (!$pp) { - return $this->raiseError("failed to run `$command'"); - } - if ($callback && $callback[0]->debug == 1) { - $olddbg = $callback[0]->debug; - $callback[0]->debug = 2; - } - - while ($line = fgets($pp, 1024)) { - if ($callback) { - call_user_func($callback, 'cmdoutput', $line); - } else { - $this->log(2, rtrim($line)); - } - } - if ($callback && isset($olddbg)) { - $callback[0]->debug = $olddbg; - } - $exitcode = @pclose($pp); - return ($exitcode == 0); - } - - // }}} - // {{{ log() - - function log($level, $msg) - { - if ($this->current_callback) { - if ($this->debug >= $level) { - call_user_func($this->current_callback, 'output', $msg); - } - return; - } - return PEAR_Common::log($level, $msg); - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command.php b/3rdparty/PEAR/Command.php deleted file mode 100644 index 2ea68743d2..0000000000 --- a/3rdparty/PEAR/Command.php +++ /dev/null @@ -1,398 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Command.php,v 1.24 2004/05/16 15:43:30 pajoye Exp $ - - -require_once "PEAR.php"; - -/** - * List of commands and what classes they are implemented in. - * @var array command => implementing class - */ -$GLOBALS['_PEAR_Command_commandlist'] = array(); - -/** - * List of shortcuts to common commands. - * @var array shortcut => command - */ -$GLOBALS['_PEAR_Command_shortcuts'] = array(); - -/** - * Array of command objects - * @var array class => object - */ -$GLOBALS['_PEAR_Command_objects'] = array(); - -/** - * Which user interface class is being used. - * @var string class name - */ -$GLOBALS['_PEAR_Command_uiclass'] = 'PEAR_Frontend_CLI'; - -/** - * Instance of $_PEAR_Command_uiclass. - * @var object - */ -$GLOBALS['_PEAR_Command_uiobject'] = null; - -/** - * PEAR command class, a simple factory class for administrative - * commands. - * - * How to implement command classes: - * - * - The class must be called PEAR_Command_Nnn, installed in the - * "PEAR/Common" subdir, with a method called getCommands() that - * returns an array of the commands implemented by the class (see - * PEAR/Command/Install.php for an example). - * - * - The class must implement a run() function that is called with three - * params: - * - * (string) command name - * (array) assoc array with options, freely defined by each - * command, for example: - * array('force' => true) - * (array) list of the other parameters - * - * The run() function returns a PEAR_CommandResponse object. Use - * these methods to get information: - * - * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL) - * *_PARTIAL means that you need to issue at least - * one more command to complete the operation - * (used for example for validation steps). - * - * string getMessage() Returns a message for the user. Remember, - * no HTML or other interface-specific markup. - * - * If something unexpected happens, run() returns a PEAR error. - * - * - DON'T OUTPUT ANYTHING! Return text for output instead. - * - * - DON'T USE HTML! The text you return will be used from both Gtk, - * web and command-line interfaces, so for now, keep everything to - * plain text. - * - * - DON'T USE EXIT OR DIE! Always use pear errors. From static - * classes do PEAR::raiseError(), from other classes do - * $this->raiseError(). - */ -class PEAR_Command -{ - // {{{ factory() - - /** - * Get the right object for executing a command. - * - * @param string $command The name of the command - * @param object $config Instance of PEAR_Config object - * - * @return object the command object or a PEAR error - * - * @access public - * @static - */ - function factory($command, &$config) - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { - $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; - } - if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { - return PEAR::raiseError("unknown command `$command'"); - } - $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; - if (!class_exists($class)) { - return PEAR::raiseError("unknown command `$command'"); - } - $ui =& PEAR_Command::getFrontendObject(); - $obj = &new $class($ui, $config); - return $obj; - } - - // }}} - // {{{ & getFrontendObject() - - /** - * Get instance of frontend object. - * - * @return object - * @static - */ - function &getFrontendObject() - { - if (empty($GLOBALS['_PEAR_Command_uiobject'])) { - $GLOBALS['_PEAR_Command_uiobject'] = &new $GLOBALS['_PEAR_Command_uiclass']; - } - return $GLOBALS['_PEAR_Command_uiobject']; - } - - // }}} - // {{{ & setFrontendClass() - - /** - * Load current frontend class. - * - * @param string $uiclass Name of class implementing the frontend - * - * @return object the frontend object, or a PEAR error - * @static - */ - function &setFrontendClass($uiclass) - { - if (is_object($GLOBALS['_PEAR_Command_uiobject']) && - is_a($GLOBALS['_PEAR_Command_uiobject'], $uiclass)) { - return $GLOBALS['_PEAR_Command_uiobject']; - } - if (!class_exists($uiclass)) { - $file = str_replace('_', '/', $uiclass) . '.php'; - if (PEAR_Command::isIncludeable($file)) { - include_once $file; - } - } - if (class_exists($uiclass)) { - $obj = &new $uiclass; - // quick test to see if this class implements a few of the most - // important frontend methods - if (method_exists($obj, 'userConfirm')) { - $GLOBALS['_PEAR_Command_uiobject'] = &$obj; - $GLOBALS['_PEAR_Command_uiclass'] = $uiclass; - return $obj; - } else { - $err = PEAR::raiseError("not a frontend class: $uiclass"); - return $err; - } - } - $err = PEAR::raiseError("no such class: $uiclass"); - return $err; - } - - // }}} - // {{{ setFrontendType() - - // }}} - // {{{ isIncludeable() - - /** - * @param string $path relative or absolute include path - * @return boolean - * @static - */ - function isIncludeable($path) - { - if (file_exists($path) && is_readable($path)) { - return true; - } - $ipath = explode(PATH_SEPARATOR, ini_get('include_path')); - foreach ($ipath as $include) { - $test = realpath($include . DIRECTORY_SEPARATOR . $path); - if (file_exists($test) && is_readable($test)) { - return true; - } - } - return false; - } - - /** - * Set current frontend. - * - * @param string $uitype Name of the frontend type (for example "CLI") - * - * @return object the frontend object, or a PEAR error - * @static - */ - function setFrontendType($uitype) - { - $uiclass = 'PEAR_Frontend_' . $uitype; - return PEAR_Command::setFrontendClass($uiclass); - } - - // }}} - // {{{ registerCommands() - - /** - * Scan through the Command directory looking for classes - * and see what commands they implement. - * - * @param bool (optional) if FALSE (default), the new list of - * commands should replace the current one. If TRUE, - * new entries will be merged with old. - * - * @param string (optional) where (what directory) to look for - * classes, defaults to the Command subdirectory of - * the directory from where this file (__FILE__) is - * included. - * - * @return bool TRUE on success, a PEAR error on failure - * - * @access public - * @static - */ - function registerCommands($merge = false, $dir = null) - { - if ($dir === null) { - $dir = dirname(__FILE__) . '/Command'; - } - $dp = @opendir($dir); - if (empty($dp)) { - return PEAR::raiseError("registerCommands: opendir($dir) failed"); - } - if (!$merge) { - $GLOBALS['_PEAR_Command_commandlist'] = array(); - } - while ($entry = readdir($dp)) { - if ($entry{0} == '.' || substr($entry, -4) != '.php' || $entry == 'Common.php') { - continue; - } - $class = "PEAR_Command_".substr($entry, 0, -4); - $file = "$dir/$entry"; - include_once $file; - // List of commands - if (empty($GLOBALS['_PEAR_Command_objects'][$class])) { - $GLOBALS['_PEAR_Command_objects'][$class] = &new $class($ui, $config); - } - $implements = $GLOBALS['_PEAR_Command_objects'][$class]->getCommands(); - foreach ($implements as $command => $desc) { - $GLOBALS['_PEAR_Command_commandlist'][$command] = $class; - $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc; - } - $shortcuts = $GLOBALS['_PEAR_Command_objects'][$class]->getShortcuts(); - foreach ($shortcuts as $shortcut => $command) { - $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command; - } - } - @closedir($dp); - return true; - } - - // }}} - // {{{ getCommands() - - /** - * Get the list of currently supported commands, and what - * classes implement them. - * - * @return array command => implementing class - * - * @access public - * @static - */ - function getCommands() - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - return $GLOBALS['_PEAR_Command_commandlist']; - } - - // }}} - // {{{ getShortcuts() - - /** - * Get the list of command shortcuts. - * - * @return array shortcut => command - * - * @access public - * @static - */ - function getShortcuts() - { - if (empty($GLOBALS['_PEAR_Command_shortcuts'])) { - PEAR_Command::registerCommands(); - } - return $GLOBALS['_PEAR_Command_shortcuts']; - } - - // }}} - // {{{ getGetoptArgs() - - /** - * Compiles arguments for getopt. - * - * @param string $command command to get optstring for - * @param string $short_args (reference) short getopt format - * @param array $long_args (reference) long getopt format - * - * @return void - * - * @access public - * @static - */ - function getGetoptArgs($command, &$short_args, &$long_args) - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { - return null; - } - $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; - $obj = &$GLOBALS['_PEAR_Command_objects'][$class]; - return $obj->getGetoptArgs($command, $short_args, $long_args); - } - - // }}} - // {{{ getDescription() - - /** - * Get description for a command. - * - * @param string $command Name of the command - * - * @return string command description - * - * @access public - * @static - */ - function getDescription($command) - { - if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) { - return null; - } - return $GLOBALS['_PEAR_Command_commanddesc'][$command]; - } - - // }}} - // {{{ getHelp() - - /** - * Get help for command. - * - * @param string $command Name of the command to return help for - * - * @access public - * @static - */ - function getHelp($command) - { - $cmds = PEAR_Command::getCommands(); - if (isset($cmds[$command])) { - $class = $cmds[$command]; - return $GLOBALS['_PEAR_Command_objects'][$class]->getHelp($command); - } - return false; - } - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Auth.php b/3rdparty/PEAR/Command/Auth.php deleted file mode 100644 index 0b9d3d3965..0000000000 --- a/3rdparty/PEAR/Command/Auth.php +++ /dev/null @@ -1,155 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Auth.php,v 1.15 2004/01/08 17:33:13 sniper Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Remote.php"; -require_once "PEAR/Config.php"; - -/** - * PEAR commands for managing configuration data. - * - */ -class PEAR_Command_Auth extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'login' => array( - 'summary' => 'Connects and authenticates to remote server', - 'shortcut' => 'li', - 'function' => 'doLogin', - 'options' => array(), - 'doc' => ' -Log in to the remote server. To use remote functions in the installer -that require any kind of privileges, you need to log in first. The -username and password you enter here will be stored in your per-user -PEAR configuration (~/.pearrc on Unix-like systems). After logging -in, your username and password will be sent along in subsequent -operations on the remote server.', - ), - 'logout' => array( - 'summary' => 'Logs out from the remote server', - 'shortcut' => 'lo', - 'function' => 'doLogout', - 'options' => array(), - 'doc' => ' -Logs out from the remote server. This command does not actually -connect to the remote server, it only deletes the stored username and -password from your user configuration.', - ) - - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Auth constructor. - * - * @access public - */ - function PEAR_Command_Auth(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doLogin() - - /** - * Execute the 'login' command. - * - * @param string $command command name - * - * @param array $options option_name => value - * - * @param array $params list of additional parameters - * - * @return bool TRUE on success, FALSE for unknown commands, or - * a PEAR error on failure - * - * @access public - */ - function doLogin($command, $options, $params) - { - $server = $this->config->get('master_server'); - $remote = new PEAR_Remote($this->config); - $username = $this->config->get('username'); - if (empty($username)) { - $username = @$_ENV['USER']; - } - $this->ui->outputData("Logging in to $server.", $command); - - list($username, $password) = $this->ui->userDialog( - $command, - array('Username', 'Password'), - array('text', 'password'), - array($username, '') - ); - $username = trim($username); - $password = trim($password); - - $this->config->set('username', $username); - $this->config->set('password', $password); - - $remote->expectError(401); - $ok = $remote->call('logintest'); - $remote->popExpect(); - if ($ok === true) { - $this->ui->outputData("Logged in.", $command); - $this->config->store(); - } else { - return $this->raiseError("Login failed!"); - } - - } - - // }}} - // {{{ doLogout() - - /** - * Execute the 'logout' command. - * - * @param string $command command name - * - * @param array $options option_name => value - * - * @param array $params list of additional parameters - * - * @return bool TRUE on success, FALSE for unknown commands, or - * a PEAR error on failure - * - * @access public - */ - function doLogout($command, $options, $params) - { - $server = $this->config->get('master_server'); - $this->ui->outputData("Logging out from $server.", $command); - $this->config->remove('username'); - $this->config->remove('password'); - $this->config->store(); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/PEAR/Command/Build.php b/3rdparty/PEAR/Command/Build.php deleted file mode 100644 index 2ecbbc92f5..0000000000 --- a/3rdparty/PEAR/Command/Build.php +++ /dev/null @@ -1,89 +0,0 @@ - | -// | Tomas V.V.Cox | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Build.php,v 1.9 2004/01/08 17:33:13 sniper Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Builder.php"; - -/** - * PEAR commands for building extensions. - * - */ -class PEAR_Command_Build extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'build' => array( - 'summary' => 'Build an Extension From C Source', - 'function' => 'doBuild', - 'shortcut' => 'b', - 'options' => array(), - 'doc' => '[package.xml] -Builds one or more extensions contained in a package.' - ), - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Build constructor. - * - * @access public - */ - function PEAR_Command_Build(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doBuild() - - function doBuild($command, $options, $params) - { - if (sizeof($params) < 1) { - $params[0] = 'package.xml'; - } - $builder = &new PEAR_Builder($this->ui); - $this->debug = $this->config->get('verbose'); - $err = $builder->build($params[0], array(&$this, 'buildCallback')); - if (PEAR::isError($err)) { - return $err; - } - return true; - } - - // }}} - // {{{ buildCallback() - - function buildCallback($what, $data) - { - if (($what == 'cmdoutput' && $this->debug > 1) || - ($what == 'output' && $this->debug > 0)) { - $this->ui->outputData(rtrim($data), 'build'); - } - } - - // }}} -} diff --git a/3rdparty/PEAR/Command/Common.php b/3rdparty/PEAR/Command/Common.php deleted file mode 100644 index c6ace694ca..0000000000 --- a/3rdparty/PEAR/Command/Common.php +++ /dev/null @@ -1,249 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.24 2004/01/08 17:33:13 sniper Exp $ - -require_once "PEAR.php"; - -class PEAR_Command_Common extends PEAR -{ - // {{{ properties - - /** - * PEAR_Config object used to pass user system and configuration - * on when executing commands - * - * @var object - */ - var $config; - - /** - * User Interface object, for all interaction with the user. - * @var object - */ - var $ui; - - var $_deps_rel_trans = array( - 'lt' => '<', - 'le' => '<=', - 'eq' => '=', - 'ne' => '!=', - 'gt' => '>', - 'ge' => '>=', - 'has' => '==' - ); - - var $_deps_type_trans = array( - 'pkg' => 'package', - 'extension' => 'extension', - 'php' => 'PHP', - 'prog' => 'external program', - 'ldlib' => 'external library for linking', - 'rtlib' => 'external runtime library', - 'os' => 'operating system', - 'websrv' => 'web server', - 'sapi' => 'SAPI backend' - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Common constructor. - * - * @access public - */ - function PEAR_Command_Common(&$ui, &$config) - { - parent::PEAR(); - $this->config = &$config; - $this->ui = &$ui; - } - - // }}} - - // {{{ getCommands() - - /** - * Return a list of all the commands defined by this class. - * @return array list of commands - * @access public - */ - function getCommands() - { - $ret = array(); - foreach (array_keys($this->commands) as $command) { - $ret[$command] = $this->commands[$command]['summary']; - } - return $ret; - } - - // }}} - // {{{ getShortcuts() - - /** - * Return a list of all the command shortcuts defined by this class. - * @return array shortcut => command - * @access public - */ - function getShortcuts() - { - $ret = array(); - foreach (array_keys($this->commands) as $command) { - if (isset($this->commands[$command]['shortcut'])) { - $ret[$this->commands[$command]['shortcut']] = $command; - } - } - return $ret; - } - - // }}} - // {{{ getOptions() - - function getOptions($command) - { - return @$this->commands[$command]['options']; - } - - // }}} - // {{{ getGetoptArgs() - - function getGetoptArgs($command, &$short_args, &$long_args) - { - $short_args = ""; - $long_args = array(); - if (empty($this->commands[$command])) { - return; - } - reset($this->commands[$command]); - while (list($option, $info) = each($this->commands[$command]['options'])) { - $larg = $sarg = ''; - if (isset($info['arg'])) { - if ($info['arg']{0} == '(') { - $larg = '=='; - $sarg = '::'; - $arg = substr($info['arg'], 1, -1); - } else { - $larg = '='; - $sarg = ':'; - $arg = $info['arg']; - } - } - if (isset($info['shortopt'])) { - $short_args .= $info['shortopt'] . $sarg; - } - $long_args[] = $option . $larg; - } - } - - // }}} - // {{{ getHelp() - /** - * Returns the help message for the given command - * - * @param string $command The command - * @return mixed A fail string if the command does not have help or - * a two elements array containing [0]=>help string, - * [1]=> help string for the accepted cmd args - */ - function getHelp($command) - { - $config = &PEAR_Config::singleton(); - $help = @$this->commands[$command]['doc']; - if (empty($help)) { - // XXX (cox) Fallback to summary if there is no doc (show both?) - if (!$help = @$this->commands[$command]['summary']) { - return "No help for command \"$command\""; - } - } - if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) { - foreach($matches[0] as $k => $v) { - $help = preg_replace("/$v/", $config->get($matches[1][$k]), $help); - } - } - return array($help, $this->getHelpArgs($command)); - } - - // }}} - // {{{ getHelpArgs() - /** - * Returns the help for the accepted arguments of a command - * - * @param string $command - * @return string The help string - */ - function getHelpArgs($command) - { - if (isset($this->commands[$command]['options']) && - count($this->commands[$command]['options'])) - { - $help = "Options:\n"; - foreach ($this->commands[$command]['options'] as $k => $v) { - if (isset($v['arg'])) { - if ($v['arg']{0} == '(') { - $arg = substr($v['arg'], 1, -1); - $sapp = " [$arg]"; - $lapp = "[=$arg]"; - } else { - $sapp = " $v[arg]"; - $lapp = "=$v[arg]"; - } - } else { - $sapp = $lapp = ""; - } - if (isset($v['shortopt'])) { - $s = $v['shortopt']; - @$help .= " -$s$sapp, --$k$lapp\n"; - } else { - @$help .= " --$k$lapp\n"; - } - $p = " "; - $doc = rtrim(str_replace("\n", "\n$p", $v['doc'])); - $help .= " $doc\n"; - } - return $help; - } - return null; - } - - // }}} - // {{{ run() - - function run($command, $options, $params) - { - $func = @$this->commands[$command]['function']; - if (empty($func)) { - // look for shortcuts - foreach (array_keys($this->commands) as $cmd) { - if (@$this->commands[$cmd]['shortcut'] == $command) { - $command = $cmd; - $func = @$this->commands[$command]['function']; - if (empty($func)) { - return $this->raiseError("unknown command `$command'"); - } - break; - } - } - } - return $this->$func($command, $options, $params); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/PEAR/Command/Config.php b/3rdparty/PEAR/Command/Config.php deleted file mode 100644 index 474a234517..0000000000 --- a/3rdparty/PEAR/Command/Config.php +++ /dev/null @@ -1,225 +0,0 @@ - | -// | Tomas V.V.Cox | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Config.php,v 1.27 2004/06/15 16:48:49 pajoye Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Config.php"; - -/** - * PEAR commands for managing configuration data. - * - */ -class PEAR_Command_Config extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'config-show' => array( - 'summary' => 'Show All Settings', - 'function' => 'doConfigShow', - 'shortcut' => 'csh', - 'options' => array(), - 'doc' => ' -Displays all configuration values. An optional argument -may be used to tell which configuration layer to display. Valid -configuration layers are "user", "system" and "default". -', - ), - 'config-get' => array( - 'summary' => 'Show One Setting', - 'function' => 'doConfigGet', - 'shortcut' => 'cg', - 'options' => array(), - 'doc' => ' [layer] -Displays the value of one configuration parameter. The -first argument is the name of the parameter, an optional second argument -may be used to tell which configuration layer to look in. Valid configuration -layers are "user", "system" and "default". If no layer is specified, a value -will be picked from the first layer that defines the parameter, in the order -just specified. -', - ), - 'config-set' => array( - 'summary' => 'Change Setting', - 'function' => 'doConfigSet', - 'shortcut' => 'cs', - 'options' => array(), - 'doc' => ' [layer] -Sets the value of one configuration parameter. The first argument is -the name of the parameter, the second argument is the new value. Some -parameters are subject to validation, and the command will fail with -an error message if the new value does not make sense. An optional -third argument may be used to specify in which layer to set the -configuration parameter. The default layer is "user". -', - ), - 'config-help' => array( - 'summary' => 'Show Information About Setting', - 'function' => 'doConfigHelp', - 'shortcut' => 'ch', - 'options' => array(), - 'doc' => '[parameter] -Displays help for a configuration parameter. Without arguments it -displays help for all configuration parameters. -', - ), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Config constructor. - * - * @access public - */ - function PEAR_Command_Config(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doConfigShow() - - function doConfigShow($command, $options, $params) - { - // $params[0] -> the layer - if ($error = $this->_checkLayer(@$params[0])) { - return $this->raiseError($error); - } - $keys = $this->config->getKeys(); - sort($keys); - $data = array('caption' => 'Configuration:'); - foreach ($keys as $key) { - $type = $this->config->getType($key); - $value = $this->config->get($key, @$params[0]); - if ($type == 'password' && $value) { - $value = '********'; - } - if ($value === false) { - $value = 'false'; - } elseif ($value === true) { - $value = 'true'; - } - $data['data'][$this->config->getGroup($key)][] = array($this->config->getPrompt($key) , $key, $value); - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doConfigGet() - - function doConfigGet($command, $options, $params) - { - // $params[0] -> the parameter - // $params[1] -> the layer - if ($error = $this->_checkLayer(@$params[1])) { - return $this->raiseError($error); - } - if (sizeof($params) < 1 || sizeof($params) > 2) { - return $this->raiseError("config-get expects 1 or 2 parameters"); - } elseif (sizeof($params) == 1) { - $this->ui->outputData($this->config->get($params[0]), $command); - } else { - $data = $this->config->get($params[0], $params[1]); - $this->ui->outputData($data, $command); - } - return true; - } - - // }}} - // {{{ doConfigSet() - - function doConfigSet($command, $options, $params) - { - // $param[0] -> a parameter to set - // $param[1] -> the value for the parameter - // $param[2] -> the layer - $failmsg = ''; - if (sizeof($params) < 2 || sizeof($params) > 3) { - $failmsg .= "config-set expects 2 or 3 parameters"; - return PEAR::raiseError($failmsg); - } - if ($error = $this->_checkLayer(@$params[2])) { - $failmsg .= $error; - return PEAR::raiseError($failmsg); - } - if (!call_user_func_array(array(&$this->config, 'set'), $params)) - { - $failmsg = "config-set (" . implode(", ", $params) . ") failed"; - } else { - $this->config->store(); - } - if ($failmsg) { - return $this->raiseError($failmsg); - } - return true; - } - - // }}} - // {{{ doConfigHelp() - - function doConfigHelp($command, $options, $params) - { - if (empty($params)) { - $params = $this->config->getKeys(); - } - $data['caption'] = "Config help" . ((count($params) == 1) ? " for $params[0]" : ''); - $data['headline'] = array('Name', 'Type', 'Description'); - $data['border'] = true; - foreach ($params as $name) { - $type = $this->config->getType($name); - $docs = $this->config->getDocs($name); - if ($type == 'set') { - $docs = rtrim($docs) . "\nValid set: " . - implode(' ', $this->config->getSetValues($name)); - } - $data['data'][] = array($name, $type, $docs); - } - $this->ui->outputData($data, $command); - } - - // }}} - // {{{ _checkLayer() - - /** - * Checks if a layer is defined or not - * - * @param string $layer The layer to search for - * @return mixed False on no error or the error message - */ - function _checkLayer($layer = null) - { - if (!empty($layer) && $layer != 'default') { - $layers = $this->config->getLayers(); - if (!in_array($layer, $layers)) { - return " only the layers: \"" . implode('" or "', $layers) . "\" are supported"; - } - } - return false; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Install.php b/3rdparty/PEAR/Command/Install.php deleted file mode 100644 index dce52f017e..0000000000 --- a/3rdparty/PEAR/Command/Install.php +++ /dev/null @@ -1,470 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Install.php,v 1.53.2.1 2004/10/19 04:08:42 cellog Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Installer.php"; - -/** - * PEAR commands for installation or deinstallation/upgrading of - * packages. - * - */ -class PEAR_Command_Install extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'install' => array( - 'summary' => 'Install Package', - 'function' => 'doInstall', - 'shortcut' => 'i', - 'options' => array( - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'will overwrite newer installed packages', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, install anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as installed', - ), - 'soft' => array( - 'shortopt' => 's', - 'doc' => 'soft install, fail silently, or upgrade if already installed', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'alldeps' => array( - 'shortopt' => 'a', - 'doc' => 'install all required and optional dependencies', - ), - 'onlyreqdeps' => array( - 'shortopt' => 'o', - 'doc' => 'install all required dependencies', - ), - ), - 'doc' => ' ... -Installs one or more PEAR packages. You can specify a package to -install in four ways: - -"Package-1.0.tgz" : installs from a local file - -"http://example.com/Package-1.0.tgz" : installs from -anywhere on the net. - -"package.xml" : installs the package described in -package.xml. Useful for testing, or for wrapping a PEAR package in -another package manager such as RPM. - -"Package" : queries your configured server -({config master_server}) and downloads the newest package with -the preferred quality/state ({config preferred_state}). - -More than one package may be specified at once. It is ok to mix these -four ways of specifying packages. -'), - 'upgrade' => array( - 'summary' => 'Upgrade Package', - 'function' => 'doInstall', - 'shortcut' => 'up', - 'options' => array( - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'overwrite newer installed packages', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'alldeps' => array( - 'shortopt' => 'a', - 'doc' => 'install all required and optional dependencies', - ), - 'onlyreqdeps' => array( - 'shortopt' => 'o', - 'doc' => 'install all required dependencies', - ), - ), - 'doc' => ' ... -Upgrades one or more PEAR packages. See documentation for the -"install" command for ways to specify a package. - -When upgrading, your package will be updated if the provided new -package has a higher version number (use the -f option if you need to -upgrade anyway). - -More than one package may be specified at once. -'), - 'upgrade-all' => array( - 'summary' => 'Upgrade All Packages', - 'function' => 'doInstall', - 'shortcut' => 'ua', - 'options' => array( - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => ' -Upgrades all packages that have a newer release available. Upgrades are -done only if there is a release available of the state specified in -"preferred_state" (currently {config preferred_state}), or a state considered -more stable. -'), - 'uninstall' => array( - 'summary' => 'Un-install Package', - 'function' => 'doUninstall', - 'shortcut' => 'un', - 'options' => array( - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, uninstall anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not remove files, only register the packages as not installed', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => ' ... -Uninstalls one or more PEAR packages. More than one package may be -specified at once. -'), - 'bundle' => array( - 'summary' => 'Unpacks a Pecl Package', - 'function' => 'doBundle', - 'shortcut' => 'bun', - 'options' => array( - 'destination' => array( - 'shortopt' => 'd', - 'arg' => 'DIR', - 'doc' => 'Optional destination directory for unpacking (defaults to current path or "ext" if exists)', - ), - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'Force the unpacking even if there were errors in the package', - ), - ), - 'doc' => ' -Unpacks a Pecl Package into the selected location. It will download the -package if needed. -'), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Install constructor. - * - * @access public - */ - function PEAR_Command_Install(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doInstall() - - function doInstall($command, $options, $params) - { - require_once 'PEAR/Downloader.php'; - if (empty($this->installer)) { - $this->installer = &new PEAR_Installer($this->ui); - } - if ($command == 'upgrade') { - $options['upgrade'] = true; - } - if ($command == 'upgrade-all') { - include_once "PEAR/Remote.php"; - $options['upgrade'] = true; - $remote = &new PEAR_Remote($this->config); - $state = $this->config->get('preferred_state'); - if (empty($state) || $state == 'any') { - $latest = $remote->call("package.listLatestReleases"); - } else { - $latest = $remote->call("package.listLatestReleases", $state); - } - if (PEAR::isError($latest)) { - return $latest; - } - $reg = new PEAR_Registry($this->config->get('php_dir')); - $installed = array_flip($reg->listPackages()); - $params = array(); - foreach ($latest as $package => $info) { - $package = strtolower($package); - if (!isset($installed[$package])) { - // skip packages we don't have installed - continue; - } - $inst_version = $reg->packageInfo($package, 'version'); - if (version_compare("$info[version]", "$inst_version", "le")) { - // installed version is up-to-date - continue; - } - $params[] = $package; - $this->ui->outputData(array('data' => "Will upgrade $package"), $command); - } - } - $this->downloader = &new PEAR_Downloader($this->ui, $options, $this->config); - $errors = array(); - $downloaded = array(); - $this->downloader->download($params); - $errors = $this->downloader->getErrorMsgs(); - if (count($errors)) { - $err['data'] = array($errors); - $err['headline'] = 'Install Errors'; - $this->ui->outputData($err); - return $this->raiseError("$command failed"); - } - $downloaded = $this->downloader->getDownloadedPackages(); - $this->installer->sortPkgDeps($downloaded); - foreach ($downloaded as $pkg) { - PEAR::pushErrorHandling(PEAR_ERROR_RETURN); - $info = $this->installer->install($pkg['file'], $options, $this->config); - PEAR::popErrorHandling(); - if (PEAR::isError($info)) { - $this->ui->outputData('ERROR: ' .$info->getMessage()); - continue; - } - if (is_array($info)) { - if ($this->config->get('verbose') > 0) { - $label = "$info[package] $info[version]"; - $out = array('data' => "$command ok: $label"); - if (isset($info['release_warnings'])) { - $out['release_warnings'] = $info['release_warnings']; - } - $this->ui->outputData($out, $command); - } - } else { - return $this->raiseError("$command failed"); - } - } - return true; - } - - // }}} - // {{{ doUninstall() - - function doUninstall($command, $options, $params) - { - if (empty($this->installer)) { - $this->installer = &new PEAR_Installer($this->ui); - } - if (sizeof($params) < 1) { - return $this->raiseError("Please supply the package(s) you want to uninstall"); - } - include_once 'PEAR/Registry.php'; - $reg = new PEAR_Registry($this->config->get('php_dir')); - $newparams = array(); - $badparams = array(); - foreach ($params as $pkg) { - $info = $reg->packageInfo($pkg); - if ($info === null) { - $badparams[] = $pkg; - } else { - $newparams[] = $info; - } - } - $this->installer->sortPkgDeps($newparams, true); - $params = array(); - foreach($newparams as $info) { - $params[] = $info['info']['package']; - } - $params = array_merge($params, $badparams); - foreach ($params as $pkg) { - if ($this->installer->uninstall($pkg, $options)) { - if ($this->config->get('verbose') > 0) { - $this->ui->outputData("uninstall ok: $pkg", $command); - } - } else { - return $this->raiseError("uninstall failed: $pkg"); - } - } - return true; - } - - // }}} - - - // }}} - // {{{ doBundle() - /* - (cox) It just downloads and untars the package, does not do - any check that the PEAR_Installer::_installFile() does. - */ - - function doBundle($command, $options, $params) - { - if (empty($this->installer)) { - $this->installer = &new PEAR_Downloader($this->ui); - } - $installer = &$this->installer; - if (sizeof($params) < 1) { - return $this->raiseError("Please supply the package you want to bundle"); - } - $pkgfile = $params[0]; - $need_download = false; - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - $need_download = true; - } elseif (!@is_file($pkgfile)) { - if ($installer->validPackageName($pkgfile)) { - $pkgfile = $installer->getPackageDownloadUrl($pkgfile); - $need_download = true; - } else { - if (strlen($pkgfile)) { - return $this->raiseError("Could not open the package file: $pkgfile"); - } else { - return $this->raiseError("No package file given"); - } - } - } - - // Download package ----------------------------------------------- - if ($need_download) { - $downloaddir = $installer->config->get('download_dir'); - if (empty($downloaddir)) { - if (PEAR::isError($downloaddir = System::mktemp('-d'))) { - return $downloaddir; - } - $installer->log(2, '+ tmp dir created at ' . $downloaddir); - } - $callback = $this->ui ? array(&$installer, '_downloadCallback') : null; - $file = $installer->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback); - if (PEAR::isError($file)) { - return $this->raiseError($file); - } - $pkgfile = $file; - } - - // Parse xml file ----------------------------------------------- - $pkginfo = $installer->infoFromTgzFile($pkgfile); - if (PEAR::isError($pkginfo)) { - return $this->raiseError($pkginfo); - } - $installer->validatePackageInfo($pkginfo, $errors, $warnings); - // XXX We allow warnings, do we have to do it? - if (count($errors)) { - if (empty($options['force'])) { - return $this->raiseError("The following errors where found:\n". - implode("\n", $errors)); - } else { - $this->log(0, "warning : the following errors were found:\n". - implode("\n", $errors)); - } - } - $pkgname = $pkginfo['package']; - - // Unpacking ------------------------------------------------- - - if (isset($options['destination'])) { - if (!is_dir($options['destination'])) { - System::mkdir('-p ' . $options['destination']); - } - $dest = realpath($options['destination']); - } else { - $pwd = getcwd(); - if (is_dir($pwd . DIRECTORY_SEPARATOR . 'ext')) { - $dest = $pwd . DIRECTORY_SEPARATOR . 'ext'; - } else { - $dest = $pwd; - } - } - $dest .= DIRECTORY_SEPARATOR . $pkgname; - $orig = $pkgname . '-' . $pkginfo['version']; - - $tar = new Archive_Tar($pkgfile); - if (!@$tar->extractModify($dest, $orig)) { - return $this->raiseError("unable to unpack $pkgfile"); - } - $this->ui->outputData("Package ready at '$dest'"); - // }}} - } - - // }}} - -} -?> diff --git a/3rdparty/PEAR/Command/Mirror.php b/3rdparty/PEAR/Command/Mirror.php deleted file mode 100644 index bf56c3db64..0000000000 --- a/3rdparty/PEAR/Command/Mirror.php +++ /dev/null @@ -1,101 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Mirror.php,v 1.5 2004/03/18 12:23:57 mj Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Command.php"; -require_once "PEAR/Remote.php"; -require_once "PEAR.php"; - -/** - * PEAR commands for providing file mirrors - * - */ -class PEAR_Command_Mirror extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'download-all' => array( - 'summary' => 'Downloads each available package from master_server', - 'function' => 'doDownloadAll', - 'shortcut' => 'da', - 'options' => array(), - 'doc' => ' - Requests a list of available packages from the package server - (master_server) and downloads them to current working directory' - ), - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Mirror constructor. - * - * @access public - * @param object PEAR_Frontend a reference to an frontend - * @param object PEAR_Config a reference to the configuration data - */ - function PEAR_Command_Mirror(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doDownloadAll() - /** - * retrieves a list of avaible Packages from master server - * and downloads them - * - * @access public - * @param string $command the command - * @param array $options the command options before the command - * @param array $params the stuff after the command name - * @return bool true if succesful - * @throw PEAR_Error - */ - function doDownloadAll($command, $options, $params) - { - $this->config->set("php_dir", "."); - $remote = &new PEAR_Remote($this->config); - $remoteInfo = $remote->call("package.listAll"); - if (PEAR::isError($remoteInfo)) { - return $remoteInfo; - } - $cmd = &PEAR_Command::factory("download", $this->config); - if (PEAR::isError($cmd)) { - return $cmd; - } - foreach ($remoteInfo as $pkgn => $pkg) { - /** - * Error handling not neccesary, because already done by - * the download command - */ - $cmd->run("download", array(), array($pkgn)); - } - - return true; - } - - // }}} -} diff --git a/3rdparty/PEAR/Command/Package.php b/3rdparty/PEAR/Command/Package.php deleted file mode 100644 index aca8711111..0000000000 --- a/3rdparty/PEAR/Command/Package.php +++ /dev/null @@ -1,819 +0,0 @@ - | -// | Martin Jansen | -// | Greg Beaver | -// +----------------------------------------------------------------------+ -// -// $Id: Package.php,v 1.61.2.7 2005/02/17 17:47:55 cellog Exp $ - -require_once 'PEAR/Common.php'; -require_once 'PEAR/Command/Common.php'; - -class PEAR_Command_Package extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'package' => array( - 'summary' => 'Build Package', - 'function' => 'doPackage', - 'shortcut' => 'p', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'Do not gzip the package file' - ), - 'showname' => array( - 'shortopt' => 'n', - 'doc' => 'Print the name of the packaged file.', - ), - ), - 'doc' => '[descfile] -Creates a PEAR package from its description file (usually called -package.xml). -' - ), - 'package-validate' => array( - 'summary' => 'Validate Package Consistency', - 'function' => 'doPackageValidate', - 'shortcut' => 'pv', - 'options' => array(), - 'doc' => ' -', - ), - 'cvsdiff' => array( - 'summary' => 'Run a "cvs diff" for all files in a package', - 'function' => 'doCvsDiff', - 'shortcut' => 'cd', - 'options' => array( - 'quiet' => array( - 'shortopt' => 'q', - 'doc' => 'Be quiet', - ), - 'reallyquiet' => array( - 'shortopt' => 'Q', - 'doc' => 'Be really quiet', - ), - 'date' => array( - 'shortopt' => 'D', - 'doc' => 'Diff against revision of DATE', - 'arg' => 'DATE', - ), - 'release' => array( - 'shortopt' => 'R', - 'doc' => 'Diff against tag for package release REL', - 'arg' => 'REL', - ), - 'revision' => array( - 'shortopt' => 'r', - 'doc' => 'Diff against revision REV', - 'arg' => 'REV', - ), - 'context' => array( - 'shortopt' => 'c', - 'doc' => 'Generate context diff', - ), - 'unified' => array( - 'shortopt' => 'u', - 'doc' => 'Generate unified diff', - ), - 'ignore-case' => array( - 'shortopt' => 'i', - 'doc' => 'Ignore case, consider upper- and lower-case letters equivalent', - ), - 'ignore-whitespace' => array( - 'shortopt' => 'b', - 'doc' => 'Ignore changes in amount of white space', - ), - 'ignore-blank-lines' => array( - 'shortopt' => 'B', - 'doc' => 'Ignore changes that insert or delete blank lines', - ), - 'brief' => array( - 'doc' => 'Report only whether the files differ, no details', - ), - 'dry-run' => array( - 'shortopt' => 'n', - 'doc' => 'Don\'t do anything, just pretend', - ), - ), - 'doc' => ' -Compares all the files in a package. Without any options, this -command will compare the current code with the last checked-in code. -Using the -r or -R option you may compare the current code with that -of a specific release. -', - ), - 'cvstag' => array( - 'summary' => 'Set CVS Release Tag', - 'function' => 'doCvsTag', - 'shortcut' => 'ct', - 'options' => array( - 'quiet' => array( - 'shortopt' => 'q', - 'doc' => 'Be quiet', - ), - 'reallyquiet' => array( - 'shortopt' => 'Q', - 'doc' => 'Be really quiet', - ), - 'slide' => array( - 'shortopt' => 'F', - 'doc' => 'Move (slide) tag if it exists', - ), - 'delete' => array( - 'shortopt' => 'd', - 'doc' => 'Remove tag', - ), - 'dry-run' => array( - 'shortopt' => 'n', - 'doc' => 'Don\'t do anything, just pretend', - ), - ), - 'doc' => ' -Sets a CVS tag on all files in a package. Use this command after you have -packaged a distribution tarball with the "package" command to tag what -revisions of what files were in that release. If need to fix something -after running cvstag once, but before the tarball is released to the public, -use the "slide" option to move the release tag. -', - ), - 'run-tests' => array( - 'summary' => 'Run Regression Tests', - 'function' => 'doRunTests', - 'shortcut' => 'rt', - 'options' => array( - 'recur' => array( - 'shortopt' => 'r', - 'doc' => 'Run tests in child directories, recursively. 4 dirs deep maximum', - ), - 'ini' => array( - 'shortopt' => 'i', - 'doc' => 'actual string of settings to pass to php in format " -d setting=blah"', - 'arg' => 'SETTINGS' - ), - 'realtimelog' => array( - 'shortopt' => 'l', - 'doc' => 'Log test runs/results as they are run', - ), - ), - 'doc' => '[testfile|dir ...] -Run regression tests with PHP\'s regression testing script (run-tests.php).', - ), - 'package-dependencies' => array( - 'summary' => 'Show package dependencies', - 'function' => 'doPackageDependencies', - 'shortcut' => 'pd', - 'options' => array(), - 'doc' => ' -List all depencies the package has.' - ), - 'sign' => array( - 'summary' => 'Sign a package distribution file', - 'function' => 'doSign', - 'shortcut' => 'si', - 'options' => array(), - 'doc' => ' -Signs a package distribution (.tar or .tgz) file with GnuPG.', - ), - 'makerpm' => array( - 'summary' => 'Builds an RPM spec file from a PEAR package', - 'function' => 'doMakeRPM', - 'shortcut' => 'rpm', - 'options' => array( - 'spec-template' => array( - 'shortopt' => 't', - 'arg' => 'FILE', - 'doc' => 'Use FILE as RPM spec file template' - ), - 'rpm-pkgname' => array( - 'shortopt' => 'p', - 'arg' => 'FORMAT', - 'doc' => 'Use FORMAT as format string for RPM package name, %s is replaced -by the PEAR package name, defaults to "PEAR::%s".', - ), - ), - 'doc' => ' - -Creates an RPM .spec file for wrapping a PEAR package inside an RPM -package. Intended to be used from the SPECS directory, with the PEAR -package tarball in the SOURCES directory: - -$ pear makerpm ../SOURCES/Net_Socket-1.0.tgz -Wrote RPM spec file PEAR::Net_Geo-1.0.spec -$ rpm -bb PEAR::Net_Socket-1.0.spec -... -Wrote: /usr/src/redhat/RPMS/i386/PEAR::Net_Socket-1.0-1.i386.rpm -', - ), - ); - - var $output; - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Package constructor. - * - * @access public - */ - function PEAR_Command_Package(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ _displayValidationResults() - - function _displayValidationResults($err, $warn, $strict = false) - { - foreach ($err as $e) { - $this->output .= "Error: $e\n"; - } - foreach ($warn as $w) { - $this->output .= "Warning: $w\n"; - } - $this->output .= sprintf('Validation: %d error(s), %d warning(s)'."\n", - sizeof($err), sizeof($warn)); - if ($strict && sizeof($err) > 0) { - $this->output .= "Fix these errors and try again."; - return false; - } - return true; - } - - // }}} - // {{{ doPackage() - - function doPackage($command, $options, $params) - { - $this->output = ''; - include_once 'PEAR/Packager.php'; - if (sizeof($params) < 1) { - $params[0] = "package.xml"; - } - $pkginfofile = isset($params[0]) ? $params[0] : 'package.xml'; - $packager =& new PEAR_Packager(); - $err = $warn = array(); - $dir = dirname($pkginfofile); - $compress = empty($options['nocompress']) ? true : false; - $result = $packager->package($pkginfofile, $compress); - if (PEAR::isError($result)) { - $this->ui->outputData($this->output, $command); - return $this->raiseError($result); - } - // Don't want output, only the package file name just created - if (isset($options['showname'])) { - $this->output = $result; - } - if (PEAR::isError($result)) { - $this->output .= "Package failed: ".$result->getMessage(); - } - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doPackageValidate() - - function doPackageValidate($command, $options, $params) - { - $this->output = ''; - if (sizeof($params) < 1) { - $params[0] = "package.xml"; - } - $obj = new PEAR_Common; - $info = null; - if ($fp = @fopen($params[0], "r")) { - $test = fread($fp, 5); - fclose($fp); - if ($test == "infoFromDescriptionFile($params[0]); - } - } - if (empty($info)) { - $info = $obj->infoFromTgzFile($params[0]); - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $obj->validatePackageInfo($info, $err, $warn); - $this->_displayValidationResults($err, $warn); - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doCvsTag() - - function doCvsTag($command, $options, $params) - { - $this->output = ''; - $_cmd = $command; - if (sizeof($params) < 1) { - $help = $this->getHelp($command); - return $this->raiseError("$command: missing parameter: $help[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromDescriptionFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $err = $warn = array(); - $obj->validatePackageInfo($info, $err, $warn); - if (!$this->_displayValidationResults($err, $warn, true)) { - $this->ui->outputData($this->output, $command); - break; - } - $version = $info['version']; - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $version); - $cvstag = "RELEASE_$cvsversion"; - $files = array_keys($info['filelist']); - $command = "cvs"; - if (isset($options['quiet'])) { - $command .= ' -q'; - } - if (isset($options['reallyquiet'])) { - $command .= ' -Q'; - } - $command .= ' tag'; - if (isset($options['slide'])) { - $command .= ' -F'; - } - if (isset($options['delete'])) { - $command .= ' -d'; - } - $command .= ' ' . $cvstag . ' ' . escapeshellarg($params[0]); - foreach ($files as $file) { - $command .= ' ' . escapeshellarg($file); - } - if ($this->config->get('verbose') > 1) { - $this->output .= "+ $command\n"; - } - $this->output .= "+ $command\n"; - if (empty($options['dry-run'])) { - $fp = popen($command, "r"); - while ($line = fgets($fp, 1024)) { - $this->output .= rtrim($line)."\n"; - } - pclose($fp); - } - $this->ui->outputData($this->output, $_cmd); - return true; - } - - // }}} - // {{{ doCvsDiff() - - function doCvsDiff($command, $options, $params) - { - $this->output = ''; - if (sizeof($params) < 1) { - $help = $this->getHelp($command); - return $this->raiseError("$command: missing parameter: $help[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromDescriptionFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $files = array_keys($info['filelist']); - $cmd = "cvs"; - if (isset($options['quiet'])) { - $cmd .= ' -q'; - unset($options['quiet']); - } - if (isset($options['reallyquiet'])) { - $cmd .= ' -Q'; - unset($options['reallyquiet']); - } - if (isset($options['release'])) { - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $options['release']); - $cvstag = "RELEASE_$cvsversion"; - $options['revision'] = $cvstag; - unset($options['release']); - } - $execute = true; - if (isset($options['dry-run'])) { - $execute = false; - unset($options['dry-run']); - } - $cmd .= ' diff'; - // the rest of the options are passed right on to "cvs diff" - foreach ($options as $option => $optarg) { - $arg = @$this->commands[$command]['options'][$option]['arg']; - $short = @$this->commands[$command]['options'][$option]['shortopt']; - $cmd .= $short ? " -$short" : " --$option"; - if ($arg && $optarg) { - $cmd .= ($short ? '' : '=') . escapeshellarg($optarg); - } - } - foreach ($files as $file) { - $cmd .= ' ' . escapeshellarg($file); - } - if ($this->config->get('verbose') > 1) { - $this->output .= "+ $cmd\n"; - } - if ($execute) { - $fp = popen($cmd, "r"); - while ($line = fgets($fp, 1024)) { - $this->output .= rtrim($line)."\n"; - } - pclose($fp); - } - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doRunTests() - - function doRunTests($command, $options, $params) - { - include_once 'PEAR/RunTest.php'; - $log = new PEAR_Common; - $log->ui = &$this->ui; // slightly hacky, but it will work - $run = new PEAR_RunTest($log); - $tests = array(); - if (isset($options['recur'])) { - $depth = 4; - } else { - $depth = 1; - } - if (!count($params)) { - $params[] = '.'; - } - foreach ($params as $p) { - if (is_dir($p)) { - $dir = System::find(array($p, '-type', 'f', - '-maxdepth', $depth, - '-name', '*.phpt')); - $tests = array_merge($tests, $dir); - } else { - if (!@file_exists($p)) { - if (!preg_match('/\.phpt$/', $p)) { - $p .= '.phpt'; - } - $dir = System::find(array(dirname($p), '-type', 'f', - '-maxdepth', $depth, - '-name', $p)); - $tests = array_merge($tests, $dir); - } else { - $tests[] = $p; - } - } - } - $ini_settings = ''; - if (isset($options['ini'])) { - $ini_settings .= $options['ini']; - } - if (isset($_ENV['TEST_PHP_INCLUDE_PATH'])) { - $ini_settings .= " -d include_path={$_ENV['TEST_PHP_INCLUDE_PATH']}"; - } - if ($ini_settings) { - $this->ui->outputData('Using INI settings: "' . $ini_settings . '"'); - } - $skipped = $passed = $failed = array(); - $this->ui->outputData('Running ' . count($tests) . ' tests', $command); - $start = time(); - if (isset($options['realtimelog'])) { - @unlink('run-tests.log'); - } - foreach ($tests as $t) { - if (isset($options['realtimelog'])) { - $fp = @fopen('run-tests.log', 'a'); - if ($fp) { - fwrite($fp, "Running test $t..."); - fclose($fp); - } - } - $result = $run->run($t, $ini_settings); - if (OS_WINDOWS) { - for($i=0;$i<2000;$i++) { - $i = $i; // delay - race conditions on windows - } - } - if (isset($options['realtimelog'])) { - $fp = @fopen('run-tests.log', 'a'); - if ($fp) { - fwrite($fp, "$result\n"); - fclose($fp); - } - } - if ($result == 'FAILED') { - $failed[] = $t; - } - if ($result == 'PASSED') { - $passed[] = $t; - } - if ($result == 'SKIPPED') { - $skipped[] = $t; - } - } - $total = date('i:s', time() - $start); - if (count($failed)) { - $output = "TOTAL TIME: $total\n"; - $output .= count($passed) . " PASSED TESTS\n"; - $output .= count($skipped) . " SKIPPED TESTS\n"; - $output .= count($failed) . " FAILED TESTS:\n"; - foreach ($failed as $failure) { - $output .= $failure . "\n"; - } - if (isset($options['realtimelog'])) { - $fp = @fopen('run-tests.log', 'a'); - } else { - $fp = @fopen('run-tests.log', 'w'); - } - if ($fp) { - fwrite($fp, $output, strlen($output)); - fclose($fp); - $this->ui->outputData('wrote log to "' . realpath('run-tests.log') . '"', $command); - } - } elseif (@file_exists('run-tests.log') && !@is_dir('run-tests.log')) { - @unlink('run-tests.log'); - } - $this->ui->outputData('TOTAL TIME: ' . $total); - $this->ui->outputData(count($passed) . ' PASSED TESTS', $command); - $this->ui->outputData(count($skipped) . ' SKIPPED TESTS', $command); - if (count($failed)) { - $this->ui->outputData(count($failed) . ' FAILED TESTS:', $command); - foreach ($failed as $failure) { - $this->ui->outputData($failure, $command); - } - } - - return true; - } - - // }}} - // {{{ doPackageDependencies() - - function doPackageDependencies($command, $options, $params) - { - // $params[0] -> the PEAR package to list its information - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - - $obj = new PEAR_Common(); - if (PEAR::isError($info = $obj->infoFromAny($params[0]))) { - return $this->raiseError($info); - } - - if (is_array($info['release_deps'])) { - $data = array( - 'caption' => 'Dependencies for ' . $info['package'], - 'border' => true, - 'headline' => array("Type", "Name", "Relation", "Version"), - ); - - foreach ($info['release_deps'] as $d) { - - if (isset($this->_deps_rel_trans[$d['rel']])) { - $rel = $this->_deps_rel_trans[$d['rel']]; - } else { - $rel = $d['rel']; - } - - if (isset($this->_deps_type_trans[$d['type']])) { - $type = ucfirst($this->_deps_type_trans[$d['type']]); - } else { - $type = $d['type']; - } - - if (isset($d['name'])) { - $name = $d['name']; - } else { - $name = ''; - } - - if (isset($d['version'])) { - $version = $d['version']; - } else { - $version = ''; - } - - $data['data'][] = array($type, $name, $rel, $version); - } - - $this->ui->outputData($data, $command); - return true; - } - - // Fallback - $this->ui->outputData("This package does not have any dependencies.", $command); - } - - // }}} - // {{{ doSign() - - function doSign($command, $options, $params) - { - // should move most of this code into PEAR_Packager - // so it'll be easy to implement "pear package --sign" - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - if (!file_exists($params[0])) { - return $this->raiseError("file does not exist: $params[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromTgzFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - include_once "Archive/Tar.php"; - include_once "System.php"; - $tar = new Archive_Tar($params[0]); - $tmpdir = System::mktemp('-d pearsign'); - if (!$tar->extractList('package.xml package.sig', $tmpdir)) { - return $this->raiseError("failed to extract tar file"); - } - if (file_exists("$tmpdir/package.sig")) { - return $this->raiseError("package already signed"); - } - @unlink("$tmpdir/package.sig"); - $input = $this->ui->userDialog($command, - array('GnuPG Passphrase'), - array('password')); - $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output $tmpdir/package.sig $tmpdir/package.xml 2>/dev/null", "w"); - if (!$gpg) { - return $this->raiseError("gpg command failed"); - } - fwrite($gpg, "$input[0]\r"); - if (pclose($gpg) || !file_exists("$tmpdir/package.sig")) { - return $this->raiseError("gpg sign failed"); - } - $tar->addModify("$tmpdir/package.sig", '', $tmpdir); - return true; - } - - // }}} - // {{{ doMakeRPM() - - /* - - (cox) - - TODO: - - - Fill the rpm dependencies in the template file. - - IDEAS: - - - Instead of mapping the role to rpm vars, perhaps it's better - - to use directly the pear cmd to install the files by itself - - in %postrun so: - - pear -d php_dir=%{_libdir}/php/pear -d test_dir=.. - - */ - - function doMakeRPM($command, $options, $params) - { - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - if (!file_exists($params[0])) { - return $this->raiseError("file does not exist: $params[0]"); - } - include_once "Archive/Tar.php"; - include_once "PEAR/Installer.php"; - include_once "System.php"; - $tar = new Archive_Tar($params[0]); - $tmpdir = System::mktemp('-d pear2rpm'); - $instroot = System::mktemp('-d pear2rpm'); - $tmp = $this->config->get('verbose'); - $this->config->set('verbose', 0); - $installer = new PEAR_Installer($this->ui); - $info = $installer->install($params[0], - array('installroot' => $instroot, - 'nodeps' => true)); - $pkgdir = "$info[package]-$info[version]"; - $info['rpm_xml_dir'] = '/var/lib/pear'; - $this->config->set('verbose', $tmp); - if (!$tar->extractList("package.xml", $tmpdir, $pkgdir)) { - return $this->raiseError("failed to extract $params[0]"); - } - if (!file_exists("$tmpdir/package.xml")) { - return $this->raiseError("no package.xml found in $params[0]"); - } - if (isset($options['spec-template'])) { - $spec_template = $options['spec-template']; - } else { - $spec_template = $this->config->get('data_dir') . - '/PEAR/template.spec'; - } - if (isset($options['rpm-pkgname'])) { - $rpm_pkgname_format = $options['rpm-pkgname']; - } else { - $rpm_pkgname_format = "PEAR::%s"; - } - - $info['extra_headers'] = ''; - $info['doc_files'] = ''; - $info['files'] = ''; - $info['rpm_package'] = sprintf($rpm_pkgname_format, $info['package']); - $srcfiles = 0; - foreach ($info['filelist'] as $name => $attr) { - - if (!isset($attr['role'])) { - continue; - } - $name = preg_replace('![/:\\\\]!', '/', $name); - if ($attr['role'] == 'doc') { - $info['doc_files'] .= " $name"; - - // Map role to the rpm vars - } else { - - $c_prefix = '%{_libdir}/php/pear'; - - switch ($attr['role']) { - - case 'php': - - $prefix = $c_prefix; break; - - case 'ext': - - $prefix = '%{_libdir}/php'; break; // XXX good place? - - case 'src': - - $srcfiles++; - - $prefix = '%{_includedir}/php'; break; // XXX good place? - - case 'test': - - $prefix = "$c_prefix/tests/" . $info['package']; break; - - case 'data': - - $prefix = "$c_prefix/data/" . $info['package']; break; - - case 'script': - - $prefix = '%{_bindir}'; break; - - } - - $name = str_replace('\\', '/', $name); - $info['files'] .= "$prefix/$name\n"; - - } - } - if ($srcfiles > 0) { - include_once "OS/Guess.php"; - $os = new OS_Guess; - $arch = $os->getCpu(); - } else { - $arch = 'noarch'; - } - $cfg = array('master_server', 'php_dir', 'ext_dir', 'doc_dir', - 'bin_dir', 'data_dir', 'test_dir'); - foreach ($cfg as $k) { - $info[$k] = $this->config->get($k); - } - $info['arch'] = $arch; - $fp = @fopen($spec_template, "r"); - if (!$fp) { - return $this->raiseError("could not open RPM spec file template $spec_template: $php_errormsg"); - } - $spec_contents = preg_replace('/@([a-z0-9_-]+)@/e', '$info["\1"]', fread($fp, filesize($spec_template))); - fclose($fp); - $spec_file = "$info[rpm_package]-$info[version].spec"; - $wp = fopen($spec_file, "wb"); - if (!$wp) { - return $this->raiseError("could not write RPM spec file $spec_file: $php_errormsg"); - } - fwrite($wp, $spec_contents); - fclose($wp); - $this->ui->outputData("Wrote RPM spec file $spec_file", $command); - - return true; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Registry.php b/3rdparty/PEAR/Command/Registry.php deleted file mode 100644 index 62cb4b00e2..0000000000 --- a/3rdparty/PEAR/Command/Registry.php +++ /dev/null @@ -1,351 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Registry.php,v 1.36 2004/01/08 17:33:13 sniper Exp $ - -require_once 'PEAR/Command/Common.php'; -require_once 'PEAR/Registry.php'; -require_once 'PEAR/Config.php'; - -class PEAR_Command_Registry extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'list' => array( - 'summary' => 'List Installed Packages', - 'function' => 'doList', - 'shortcut' => 'l', - 'options' => array(), - 'doc' => '[package] -If invoked without parameters, this command lists the PEAR packages -installed in your php_dir ({config php_dir)). With a parameter, it -lists the files in that package. -', - ), - 'shell-test' => array( - 'summary' => 'Shell Script Test', - 'function' => 'doShellTest', - 'shortcut' => 'st', - 'options' => array(), - 'doc' => ' [[relation] version] -Tests if a package is installed in the system. Will exit(1) if it is not. - The version comparison operator. One of: - <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne - The version to compare with -'), - 'info' => array( - 'summary' => 'Display information about a package', - 'function' => 'doInfo', - 'shortcut' => 'in', - 'options' => array(), - 'doc' => ' -Displays information about a package. The package argument may be a -local package file, an URL to a package file, or the name of an -installed package.' - ) - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Registry constructor. - * - * @access public - */ - function PEAR_Command_Registry(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doList() - - function _sortinfo($a, $b) - { - return strcmp($a['package'], $b['package']); - } - - function doList($command, $options, $params) - { - $reg = new PEAR_Registry($this->config->get('php_dir')); - if (sizeof($params) == 0) { - $installed = $reg->packageInfo(); - usort($installed, array(&$this, '_sortinfo')); - $i = $j = 0; - $data = array( - 'caption' => 'Installed packages:', - 'border' => true, - 'headline' => array('Package', 'Version', 'State') - ); - foreach ($installed as $package) { - $data['data'][] = array($package['package'], - $package['version'], - @$package['release_state']); - } - if (count($installed)==0) { - $data = '(no packages installed)'; - } - $this->ui->outputData($data, $command); - } else { - if (file_exists($params[0]) && !is_dir($params[0])) { - include_once "PEAR/Common.php"; - $obj = &new PEAR_Common; - $info = $obj->infoFromAny($params[0]); - $headings = array('Package File', 'Install Path'); - $installed = false; - } else { - $info = $reg->packageInfo($params[0]); - $headings = array('Type', 'Install Path'); - $installed = true; - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - if ($info === null) { - return $this->raiseError("`$params[0]' not installed"); - } - $list = $info['filelist']; - if ($installed) { - $caption = 'Installed Files For ' . $params[0]; - } else { - $caption = 'Contents of ' . basename($params[0]); - } - $data = array( - 'caption' => $caption, - 'border' => true, - 'headline' => $headings); - foreach ($list as $file => $att) { - if ($installed) { - if (empty($att['installed_as'])) { - continue; - } - $data['data'][] = array($att['role'], $att['installed_as']); - } else { - if (isset($att['baseinstalldir'])) { - $dest = $att['baseinstalldir'] . DIRECTORY_SEPARATOR . - $file; - } else { - $dest = $file; - } - switch ($att['role']) { - case 'test': - case 'data': - if ($installed) { - break 2; - } - $dest = '-- will not be installed --'; - break; - case 'doc': - $dest = $this->config->get('doc_dir') . DIRECTORY_SEPARATOR . - $dest; - break; - case 'php': - default: - $dest = $this->config->get('php_dir') . DIRECTORY_SEPARATOR . - $dest; - } - $dest = preg_replace('!/+!', '/', $dest); - $file = preg_replace('!/+!', '/', $file); - $data['data'][] = array($file, $dest); - } - } - $this->ui->outputData($data, $command); - - - } - return true; - } - - // }}} - // {{{ doShellTest() - - function doShellTest($command, $options, $params) - { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $reg = &new PEAR_Registry($this->config->get('php_dir')); - // "pear shell-test Foo" - if (sizeof($params) == 1) { - if (!$reg->packageExists($params[0])) { - exit(1); - } - // "pear shell-test Foo 1.0" - } elseif (sizeof($params) == 2) { - $v = $reg->packageInfo($params[0], 'version'); - if (!$v || !version_compare("$v", "{$params[1]}", "ge")) { - exit(1); - } - // "pear shell-test Foo ge 1.0" - } elseif (sizeof($params) == 3) { - $v = $reg->packageInfo($params[0], 'version'); - if (!$v || !version_compare("$v", "{$params[2]}", $params[1])) { - exit(1); - } - } else { - $this->popErrorHandling(); - $this->raiseError("$command: expects 1 to 3 parameters"); - exit(1); - } - } - - // }}} - // {{{ doInfo - - function doInfo($command, $options, $params) - { - // $params[0] The package for showing info - if (sizeof($params) != 1) { - return $this->raiseError("This command only accepts one param: ". - "the package you want information"); - } - if (@is_file($params[0])) { - $obj = &new PEAR_Common(); - $info = $obj->infoFromAny($params[0]); - } else { - $reg = &new PEAR_Registry($this->config->get('php_dir')); - $info = $reg->packageInfo($params[0]); - } - if (PEAR::isError($info)) { - return $info; - } - if (empty($info)) { - $this->raiseError("Nothing found for `$params[0]'"); - return; - } - unset($info['filelist']); - unset($info['changelog']); - $keys = array_keys($info); - $longtext = array('description', 'summary'); - foreach ($keys as $key) { - if (is_array($info[$key])) { - switch ($key) { - case 'maintainers': { - $i = 0; - $mstr = ''; - foreach ($info[$key] as $m) { - if ($i++ > 0) { - $mstr .= "\n"; - } - $mstr .= $m['name'] . " <"; - if (isset($m['email'])) { - $mstr .= $m['email']; - } else { - $mstr .= $m['handle'] . '@php.net'; - } - $mstr .= "> ($m[role])"; - } - $info[$key] = $mstr; - break; - } - case 'release_deps': { - $i = 0; - $dstr = ''; - foreach ($info[$key] as $d) { - if (isset($this->_deps_rel_trans[$d['rel']])) { - $rel = $this->_deps_rel_trans[$d['rel']]; - } else { - $rel = $d['rel']; - } - if (isset($this->_deps_type_trans[$d['type']])) { - $type = ucfirst($this->_deps_type_trans[$d['type']]); - } else { - $type = $d['type']; - } - if (isset($d['name'])) { - $name = $d['name'] . ' '; - } else { - $name = ''; - } - if (isset($d['version'])) { - $version = $d['version'] . ' '; - } else { - $version = ''; - } - $dstr .= "$type $name$rel $version\n"; - } - $info[$key] = $dstr; - break; - } - case 'provides' : { - $debug = $this->config->get('verbose'); - if ($debug < 2) { - $pstr = 'Classes: '; - } else { - $pstr = ''; - } - $i = 0; - foreach ($info[$key] as $p) { - if ($debug < 2 && $p['type'] != "class") { - continue; - } - // Only print classes when verbosity mode is < 2 - if ($debug < 2) { - if ($i++ > 0) { - $pstr .= ", "; - } - $pstr .= $p['name']; - } else { - if ($i++ > 0) { - $pstr .= "\n"; - } - $pstr .= ucfirst($p['type']) . " " . $p['name']; - if (isset($p['explicit']) && $p['explicit'] == 1) { - $pstr .= " (explicit)"; - } - } - } - $info[$key] = $pstr; - break; - } - default: { - $info[$key] = implode(", ", $info[$key]); - break; - } - } - } - if ($key == '_lastmodified') { - $hdate = date('Y-m-d', $info[$key]); - unset($info[$key]); - $info['Last Modified'] = $hdate; - } else { - $info[$key] = trim($info[$key]); - if (in_array($key, $longtext)) { - $info[$key] = preg_replace('/ +/', ' ', $info[$key]); - } - } - } - $caption = 'About ' . $info['package'] . '-' . $info['version']; - $data = array( - 'caption' => $caption, - 'border' => true); - foreach ($info as $key => $value) { - $key = ucwords(trim(str_replace('_', ' ', $key))); - $data['data'][] = array($key, $value); - } - $data['raw'] = $info; - - $this->ui->outputData($data, 'package-info'); - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Remote.php b/3rdparty/PEAR/Command/Remote.php deleted file mode 100644 index bbd16093f5..0000000000 --- a/3rdparty/PEAR/Command/Remote.php +++ /dev/null @@ -1,435 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Remote.php,v 1.39 2004/04/03 15:56:00 cellog Exp $ - -require_once 'PEAR/Command/Common.php'; -require_once 'PEAR/Common.php'; -require_once 'PEAR/Remote.php'; -require_once 'PEAR/Registry.php'; - -class PEAR_Command_Remote extends PEAR_Command_Common -{ - // {{{ command definitions - - var $commands = array( - 'remote-info' => array( - 'summary' => 'Information About Remote Packages', - 'function' => 'doRemoteInfo', - 'shortcut' => 'ri', - 'options' => array(), - 'doc' => ' -Get details on a package from the server.', - ), - 'list-upgrades' => array( - 'summary' => 'List Available Upgrades', - 'function' => 'doListUpgrades', - 'shortcut' => 'lu', - 'options' => array(), - 'doc' => ' -List releases on the server of packages you have installed where -a newer version is available with the same release state (stable etc.).' - ), - 'remote-list' => array( - 'summary' => 'List Remote Packages', - 'function' => 'doRemoteList', - 'shortcut' => 'rl', - 'options' => array(), - 'doc' => ' -Lists the packages available on the configured server along with the -latest stable release of each package.', - ), - 'search' => array( - 'summary' => 'Search remote package database', - 'function' => 'doSearch', - 'shortcut' => 'sp', - 'options' => array(), - 'doc' => ' -Lists all packages which match the search parameters (first param -is package name, second package info)', - ), - 'list-all' => array( - 'summary' => 'List All Packages', - 'function' => 'doListAll', - 'shortcut' => 'la', - 'options' => array(), - 'doc' => ' -Lists the packages available on the configured server along with the -latest stable release of each package.', - ), - 'download' => array( - 'summary' => 'Download Package', - 'function' => 'doDownload', - 'shortcut' => 'd', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'download an uncompressed (.tar) file', - ), - ), - 'doc' => '{package|package-version} -Download a package tarball. The file will be named as suggested by the -server, for example if you download the DB package and the latest stable -version of DB is 1.2, the downloaded file will be DB-1.2.tgz.', - ), - 'clear-cache' => array( - 'summary' => 'Clear XML-RPC Cache', - 'function' => 'doClearCache', - 'shortcut' => 'cc', - 'options' => array(), - 'doc' => ' -Clear the XML-RPC cache. See also the cache_ttl configuration -parameter. -', - ), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Remote constructor. - * - * @access public - */ - function PEAR_Command_Remote(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doRemoteInfo() - - function doRemoteInfo($command, $options, $params) - { - if (sizeof($params) != 1) { - return $this->raiseError("$command expects one param: the remote package name"); - } - $r = new PEAR_Remote($this->config); - $info = $r->call('package.info', $params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - - $reg = new PEAR_Registry($this->config->get('php_dir')); - $installed = $reg->packageInfo($info['name']); - $info['installed'] = $installed['version'] ? $installed['version'] : '- no -'; - - $this->ui->outputData($info, $command); - - return true; - } - - // }}} - // {{{ doRemoteList() - - function doRemoteList($command, $options, $params) - { - $r = new PEAR_Remote($this->config); - $list_options = false; - if ($this->config->get('preferred_state') == 'stable') - $list_options = true; - $available = $r->call('package.listAll', $list_options); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - $i = $j = 0; - $data = array( - 'caption' => 'Available packages:', - 'border' => true, - 'headline' => array('Package', 'Version'), - ); - foreach ($available as $name => $info) { - $data['data'][] = array($name, isset($info['stable']) ? $info['stable'] : '-n/a-'); - } - if (count($available)==0) { - $data = '(no packages installed yet)'; - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doListAll() - - function doListAll($command, $options, $params) - { - $r = new PEAR_Remote($this->config); - $reg = new PEAR_Registry($this->config->get('php_dir')); - $list_options = false; - if ($this->config->get('preferred_state') == 'stable') - $list_options = true; - $available = $r->call('package.listAll', $list_options); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - if (!is_array($available)) { - return $this->raiseError('The package list could not be fetched from the remote server. Please try again. (Debug info: "'.$available.'")'); - } - $data = array( - 'caption' => 'All packages:', - 'border' => true, - 'headline' => array('Package', 'Latest', 'Local'), - ); - $local_pkgs = $reg->listPackages(); - - foreach ($available as $name => $info) { - $installed = $reg->packageInfo($name); - $desc = $info['summary']; - if (isset($params[$name])) - $desc .= "\n\n".$info['description']; - - if (isset($options['mode'])) - { - if ($options['mode'] == 'installed' && !isset($installed['version'])) - continue; - if ($options['mode'] == 'notinstalled' && isset($installed['version'])) - continue; - if ($options['mode'] == 'upgrades' - && (!isset($installed['version']) || $installed['version'] == $info['stable'])) - { - continue; - } - } - $pos = array_search(strtolower($name), $local_pkgs); - if ($pos !== false) { - unset($local_pkgs[$pos]); - } - - $data['data'][$info['category']][] = array( - $name, - @$info['stable'], - @$installed['version'], - @$desc, - @$info['deps'], - ); - } - - foreach ($local_pkgs as $name) { - $info = $reg->packageInfo($name); - $data['data']['Local'][] = array( - $info['package'], - '', - $info['version'], - $info['summary'], - @$info['release_deps'] - ); - } - - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doSearch() - - function doSearch($command, $options, $params) - { - if ((!isset($params[0]) || empty($params[0])) - && (!isset($params[1]) || empty($params[1]))) - { - return $this->raiseError('no valid search string supplied'); - }; - - $r = new PEAR_Remote($this->config); - $reg = new PEAR_Registry($this->config->get('php_dir')); - $available = $r->call('package.listAll', true, false); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - $data = array( - 'caption' => 'Matched packages:', - 'border' => true, - 'headline' => array('Package', 'Stable/(Latest)', 'Local'), - ); - - foreach ($available as $name => $info) { - $found = (!empty($params[0]) && stristr($name, $params[0]) !== false); - if (!$found && !(isset($params[1]) && !empty($params[1]) - && (stristr($info['summary'], $params[1]) !== false - || stristr($info['description'], $params[1]) !== false))) - { - continue; - }; - - $installed = $reg->packageInfo($name); - $desc = $info['summary']; - if (isset($params[$name])) - $desc .= "\n\n".$info['description']; - - $unstable = ''; - if ($info['unstable']) { - $unstable = '/(' . $info['unstable'] . $info['state'] . ')'; - } - if (!isset($info['stable']) || !$info['stable']) { - $info['stable'] = 'none'; - } - $data['data'][$info['category']][] = array( - $name, - $info['stable'] . $unstable, - $installed['version'], - $desc, - ); - } - if (!isset($data['data'])) { - return $this->raiseError('no packages found'); - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doDownload() - - function doDownload($command, $options, $params) - { - //$params[0] -> The package to download - if (count($params) != 1) { - return PEAR::raiseError("download expects one argument: the package to download"); - } - $server = $this->config->get('master_server'); - if (!ereg('^http://', $params[0])) { - $getoption = isset($options['nocompress'])&&$options['nocompress']==1?'?uncompress=on':''; - $pkgfile = "http://$server/get/$params[0]".$getoption; - } else { - $pkgfile = $params[0]; - } - $this->bytes_downloaded = 0; - $saved = PEAR_Common::downloadHttp($pkgfile, $this->ui, '.', - array(&$this, 'downloadCallback')); - if (PEAR::isError($saved)) { - return $this->raiseError($saved); - } - $fname = basename($saved); - $this->ui->outputData("File $fname downloaded ($this->bytes_downloaded bytes)", $command); - return true; - } - - function downloadCallback($msg, $params = null) - { - if ($msg == 'done') { - $this->bytes_downloaded = $params; - } - } - - // }}} - // {{{ doListUpgrades() - - function doListUpgrades($command, $options, $params) - { - include_once "PEAR/Registry.php"; - $remote = new PEAR_Remote($this->config); - if (empty($params[0])) { - $state = $this->config->get('preferred_state'); - } else { - $state = $params[0]; - } - $caption = 'Available Upgrades'; - if (empty($state) || $state == 'any') { - $latest = $remote->call("package.listLatestReleases"); - } else { - $latest = $remote->call("package.listLatestReleases", $state); - $caption .= ' (' . implode(', ', PEAR_Common::betterStates($state, true)) . ')'; - } - $caption .= ':'; - if (PEAR::isError($latest)) { - return $latest; - } - $reg = new PEAR_Registry($this->config->get('php_dir')); - $inst = array_flip($reg->listPackages()); - $data = array( - 'caption' => $caption, - 'border' => 1, - 'headline' => array('Package', 'Local', 'Remote', 'Size'), - ); - foreach ((array)$latest as $pkg => $info) { - $package = strtolower($pkg); - if (!isset($inst[$package])) { - // skip packages we don't have installed - continue; - } - extract($info); - $pkginfo = $reg->packageInfo($package); - $inst_version = $pkginfo['version']; - $inst_state = $pkginfo['release_state']; - if (version_compare("$version", "$inst_version", "le")) { - // installed version is up-to-date - continue; - } - if ($filesize >= 20480) { - $filesize += 1024 - ($filesize % 1024); - $fs = sprintf("%dkB", $filesize / 1024); - } elseif ($filesize > 0) { - $filesize += 103 - ($filesize % 103); - $fs = sprintf("%.1fkB", $filesize / 1024.0); - } else { - $fs = " -"; // XXX center instead - } - $data['data'][] = array($pkg, "$inst_version ($inst_state)", "$version ($state)", $fs); - } - if (empty($data['data'])) { - $this->ui->outputData('No upgrades available'); - } else { - $this->ui->outputData($data, $command); - } - return true; - } - - // }}} - // {{{ doClearCache() - - function doClearCache($command, $options, $params) - { - $cache_dir = $this->config->get('cache_dir'); - $verbose = $this->config->get('verbose'); - $output = ''; - if (!($dp = @opendir($cache_dir))) { - return $this->raiseError("opendir($cache_dir) failed: $php_errormsg"); - } - if ($verbose >= 1) { - $output .= "reading directory $cache_dir\n"; - } - $num = 0; - while ($ent = readdir($dp)) { - if (preg_match('/^xmlrpc_cache_[a-z0-9]{32}$/', $ent)) { - $path = $cache_dir . DIRECTORY_SEPARATOR . $ent; - $ok = @unlink($path); - if ($ok) { - if ($verbose >= 2) { - $output .= "deleted $path\n"; - } - $num++; - } elseif ($verbose >= 1) { - $output .= "failed to delete $path\n"; - } - } - } - closedir($dp); - if ($verbose >= 1) { - $output .= "$num cache entries cleared\n"; - } - $this->ui->outputData(rtrim($output), $command); - return $num; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Common.php b/3rdparty/PEAR/Common.php deleted file mode 100644 index fba53a3779..0000000000 --- a/3rdparty/PEAR/Common.php +++ /dev/null @@ -1,2094 +0,0 @@ - | -// | Tomas V.V.Cox | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.126.2.2 2004/12/27 07:04:19 cellog Exp $ - -require_once 'PEAR.php'; -require_once 'Archive/Tar.php'; -require_once 'System.php'; -require_once 'PEAR/Config.php'; - -// {{{ constants and globals - -/** - * PEAR_Common error when an invalid PHP file is passed to PEAR_Common::analyzeSourceCode() - */ -define('PEAR_COMMON_ERROR_INVALIDPHP', 1); -define('_PEAR_COMMON_PACKAGE_NAME_PREG', '[A-Za-z][a-zA-Z0-9_]+'); -define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^' . _PEAR_COMMON_PACKAGE_NAME_PREG . '$/'); - -// this should allow: 1, 1.0, 1.0RC1, 1.0dev, 1.0dev123234234234, 1.0a1, 1.0b1, 1.0pl1 -define('_PEAR_COMMON_PACKAGE_VERSION_PREG', '\d+(?:\.\d+)*(?:[a-zA-Z]+\d*)?'); -define('PEAR_COMMON_PACKAGE_VERSION_PREG', '/^' . _PEAR_COMMON_PACKAGE_VERSION_PREG . '$/i'); - -// XXX far from perfect :-) -define('PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '/^(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?$/'); - -/** - * List of temporary files and directories registered by - * PEAR_Common::addTempFile(). - * @var array - */ -$GLOBALS['_PEAR_Common_tempfiles'] = array(); - -/** - * Valid maintainer roles - * @var array - */ -$GLOBALS['_PEAR_Common_maintainer_roles'] = array('lead','developer','contributor','helper'); - -/** - * Valid release states - * @var array - */ -$GLOBALS['_PEAR_Common_release_states'] = array('alpha','beta','stable','snapshot','devel'); - -/** - * Valid dependency types - * @var array - */ -$GLOBALS['_PEAR_Common_dependency_types'] = array('pkg','ext','php','prog','ldlib','rtlib','os','websrv','sapi'); - -/** - * Valid dependency relations - * @var array - */ -$GLOBALS['_PEAR_Common_dependency_relations'] = array('has','eq','lt','le','gt','ge','not', 'ne'); - -/** - * Valid file roles - * @var array - */ -$GLOBALS['_PEAR_Common_file_roles'] = array('php','ext','test','doc','data','src','script'); - -/** - * Valid replacement types - * @var array - */ -$GLOBALS['_PEAR_Common_replacement_types'] = array('php-const', 'pear-config', 'package-info'); - -/** - * Valid "provide" types - * @var array - */ -$GLOBALS['_PEAR_Common_provide_types'] = array('ext', 'prog', 'class', 'function', 'feature', 'api'); - -/** - * Valid "provide" types - * @var array - */ -$GLOBALS['_PEAR_Common_script_phases'] = array('pre-install', 'post-install', 'pre-uninstall', 'post-uninstall', 'pre-build', 'post-build', 'pre-configure', 'post-configure', 'pre-setup', 'post-setup'); - -// }}} - -/** - * Class providing common functionality for PEAR administration classes. - * @deprecated This class will disappear, and its components will be spread - * into smaller classes, like the AT&T breakup - */ -class PEAR_Common extends PEAR -{ - // {{{ properties - - /** stack of elements, gives some sort of XML context */ - var $element_stack = array(); - - /** name of currently parsed XML element */ - var $current_element; - - /** array of attributes of the currently parsed XML element */ - var $current_attributes = array(); - - /** assoc with information about a package */ - var $pkginfo = array(); - - /** - * User Interface object (PEAR_Frontend_* class). If null, - * the log() method uses print. - * @var object - */ - var $ui = null; - - /** - * Configuration object (PEAR_Config). - * @var object - */ - var $config = null; - - var $current_path = null; - - /** - * PEAR_SourceAnalyzer instance - * @var object - */ - var $source_analyzer = null; - /** - * Flag variable used to mark a valid package file - * @var boolean - * @access private - */ - var $_validPackageFile; - - // }}} - - // {{{ constructor - - /** - * PEAR_Common constructor - * - * @access public - */ - function PEAR_Common() - { - parent::PEAR(); - $this->config = &PEAR_Config::singleton(); - $this->debug = $this->config->get('verbose'); - } - - // }}} - // {{{ destructor - - /** - * PEAR_Common destructor - * - * @access private - */ - function _PEAR_Common() - { - // doesn't work due to bug #14744 - //$tempfiles = $this->_tempfiles; - $tempfiles =& $GLOBALS['_PEAR_Common_tempfiles']; - while ($file = array_shift($tempfiles)) { - if (@is_dir($file)) { - System::rm(array('-rf', $file)); - } elseif (file_exists($file)) { - unlink($file); - } - } - } - - // }}} - // {{{ addTempFile() - - /** - * Register a temporary file or directory. When the destructor is - * executed, all registered temporary files and directories are - * removed. - * - * @param string $file name of file or directory - * - * @return void - * - * @access public - */ - function addTempFile($file) - { - $GLOBALS['_PEAR_Common_tempfiles'][] = $file; - } - - // }}} - // {{{ mkDirHier() - - /** - * Wrapper to System::mkDir(), creates a directory as well as - * any necessary parent directories. - * - * @param string $dir directory name - * - * @return bool TRUE on success, or a PEAR error - * - * @access public - */ - function mkDirHier($dir) - { - $this->log(2, "+ create dir $dir"); - return System::mkDir(array('-p', $dir)); - } - - // }}} - // {{{ log() - - /** - * Logging method. - * - * @param int $level log level (0 is quiet, higher is noisier) - * @param string $msg message to write to the log - * - * @return void - * - * @access public - */ - function log($level, $msg, $append_crlf = true) - { - if ($this->debug >= $level) { - if (is_object($this->ui)) { - $this->ui->log($msg, $append_crlf); - } else { - print "$msg\n"; - } - } - } - - // }}} - // {{{ mkTempDir() - - /** - * Create and register a temporary directory. - * - * @param string $tmpdir (optional) Directory to use as tmpdir. - * Will use system defaults (for example - * /tmp or c:\windows\temp) if not specified - * - * @return string name of created directory - * - * @access public - */ - function mkTempDir($tmpdir = '') - { - if ($tmpdir) { - $topt = array('-t', $tmpdir); - } else { - $topt = array(); - } - $topt = array_merge($topt, array('-d', 'pear')); - if (!$tmpdir = System::mktemp($topt)) { - return false; - } - $this->addTempFile($tmpdir); - return $tmpdir; - } - - // }}} - // {{{ setFrontendObject() - - /** - * Set object that represents the frontend to be used. - * - * @param object Reference of the frontend object - * @return void - * @access public - */ - function setFrontendObject(&$ui) - { - $this->ui = &$ui; - } - - // }}} - - // {{{ _unIndent() - - /** - * Unindent given string (?) - * - * @param string $str The string that has to be unindented. - * @return string - * @access private - */ - function _unIndent($str) - { - // remove leading newlines - $str = preg_replace('/^[\r\n]+/', '', $str); - // find whitespace at the beginning of the first line - $indent_len = strspn($str, " \t"); - $indent = substr($str, 0, $indent_len); - $data = ''; - // remove the same amount of whitespace from following lines - foreach (explode("\n", $str) as $line) { - if (substr($line, 0, $indent_len) == $indent) { - $data .= substr($line, $indent_len) . "\n"; - } - } - return $data; - } - - // }}} - // {{{ _element_start() - - /** - * XML parser callback for starting elements. Used while package - * format version is not yet known. - * - * @param resource $xp XML parser resource - * @param string $name name of starting element - * @param array $attribs element attributes, name => value - * - * @return void - * - * @access private - */ - function _element_start($xp, $name, $attribs) - { - array_push($this->element_stack, $name); - $this->current_element = $name; - $spos = sizeof($this->element_stack) - 2; - $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : ''; - $this->current_attributes = $attribs; - switch ($name) { - case 'package': { - $this->_validPackageFile = true; - if (isset($attribs['version'])) { - $vs = preg_replace('/[^0-9a-z]/', '_', $attribs['version']); - } else { - $vs = '1_0'; - } - $elem_start = '_element_start_'. $vs; - $elem_end = '_element_end_'. $vs; - $cdata = '_pkginfo_cdata_'. $vs; - if (!method_exists($this, $elem_start) || - !method_exists($this, $elem_end) || - !method_exists($this, $cdata)) { - $this->raiseError("No handlers for package.xml version $attribs[version]"); - return; - } - xml_set_element_handler($xp, $elem_start, $elem_end); - xml_set_character_data_handler($xp, $cdata); - break; - } - } - } - - // }}} - // {{{ _element_end() - - /** - * XML parser callback for ending elements. Used while package - * format version is not yet known. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_end($xp, $name) - { - } - - // }}} - - // Support for package DTD v1.0: - // {{{ _element_start_1_0() - - /** - * XML parser callback for ending elements. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_start_1_0($xp, $name, $attribs) - { - array_push($this->element_stack, $name); - $this->current_element = $name; - $spos = sizeof($this->element_stack) - 2; - $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : ''; - $this->current_attributes = $attribs; - $this->cdata = ''; - switch ($name) { - case 'dir': - if ($this->in_changelog) { - break; - } - if ($attribs['name'] != '/') { - $this->dir_names[] = $attribs['name']; - } - if (isset($attribs['baseinstalldir'])) { - $this->dir_install = $attribs['baseinstalldir']; - } - if (isset($attribs['role'])) { - $this->dir_role = $attribs['role']; - } - break; - case 'file': - if ($this->in_changelog) { - break; - } - if (isset($attribs['name'])) { - $path = ''; - if (count($this->dir_names)) { - foreach ($this->dir_names as $dir) { - $path .= $dir . DIRECTORY_SEPARATOR; - } - } - $path .= $attribs['name']; - unset($attribs['name']); - $this->current_path = $path; - $this->filelist[$path] = $attribs; - // Set the baseinstalldir only if the file don't have this attrib - if (!isset($this->filelist[$path]['baseinstalldir']) && - isset($this->dir_install)) - { - $this->filelist[$path]['baseinstalldir'] = $this->dir_install; - } - // Set the Role - if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) { - $this->filelist[$path]['role'] = $this->dir_role; - } - } - break; - case 'replace': - if (!$this->in_changelog) { - $this->filelist[$this->current_path]['replacements'][] = $attribs; - } - break; - case 'maintainers': - $this->pkginfo['maintainers'] = array(); - $this->m_i = 0; // maintainers array index - break; - case 'maintainer': - // compatibility check - if (!isset($this->pkginfo['maintainers'])) { - $this->pkginfo['maintainers'] = array(); - $this->m_i = 0; - } - $this->pkginfo['maintainers'][$this->m_i] = array(); - $this->current_maintainer =& $this->pkginfo['maintainers'][$this->m_i]; - break; - case 'changelog': - $this->pkginfo['changelog'] = array(); - $this->c_i = 0; // changelog array index - $this->in_changelog = true; - break; - case 'release': - if ($this->in_changelog) { - $this->pkginfo['changelog'][$this->c_i] = array(); - $this->current_release = &$this->pkginfo['changelog'][$this->c_i]; - } else { - $this->current_release = &$this->pkginfo; - } - break; - case 'deps': - if (!$this->in_changelog) { - $this->pkginfo['release_deps'] = array(); - } - break; - case 'dep': - // dependencies array index - if (!$this->in_changelog) { - $this->d_i++; - $this->pkginfo['release_deps'][$this->d_i] = $attribs; - } - break; - case 'configureoptions': - if (!$this->in_changelog) { - $this->pkginfo['configure_options'] = array(); - } - break; - case 'configureoption': - if (!$this->in_changelog) { - $this->pkginfo['configure_options'][] = $attribs; - } - break; - case 'provides': - if (empty($attribs['type']) || empty($attribs['name'])) { - break; - } - $attribs['explicit'] = true; - $this->pkginfo['provides']["$attribs[type];$attribs[name]"] = $attribs; - break; - } - } - - // }}} - // {{{ _element_end_1_0() - - /** - * XML parser callback for ending elements. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_end_1_0($xp, $name) - { - $data = trim($this->cdata); - switch ($name) { - case 'name': - switch ($this->prev_element) { - case 'package': - // XXX should we check the package name here? - $this->pkginfo['package'] = ereg_replace('[^a-zA-Z0-9._]', '_', $data); - break; - case 'maintainer': - $this->current_maintainer['name'] = $data; - break; - } - break; - case 'summary': - $this->pkginfo['summary'] = $data; - break; - case 'description': - $data = $this->_unIndent($this->cdata); - $this->pkginfo['description'] = $data; - break; - case 'user': - $this->current_maintainer['handle'] = $data; - break; - case 'email': - $this->current_maintainer['email'] = $data; - break; - case 'role': - $this->current_maintainer['role'] = $data; - break; - case 'version': - $data = ereg_replace ('[^a-zA-Z0-9._\-]', '_', $data); - if ($this->in_changelog) { - $this->current_release['version'] = $data; - } else { - $this->pkginfo['version'] = $data; - } - break; - case 'date': - if ($this->in_changelog) { - $this->current_release['release_date'] = $data; - } else { - $this->pkginfo['release_date'] = $data; - } - break; - case 'notes': - // try to "de-indent" release notes in case someone - // has been over-indenting their xml ;-) - $data = $this->_unIndent($this->cdata); - if ($this->in_changelog) { - $this->current_release['release_notes'] = $data; - } else { - $this->pkginfo['release_notes'] = $data; - } - break; - case 'warnings': - if ($this->in_changelog) { - $this->current_release['release_warnings'] = $data; - } else { - $this->pkginfo['release_warnings'] = $data; - } - break; - case 'state': - if ($this->in_changelog) { - $this->current_release['release_state'] = $data; - } else { - $this->pkginfo['release_state'] = $data; - } - break; - case 'license': - if ($this->in_changelog) { - $this->current_release['release_license'] = $data; - } else { - $this->pkginfo['release_license'] = $data; - } - break; - case 'dep': - if ($data && !$this->in_changelog) { - $this->pkginfo['release_deps'][$this->d_i]['name'] = $data; - } - break; - case 'dir': - if ($this->in_changelog) { - break; - } - array_pop($this->dir_names); - break; - case 'file': - if ($this->in_changelog) { - break; - } - if ($data) { - $path = ''; - if (count($this->dir_names)) { - foreach ($this->dir_names as $dir) { - $path .= $dir . DIRECTORY_SEPARATOR; - } - } - $path .= $data; - $this->filelist[$path] = $this->current_attributes; - // Set the baseinstalldir only if the file don't have this attrib - if (!isset($this->filelist[$path]['baseinstalldir']) && - isset($this->dir_install)) - { - $this->filelist[$path]['baseinstalldir'] = $this->dir_install; - } - // Set the Role - if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) { - $this->filelist[$path]['role'] = $this->dir_role; - } - } - break; - case 'maintainer': - if (empty($this->pkginfo['maintainers'][$this->m_i]['role'])) { - $this->pkginfo['maintainers'][$this->m_i]['role'] = 'lead'; - } - $this->m_i++; - break; - case 'release': - if ($this->in_changelog) { - $this->c_i++; - } - break; - case 'changelog': - $this->in_changelog = false; - break; - } - array_pop($this->element_stack); - $spos = sizeof($this->element_stack) - 1; - $this->current_element = ($spos > 0) ? $this->element_stack[$spos] : ''; - $this->cdata = ''; - } - - // }}} - // {{{ _pkginfo_cdata_1_0() - - /** - * XML parser callback for character data. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name character data - * - * @return void - * - * @access private - */ - function _pkginfo_cdata_1_0($xp, $data) - { - if (isset($this->cdata)) { - $this->cdata .= $data; - } - } - - // }}} - - // {{{ infoFromTgzFile() - - /** - * Returns information about a package file. Expects the name of - * a gzipped tar file as input. - * - * @param string $file name of .tgz file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromTgzFile($file) - { - if (!@is_file($file)) { - return $this->raiseError("could not open file \"$file\""); - } - $tar = new Archive_Tar($file); - if ($this->debug <= 1) { - $tar->pushErrorHandling(PEAR_ERROR_RETURN); - } - $content = $tar->listContent(); - if ($this->debug <= 1) { - $tar->popErrorHandling(); - } - if (!is_array($content)) { - $file = realpath($file); - return $this->raiseError("Could not get contents of package \"$file\"". - '. Invalid tgz file.'); - } - $xml = null; - foreach ($content as $file) { - $name = $file['filename']; - if ($name == 'package.xml') { - $xml = $name; - break; - } elseif (ereg('package.xml$', $name, $match)) { - $xml = $match[0]; - break; - } - } - $tmpdir = System::mkTemp(array('-d', 'pear')); - $this->addTempFile($tmpdir); - if (!$xml || !$tar->extractList(array($xml), $tmpdir)) { - return $this->raiseError('could not extract the package.xml file'); - } - return $this->infoFromDescriptionFile("$tmpdir/$xml"); - } - - // }}} - // {{{ infoFromDescriptionFile() - - /** - * Returns information about a package file. Expects the name of - * a package xml file as input. - * - * @param string $descfile name of package xml file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromDescriptionFile($descfile) - { - if (!@is_file($descfile) || !is_readable($descfile) || - (!$fp = @fopen($descfile, 'r'))) { - return $this->raiseError("Unable to open $descfile"); - } - - // read the whole thing so we only get one cdata callback - // for each block of cdata - $data = fread($fp, filesize($descfile)); - return $this->infoFromString($data); - } - - // }}} - // {{{ infoFromString() - - /** - * Returns information about a package file. Expects the contents - * of a package xml file as input. - * - * @param string $data name of package xml file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromString($data) - { - require_once('PEAR/Dependency.php'); - if (PEAR_Dependency::checkExtension($error, 'xml')) { - return $this->raiseError($error); - } - $xp = @xml_parser_create(); - if (!$xp) { - return $this->raiseError('Unable to create XML parser'); - } - xml_set_object($xp, $this); - xml_set_element_handler($xp, '_element_start', '_element_end'); - xml_set_character_data_handler($xp, '_pkginfo_cdata'); - xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, false); - - $this->element_stack = array(); - $this->pkginfo = array('provides' => array()); - $this->current_element = false; - unset($this->dir_install); - $this->pkginfo['filelist'] = array(); - $this->filelist =& $this->pkginfo['filelist']; - $this->dir_names = array(); - $this->in_changelog = false; - $this->d_i = 0; - $this->cdata = ''; - $this->_validPackageFile = false; - - if (!xml_parse($xp, $data, 1)) { - $code = xml_get_error_code($xp); - $msg = sprintf("XML error: %s at line %d", - xml_error_string($code), - xml_get_current_line_number($xp)); - xml_parser_free($xp); - return $this->raiseError($msg, $code); - } - - xml_parser_free($xp); - - if (!$this->_validPackageFile) { - return $this->raiseError('Invalid Package File, no tag'); - } - foreach ($this->pkginfo as $k => $v) { - if (!is_array($v)) { - $this->pkginfo[$k] = trim($v); - } - } - return $this->pkginfo; - } - // }}} - // {{{ infoFromAny() - - /** - * Returns package information from different sources - * - * This method is able to extract information about a package - * from a .tgz archive or from a XML package definition file. - * - * @access public - * @param string Filename of the source ('package.xml', '.tgz') - * @return string - */ - function infoFromAny($info) - { - if (is_string($info) && file_exists($info)) { - $tmp = substr($info, -4); - if ($tmp == '.xml') { - $info = $this->infoFromDescriptionFile($info); - } elseif ($tmp == '.tar' || $tmp == '.tgz') { - $info = $this->infoFromTgzFile($info); - } else { - $fp = fopen($info, "r"); - $test = fread($fp, 5); - fclose($fp); - if ($test == "infoFromDescriptionFile($info); - } else { - $info = $this->infoFromTgzFile($info); - } - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - } - return $info; - } - - // }}} - // {{{ xmlFromInfo() - - /** - * Return an XML document based on the package info (as returned - * by the PEAR_Common::infoFrom* methods). - * - * @param array $pkginfo package info - * - * @return string XML data - * - * @access public - */ - function xmlFromInfo($pkginfo) - { - static $maint_map = array( - "handle" => "user", - "name" => "name", - "email" => "email", - "role" => "role", - ); - $ret = "\n"; - $ret .= "\n"; - $ret .= " - $pkginfo[package] - ".htmlspecialchars($pkginfo['summary'])." - ".htmlspecialchars($pkginfo['description'])." - -"; - foreach ($pkginfo['maintainers'] as $maint) { - $ret .= " \n"; - foreach ($maint_map as $idx => $elm) { - $ret .= " <$elm>"; - $ret .= htmlspecialchars($maint[$idx]); - $ret .= "\n"; - } - $ret .= " \n"; - } - $ret .= " \n"; - $ret .= $this->_makeReleaseXml($pkginfo); - if (@sizeof($pkginfo['changelog']) > 0) { - $ret .= " \n"; - foreach ($pkginfo['changelog'] as $oldrelease) { - $ret .= $this->_makeReleaseXml($oldrelease, true); - } - $ret .= " \n"; - } - $ret .= "\n"; - return $ret; - } - - // }}} - // {{{ _makeReleaseXml() - - /** - * Generate part of an XML description with release information. - * - * @param array $pkginfo array with release information - * @param bool $changelog whether the result will be in a changelog element - * - * @return string XML data - * - * @access private - */ - function _makeReleaseXml($pkginfo, $changelog = false) - { - // XXX QUOTE ENTITIES IN PCDATA, OR EMBED IN CDATA BLOCKS!! - $indent = $changelog ? " " : ""; - $ret = "$indent \n"; - if (!empty($pkginfo['version'])) { - $ret .= "$indent $pkginfo[version]\n"; - } - if (!empty($pkginfo['release_date'])) { - $ret .= "$indent $pkginfo[release_date]\n"; - } - if (!empty($pkginfo['release_license'])) { - $ret .= "$indent $pkginfo[release_license]\n"; - } - if (!empty($pkginfo['release_state'])) { - $ret .= "$indent $pkginfo[release_state]\n"; - } - if (!empty($pkginfo['release_notes'])) { - $ret .= "$indent ".htmlspecialchars($pkginfo['release_notes'])."\n"; - } - if (!empty($pkginfo['release_warnings'])) { - $ret .= "$indent ".htmlspecialchars($pkginfo['release_warnings'])."\n"; - } - if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) { - $ret .= "$indent \n"; - foreach ($pkginfo['release_deps'] as $dep) { - $ret .= "$indent $what) { - $ret .= "$indent $fa) { - @$ret .= "$indent $v) { - $ret .= " $k=\"" . htmlspecialchars($v) .'"'; - } - $ret .= "/>\n"; - } - @$ret .= "$indent \n"; - } - } - $ret .= "$indent \n"; - } - $ret .= "$indent \n"; - return $ret; - } - - // }}} - // {{{ validatePackageInfo() - - /** - * Validate XML package definition file. - * - * @param string $info Filename of the package archive or of the - * package definition file - * @param array $errors Array that will contain the errors - * @param array $warnings Array that will contain the warnings - * @param string $dir_prefix (optional) directory where source files - * may be found, or empty if they are not available - * @access public - * @return boolean - */ - function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '') - { - if (PEAR::isError($info = $this->infoFromAny($info))) { - return $this->raiseError($info); - } - if (!is_array($info)) { - return false; - } - - $errors = array(); - $warnings = array(); - if (!isset($info['package'])) { - $errors[] = 'missing package name'; - } elseif (!$this->validPackageName($info['package'])) { - $errors[] = 'invalid package name'; - } - $this->_packageName = $pn = $info['package']; - - if (empty($info['summary'])) { - $errors[] = 'missing summary'; - } elseif (strpos(trim($info['summary']), "\n") !== false) { - $warnings[] = 'summary should be on a single line'; - } - if (empty($info['description'])) { - $errors[] = 'missing description'; - } - if (empty($info['release_license'])) { - $errors[] = 'missing license'; - } - if (!isset($info['version'])) { - $errors[] = 'missing version'; - } elseif (!$this->validPackageVersion($info['version'])) { - $errors[] = 'invalid package release version'; - } - if (empty($info['release_state'])) { - $errors[] = 'missing release state'; - } elseif (!in_array($info['release_state'], PEAR_Common::getReleaseStates())) { - $errors[] = "invalid release state `$info[release_state]', should be one of: " - . implode(' ', PEAR_Common::getReleaseStates()); - } - if (empty($info['release_date'])) { - $errors[] = 'missing release date'; - } elseif (!preg_match('/^\d{4}-\d\d-\d\d$/', $info['release_date'])) { - $errors[] = "invalid release date `$info[release_date]', format is YYYY-MM-DD"; - } - if (empty($info['release_notes'])) { - $errors[] = "missing release notes"; - } - if (empty($info['maintainers'])) { - $errors[] = 'no maintainer(s)'; - } else { - $i = 1; - foreach ($info['maintainers'] as $m) { - if (empty($m['handle'])) { - $errors[] = "maintainer $i: missing handle"; - } - if (empty($m['role'])) { - $errors[] = "maintainer $i: missing role"; - } elseif (!in_array($m['role'], PEAR_Common::getUserRoles())) { - $errors[] = "maintainer $i: invalid role `$m[role]', should be one of: " - . implode(' ', PEAR_Common::getUserRoles()); - } - if (empty($m['name'])) { - $errors[] = "maintainer $i: missing name"; - } - if (empty($m['email'])) { - $errors[] = "maintainer $i: missing email"; - } - $i++; - } - } - if (!empty($info['release_deps'])) { - $i = 1; - foreach ($info['release_deps'] as $d) { - if (empty($d['type'])) { - $errors[] = "dependency $i: missing type"; - } elseif (!in_array($d['type'], PEAR_Common::getDependencyTypes())) { - $errors[] = "dependency $i: invalid type '$d[type]', should be one of: " . - implode(' ', PEAR_Common::getDependencyTypes()); - } - if (empty($d['rel'])) { - $errors[] = "dependency $i: missing relation"; - } elseif (!in_array($d['rel'], PEAR_Common::getDependencyRelations())) { - $errors[] = "dependency $i: invalid relation '$d[rel]', should be one of: " - . implode(' ', PEAR_Common::getDependencyRelations()); - } - if (!empty($d['optional'])) { - if (!in_array($d['optional'], array('yes', 'no'))) { - $errors[] = "dependency $i: invalid relation optional attribute '$d[optional]', should be one of: yes no"; - } else { - if (($d['rel'] == 'not' || $d['rel'] == 'ne') && $d['optional'] == 'yes') { - $errors[] = "dependency $i: 'not' and 'ne' dependencies cannot be " . - "optional"; - } - } - } - if ($d['rel'] != 'not' && $d['rel'] != 'has' && empty($d['version'])) { - $warnings[] = "dependency $i: missing version"; - } elseif (($d['rel'] == 'not' || $d['rel'] == 'has') && !empty($d['version'])) { - $warnings[] = "dependency $i: version ignored for `$d[rel]' dependencies"; - } - if ($d['rel'] == 'not' && !empty($d['version'])) { - $warnings[] = "dependency $i: 'not' defines a total conflict, to exclude " . - "specific versions, use 'ne'"; - } - if ($d['type'] == 'php' && !empty($d['name'])) { - $warnings[] = "dependency $i: name ignored for php type dependencies"; - } elseif ($d['type'] != 'php' && empty($d['name'])) { - $errors[] = "dependency $i: missing name"; - } - if ($d['type'] == 'php' && $d['rel'] == 'not') { - $errors[] = "dependency $i: PHP dependencies cannot use 'not' " . - "rel, use 'ne' to exclude versions"; - } - $i++; - } - } - if (!empty($info['configure_options'])) { - $i = 1; - foreach ($info['configure_options'] as $c) { - if (empty($c['name'])) { - $errors[] = "configure option $i: missing name"; - } - if (empty($c['prompt'])) { - $errors[] = "configure option $i: missing prompt"; - } - $i++; - } - } - if (empty($info['filelist'])) { - $errors[] = 'no files'; - } else { - foreach ($info['filelist'] as $file => $fa) { - if (empty($fa['role'])) { - $errors[] = "file $file: missing role"; - continue; - } elseif (!in_array($fa['role'], PEAR_Common::getFileRoles())) { - $errors[] = "file $file: invalid role, should be one of: " - . implode(' ', PEAR_Common::getFileRoles()); - } - if ($fa['role'] == 'php' && $dir_prefix) { - $this->log(1, "Analyzing $file"); - $srcinfo = $this->analyzeSourceCode($dir_prefix . DIRECTORY_SEPARATOR . $file); - if ($srcinfo) { - $this->buildProvidesArray($srcinfo); - } - } - - // (ssb) Any checks we can do for baseinstalldir? - // (cox) Perhaps checks that either the target dir and - // baseInstall doesn't cointain "../../" - } - } - $this->_packageName = $pn = $info['package']; - $pnl = strlen($pn); - foreach ((array)$this->pkginfo['provides'] as $key => $what) { - if (isset($what['explicit'])) { - // skip conformance checks if the provides entry is - // specified in the package.xml file - continue; - } - extract($what); - if ($type == 'class') { - if (!strncasecmp($name, $pn, $pnl)) { - continue; - } - $warnings[] = "in $file: class \"$name\" not prefixed with package name \"$pn\""; - } elseif ($type == 'function') { - if (strstr($name, '::') || !strncasecmp($name, $pn, $pnl)) { - continue; - } - $warnings[] = "in $file: function \"$name\" not prefixed with package name \"$pn\""; - } - } - - - return true; - } - - // }}} - // {{{ buildProvidesArray() - - /** - * Build a "provides" array from data returned by - * analyzeSourceCode(). The format of the built array is like - * this: - * - * array( - * 'class;MyClass' => 'array('type' => 'class', 'name' => 'MyClass'), - * ... - * ) - * - * - * @param array $srcinfo array with information about a source file - * as returned by the analyzeSourceCode() method. - * - * @return void - * - * @access public - * - */ - function buildProvidesArray($srcinfo) - { - $file = basename($srcinfo['source_file']); - $pn = ''; - if (isset($this->_packageName)) { - $pn = $this->_packageName; - } - $pnl = strlen($pn); - foreach ($srcinfo['declared_classes'] as $class) { - $key = "class;$class"; - if (isset($this->pkginfo['provides'][$key])) { - continue; - } - $this->pkginfo['provides'][$key] = - array('file'=> $file, 'type' => 'class', 'name' => $class); - if (isset($srcinfo['inheritance'][$class])) { - $this->pkginfo['provides'][$key]['extends'] = - $srcinfo['inheritance'][$class]; - } - } - foreach ($srcinfo['declared_methods'] as $class => $methods) { - foreach ($methods as $method) { - $function = "$class::$method"; - $key = "function;$function"; - if ($method{0} == '_' || !strcasecmp($method, $class) || - isset($this->pkginfo['provides'][$key])) { - continue; - } - $this->pkginfo['provides'][$key] = - array('file'=> $file, 'type' => 'function', 'name' => $function); - } - } - - foreach ($srcinfo['declared_functions'] as $function) { - $key = "function;$function"; - if ($function{0} == '_' || isset($this->pkginfo['provides'][$key])) { - continue; - } - if (!strstr($function, '::') && strncasecmp($function, $pn, $pnl)) { - $warnings[] = "in1 " . $file . ": function \"$function\" not prefixed with package name \"$pn\""; - } - $this->pkginfo['provides'][$key] = - array('file'=> $file, 'type' => 'function', 'name' => $function); - } - } - - // }}} - // {{{ analyzeSourceCode() - - /** - * Analyze the source code of the given PHP file - * - * @param string Filename of the PHP file - * @return mixed - * @access public - */ - function analyzeSourceCode($file) - { - if (!function_exists("token_get_all")) { - return false; - } - if (!defined('T_DOC_COMMENT')) { - define('T_DOC_COMMENT', T_COMMENT); - } - if (!defined('T_INTERFACE')) { - define('T_INTERFACE', -1); - } - if (!defined('T_IMPLEMENTS')) { - define('T_IMPLEMENTS', -1); - } - if (!$fp = @fopen($file, "r")) { - return false; - } - $contents = fread($fp, filesize($file)); - $tokens = token_get_all($contents); -/* - for ($i = 0; $i < sizeof($tokens); $i++) { - @list($token, $data) = $tokens[$i]; - if (is_string($token)) { - var_dump($token); - } else { - print token_name($token) . ' '; - var_dump(rtrim($data)); - } - } -*/ - $look_for = 0; - $paren_level = 0; - $bracket_level = 0; - $brace_level = 0; - $lastphpdoc = ''; - $current_class = ''; - $current_interface = ''; - $current_class_level = -1; - $current_function = ''; - $current_function_level = -1; - $declared_classes = array(); - $declared_interfaces = array(); - $declared_functions = array(); - $declared_methods = array(); - $used_classes = array(); - $used_functions = array(); - $extends = array(); - $implements = array(); - $nodeps = array(); - $inquote = false; - $interface = false; - for ($i = 0; $i < sizeof($tokens); $i++) { - if (is_array($tokens[$i])) { - list($token, $data) = $tokens[$i]; - } else { - $token = $tokens[$i]; - $data = ''; - } - if ($inquote) { - if ($token != '"') { - continue; - } else { - $inquote = false; - } - } - switch ($token) { - case T_WHITESPACE: - continue; - case ';': - if ($interface) { - $current_function = ''; - $current_function_level = -1; - } - break; - case '"': - $inquote = true; - break; - case T_CURLY_OPEN: - case T_DOLLAR_OPEN_CURLY_BRACES: - case '{': $brace_level++; continue 2; - case '}': - $brace_level--; - if ($current_class_level == $brace_level) { - $current_class = ''; - $current_class_level = -1; - } - if ($current_function_level == $brace_level) { - $current_function = ''; - $current_function_level = -1; - } - continue 2; - case '[': $bracket_level++; continue 2; - case ']': $bracket_level--; continue 2; - case '(': $paren_level++; continue 2; - case ')': $paren_level--; continue 2; - case T_INTERFACE: - $interface = true; - case T_CLASS: - if (($current_class_level != -1) || ($current_function_level != -1)) { - PEAR::raiseError("Parser error: Invalid PHP file $file", - PEAR_COMMON_ERROR_INVALIDPHP); - return false; - } - case T_FUNCTION: - case T_NEW: - case T_EXTENDS: - case T_IMPLEMENTS: - $look_for = $token; - continue 2; - case T_STRING: - if (version_compare(zend_version(), '2.0', '<')) { - if (in_array(strtolower($data), - array('public', 'private', 'protected', 'abstract', - 'interface', 'implements', 'clone', 'throw') - )) { - PEAR::raiseError('Error: PHP5 packages must be packaged by php 5 PEAR'); - return false; - } - } - if ($look_for == T_CLASS) { - $current_class = $data; - $current_class_level = $brace_level; - $declared_classes[] = $current_class; - } elseif ($look_for == T_INTERFACE) { - $current_interface = $data; - $current_class_level = $brace_level; - $declared_interfaces[] = $current_interface; - } elseif ($look_for == T_IMPLEMENTS) { - $implements[$current_class] = $data; - } elseif ($look_for == T_EXTENDS) { - $extends[$current_class] = $data; - } elseif ($look_for == T_FUNCTION) { - if ($current_class) { - $current_function = "$current_class::$data"; - $declared_methods[$current_class][] = $data; - } elseif ($current_interface) { - $current_function = "$current_interface::$data"; - $declared_methods[$current_interface][] = $data; - } else { - $current_function = $data; - $declared_functions[] = $current_function; - } - $current_function_level = $brace_level; - $m = array(); - } elseif ($look_for == T_NEW) { - $used_classes[$data] = true; - } - $look_for = 0; - continue 2; - case T_VARIABLE: - $look_for = 0; - continue 2; - case T_DOC_COMMENT: - case T_COMMENT: - if (preg_match('!^/\*\*\s!', $data)) { - $lastphpdoc = $data; - if (preg_match_all('/@nodep\s+(\S+)/', $lastphpdoc, $m)) { - $nodeps = array_merge($nodeps, $m[1]); - } - } - continue 2; - case T_DOUBLE_COLON: - if (!($tokens[$i - 1][0] == T_WHITESPACE || $tokens[$i - 1][0] == T_STRING)) { - PEAR::raiseError("Parser error: Invalid PHP file $file", - PEAR_COMMON_ERROR_INVALIDPHP); - return false; - } - $class = $tokens[$i - 1][1]; - if (strtolower($class) != 'parent') { - $used_classes[$class] = true; - } - continue 2; - } - } - return array( - "source_file" => $file, - "declared_classes" => $declared_classes, - "declared_interfaces" => $declared_interfaces, - "declared_methods" => $declared_methods, - "declared_functions" => $declared_functions, - "used_classes" => array_diff(array_keys($used_classes), $nodeps), - "inheritance" => $extends, - "implements" => $implements, - ); - } - - // }}} - // {{{ betterStates() - - /** - * Return an array containing all of the states that are more stable than - * or equal to the passed in state - * - * @param string Release state - * @param boolean Determines whether to include $state in the list - * @return false|array False if $state is not a valid release state - */ - function betterStates($state, $include = false) - { - static $states = array('snapshot', 'devel', 'alpha', 'beta', 'stable'); - $i = array_search($state, $states); - if ($i === false) { - return false; - } - if ($include) { - $i--; - } - return array_slice($states, $i + 1); - } - - // }}} - // {{{ detectDependencies() - - function detectDependencies($any, $status_callback = null) - { - if (!function_exists("token_get_all")) { - return false; - } - if (PEAR::isError($info = $this->infoFromAny($any))) { - return $this->raiseError($info); - } - if (!is_array($info)) { - return false; - } - $deps = array(); - $used_c = $decl_c = $decl_f = $decl_m = array(); - foreach ($info['filelist'] as $file => $fa) { - $tmp = $this->analyzeSourceCode($file); - $used_c = @array_merge($used_c, $tmp['used_classes']); - $decl_c = @array_merge($decl_c, $tmp['declared_classes']); - $decl_f = @array_merge($decl_f, $tmp['declared_functions']); - $decl_m = @array_merge($decl_m, $tmp['declared_methods']); - $inheri = @array_merge($inheri, $tmp['inheritance']); - } - $used_c = array_unique($used_c); - $decl_c = array_unique($decl_c); - $undecl_c = array_diff($used_c, $decl_c); - return array('used_classes' => $used_c, - 'declared_classes' => $decl_c, - 'declared_methods' => $decl_m, - 'declared_functions' => $decl_f, - 'undeclared_classes' => $undecl_c, - 'inheritance' => $inheri, - ); - } - - // }}} - // {{{ getUserRoles() - - /** - * Get the valid roles for a PEAR package maintainer - * - * @return array - * @static - */ - function getUserRoles() - { - return $GLOBALS['_PEAR_Common_maintainer_roles']; - } - - // }}} - // {{{ getReleaseStates() - - /** - * Get the valid package release states of packages - * - * @return array - * @static - */ - function getReleaseStates() - { - return $GLOBALS['_PEAR_Common_release_states']; - } - - // }}} - // {{{ getDependencyTypes() - - /** - * Get the implemented dependency types (php, ext, pkg etc.) - * - * @return array - * @static - */ - function getDependencyTypes() - { - return $GLOBALS['_PEAR_Common_dependency_types']; - } - - // }}} - // {{{ getDependencyRelations() - - /** - * Get the implemented dependency relations (has, lt, ge etc.) - * - * @return array - * @static - */ - function getDependencyRelations() - { - return $GLOBALS['_PEAR_Common_dependency_relations']; - } - - // }}} - // {{{ getFileRoles() - - /** - * Get the implemented file roles - * - * @return array - * @static - */ - function getFileRoles() - { - return $GLOBALS['_PEAR_Common_file_roles']; - } - - // }}} - // {{{ getReplacementTypes() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getReplacementTypes() - { - return $GLOBALS['_PEAR_Common_replacement_types']; - } - - // }}} - // {{{ getProvideTypes() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getProvideTypes() - { - return $GLOBALS['_PEAR_Common_provide_types']; - } - - // }}} - // {{{ getScriptPhases() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getScriptPhases() - { - return $GLOBALS['_PEAR_Common_script_phases']; - } - - // }}} - // {{{ validPackageName() - - /** - * Test whether a string contains a valid package name. - * - * @param string $name the package name to test - * - * @return bool - * - * @access public - */ - function validPackageName($name) - { - return (bool)preg_match(PEAR_COMMON_PACKAGE_NAME_PREG, $name); - } - - - // }}} - // {{{ validPackageVersion() - - /** - * Test whether a string contains a valid package version. - * - * @param string $ver the package version to test - * - * @return bool - * - * @access public - */ - function validPackageVersion($ver) - { - return (bool)preg_match(PEAR_COMMON_PACKAGE_VERSION_PREG, $ver); - } - - - // }}} - - // {{{ downloadHttp() - - /** - * Download a file through HTTP. Considers suggested file name in - * Content-disposition: header and can run a callback function for - * different events. The callback will be called with two - * parameters: the callback type, and parameters. The implemented - * callback types are: - * - * 'setup' called at the very beginning, parameter is a UI object - * that should be used for all output - * 'message' the parameter is a string with an informational message - * 'saveas' may be used to save with a different file name, the - * parameter is the filename that is about to be used. - * If a 'saveas' callback returns a non-empty string, - * that file name will be used as the filename instead. - * Note that $save_dir will not be affected by this, only - * the basename of the file. - * 'start' download is starting, parameter is number of bytes - * that are expected, or -1 if unknown - * 'bytesread' parameter is the number of bytes read so far - * 'done' download is complete, parameter is the total number - * of bytes read - * 'connfailed' if the TCP connection fails, this callback is called - * with array(host,port,errno,errmsg) - * 'writefailed' if writing to disk fails, this callback is called - * with array(destfile,errmsg) - * - * If an HTTP proxy has been configured (http_proxy PEAR_Config - * setting), the proxy will be used. - * - * @param string $url the URL to download - * @param object $ui PEAR_Frontend_* instance - * @param object $config PEAR_Config instance - * @param string $save_dir (optional) directory to save file in - * @param mixed $callback (optional) function/method to call for status - * updates - * - * @return string Returns the full path of the downloaded file or a PEAR - * error on failure. If the error is caused by - * socket-related errors, the error object will - * have the fsockopen error code available through - * getCode(). - * - * @access public - */ - function downloadHttp($url, &$ui, $save_dir = '.', $callback = null) - { - if ($callback) { - call_user_func($callback, 'setup', array(&$ui)); - } - if (preg_match('!^http://([^/:?#]*)(:(\d+))?(/.*)!', $url, $matches)) { - list(,$host,,$port,$path) = $matches; - } - if (isset($this)) { - $config = &$this->config; - } else { - $config = &PEAR_Config::singleton(); - } - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - if ($proxy = parse_url($config->get('http_proxy'))) { - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @$proxy['user']; - $proxy_pass = @$proxy['pass']; - - if ($proxy_port == '') { - $proxy_port = 8080; - } - if ($callback) { - call_user_func($callback, 'message', "Using HTTP proxy $host:$port"); - } - } - if (empty($port)) { - $port = 80; - } - if ($proxy_host != '') { - $fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr); - if (!$fp) { - if ($callback) { - call_user_func($callback, 'connfailed', array($proxy_host, $proxy_port, - $errno, $errstr)); - } - return PEAR::raiseError("Connection to `$proxy_host:$proxy_port' failed: $errstr", $errno); - } - $request = "GET $url HTTP/1.0\r\n"; - } else { - $fp = @fsockopen($host, $port, $errno, $errstr); - if (!$fp) { - if ($callback) { - call_user_func($callback, 'connfailed', array($host, $port, - $errno, $errstr)); - } - return PEAR::raiseError("Connection to `$host:$port' failed: $errstr", $errno); - } - $request = "GET $path HTTP/1.0\r\n"; - } - $request .= "Host: $host:$port\r\n". - "User-Agent: PHP/".PHP_VERSION."\r\n"; - if ($proxy_host != '' && $proxy_user != '') { - $request .= 'Proxy-Authorization: Basic ' . - base64_encode($proxy_user . ':' . $proxy_pass) . "\r\n"; - } - $request .= "\r\n"; - fwrite($fp, $request); - $headers = array(); - while (trim($line = fgets($fp, 1024))) { - if (preg_match('/^([^:]+):\s+(.*)\s*$/', $line, $matches)) { - $headers[strtolower($matches[1])] = trim($matches[2]); - } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) { - if ($matches[1] != 200) { - return PEAR::raiseError("File http://$host:$port$path not valid (received: $line)"); - } - } - } - if (isset($headers['content-disposition']) && - preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|$)/', $headers['content-disposition'], $matches)) { - $save_as = basename($matches[1]); - } else { - $save_as = basename($url); - } - if ($callback) { - $tmp = call_user_func($callback, 'saveas', $save_as); - if ($tmp) { - $save_as = $tmp; - } - } - $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as; - if (!$wp = @fopen($dest_file, 'wb')) { - fclose($fp); - if ($callback) { - call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg)); - } - return PEAR::raiseError("could not open $dest_file for writing"); - } - if (isset($headers['content-length'])) { - $length = $headers['content-length']; - } else { - $length = -1; - } - $bytes = 0; - if ($callback) { - call_user_func($callback, 'start', array(basename($dest_file), $length)); - } - while ($data = @fread($fp, 1024)) { - $bytes += strlen($data); - if ($callback) { - call_user_func($callback, 'bytesread', $bytes); - } - if (!@fwrite($wp, $data)) { - fclose($fp); - if ($callback) { - call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg)); - } - return PEAR::raiseError("$dest_file: write failed ($php_errormsg)"); - } - } - fclose($fp); - fclose($wp); - if ($callback) { - call_user_func($callback, 'done', $bytes); - } - return $dest_file; - } - - // }}} - // {{{ sortPkgDeps() - - /** - * Sort a list of arrays of array(downloaded packagefilename) by dependency. - * - * It also removes duplicate dependencies - * @param array - * @param boolean Sort packages in reverse order if true - * @return array array of array(packagefilename, package.xml contents) - */ - function sortPkgDeps(&$packages, $uninstall = false) - { - $ret = array(); - if ($uninstall) { - foreach($packages as $packageinfo) { - $ret[] = array('info' => $packageinfo); - } - } else { - foreach($packages as $packagefile) { - if (!is_array($packagefile)) { - $ret[] = array('file' => $packagefile, - 'info' => $a = $this->infoFromAny($packagefile), - 'pkg' => $a['package']); - } else { - $ret[] = $packagefile; - } - } - } - $checkdupes = array(); - $newret = array(); - foreach($ret as $i => $p) { - if (!isset($checkdupes[$p['info']['package']])) { - $checkdupes[$p['info']['package']][] = $i; - $newret[] = $p; - } - } - $this->_packageSortTree = $this->_getPkgDepTree($newret); - - $func = $uninstall ? '_sortPkgDepsRev' : '_sortPkgDeps'; - usort($newret, array(&$this, $func)); - $this->_packageSortTree = null; - $packages = $newret; - } - - // }}} - // {{{ _sortPkgDeps() - - /** - * Compare two package's package.xml, and sort - * so that dependencies are installed first - * - * This is a crude compare, real dependency checking is done on install. - * The only purpose this serves is to make the command-line - * order-independent (you can list a dependent package first, and - * installation occurs in the order required) - * @access private - */ - function _sortPkgDeps($p1, $p2) - { - $p1name = $p1['info']['package']; - $p2name = $p2['info']['package']; - $p1deps = $this->_getPkgDeps($p1); - $p2deps = $this->_getPkgDeps($p2); - if (!count($p1deps) && !count($p2deps)) { - return 0; // order makes no difference - } - if (!count($p1deps)) { - return -1; // package 2 has dependencies, package 1 doesn't - } - if (!count($p2deps)) { - return 1; // package 1 has dependencies, package 2 doesn't - } - // both have dependencies - if (in_array($p1name, $p2deps)) { - return -1; // put package 1 first: package 2 depends on package 1 - } - if (in_array($p2name, $p1deps)) { - return 1; // put package 2 first: package 1 depends on package 2 - } - if ($this->_removedDependency($p1name, $p2name)) { - return -1; // put package 1 first: package 2 depends on packages that depend on package 1 - } - if ($this->_removedDependency($p2name, $p1name)) { - return 1; // put package 2 first: package 1 depends on packages that depend on package 2 - } - // doesn't really matter if neither depends on the other - return 0; - } - - // }}} - // {{{ _sortPkgDepsRev() - - /** - * Compare two package's package.xml, and sort - * so that dependencies are uninstalled last - * - * This is a crude compare, real dependency checking is done on uninstall. - * The only purpose this serves is to make the command-line - * order-independent (you can list a dependency first, and - * uninstallation occurs in the order required) - * @access private - */ - function _sortPkgDepsRev($p1, $p2) - { - $p1name = $p1['info']['package']; - $p2name = $p2['info']['package']; - $p1deps = $this->_getRevPkgDeps($p1); - $p2deps = $this->_getRevPkgDeps($p2); - if (!count($p1deps) && !count($p2deps)) { - return 0; // order makes no difference - } - if (!count($p1deps)) { - return 1; // package 2 has dependencies, package 1 doesn't - } - if (!count($p2deps)) { - return -1; // package 2 has dependencies, package 1 doesn't - } - // both have dependencies - if (in_array($p1name, $p2deps)) { - return 1; // put package 1 last - } - if (in_array($p2name, $p1deps)) { - return -1; // put package 2 last - } - if ($this->_removedDependency($p1name, $p2name)) { - return 1; // put package 1 last: package 2 depends on packages that depend on package 1 - } - if ($this->_removedDependency($p2name, $p1name)) { - return -1; // put package 2 last: package 1 depends on packages that depend on package 2 - } - // doesn't really matter if neither depends on the other - return 0; - } - - // }}} - // {{{ _getPkgDeps() - - /** - * get an array of package dependency names - * @param array - * @return array - * @access private - */ - function _getPkgDeps($p) - { - if (!isset($p['info']['releases'])) { - return $this->_getRevPkgDeps($p); - } - $rel = array_shift($p['info']['releases']); - if (!isset($rel['deps'])) { - return array(); - } - $ret = array(); - foreach($rel['deps'] as $dep) { - if ($dep['type'] == 'pkg') { - $ret[] = $dep['name']; - } - } - return $ret; - } - - // }}} - // {{{ _getPkgDeps() - - /** - * get an array representation of the package dependency tree - * @return array - * @access private - */ - function _getPkgDepTree($packages) - { - $tree = array(); - foreach ($packages as $p) { - $package = $p['info']['package']; - $deps = $this->_getPkgDeps($p); - $tree[$package] = $deps; - } - return $tree; - } - - // }}} - // {{{ _removedDependency($p1, $p2) - - /** - * get an array of package dependency names for uninstall - * @param string package 1 name - * @param string package 2 name - * @return bool - * @access private - */ - function _removedDependency($p1, $p2) - { - if (empty($this->_packageSortTree[$p2])) { - return false; - } - if (!in_array($p1, $this->_packageSortTree[$p2])) { - foreach ($this->_packageSortTree[$p2] as $potential) { - if ($this->_removedDependency($p1, $potential)) { - return true; - } - } - return false; - } - return true; - } - - // }}} - // {{{ _getRevPkgDeps() - - /** - * get an array of package dependency names for uninstall - * @param array - * @return array - * @access private - */ - function _getRevPkgDeps($p) - { - if (!isset($p['info']['release_deps'])) { - return array(); - } - $ret = array(); - foreach($p['info']['release_deps'] as $dep) { - if ($dep['type'] == 'pkg') { - $ret[] = $dep['name']; - } - } - return $ret; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Config.php b/3rdparty/PEAR/Config.php deleted file mode 100644 index ba64173525..0000000000 --- a/3rdparty/PEAR/Config.php +++ /dev/null @@ -1,1169 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Config.php,v 1.52 2004/01/08 17:33:12 sniper Exp $ - -require_once 'PEAR.php'; -require_once 'System.php'; - -/** - * Last created PEAR_Config instance. - * @var object - */ -$GLOBALS['_PEAR_Config_instance'] = null; -if (!defined('PEAR_INSTALL_DIR') || !PEAR_INSTALL_DIR) { - $PEAR_INSTALL_DIR = PHP_LIBDIR . DIRECTORY_SEPARATOR . 'pear'; -} else { - $PEAR_INSTALL_DIR = PEAR_INSTALL_DIR; -} - -// Below we define constants with default values for all configuration -// parameters except username/password. All of them can have their -// defaults set through environment variables. The reason we use the -// PHP_ prefix is for some security, PHP protects environment -// variables starting with PHP_*. - -if (getenv('PHP_PEAR_SYSCONF_DIR')) { - define('PEAR_CONFIG_SYSCONFDIR', getenv('PHP_PEAR_SYSCONF_DIR')); -} elseif (getenv('SystemRoot')) { - define('PEAR_CONFIG_SYSCONFDIR', getenv('SystemRoot')); -} else { - define('PEAR_CONFIG_SYSCONFDIR', PHP_SYSCONFDIR); -} - -// Default for master_server -if (getenv('PHP_PEAR_MASTER_SERVER')) { - define('PEAR_CONFIG_DEFAULT_MASTER_SERVER', getenv('PHP_PEAR_MASTER_SERVER')); -} else { - define('PEAR_CONFIG_DEFAULT_MASTER_SERVER', 'pear.php.net'); -} - -// Default for http_proxy -if (getenv('PHP_PEAR_HTTP_PROXY')) { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', getenv('PHP_PEAR_HTTP_PROXY')); -} elseif (getenv('http_proxy')) { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', getenv('http_proxy')); -} else { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', ''); -} - -// Default for php_dir -if (getenv('PHP_PEAR_INSTALL_DIR')) { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', getenv('PHP_PEAR_INSTALL_DIR')); -} else { - if (@is_dir($PEAR_INSTALL_DIR)) { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', - $PEAR_INSTALL_DIR); - } else { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', $PEAR_INSTALL_DIR); - } -} - -// Default for ext_dir -if (getenv('PHP_PEAR_EXTENSION_DIR')) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', getenv('PHP_PEAR_EXTENSION_DIR')); -} else { - if (ini_get('extension_dir')) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', ini_get('extension_dir')); - } elseif (defined('PEAR_EXTENSION_DIR') && @is_dir(PEAR_EXTENSION_DIR)) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', PEAR_EXTENSION_DIR); - } elseif (defined('PHP_EXTENSION_DIR')) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', PHP_EXTENSION_DIR); - } else { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', '.'); - } -} - -// Default for doc_dir -if (getenv('PHP_PEAR_DOC_DIR')) { - define('PEAR_CONFIG_DEFAULT_DOC_DIR', getenv('PHP_PEAR_DOC_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_DOC_DIR', - $PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'docs'); -} - -// Default for bin_dir -if (getenv('PHP_PEAR_BIN_DIR')) { - define('PEAR_CONFIG_DEFAULT_BIN_DIR', getenv('PHP_PEAR_BIN_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_BIN_DIR', PHP_BINDIR); -} - -// Default for data_dir -if (getenv('PHP_PEAR_DATA_DIR')) { - define('PEAR_CONFIG_DEFAULT_DATA_DIR', getenv('PHP_PEAR_DATA_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_DATA_DIR', - $PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'data'); -} - -// Default for test_dir -if (getenv('PHP_PEAR_TEST_DIR')) { - define('PEAR_CONFIG_DEFAULT_TEST_DIR', getenv('PHP_PEAR_TEST_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_TEST_DIR', - $PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'tests'); -} - -// Default for cache_dir -if (getenv('PHP_PEAR_CACHE_DIR')) { - define('PEAR_CONFIG_DEFAULT_CACHE_DIR', getenv('PHP_PEAR_CACHE_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_CACHE_DIR', - System::tmpdir() . DIRECTORY_SEPARATOR . 'pear' . - DIRECTORY_SEPARATOR . 'cache'); -} - -// Default for php_bin -if (getenv('PHP_PEAR_PHP_BIN')) { - define('PEAR_CONFIG_DEFAULT_PHP_BIN', getenv('PHP_PEAR_PHP_BIN')); -} else { - define('PEAR_CONFIG_DEFAULT_PHP_BIN', PEAR_CONFIG_DEFAULT_BIN_DIR. - DIRECTORY_SEPARATOR.'php'.(OS_WINDOWS ? '.exe' : '')); -} - -// Default for verbose -if (getenv('PHP_PEAR_VERBOSE')) { - define('PEAR_CONFIG_DEFAULT_VERBOSE', getenv('PHP_PEAR_VERBOSE')); -} else { - define('PEAR_CONFIG_DEFAULT_VERBOSE', 1); -} - -// Default for preferred_state -if (getenv('PHP_PEAR_PREFERRED_STATE')) { - define('PEAR_CONFIG_DEFAULT_PREFERRED_STATE', getenv('PHP_PEAR_PREFERRED_STATE')); -} else { - define('PEAR_CONFIG_DEFAULT_PREFERRED_STATE', 'stable'); -} - -// Default for umask -if (getenv('PHP_PEAR_UMASK')) { - define('PEAR_CONFIG_DEFAULT_UMASK', getenv('PHP_PEAR_UMASK')); -} else { - define('PEAR_CONFIG_DEFAULT_UMASK', decoct(umask())); -} - -// Default for cache_ttl -if (getenv('PHP_PEAR_CACHE_TTL')) { - define('PEAR_CONFIG_DEFAULT_CACHE_TTL', getenv('PHP_PEAR_CACHE_TTL')); -} else { - define('PEAR_CONFIG_DEFAULT_CACHE_TTL', 3600); -} - -// Default for sig_type -if (getenv('PHP_PEAR_SIG_TYPE')) { - define('PEAR_CONFIG_DEFAULT_SIG_TYPE', getenv('PHP_PEAR_SIG_TYPE')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_TYPE', 'gpg'); -} - -// Default for sig_bin -if (getenv('PHP_PEAR_SIG_BIN')) { - define('PEAR_CONFIG_DEFAULT_SIG_BIN', getenv('PHP_PEAR_SIG_BIN')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_BIN', - System::which( - 'gpg', OS_WINDOWS ? 'c:\gnupg\gpg.exe' : '/usr/local/bin/gpg')); -} - -// Default for sig_keydir -if (getenv('PHP_PEAR_SIG_KEYDIR')) { - define('PEAR_CONFIG_DEFAULT_SIG_KEYDIR', getenv('PHP_PEAR_SIG_KEYDIR')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_KEYDIR', - PEAR_CONFIG_SYSCONFDIR . DIRECTORY_SEPARATOR . 'pearkeys'); -} - -/** - * This is a class for storing configuration data, keeping track of - * which are system-defined, user-defined or defaulted. - */ -class PEAR_Config extends PEAR -{ - // {{{ properties - - /** - * Array of config files used. - * - * @var array layer => config file - */ - var $files = array( - 'system' => '', - 'user' => '', - ); - - var $layers = array(); - - /** - * Configuration data, two-dimensional array where the first - * dimension is the config layer ('user', 'system' and 'default'), - * and the second dimension is keyname => value. - * - * The order in the first dimension is important! Earlier - * layers will shadow later ones when a config value is - * requested (if a 'user' value exists, it will be returned first, - * then 'system' and finally 'default'). - * - * @var array layer => array(keyname => value, ...) - */ - var $configuration = array( - 'user' => array(), - 'system' => array(), - 'default' => array(), - ); - - /** - * Information about the configuration data. Stores the type, - * default value and a documentation string for each configuration - * value. - * - * @var array layer => array(infotype => value, ...) - */ - var $configuration_info = array( - // Internet Access - 'master_server' => array( - 'type' => 'string', - 'default' => 'pear.php.net', - 'doc' => 'name of the main PEAR server', - 'prompt' => 'PEAR server', - 'group' => 'Internet Access', - ), - 'http_proxy' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_HTTP_PROXY, - 'doc' => 'HTTP proxy (host:port) to use when downloading packages', - 'prompt' => 'HTTP Proxy Server Address', - 'group' => 'Internet Access', - ), - // File Locations - 'php_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_PHP_DIR, - 'doc' => 'directory where .php files are installed', - 'prompt' => 'PEAR directory', - 'group' => 'File Locations', - ), - 'ext_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_EXT_DIR, - 'doc' => 'directory where loadable extensions are installed', - 'prompt' => 'PHP extension directory', - 'group' => 'File Locations', - ), - 'doc_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_DOC_DIR, - 'doc' => 'directory where documentation is installed', - 'prompt' => 'PEAR documentation directory', - 'group' => 'File Locations', - ), - 'bin_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_BIN_DIR, - 'doc' => 'directory where executables are installed', - 'prompt' => 'PEAR executables directory', - 'group' => 'File Locations', - ), - 'data_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_DATA_DIR, - 'doc' => 'directory where data files are installed', - 'prompt' => 'PEAR data directory', - 'group' => 'File Locations (Advanced)', - ), - 'test_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_TEST_DIR, - 'doc' => 'directory where regression tests are installed', - 'prompt' => 'PEAR test directory', - 'group' => 'File Locations (Advanced)', - ), - 'cache_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_CACHE_DIR, - 'doc' => 'directory which is used for XMLRPC cache', - 'prompt' => 'PEAR Installer cache directory', - 'group' => 'File Locations (Advanced)', - ), - 'php_bin' => array( - 'type' => 'file', - 'default' => PEAR_CONFIG_DEFAULT_PHP_BIN, - 'doc' => 'PHP CLI/CGI binary for executing scripts', - 'prompt' => 'PHP CLI/CGI binary', - 'group' => 'File Locations (Advanced)', - ), - // Maintainers - 'username' => array( - 'type' => 'string', - 'default' => '', - 'doc' => '(maintainers) your PEAR account name', - 'prompt' => 'PEAR username (for maintainers)', - 'group' => 'Maintainers', - ), - 'password' => array( - 'type' => 'password', - 'default' => '', - 'doc' => '(maintainers) your PEAR account password', - 'prompt' => 'PEAR password (for maintainers)', - 'group' => 'Maintainers', - ), - // Advanced - 'verbose' => array( - 'type' => 'integer', - 'default' => PEAR_CONFIG_DEFAULT_VERBOSE, - 'doc' => 'verbosity level -0: really quiet -1: somewhat quiet -2: verbose -3: debug', - 'prompt' => 'Debug Log Level', - 'group' => 'Advanced', - ), - 'preferred_state' => array( - 'type' => 'set', - 'default' => PEAR_CONFIG_DEFAULT_PREFERRED_STATE, - 'doc' => 'the installer will prefer releases with this state when installing packages without a version or state specified', - 'valid_set' => array( - 'stable', 'beta', 'alpha', 'devel', 'snapshot'), - 'prompt' => 'Preferred Package State', - 'group' => 'Advanced', - ), - 'umask' => array( - 'type' => 'mask', - 'default' => PEAR_CONFIG_DEFAULT_UMASK, - 'doc' => 'umask used when creating files (Unix-like systems only)', - 'prompt' => 'Unix file mask', - 'group' => 'Advanced', - ), - 'cache_ttl' => array( - 'type' => 'integer', - 'default' => PEAR_CONFIG_DEFAULT_CACHE_TTL, - 'doc' => 'amount of secs where the local cache is used and not updated', - 'prompt' => 'Cache TimeToLive', - 'group' => 'Advanced', - ), - 'sig_type' => array( - 'type' => 'set', - 'default' => PEAR_CONFIG_DEFAULT_SIG_TYPE, - 'doc' => 'which package signature mechanism to use', - 'valid_set' => array('gpg'), - 'prompt' => 'Package Signature Type', - 'group' => 'Maintainers', - ), - 'sig_bin' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_SIG_BIN, - 'doc' => 'which package signature mechanism to use', - 'prompt' => 'Signature Handling Program', - 'group' => 'Maintainers', - ), - 'sig_keyid' => array( - 'type' => 'string', - 'default' => '', - 'doc' => 'which key to use for signing with', - 'prompt' => 'Signature Key Id', - 'group' => 'Maintainers', - ), - 'sig_keydir' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_SIG_KEYDIR, - 'doc' => 'which package signature mechanism to use', - 'prompt' => 'Signature Key Directory', - 'group' => 'Maintainers', - ), - ); - - // }}} - - // {{{ PEAR_Config([file], [defaults_file]) - - /** - * Constructor. - * - * @param string (optional) file to read user-defined options from - * @param string (optional) file to read system-wide defaults from - * - * @access public - * - * @see PEAR_Config::singleton - */ - function PEAR_Config($user_file = '', $system_file = '') - { - $this->PEAR(); - $sl = DIRECTORY_SEPARATOR; - if (empty($user_file)) { - if (OS_WINDOWS) { - $user_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pear.ini'; - } else { - $user_file = getenv('HOME') . $sl . '.pearrc'; - } - } - if (empty($system_file)) { - if (OS_WINDOWS) { - $system_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pearsys.ini'; - } else { - $system_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pear.conf'; - } - } - $this->layers = array_keys($this->configuration); - $this->files['user'] = $user_file; - $this->files['system'] = $system_file; - if ($user_file && file_exists($user_file)) { - $this->readConfigFile($user_file); - } - if ($system_file && file_exists($system_file)) { - $this->mergeConfigFile($system_file, false, 'system'); - } - foreach ($this->configuration_info as $key => $info) { - $this->configuration['default'][$key] = $info['default']; - } - //$GLOBALS['_PEAR_Config_instance'] = &$this; - } - - // }}} - // {{{ singleton([file], [defaults_file]) - - /** - * Static singleton method. If you want to keep only one instance - * of this class in use, this method will give you a reference to - * the last created PEAR_Config object if one exists, or create a - * new object. - * - * @param string (optional) file to read user-defined options from - * @param string (optional) file to read system-wide defaults from - * - * @return object an existing or new PEAR_Config instance - * - * @access public - * - * @see PEAR_Config::PEAR_Config - */ - function &singleton($user_file = '', $system_file = '') - { - if (is_object($GLOBALS['_PEAR_Config_instance'])) { - return $GLOBALS['_PEAR_Config_instance']; - } - $GLOBALS['_PEAR_Config_instance'] = - &new PEAR_Config($user_file, $system_file); - return $GLOBALS['_PEAR_Config_instance']; - } - - // }}} - // {{{ readConfigFile([file], [layer]) - - /** - * Reads configuration data from a file. All existing values in - * the config layer are discarded and replaced with data from the - * file. - * - * @param string (optional) file to read from, if NULL or not - * specified, the last-used file for the same layer (second param) - * is used - * - * @param string (optional) config layer to insert data into - * ('user' or 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public - */ - function readConfigFile($file = null, $layer = 'user') - { - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = $this->_readConfigDataFrom($file); - if (PEAR::isError($data)) { - return $data; - } - $this->_decodeInput($data); - $this->configuration[$layer] = $data; - return true; - } - - // }}} - // {{{ mergeConfigFile(file, [override], [layer]) - - /** - * Merges data into a config layer from a file. Does the same - * thing as readConfigFile, except it does not replace all - * existing values in the config layer. - * - * @param string file to read from - * - * @param bool (optional) whether to overwrite existing data - * (default TRUE) - * - * @param string config layer to insert data into ('user' or - * 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public. - */ - function mergeConfigFile($file, $override = true, $layer = 'user') - { - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = $this->_readConfigDataFrom($file); - if (PEAR::isError($data)) { - return $data; - } - $this->_decodeInput($data); - if ($override) { - $this->configuration[$layer] = array_merge($this->configuration[$layer], $data); - } else { - $this->configuration[$layer] = array_merge($data, $this->configuration[$layer]); - } - return true; - } - - // }}} - // {{{ writeConfigFile([file], [layer]) - - /** - * Writes data into a config layer from a file. - * - * @param string file to read from - * - * @param bool (optional) whether to overwrite existing data - * (default TRUE) - * - * @param string config layer to insert data into ('user' or - * 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public. - */ - function writeConfigFile($file = null, $layer = 'user', $data = null) - { - if ($layer == 'both' || $layer == 'all') { - foreach ($this->files as $type => $file) { - $err = $this->writeConfigFile($file, $type, $data); - if (PEAR::isError($err)) { - return $err; - } - } - return true; - } - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = ($data === null) ? $this->configuration[$layer] : $data; - $this->_encodeOutput($data); - $opt = array('-p', dirname($file)); - if (!@System::mkDir($opt)) { - return $this->raiseError("could not create directory: " . dirname($file)); - } - if (@is_file($file) && !@is_writeable($file)) { - return $this->raiseError("no write access to $file!"); - } - $fp = @fopen($file, "w"); - if (!$fp) { - return $this->raiseError("PEAR_Config::writeConfigFile fopen('$file','w') failed"); - } - $contents = "#PEAR_Config 0.9\n" . serialize($data); - if (!@fwrite($fp, $contents)) { - return $this->raiseError("PEAR_Config::writeConfigFile: fwrite failed"); - } - return true; - } - - // }}} - // {{{ _readConfigDataFrom(file) - - /** - * Reads configuration data from a file and returns the parsed data - * in an array. - * - * @param string file to read from - * - * @return array configuration data or a PEAR error on failure - * - * @access private - */ - function _readConfigDataFrom($file) - { - $fp = @fopen($file, "r"); - if (!$fp) { - return $this->raiseError("PEAR_Config::readConfigFile fopen('$file','r') failed"); - } - $size = filesize($file); - $rt = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - $contents = fread($fp, $size); - set_magic_quotes_runtime($rt); - fclose($fp); - $version = '0.1'; - if (preg_match('/^#PEAR_Config\s+(\S+)\s+/si', $contents, $matches)) { - $version = $matches[1]; - $contents = substr($contents, strlen($matches[0])); - } - if (version_compare("$version", '1', '<')) { - $data = unserialize($contents); - if (!is_array($data)) { - if (strlen(trim($contents)) > 0) { - $error = "PEAR_Config: bad data in $file"; -// if (isset($this)) { - return $this->raiseError($error); -// } else { -// return PEAR::raiseError($error); - } else { - $data = array(); - } - } - // add parsing of newer formats here... - } else { - return $this->raiseError("$file: unknown version `$version'"); - } - return $data; - } - - // }}} - // {{{ getConfFile(layer) - /** - * Gets the file used for storing the config for a layer - * - * @param string $layer 'user' or 'system' - */ - - function getConfFile($layer) - { - return $this->files[$layer]; - } - - // }}} - // {{{ _encodeOutput(&data) - - /** - * Encodes/scrambles configuration data before writing to files. - * Currently, 'password' values will be base64-encoded as to avoid - * that people spot cleartext passwords by accident. - * - * @param array (reference) array to encode values in - * - * @return bool TRUE on success - * - * @access private - */ - function _encodeOutput(&$data) - { - foreach ($data as $key => $value) { - if (!isset($this->configuration_info[$key])) { - continue; - } - $type = $this->configuration_info[$key]['type']; - switch ($type) { - // we base64-encode passwords so they are at least - // not shown in plain by accident - case 'password': { - $data[$key] = base64_encode($data[$key]); - break; - } - case 'mask': { - $data[$key] = octdec($data[$key]); - break; - } - } - } - return true; - } - - // }}} - // {{{ _decodeInput(&data) - - /** - * Decodes/unscrambles configuration data after reading from files. - * - * @param array (reference) array to encode values in - * - * @return bool TRUE on success - * - * @access private - * - * @see PEAR_Config::_encodeOutput - */ - function _decodeInput(&$data) - { - if (!is_array($data)) { - return true; - } - foreach ($data as $key => $value) { - if (!isset($this->configuration_info[$key])) { - continue; - } - $type = $this->configuration_info[$key]['type']; - switch ($type) { - case 'password': { - $data[$key] = base64_decode($data[$key]); - break; - } - case 'mask': { - $data[$key] = decoct($data[$key]); - break; - } - } - } - return true; - } - - // }}} - // {{{ get(key, [layer]) - - /** - * Returns a configuration value, prioritizing layers as per the - * layers property. - * - * @param string config key - * - * @return mixed the config value, or NULL if not found - * - * @access public - */ - function get($key, $layer = null) - { - if ($layer === null) { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return $this->configuration[$layer][$key]; - } - } - } elseif (isset($this->configuration[$layer][$key])) { - return $this->configuration[$layer][$key]; - } - return null; - } - - // }}} - // {{{ set(key, value, [layer]) - - /** - * Set a config value in a specific layer (defaults to 'user'). - * Enforces the types defined in the configuration_info array. An - * integer config variable will be cast to int, and a set config - * variable will be validated against its legal values. - * - * @param string config key - * - * @param string config value - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function set($key, $value, $layer = 'user') - { - if (empty($this->configuration_info[$key])) { - return false; - } - extract($this->configuration_info[$key]); - switch ($type) { - case 'integer': - $value = (int)$value; - break; - case 'set': { - // If a valid_set is specified, require the value to - // be in the set. If there is no valid_set, accept - // any value. - if ($valid_set) { - reset($valid_set); - if ((key($valid_set) === 0 && !in_array($value, $valid_set)) || - (key($valid_set) !== 0 && empty($valid_set[$value]))) - { - return false; - } - } - break; - } - } - $this->configuration[$layer][$key] = $value; - return true; - } - - // }}} - // {{{ getType(key) - - /** - * Get the type of a config value. - * - * @param string config key - * - * @return string type, one of "string", "integer", "file", - * "directory", "set" or "password". - * - * @access public - * - */ - function getType($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['type']; - } - return false; - } - - // }}} - // {{{ getDocs(key) - - /** - * Get the documentation for a config value. - * - * @param string config key - * - * @return string documentation string - * - * @access public - * - */ - function getDocs($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['doc']; - } - return false; - } - // }}} - // {{{ getPrompt(key) - - /** - * Get the short documentation for a config value. - * - * @param string config key - * - * @return string short documentation string - * - * @access public - * - */ - function getPrompt($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['prompt']; - } - return false; - } - // }}} - // {{{ getGroup(key) - - /** - * Get the parameter group for a config key. - * - * @param string config key - * - * @return string parameter group - * - * @access public - * - */ - function getGroup($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['group']; - } - return false; - } - - // }}} - // {{{ getGroups() - - /** - * Get the list of parameter groups. - * - * @return array list of parameter groups - * - * @access public - * - */ - function getGroups() - { - $tmp = array(); - foreach ($this->configuration_info as $key => $info) { - $tmp[$info['group']] = 1; - } - return array_keys($tmp); - } - - // }}} - // {{{ getGroupKeys() - - /** - * Get the list of the parameters in a group. - * - * @param string $group parameter group - * - * @return array list of parameters in $group - * - * @access public - * - */ - function getGroupKeys($group) - { - $keys = array(); - foreach ($this->configuration_info as $key => $info) { - if ($info['group'] == $group) { - $keys[] = $key; - } - } - return $keys; - } - - // }}} - // {{{ getSetValues(key) - - /** - * Get the list of allowed set values for a config value. Returns - * NULL for config values that are not sets. - * - * @param string config key - * - * @return array enumerated array of set values, or NULL if the - * config key is unknown or not a set - * - * @access public - * - */ - function getSetValues($key) - { - if (isset($this->configuration_info[$key]) && - isset($this->configuration_info[$key]['type']) && - $this->configuration_info[$key]['type'] == 'set') - { - $valid_set = $this->configuration_info[$key]['valid_set']; - reset($valid_set); - if (key($valid_set) === 0) { - return $valid_set; - } - return array_keys($valid_set); - } - return false; - } - - // }}} - // {{{ getKeys() - - /** - * Get all the current config keys. - * - * @return array simple array of config keys - * - * @access public - */ - function getKeys() - { - $keys = array(); - foreach ($this->layers as $layer) { - $keys = array_merge($keys, $this->configuration[$layer]); - } - return array_keys($keys); - } - - // }}} - // {{{ remove(key, [layer]) - - /** - * Remove the a config key from a specific config layer. - * - * @param string config key - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function remove($key, $layer = 'user') - { - if (isset($this->configuration[$layer][$key])) { - unset($this->configuration[$layer][$key]); - return true; - } - return false; - } - - // }}} - // {{{ removeLayer(layer) - - /** - * Temporarily remove an entire config layer. USE WITH CARE! - * - * @param string config key - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function removeLayer($layer) - { - if (isset($this->configuration[$layer])) { - $this->configuration[$layer] = array(); - return true; - } - return false; - } - - // }}} - // {{{ store([layer]) - - /** - * Stores configuration data in a layer. - * - * @param string config layer to store - * - * @return bool TRUE on success, or PEAR error on failure - * - * @access public - */ - function store($layer = 'user', $data = null) - { - return $this->writeConfigFile(null, $layer, $data); - } - - // }}} - // {{{ toDefault(key) - - /** - * Unset the user-defined value of a config key, reverting the - * value to the system-defined one. - * - * @param string config key - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function toDefault($key) - { - trigger_error("PEAR_Config::toDefault() deprecated, use PEAR_Config::remove() instead", E_USER_NOTICE); - return $this->remove($key, 'user'); - } - - // }}} - // {{{ definedBy(key) - - /** - * Tells what config layer that gets to define a key. - * - * @param string config key - * - * @return string the config layer, or an empty string if not found - * - * @access public - */ - function definedBy($key) - { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return $layer; - } - } - return ''; - } - - // }}} - // {{{ isDefaulted(key) - - /** - * Tells whether a config value has a system-defined value. - * - * @param string config key - * - * @return bool - * - * @access public - * - * @deprecated - */ - function isDefaulted($key) - { - trigger_error("PEAR_Config::isDefaulted() deprecated, use PEAR_Config::definedBy() instead", E_USER_NOTICE); - return $this->definedBy($key) == 'system'; - } - - // }}} - // {{{ isDefined(key) - - /** - * Tells whether a given key exists as a config value. - * - * @param string config key - * - * @return bool whether exists in this object - * - * @access public - */ - function isDefined($key) - { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return true; - } - } - return false; - } - - // }}} - // {{{ isDefinedLayer(key) - - /** - * Tells whether a given config layer exists. - * - * @param string config layer - * - * @return bool whether exists in this object - * - * @access public - */ - function isDefinedLayer($layer) - { - return isset($this->configuration[$layer]); - } - - // }}} - // {{{ getLayers() - - /** - * Returns the layers defined (except the 'default' one) - * - * @return array of the defined layers - */ - function getLayers() - { - $cf = $this->configuration; - unset($cf['default']); - return array_keys($cf); - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Dependency.php b/3rdparty/PEAR/Dependency.php deleted file mode 100644 index 705167aa70..0000000000 --- a/3rdparty/PEAR/Dependency.php +++ /dev/null @@ -1,487 +0,0 @@ - | -// | Stig Bakken | -// +----------------------------------------------------------------------+ -// -// $Id: Dependency.php,v 1.36.4.1 2004/12/27 07:04:19 cellog Exp $ - -require_once "PEAR.php"; - -define('PEAR_DEPENDENCY_MISSING', -1); -define('PEAR_DEPENDENCY_CONFLICT', -2); -define('PEAR_DEPENDENCY_UPGRADE_MINOR', -3); -define('PEAR_DEPENDENCY_UPGRADE_MAJOR', -4); -define('PEAR_DEPENDENCY_BAD_DEPENDENCY', -5); -define('PEAR_DEPENDENCY_MISSING_OPTIONAL', -6); -define('PEAR_DEPENDENCY_CONFLICT_OPTIONAL', -7); -define('PEAR_DEPENDENCY_UPGRADE_MINOR_OPTIONAL', -8); -define('PEAR_DEPENDENCY_UPGRADE_MAJOR_OPTIONAL', -9); - -/** - * Dependency check for PEAR packages - * - * The class is based on the dependency RFC that can be found at - * http://cvs.php.net/cvs.php/pearweb/rfc. It requires PHP >= 4.1 - * - * @author Tomas V.V.Vox - * @author Stig Bakken - */ -class PEAR_Dependency -{ - // {{{ constructor - /** - * Constructor - * - * @access public - * @param object Registry object - * @return void - */ - function PEAR_Dependency(&$registry) - { - $this->registry = &$registry; - } - - // }}} - // {{{ callCheckMethod() - - /** - * This method maps the XML dependency definition to the - * corresponding one from PEAR_Dependency - * - *
-    * $opts => Array
-    *    (
-    *        [type] => pkg
-    *        [rel] => ge
-    *        [version] => 3.4
-    *        [name] => HTML_Common
-    *        [optional] => false
-    *    )
-    * 
- * - * @param string Error message - * @param array Options - * @return boolean - */ - function callCheckMethod(&$errmsg, $opts) - { - $rel = isset($opts['rel']) ? $opts['rel'] : 'has'; - $req = isset($opts['version']) ? $opts['version'] : null; - $name = isset($opts['name']) ? $opts['name'] : null; - $opt = (isset($opts['optional']) && $opts['optional'] == 'yes') ? - $opts['optional'] : null; - $errmsg = ''; - switch ($opts['type']) { - case 'pkg': - return $this->checkPackage($errmsg, $name, $req, $rel, $opt); - break; - case 'ext': - return $this->checkExtension($errmsg, $name, $req, $rel, $opt); - break; - case 'php': - return $this->checkPHP($errmsg, $req, $rel); - break; - case 'prog': - return $this->checkProgram($errmsg, $name); - break; - case 'os': - return $this->checkOS($errmsg, $name); - break; - case 'sapi': - return $this->checkSAPI($errmsg, $name); - break; - case 'zend': - return $this->checkZend($errmsg, $name); - break; - default: - return "'{$opts['type']}' dependency type not supported"; - } - } - - // }}} - // {{{ checkPackage() - - /** - * Package dependencies check method - * - * @param string $errmsg Empty string, it will be populated with an error message, if any - * @param string $name Name of the package to test - * @param string $req The package version required - * @param string $relation How to compare versions with each other - * @param bool $opt Whether the relationship is optional - * - * @return mixed bool false if no error or the error string - */ - function checkPackage(&$errmsg, $name, $req = null, $relation = 'has', - $opt = false) - { - if (is_string($req) && substr($req, 0, 2) == 'v.') { - $req = substr($req, 2); - } - switch ($relation) { - case 'has': - if (!$this->registry->packageExists($name)) { - if ($opt) { - $errmsg = "package `$name' is recommended to utilize some features."; - return PEAR_DEPENDENCY_MISSING_OPTIONAL; - } - $errmsg = "requires package `$name'"; - return PEAR_DEPENDENCY_MISSING; - } - return false; - case 'not': - if ($this->registry->packageExists($name)) { - $errmsg = "conflicts with package `$name'"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - case 'lt': - case 'le': - case 'eq': - case 'ne': - case 'ge': - case 'gt': - $version = $this->registry->packageInfo($name, 'version'); - if (!$this->registry->packageExists($name) - || !version_compare("$version", "$req", $relation)) - { - $code = $this->codeFromRelation($relation, $version, $req, $opt); - if ($opt) { - $errmsg = "package `$name' version " . $this->signOperator($relation) . - " $req is recommended to utilize some features."; - if ($version) { - $errmsg .= " Installed version is $version"; - } - return $code; - } - $errmsg = "requires package `$name' " . - $this->signOperator($relation) . " $req"; - return $code; - } - return false; - } - $errmsg = "relation '$relation' with requirement '$req' is not supported (name=$name)"; - return PEAR_DEPENDENCY_BAD_DEPENDENCY; - } - - // }}} - // {{{ checkPackageUninstall() - - /** - * Check package dependencies on uninstall - * - * @param string $error The resultant error string - * @param string $warning The resultant warning string - * @param string $name Name of the package to test - * - * @return bool true if there were errors - */ - function checkPackageUninstall(&$error, &$warning, $package) - { - $error = null; - $packages = $this->registry->listPackages(); - foreach ($packages as $pkg) { - if ($pkg == $package) { - continue; - } - $deps = $this->registry->packageInfo($pkg, 'release_deps'); - if (empty($deps)) { - continue; - } - foreach ($deps as $dep) { - if ($dep['type'] == 'pkg' && strcasecmp($dep['name'], $package) == 0) { - if ($dep['rel'] == 'ne' || $dep['rel'] == 'not') { - continue; - } - if (isset($dep['optional']) && $dep['optional'] == 'yes') { - $warning .= "\nWarning: Package '$pkg' optionally depends on '$package'"; - } else { - $error .= "Package '$pkg' depends on '$package'\n"; - } - } - } - } - return ($error) ? true : false; - } - - // }}} - // {{{ checkExtension() - - /** - * Extension dependencies check method - * - * @param string $name Name of the extension to test - * @param string $req_ext_ver Required extension version to compare with - * @param string $relation How to compare versions with eachother - * @param bool $opt Whether the relationship is optional - * - * @return mixed bool false if no error or the error string - */ - function checkExtension(&$errmsg, $name, $req = null, $relation = 'has', - $opt = false) - { - if ($relation == 'not') { - if (extension_loaded($name)) { - $errmsg = "conflicts with PHP extension '$name'"; - return PEAR_DEPENDENCY_CONFLICT; - } else { - return false; - } - } - - if (!extension_loaded($name)) { - if ($relation == 'not') { - return false; - } - if ($opt) { - $errmsg = "'$name' PHP extension is recommended to utilize some features"; - return PEAR_DEPENDENCY_MISSING_OPTIONAL; - } - $errmsg = "'$name' PHP extension is not installed"; - return PEAR_DEPENDENCY_MISSING; - } - if ($relation == 'has') { - return false; - } - $code = false; - if (is_string($req) && substr($req, 0, 2) == 'v.') { - $req = substr($req, 2); - } - $ext_ver = phpversion($name); - $operator = $relation; - // Force params to be strings, otherwise the comparation will fail (ex. 0.9==0.90) - if (!version_compare("$ext_ver", "$req", $operator)) { - $errmsg = "'$name' PHP extension version " . - $this->signOperator($operator) . " $req is required"; - $code = $this->codeFromRelation($relation, $ext_ver, $req, $opt); - if ($opt) { - $errmsg = "'$name' PHP extension version " . $this->signOperator($operator) . - " $req is recommended to utilize some features"; - return $code; - } - } - return $code; - } - - // }}} - // {{{ checkOS() - - /** - * Operating system dependencies check method - * - * @param string $os Name of the operating system - * - * @return mixed bool false if no error or the error string - */ - function checkOS(&$errmsg, $os) - { - // XXX Fixme: Implement a more flexible way, like - // comma separated values or something similar to PEAR_OS - static $myos; - if (empty($myos)) { - include_once "OS/Guess.php"; - $myos = new OS_Guess(); - } - // only 'has' relation is currently supported - if ($myos->matchSignature($os)) { - return false; - } - $errmsg = "'$os' operating system not supported"; - return PEAR_DEPENDENCY_CONFLICT; - } - - // }}} - // {{{ checkPHP() - - /** - * PHP version check method - * - * @param string $req which version to compare - * @param string $relation how to compare the version - * - * @return mixed bool false if no error or the error string - */ - function checkPHP(&$errmsg, $req, $relation = 'ge') - { - // this would be a bit stupid, but oh well :) - if ($relation == 'has') { - return false; - } - if ($relation == 'not') { - $errmsg = 'Invalid dependency - "not" is not allowed for php dependencies, ' . - 'php cannot conflict with itself'; - return PEAR_DEPENDENCY_BAD_DEPENDENCY; - } - if (substr($req, 0, 2) == 'v.') { - $req = substr($req,2, strlen($req) - 2); - } - $php_ver = phpversion(); - $operator = $relation; - if (!version_compare("$php_ver", "$req", $operator)) { - $errmsg = "PHP version " . $this->signOperator($operator) . - " $req is required"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - } - - // }}} - // {{{ checkProgram() - - /** - * External program check method. Looks for executable files in - * directories listed in the PATH environment variable. - * - * @param string $program which program to look for - * - * @return mixed bool false if no error or the error string - */ - function checkProgram(&$errmsg, $program) - { - // XXX FIXME honor safe mode - $exe_suffix = OS_WINDOWS ? '.exe' : ''; - $path_elements = explode(PATH_SEPARATOR, getenv('PATH')); - foreach ($path_elements as $dir) { - $file = $dir . DIRECTORY_SEPARATOR . $program . $exe_suffix; - if (@file_exists($file) && @is_executable($file)) { - return false; - } - } - $errmsg = "'$program' program is not present in the PATH"; - return PEAR_DEPENDENCY_MISSING; - } - - // }}} - // {{{ checkSAPI() - - /** - * SAPI backend check method. Version comparison is not yet - * available here. - * - * @param string $name name of SAPI backend - * @param string $req which version to compare - * @param string $relation how to compare versions (currently - * hardcoded to 'has') - * @return mixed bool false if no error or the error string - */ - function checkSAPI(&$errmsg, $name, $req = null, $relation = 'has') - { - // XXX Fixme: There is no way to know if the user has or - // not other SAPI backends installed than the installer one - - $sapi_backend = php_sapi_name(); - // Version comparisons not supported, sapi backends don't have - // version information yet. - if ($sapi_backend == $name) { - return false; - } - $errmsg = "'$sapi_backend' SAPI backend not supported"; - return PEAR_DEPENDENCY_CONFLICT; - } - - // }}} - // {{{ checkZend() - - /** - * Zend version check method - * - * @param string $req which version to compare - * @param string $relation how to compare the version - * - * @return mixed bool false if no error or the error string - */ - function checkZend(&$errmsg, $req, $relation = 'ge') - { - if (substr($req, 0, 2) == 'v.') { - $req = substr($req,2, strlen($req) - 2); - } - $zend_ver = zend_version(); - $operator = substr($relation,0,2); - if (!version_compare("$zend_ver", "$req", $operator)) { - $errmsg = "Zend version " . $this->signOperator($operator) . - " $req is required"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - } - - // }}} - // {{{ signOperator() - - /** - * Converts text comparing operators to them sign equivalents - * - * Example: 'ge' to '>=' - * - * @access public - * @param string Operator - * @return string Sign equivalent - */ - function signOperator($operator) - { - switch($operator) { - case 'lt': return '<'; - case 'le': return '<='; - case 'gt': return '>'; - case 'ge': return '>='; - case 'eq': return '=='; - case 'ne': return '!='; - default: - return $operator; - } - } - - // }}} - // {{{ codeFromRelation() - - /** - * Convert relation into corresponding code - * - * @access public - * @param string Relation - * @param string Version - * @param string Requirement - * @param bool Optional dependency indicator - * @return integer - */ - function codeFromRelation($relation, $version, $req, $opt = false) - { - $code = PEAR_DEPENDENCY_BAD_DEPENDENCY; - switch ($relation) { - case 'gt': case 'ge': case 'eq': - // upgrade - $have_major = preg_replace('/\D.*/', '', $version); - $need_major = preg_replace('/\D.*/', '', $req); - if ($need_major > $have_major) { - $code = $opt ? PEAR_DEPENDENCY_UPGRADE_MAJOR_OPTIONAL : - PEAR_DEPENDENCY_UPGRADE_MAJOR; - } else { - $code = $opt ? PEAR_DEPENDENCY_UPGRADE_MINOR_OPTIONAL : - PEAR_DEPENDENCY_UPGRADE_MINOR; - } - break; - case 'lt': case 'le': case 'ne': - $code = $opt ? PEAR_DEPENDENCY_CONFLICT_OPTIONAL : - PEAR_DEPENDENCY_CONFLICT; - break; - } - return $code; - } - - // }}} -} -?> diff --git a/3rdparty/PEAR/Downloader.php b/3rdparty/PEAR/Downloader.php deleted file mode 100644 index 5e16dc5ffb..0000000000 --- a/3rdparty/PEAR/Downloader.php +++ /dev/null @@ -1,680 +0,0 @@ - | -// | Tomas V.V.Cox | -// | Martin Jansen | -// +----------------------------------------------------------------------+ -// -// $Id: Downloader.php,v 1.17.2.1 2004/10/22 22:54:03 cellog Exp $ - -require_once 'PEAR/Common.php'; -require_once 'PEAR/Registry.php'; -require_once 'PEAR/Dependency.php'; -require_once 'PEAR/Remote.php'; -require_once 'System.php'; - - -define('PEAR_INSTALLER_OK', 1); -define('PEAR_INSTALLER_FAILED', 0); -define('PEAR_INSTALLER_SKIPPED', -1); -define('PEAR_INSTALLER_ERROR_NO_PREF_STATE', 2); - -/** - * Administration class used to download PEAR packages and maintain the - * installed package database. - * - * @since PEAR 1.4 - * @author Greg Beaver - */ -class PEAR_Downloader extends PEAR_Common -{ - /** - * @var PEAR_Config - * @access private - */ - var $_config; - - /** - * @var PEAR_Registry - * @access private - */ - var $_registry; - - /** - * @var PEAR_Remote - * @access private - */ - var $_remote; - - /** - * Preferred Installation State (snapshot, devel, alpha, beta, stable) - * @var string|null - * @access private - */ - var $_preferredState; - - /** - * Options from command-line passed to Install. - * - * Recognized options:
- * - onlyreqdeps : install all required dependencies as well - * - alldeps : install all dependencies, including optional - * - installroot : base relative path to install files in - * - force : force a download even if warnings would prevent it - * @see PEAR_Command_Install - * @access private - * @var array - */ - var $_options; - - /** - * Downloaded Packages after a call to download(). - * - * Format of each entry: - * - * - * array('pkg' => 'package_name', 'file' => '/path/to/local/file', - * 'info' => array() // parsed package.xml - * ); - * - * @access private - * @var array - */ - var $_downloadedPackages = array(); - - /** - * Packages slated for download. - * - * This is used to prevent downloading a package more than once should it be a dependency - * for two packages to be installed. - * Format of each entry: - * - *
-     * array('package_name1' => parsed package.xml, 'package_name2' => parsed package.xml,
-     * );
-     * 
- * @access private - * @var array - */ - var $_toDownload = array(); - - /** - * Array of every package installed, with names lower-cased. - * - * Format: - * - * array('package1' => 0, 'package2' => 1, ); - * - * @var array - */ - var $_installed = array(); - - /** - * @var array - * @access private - */ - var $_errorStack = array(); - - // {{{ PEAR_Downloader() - - function PEAR_Downloader(&$ui, $options, &$config) - { - $this->_options = $options; - $this->_config = &$config; - $this->_preferredState = $this->_config->get('preferred_state'); - $this->ui = &$ui; - if (!$this->_preferredState) { - // don't inadvertantly use a non-set preferred_state - $this->_preferredState = null; - } - - $php_dir = $this->_config->get('php_dir'); - if (isset($this->_options['installroot'])) { - if (substr($this->_options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $this->_options['installroot'] = substr($this->_options['installroot'], 0, -1); - } - $php_dir = $this->_prependPath($php_dir, $this->_options['installroot']); - } - $this->_registry = &new PEAR_Registry($php_dir); - $this->_remote = &new PEAR_Remote($config); - - if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) { - $this->_installed = $this->_registry->listPackages(); - array_walk($this->_installed, create_function('&$v,$k','$v = strtolower($v);')); - $this->_installed = array_flip($this->_installed); - } - parent::PEAR_Common(); - } - - // }}} - // {{{ configSet() - function configSet($key, $value, $layer = 'user') - { - $this->_config->set($key, $value, $layer); - $this->_preferredState = $this->_config->get('preferred_state'); - if (!$this->_preferredState) { - // don't inadvertantly use a non-set preferred_state - $this->_preferredState = null; - } - } - - // }}} - // {{{ setOptions() - function setOptions($options) - { - $this->_options = $options; - } - - // }}} - // {{{ _downloadFile() - /** - * @param string filename to download - * @param string version/state - * @param string original value passed to command-line - * @param string|null preferred state (snapshot/devel/alpha/beta/stable) - * Defaults to configuration preferred state - * @return null|PEAR_Error|string - * @access private - */ - function _downloadFile($pkgfile, $version, $origpkgfile, $state = null) - { - if (is_null($state)) { - $state = $this->_preferredState; - } - // {{{ check the package filename, and whether it's already installed - $need_download = false; - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - $need_download = true; - } elseif (!@is_file($pkgfile)) { - if ($this->validPackageName($pkgfile)) { - if ($this->_registry->packageExists($pkgfile)) { - if (empty($this->_options['upgrade']) && empty($this->_options['force'])) { - $errors[] = "$pkgfile already installed"; - return; - } - } - $pkgfile = $this->getPackageDownloadUrl($pkgfile, $version); - $need_download = true; - } else { - if (strlen($pkgfile)) { - $errors[] = "Could not open the package file: $pkgfile"; - } else { - $errors[] = "No package file given"; - } - return; - } - } - // }}} - - // {{{ Download package ----------------------------------------------- - if ($need_download) { - $downloaddir = $this->_config->get('download_dir'); - if (empty($downloaddir)) { - if (PEAR::isError($downloaddir = System::mktemp('-d'))) { - return $downloaddir; - } - $this->log(3, '+ tmp dir created at ' . $downloaddir); - } - $callback = $this->ui ? array(&$this, '_downloadCallback') : null; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $file = $this->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback); - $this->popErrorHandling(); - if (PEAR::isError($file)) { - if ($this->validPackageName($origpkgfile)) { - if (!PEAR::isError($info = $this->_remote->call('package.info', - $origpkgfile))) { - if (!count($info['releases'])) { - return $this->raiseError('Package ' . $origpkgfile . - ' has no releases'); - } else { - return $this->raiseError('No releases of preferred state "' - . $state . '" exist for package ' . $origpkgfile . - '. Use ' . $origpkgfile . '-state to install another' . - ' state (like ' . $origpkgfile .'-beta)', - PEAR_INSTALLER_ERROR_NO_PREF_STATE); - } - } else { - return $pkgfile; - } - } else { - return $this->raiseError($file); - } - } - $pkgfile = $file; - } - // }}} - return $pkgfile; - } - // }}} - // {{{ getPackageDownloadUrl() - - function getPackageDownloadUrl($package, $version = null) - { - if ($version) { - $package .= "-$version"; - } - if ($this === null || $this->_config === null) { - $package = "http://pear.php.net/get/$package"; - } else { - $package = "http://" . $this->_config->get('master_server') . - "/get/$package"; - } - if (!extension_loaded("zlib")) { - $package .= '?uncompress=yes'; - } - return $package; - } - - // }}} - // {{{ extractDownloadFileName($pkgfile, &$version) - - function extractDownloadFileName($pkgfile, &$version) - { - if (@is_file($pkgfile)) { - return $pkgfile; - } - // regex defined in Common.php - if (preg_match(PEAR_COMMON_PACKAGE_DOWNLOAD_PREG, $pkgfile, $m)) { - $version = (isset($m[3])) ? $m[3] : null; - return $m[1]; - } - $version = null; - return $pkgfile; - } - - // }}} - - // }}} - // {{{ getDownloadedPackages() - - /** - * Retrieve a list of downloaded packages after a call to {@link download()}. - * - * Also resets the list of downloaded packages. - * @return array - */ - function getDownloadedPackages() - { - $ret = $this->_downloadedPackages; - $this->_downloadedPackages = array(); - $this->_toDownload = array(); - return $ret; - } - - // }}} - // {{{ download() - - /** - * Download any files and their dependencies, if necessary - * - * BC-compatible method name - * @param array a mixed list of package names, local files, or package.xml - */ - function download($packages) - { - return $this->doDownload($packages); - } - - // }}} - // {{{ doDownload() - - /** - * Download any files and their dependencies, if necessary - * - * @param array a mixed list of package names, local files, or package.xml - */ - function doDownload($packages) - { - $mywillinstall = array(); - $state = $this->_preferredState; - - // {{{ download files in this list if necessary - foreach($packages as $pkgfile) { - $need_download = false; - if (!is_file($pkgfile)) { - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - $need_download = true; - } - $pkgfile = $this->_downloadNonFile($pkgfile); - if (PEAR::isError($pkgfile)) { - return $pkgfile; - } - if ($pkgfile === false) { - continue; - } - } // end is_file() - - $tempinfo = $this->infoFromAny($pkgfile); - if ($need_download) { - $this->_toDownload[] = $tempinfo['package']; - } - if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) { - // ignore dependencies if there are any errors - if (!PEAR::isError($tempinfo)) { - $mywillinstall[strtolower($tempinfo['package'])] = @$tempinfo['release_deps']; - } - } - $this->_downloadedPackages[] = array('pkg' => $tempinfo['package'], - 'file' => $pkgfile, 'info' => $tempinfo); - } // end foreach($packages) - // }}} - - // {{{ extract dependencies from downloaded files and then download - // them if necessary - if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) { - $deppackages = array(); - foreach ($mywillinstall as $package => $alldeps) { - if (!is_array($alldeps)) { - // there are no dependencies - continue; - } - $fail = false; - foreach ($alldeps as $info) { - if ($info['type'] != 'pkg') { - continue; - } - $ret = $this->_processDependency($package, $info, $mywillinstall); - if ($ret === false) { - continue; - } - if ($ret === 0) { - $fail = true; - continue; - } - if (PEAR::isError($ret)) { - return $ret; - } - $deppackages[] = $ret; - } // foreach($alldeps - if ($fail) { - $deppackages = array(); - } - } - - if (count($deppackages)) { - $this->doDownload($deppackages); - } - } // }}} if --alldeps or --onlyreqdeps - } - - // }}} - // {{{ _downloadNonFile($pkgfile) - - /** - * @return false|PEAR_Error|string false if loop should be broken out of, - * string if the file was downloaded, - * PEAR_Error on exception - * @access private - */ - function _downloadNonFile($pkgfile) - { - $origpkgfile = $pkgfile; - $state = null; - $pkgfile = $this->extractDownloadFileName($pkgfile, $version); - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - return $this->_downloadFile($pkgfile, $version, $origpkgfile); - } - if (!$this->validPackageName($pkgfile)) { - return $this->raiseError("Package name '$pkgfile' not valid"); - } - // ignore packages that are installed unless we are upgrading - $curinfo = $this->_registry->packageInfo($pkgfile); - if ($this->_registry->packageExists($pkgfile) - && empty($this->_options['upgrade']) && empty($this->_options['force'])) { - $this->log(0, "Package '{$curinfo['package']}' already installed, skipping"); - return false; - } - if (in_array($pkgfile, $this->_toDownload)) { - return false; - } - $releases = $this->_remote->call('package.info', $pkgfile, 'releases', true); - if (!count($releases)) { - return $this->raiseError("No releases found for package '$pkgfile'"); - } - // Want a specific version/state - if ($version !== null) { - // Passed Foo-1.2 - if ($this->validPackageVersion($version)) { - if (!isset($releases[$version])) { - return $this->raiseError("No release with version '$version' found for '$pkgfile'"); - } - // Passed Foo-alpha - } elseif (in_array($version, $this->getReleaseStates())) { - $state = $version; - $version = 0; - foreach ($releases as $ver => $inf) { - if ($inf['state'] == $state && version_compare("$version", "$ver") < 0) { - $version = $ver; - break; - } - } - if ($version == 0) { - return $this->raiseError("No release with state '$state' found for '$pkgfile'"); - } - // invalid suffix passed - } else { - return $this->raiseError("Invalid suffix '-$version', be sure to pass a valid PEAR ". - "version number or release state"); - } - // Guess what to download - } else { - $states = $this->betterStates($this->_preferredState, true); - $possible = false; - $version = 0; - $higher_version = 0; - $prev_hi_ver = 0; - foreach ($releases as $ver => $inf) { - if (in_array($inf['state'], $states) && version_compare("$version", "$ver") < 0) { - $version = $ver; - break; - } else { - $ver = (string)$ver; - if (version_compare($prev_hi_ver, $ver) < 0) { - $prev_hi_ver = $higher_version = $ver; - } - } - } - if ($version === 0 && !isset($this->_options['force'])) { - return $this->raiseError('No release with state equal to: \'' . implode(', ', $states) . - "' found for '$pkgfile'"); - } elseif ($version === 0) { - $this->log(0, "Warning: $pkgfile is state '" . $releases[$higher_version]['state'] . "' which is less stable " . - "than state '$this->_preferredState'"); - } - } - // Check if we haven't already the version - if (empty($this->_options['force']) && !is_null($curinfo)) { - if ($curinfo['version'] == $version) { - $this->log(0, "Package '{$curinfo['package']}-{$curinfo['version']}' already installed, skipping"); - return false; - } elseif (version_compare("$version", "{$curinfo['version']}") < 0) { - $this->log(0, "Package '{$curinfo['package']}' version '{$curinfo['version']}' " . - " is installed and {$curinfo['version']} is > requested '$version', skipping"); - return false; - } - } - $this->_toDownload[] = $pkgfile; - return $this->_downloadFile($pkgfile, $version, $origpkgfile, $state); - } - - // }}} - // {{{ _processDependency($package, $info, $mywillinstall) - - /** - * Process a dependency, download if necessary - * @param array dependency information from PEAR_Remote call - * @param array packages that will be installed in this iteration - * @return false|string|PEAR_Error - * @access private - * @todo Add test for relation 'lt'/'le' -> make sure that the dependency requested is - * in fact lower than the required value. This will be very important for BC dependencies - */ - function _processDependency($package, $info, $mywillinstall) - { - $state = $this->_preferredState; - if (!isset($this->_options['alldeps']) && isset($info['optional']) && - $info['optional'] == 'yes') { - // skip optional deps - $this->log(0, "skipping Package '$package' optional dependency '$info[name]'"); - return false; - } - // {{{ get releases - $releases = $this->_remote->call('package.info', $info['name'], 'releases', true); - if (PEAR::isError($releases)) { - return $releases; - } - if (!count($releases)) { - if (!isset($this->_installed[strtolower($info['name'])])) { - $this->pushError("Package '$package' dependency '$info[name]' ". - "has no releases"); - } - return false; - } - $found = false; - $save = $releases; - while(count($releases) && !$found) { - if (!empty($state) && $state != 'any') { - list($release_version, $release) = each($releases); - if ($state != $release['state'] && - !in_array($release['state'], $this->betterStates($state))) - { - // drop this release - it ain't stable enough - array_shift($releases); - } else { - $found = true; - } - } else { - $found = true; - } - } - if (!count($releases) && !$found) { - $get = array(); - foreach($save as $release) { - $get = array_merge($get, - $this->betterStates($release['state'], true)); - } - $savestate = array_shift($get); - $this->pushError( "Release for '$package' dependency '$info[name]' " . - "has state '$savestate', requires '$state'"); - return 0; - } - if (in_array(strtolower($info['name']), $this->_toDownload) || - isset($mywillinstall[strtolower($info['name'])])) { - // skip upgrade check for packages we will install - return false; - } - if (!isset($this->_installed[strtolower($info['name'])])) { - // check to see if we can install the specific version required - if ($info['rel'] == 'eq') { - return $info['name'] . '-' . $info['version']; - } - // skip upgrade check for packages we don't have installed - return $info['name']; - } - // }}} - - // {{{ see if a dependency must be upgraded - $inst_version = $this->_registry->packageInfo($info['name'], 'version'); - if (!isset($info['version'])) { - // this is a rel='has' dependency, check against latest - if (version_compare($release_version, $inst_version, 'le')) { - return false; - } else { - return $info['name']; - } - } - if (version_compare($info['version'], $inst_version, 'le')) { - // installed version is up-to-date - return false; - } - return $info['name']; - } - - // }}} - // {{{ _downloadCallback() - - function _downloadCallback($msg, $params = null) - { - switch ($msg) { - case 'saveas': - $this->log(1, "downloading $params ..."); - break; - case 'done': - $this->log(1, '...done: ' . number_format($params, 0, '', ',') . ' bytes'); - break; - case 'bytesread': - static $bytes; - if (empty($bytes)) { - $bytes = 0; - } - if (!($bytes % 10240)) { - $this->log(1, '.', false); - } - $bytes += $params; - break; - case 'start': - $this->log(1, "Starting to download {$params[0]} (".number_format($params[1], 0, '', ',')." bytes)"); - break; - } - if (method_exists($this->ui, '_downloadCallback')) - $this->ui->_downloadCallback($msg, $params); - } - - // }}} - // {{{ _prependPath($path, $prepend) - - function _prependPath($path, $prepend) - { - if (strlen($prepend) > 0) { - if (OS_WINDOWS && preg_match('/^[a-z]:/i', $path)) { - $path = $prepend . substr($path, 2); - } else { - $path = $prepend . $path; - } - } - return $path; - } - // }}} - // {{{ pushError($errmsg, $code) - - /** - * @param string - * @param integer - */ - function pushError($errmsg, $code = -1) - { - array_push($this->_errorStack, array($errmsg, $code)); - } - - // }}} - // {{{ getErrorMsgs() - - function getErrorMsgs() - { - $msgs = array(); - $errs = $this->_errorStack; - foreach ($errs as $err) { - $msgs[] = $err[0]; - } - $this->_errorStack = array(); - return $msgs; - } - - // }}} -} -// }}} - -?> diff --git a/3rdparty/PEAR/ErrorStack.php b/3rdparty/PEAR/ErrorStack.php deleted file mode 100644 index da52f08d34..0000000000 --- a/3rdparty/PEAR/ErrorStack.php +++ /dev/null @@ -1,981 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: ErrorStack.php,v 1.7.2.5 2005/01/01 21:26:51 cellog Exp $ - -/** - * Error Stack Implementation - * - * This is an incredibly simple implementation of a very complex error handling - * facility. It contains the ability - * to track multiple errors from multiple packages simultaneously. In addition, - * it can track errors of many levels, save data along with the error, context - * information such as the exact file, line number, class and function that - * generated the error, and if necessary, it can raise a traditional PEAR_Error. - * It has built-in support for PEAR::Log, to log errors as they occur - * - * Since version 0.2alpha, it is also possible to selectively ignore errors, - * through the use of an error callback, see {@link pushCallback()} - * - * Since version 0.3alpha, it is possible to specify the exception class - * returned from {@link push()} - * - * Since version PEAR1.3.2, ErrorStack no longer instantiates an exception class. This can - * still be done quite handily in an error callback or by manipulating the returned array - * @author Greg Beaver - * @version PEAR1.3.2 (beta) - * @package PEAR_ErrorStack - * @category Debugging - * @license http://www.php.net/license/3_0.txt PHP License v3.0 - */ - -/** - * Singleton storage - * - * Format: - *
- * array(
- *  'package1' => PEAR_ErrorStack object,
- *  'package2' => PEAR_ErrorStack object,
- *  ...
- * )
- * 
- * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] - */ -$GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] = array(); - -/** - * Global error callback (default) - * - * This is only used if set to non-false. * is the default callback for - * all packages, whereas specific packages may set a default callback - * for all instances, regardless of whether they are a singleton or not. - * - * To exclude non-singletons, only set the local callback for the singleton - * @see PEAR_ErrorStack::setDefaultCallback() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'] - */ -$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'] = array( - '*' => false, -); - -/** - * Global Log object (default) - * - * This is only used if set to non-false. Use to set a default log object for - * all stacks, regardless of instantiation order or location - * @see PEAR_ErrorStack::setDefaultLogger() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] - */ -$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = false; - -/** - * Global Overriding Callback - * - * This callback will override any error callbacks that specific loggers have set. - * Use with EXTREME caution - * @see PEAR_ErrorStack::staticPushCallback() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] - */ -$GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array(); - -/**#@+ - * One of four possible return values from the error Callback - * @see PEAR_ErrorStack::_errorCallback() - */ -/** - * If this is returned, then the error will be both pushed onto the stack - * and logged. - */ -define('PEAR_ERRORSTACK_PUSHANDLOG', 1); -/** - * If this is returned, then the error will only be pushed onto the stack, - * and not logged. - */ -define('PEAR_ERRORSTACK_PUSH', 2); -/** - * If this is returned, then the error will only be logged, but not pushed - * onto the error stack. - */ -define('PEAR_ERRORSTACK_LOG', 3); -/** - * If this is returned, then the error is completely ignored. - */ -define('PEAR_ERRORSTACK_IGNORE', 4); -/** - * If this is returned, then the error is logged and die() is called. - */ -define('PEAR_ERRORSTACK_DIE', 5); -/**#@-*/ - -/** - * Error code for an attempt to instantiate a non-class as a PEAR_ErrorStack in - * the singleton method. - */ -define('PEAR_ERRORSTACK_ERR_NONCLASS', 1); - -/** - * Error code for an attempt to pass an object into {@link PEAR_ErrorStack::getMessage()} - * that has no __toString() method - */ -define('PEAR_ERRORSTACK_ERR_OBJTOSTRING', 2); -/** - * Error Stack Implementation - * - * Usage: - * - * // global error stack - * $global_stack = &PEAR_ErrorStack::singleton('MyPackage'); - * // local error stack - * $local_stack = new PEAR_ErrorStack('MyPackage'); - * - * @copyright 2004 Gregory Beaver - * @package PEAR_ErrorStack - * @license http://www.php.net/license/3_0.txt PHP License - */ -class PEAR_ErrorStack { - /** - * Errors are stored in the order that they are pushed on the stack. - * @since 0.4alpha Errors are no longer organized by error level. - * This renders pop() nearly unusable, and levels could be more easily - * handled in a callback anyway - * @var array - * @access private - */ - var $_errors = array(); - - /** - * Storage of errors by level. - * - * Allows easy retrieval and deletion of only errors from a particular level - * @since PEAR 1.4.0dev - * @var array - * @access private - */ - var $_errorsByLevel = array(); - - /** - * Package name this error stack represents - * @var string - * @access protected - */ - var $_package; - - /** - * Determines whether a PEAR_Error is thrown upon every error addition - * @var boolean - * @access private - */ - var $_compat = false; - - /** - * If set to a valid callback, this will be used to generate the error - * message from the error code, otherwise the message passed in will be - * used - * @var false|string|array - * @access private - */ - var $_msgCallback = false; - - /** - * If set to a valid callback, this will be used to generate the error - * context for an error. For PHP-related errors, this will be a file - * and line number as retrieved from debug_backtrace(), but can be - * customized for other purposes. The error might actually be in a separate - * configuration file, or in a database query. - * @var false|string|array - * @access protected - */ - var $_contextCallback = false; - - /** - * If set to a valid callback, this will be called every time an error - * is pushed onto the stack. The return value will be used to determine - * whether to allow an error to be pushed or logged. - * - * The return value must be one an PEAR_ERRORSTACK_* constant - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @var false|string|array - * @access protected - */ - var $_errorCallback = array(); - - /** - * PEAR::Log object for logging errors - * @var false|Log - * @access protected - */ - var $_logger = false; - - /** - * Error messages - designed to be overridden - * @var array - * @abstract - */ - var $_errorMsgs = array(); - - /** - * Set up a new error stack - * - * @param string $package name of the package this error stack represents - * @param callback $msgCallback callback used for error message generation - * @param callback $contextCallback callback used for context generation, - * defaults to {@link getFileLine()} - * @param boolean $throwPEAR_Error - */ - function PEAR_ErrorStack($package, $msgCallback = false, $contextCallback = false, - $throwPEAR_Error = false) - { - $this->_package = $package; - $this->setMessageCallback($msgCallback); - $this->setContextCallback($contextCallback); - $this->_compat = $throwPEAR_Error; - } - - /** - * Return a single error stack for this package. - * - * Note that all parameters are ignored if the stack for package $package - * has already been instantiated - * @param string $package name of the package this error stack represents - * @param callback $msgCallback callback used for error message generation - * @param callback $contextCallback callback used for context generation, - * defaults to {@link getFileLine()} - * @param boolean $throwPEAR_Error - * @param string $stackClass class to instantiate - * @static - * @return PEAR_ErrorStack - */ - function &singleton($package, $msgCallback = false, $contextCallback = false, - $throwPEAR_Error = false, $stackClass = 'PEAR_ErrorStack') - { - if (isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]; - } - if (!class_exists($stackClass)) { - if (function_exists('debug_backtrace')) { - $trace = debug_backtrace(); - } - PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_NONCLASS, - 'exception', array('stackclass' => $stackClass), - 'stack class "%stackclass%" is not a valid class name (should be like PEAR_ErrorStack)', - false, $trace); - } - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package] = - &new $stackClass($package, $msgCallback, $contextCallback, $throwPEAR_Error); - } - - /** - * Internal error handler for PEAR_ErrorStack class - * - * Dies if the error is an exception (and would have died anyway) - * @access private - */ - function _handleError($err) - { - if ($err['level'] == 'exception') { - $message = $err['message']; - if (isset($_SERVER['REQUEST_URI'])) { - echo '
'; - } else { - echo "\n"; - } - var_dump($err['context']); - die($message); - } - } - - /** - * Set up a PEAR::Log object for all error stacks that don't have one - * @param Log $log - * @static - */ - function setDefaultLogger(&$log) - { - if (is_object($log) && method_exists($log, 'log') ) { - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log; - } elseif (is_callable($log)) { - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log; - } - } - - /** - * Set up a PEAR::Log object for this error stack - * @param Log $log - */ - function setLogger(&$log) - { - if (is_object($log) && method_exists($log, 'log') ) { - $this->_logger = &$log; - } elseif (is_callable($log)) { - $this->_logger = &$log; - } - } - - /** - * Set an error code => error message mapping callback - * - * This method sets the callback that can be used to generate error - * messages for any instance - * @param array|string Callback function/method - */ - function setMessageCallback($msgCallback) - { - if (!$msgCallback) { - $this->_msgCallback = array(&$this, 'getErrorMessage'); - } else { - if (is_callable($msgCallback)) { - $this->_msgCallback = $msgCallback; - } - } - } - - /** - * Get an error code => error message mapping callback - * - * This method returns the current callback that can be used to generate error - * messages - * @return array|string|false Callback function/method or false if none - */ - function getMessageCallback() - { - return $this->_msgCallback; - } - - /** - * Sets a default callback to be used by all error stacks - * - * This method sets the callback that can be used to generate error - * messages for a singleton - * @param array|string Callback function/method - * @param string Package name, or false for all packages - * @static - */ - function setDefaultCallback($callback = false, $package = false) - { - if (!is_callable($callback)) { - $callback = false; - } - $package = $package ? $package : '*'; - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$package] = $callback; - } - - /** - * Set a callback that generates context information (location of error) for an error stack - * - * This method sets the callback that can be used to generate context - * information for an error. Passing in NULL will disable context generation - * and remove the expensive call to debug_backtrace() - * @param array|string|null Callback function/method - */ - function setContextCallback($contextCallback) - { - if ($contextCallback === null) { - return $this->_contextCallback = false; - } - if (!$contextCallback) { - $this->_contextCallback = array(&$this, 'getFileLine'); - } else { - if (is_callable($contextCallback)) { - $this->_contextCallback = $contextCallback; - } - } - } - - /** - * Set an error Callback - * If set to a valid callback, this will be called every time an error - * is pushed onto the stack. The return value will be used to determine - * whether to allow an error to be pushed or logged. - * - * The return value must be one of the ERRORSTACK_* constants. - * - * This functionality can be used to emulate PEAR's pushErrorHandling, and - * the PEAR_ERROR_CALLBACK mode, without affecting the integrity of - * the error stack or logging - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @see popCallback() - * @param string|array $cb - */ - function pushCallback($cb) - { - array_push($this->_errorCallback, $cb); - } - - /** - * Remove a callback from the error callback stack - * @see pushCallback() - * @return array|string|false - */ - function popCallback() - { - if (!count($this->_errorCallback)) { - return false; - } - return array_pop($this->_errorCallback); - } - - /** - * Set a temporary overriding error callback for every package error stack - * - * Use this to temporarily disable all existing callbacks (can be used - * to emulate the @ operator, for instance) - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @see staticPopCallback(), pushCallback() - * @param string|array $cb - * @static - */ - function staticPushCallback($cb) - { - array_push($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'], $cb); - } - - /** - * Remove a temporary overriding error callback - * @see staticPushCallback() - * @return array|string|false - * @static - */ - function staticPopCallback() - { - $ret = array_pop($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK']); - if (!is_array($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'])) { - $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array(); - } - return $ret; - } - - /** - * Add an error to the stack - * - * If the message generator exists, it is called with 2 parameters. - * - the current Error Stack object - * - an array that is in the same format as an error. Available indices - * are 'code', 'package', 'time', 'params', 'level', and 'context' - * - * Next, if the error should contain context information, this is - * handled by the context grabbing method. - * Finally, the error is pushed onto the proper error stack - * @param int $code Package-specific error code - * @param string $level Error level. This is NOT spell-checked - * @param array $params associative array of error parameters - * @param string $msg Error message, or a portion of it if the message - * is to be generated - * @param array $repackage If this error re-packages an error pushed by - * another package, place the array returned from - * {@link pop()} in this parameter - * @param array $backtrace Protected parameter: use this to pass in the - * {@link debug_backtrace()} that should be used - * to find error context - * @return PEAR_Error|array|Exception - * if compatibility mode is on, a PEAR_Error is also - * thrown. If the class Exception exists, then one - * is returned to allow code like: - * - * throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob'))); - * - * - * The errorData property of the exception class will be set to the array - * that would normally be returned. If a PEAR_Error is returned, the userinfo - * property is set to the array - * - * Otherwise, an array is returned in this format: - * - * array( - * 'code' => $code, - * 'params' => $params, - * 'package' => $this->_package, - * 'level' => $level, - * 'time' => time(), - * 'context' => $context, - * 'message' => $msg, - * //['repackage' => $err] repackaged error array/Exception class - * ); - * - */ - function push($code, $level = 'error', $params = array(), $msg = false, - $repackage = false, $backtrace = false) - { - $context = false; - // grab error context - if ($this->_contextCallback) { - if (!$backtrace) { - $backtrace = debug_backtrace(); - } - $context = call_user_func($this->_contextCallback, $code, $params, $backtrace); - } - - // save error - $time = explode(' ', microtime()); - $time = $time[1] + $time[0]; - $err = array( - 'code' => $code, - 'params' => $params, - 'package' => $this->_package, - 'level' => $level, - 'time' => $time, - 'context' => $context, - 'message' => $msg, - ); - - // set up the error message, if necessary - if ($this->_msgCallback) { - $msg = call_user_func_array($this->_msgCallback, - array(&$this, $err)); - $err['message'] = $msg; - } - - if ($repackage) { - $err['repackage'] = $repackage; - } - $push = $log = true; - $die = false; - // try the overriding callback first - $callback = $this->staticPopCallback(); - if ($callback) { - $this->staticPushCallback($callback); - } - if (!is_callable($callback)) { - // try the local callback next - $callback = $this->popCallback(); - if (is_callable($callback)) { - $this->pushCallback($callback); - } else { - // try the default callback - $callback = isset($GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package]) ? - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package] : - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK']['*']; - } - } - if (is_callable($callback)) { - switch(call_user_func($callback, $err)){ - case PEAR_ERRORSTACK_IGNORE: - return $err; - break; - case PEAR_ERRORSTACK_PUSH: - $log = false; - break; - case PEAR_ERRORSTACK_LOG: - $push = false; - break; - case PEAR_ERRORSTACK_DIE: - $die = true; - break; - // anything else returned has the same effect as pushandlog - } - } - if ($push) { - array_unshift($this->_errors, $err); - $this->_errorsByLevel[$err['level']][] = &$this->_errors[0]; - } - if ($log) { - if ($this->_logger || $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']) { - $this->_log($err); - } - } - if ($die) { - die(); - } - if ($this->_compat && $push) { - return $this->raiseError($msg, $code, null, null, $err); - } - return $err; - } - - /** - * Static version of {@link push()} - * - * @param string $package Package name this error belongs to - * @param int $code Package-specific error code - * @param string $level Error level. This is NOT spell-checked - * @param array $params associative array of error parameters - * @param string $msg Error message, or a portion of it if the message - * is to be generated - * @param array $repackage If this error re-packages an error pushed by - * another package, place the array returned from - * {@link pop()} in this parameter - * @param array $backtrace Protected parameter: use this to pass in the - * {@link debug_backtrace()} that should be used - * to find error context - * @return PEAR_Error|null|Exception - * if compatibility mode is on, a PEAR_Error is also - * thrown. If the class Exception exists, then one - * is returned to allow code like: - * - * throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob'))); - * - * @static - */ - function staticPush($package, $code, $level = 'error', $params = array(), - $msg = false, $repackage = false, $backtrace = false) - { - $s = &PEAR_ErrorStack::singleton($package); - if ($s->_contextCallback) { - if (!$backtrace) { - if (function_exists('debug_backtrace')) { - $backtrace = debug_backtrace(); - } - } - } - return $s->push($code, $level, $params, $msg, $repackage, $backtrace); - } - - /** - * Log an error using PEAR::Log - * @param array $err Error array - * @param array $levels Error level => Log constant map - * @access protected - */ - function _log($err) - { - if ($this->_logger) { - $logger = &$this->_logger; - } else { - $logger = &$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']; - } - if (is_a($logger, 'Log')) { - $levels = array( - 'exception' => PEAR_LOG_CRIT, - 'alert' => PEAR_LOG_ALERT, - 'critical' => PEAR_LOG_CRIT, - 'error' => PEAR_LOG_ERR, - 'warning' => PEAR_LOG_WARNING, - 'notice' => PEAR_LOG_NOTICE, - 'info' => PEAR_LOG_INFO, - 'debug' => PEAR_LOG_DEBUG); - if (isset($levels[$err['level']])) { - $level = $levels[$err['level']]; - } else { - $level = PEAR_LOG_INFO; - } - $logger->log($err['message'], $level, $err); - } else { // support non-standard logs - call_user_func($logger, $err); - } - } - - - /** - * Pop an error off of the error stack - * - * @return false|array - * @since 0.4alpha it is no longer possible to specify a specific error - * level to return - the last error pushed will be returned, instead - */ - function pop() - { - return @array_shift($this->_errors); - } - - /** - * Determine whether there are any errors on the stack - * @param string|array Level name. Use to determine if any errors - * of level (string), or levels (array) have been pushed - * @return boolean - */ - function hasErrors($level = false) - { - if ($level) { - return isset($this->_errorsByLevel[$level]); - } - return count($this->_errors); - } - - /** - * Retrieve all errors since last purge - * - * @param boolean set in order to empty the error stack - * @param string level name, to return only errors of a particular severity - * @return array - */ - function getErrors($purge = false, $level = false) - { - if (!$purge) { - if ($level) { - if (!isset($this->_errorsByLevel[$level])) { - return array(); - } else { - return $this->_errorsByLevel[$level]; - } - } else { - return $this->_errors; - } - } - if ($level) { - $ret = $this->_errorsByLevel[$level]; - foreach ($this->_errorsByLevel[$level] as $i => $unused) { - // entries are references to the $_errors array - $this->_errorsByLevel[$level][$i] = false; - } - // array_filter removes all entries === false - $this->_errors = array_filter($this->_errors); - unset($this->_errorsByLevel[$level]); - return $ret; - } - $ret = $this->_errors; - $this->_errors = array(); - $this->_errorsByLevel = array(); - return $ret; - } - - /** - * Determine whether there are any errors on a single error stack, or on any error stack - * - * The optional parameter can be used to test the existence of any errors without the need of - * singleton instantiation - * @param string|false Package name to check for errors - * @param string Level name to check for a particular severity - * @return boolean - * @static - */ - function staticHasErrors($package = false, $level = false) - { - if ($package) { - if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { - return false; - } - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->hasErrors($level); - } - foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { - if ($obj->hasErrors($level)) { - return true; - } - } - return false; - } - - /** - * Get a list of all errors since last purge, organized by package - * @since PEAR 1.4.0dev BC break! $level is now in the place $merge used to be - * @param boolean $purge Set to purge the error stack of existing errors - * @param string $level Set to a level name in order to retrieve only errors of a particular level - * @param boolean $merge Set to return a flat array, not organized by package - * @param array $sortfunc Function used to sort a merged array - default - * sorts by time, and should be good for most cases - * @static - * @return array - */ - function staticGetErrors($purge = false, $level = false, $merge = false, - $sortfunc = array('PEAR_ErrorStack', '_sortErrors')) - { - $ret = array(); - if (!is_callable($sortfunc)) { - $sortfunc = array('PEAR_ErrorStack', '_sortErrors'); - } - foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { - $test = $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->getErrors($purge, $level); - if ($test) { - if ($merge) { - $ret = array_merge($ret, $test); - } else { - $ret[$package] = $test; - } - } - } - if ($merge) { - usort($ret, $sortfunc); - } - return $ret; - } - - /** - * Error sorting function, sorts by time - * @access private - */ - function _sortErrors($a, $b) - { - if ($a['time'] == $b['time']) { - return 0; - } - if ($a['time'] < $b['time']) { - return 1; - } - return -1; - } - - /** - * Standard file/line number/function/class context callback - * - * This function uses a backtrace generated from {@link debug_backtrace()} - * and so will not work at all in PHP < 4.3.0. The frame should - * reference the frame that contains the source of the error. - * @return array|false either array('file' => file, 'line' => line, - * 'function' => function name, 'class' => class name) or - * if this doesn't work, then false - * @param unused - * @param integer backtrace frame. - * @param array Results of debug_backtrace() - * @static - */ - function getFileLine($code, $params, $backtrace = null) - { - if ($backtrace === null) { - return false; - } - $frame = 0; - $functionframe = 1; - if (!isset($backtrace[1])) { - $functionframe = 0; - } else { - while (isset($backtrace[$functionframe]['function']) && - $backtrace[$functionframe]['function'] == 'eval' && - isset($backtrace[$functionframe + 1])) { - $functionframe++; - } - } - if (isset($backtrace[$frame])) { - if (!isset($backtrace[$frame]['file'])) { - $frame++; - } - $funcbacktrace = $backtrace[$functionframe]; - $filebacktrace = $backtrace[$frame]; - $ret = array('file' => $filebacktrace['file'], - 'line' => $filebacktrace['line']); - // rearrange for eval'd code or create function errors - if (strpos($filebacktrace['file'], '(') && - preg_match(';^(.*?)\((\d+)\) : (.*?)$;', $filebacktrace['file'], - $matches)) { - $ret['file'] = $matches[1]; - $ret['line'] = $matches[2] + 0; - } - if (isset($funcbacktrace['function']) && isset($backtrace[1])) { - if ($funcbacktrace['function'] != 'eval') { - if ($funcbacktrace['function'] == '__lambda_func') { - $ret['function'] = 'create_function() code'; - } else { - $ret['function'] = $funcbacktrace['function']; - } - } - } - if (isset($funcbacktrace['class']) && isset($backtrace[1])) { - $ret['class'] = $funcbacktrace['class']; - } - return $ret; - } - return false; - } - - /** - * Standard error message generation callback - * - * This method may also be called by a custom error message generator - * to fill in template values from the params array, simply - * set the third parameter to the error message template string to use - * - * The special variable %__msg% is reserved: use it only to specify - * where a message passed in by the user should be placed in the template, - * like so: - * - * Error message: %msg% - internal error - * - * If the message passed like so: - * - * - * $stack->push(ERROR_CODE, 'error', array(), 'server error 500'); - * - * - * The returned error message will be "Error message: server error 500 - - * internal error" - * @param PEAR_ErrorStack - * @param array - * @param string|false Pre-generated error message template - * @static - * @return string - */ - function getErrorMessage(&$stack, $err, $template = false) - { - if ($template) { - $mainmsg = $template; - } else { - $mainmsg = $stack->getErrorMessageTemplate($err['code']); - } - $mainmsg = str_replace('%__msg%', $err['message'], $mainmsg); - if (count($err['params'])) { - foreach ($err['params'] as $name => $val) { - if (is_array($val)) { - // @ is needed in case $val is a multi-dimensional array - $val = @implode(', ', $val); - } - if (is_object($val)) { - if (method_exists($val, '__toString')) { - $val = $val->__toString(); - } else { - PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_OBJTOSTRING, - 'warning', array('obj' => get_class($val)), - 'object %obj% passed into getErrorMessage, but has no __toString() method'); - $val = 'Object'; - } - } - $mainmsg = str_replace('%' . $name . '%', $val, $mainmsg); - } - } - return $mainmsg; - } - - /** - * Standard Error Message Template generator from code - * @return string - */ - function getErrorMessageTemplate($code) - { - if (!isset($this->_errorMsgs[$code])) { - return '%__msg%'; - } - return $this->_errorMsgs[$code]; - } - - /** - * Set the Error Message Template array - * - * The array format must be: - *
-     * array(error code => 'message template',...)
-     * 
- * - * Error message parameters passed into {@link push()} will be used as input - * for the error message. If the template is 'message %foo% was %bar%', and the - * parameters are array('foo' => 'one', 'bar' => 'six'), the error message returned will - * be 'message one was six' - * @return string - */ - function setErrorMessageTemplate($template) - { - $this->_errorMsgs = $template; - } - - - /** - * emulate PEAR::raiseError() - * - * @return PEAR_Error - */ - function raiseError() - { - require_once 'PEAR.php'; - $args = func_get_args(); - return call_user_func_array(array('PEAR', 'raiseError'), $args); - } -} -$stack = &PEAR_ErrorStack::singleton('PEAR_ErrorStack'); -$stack->pushCallback(array('PEAR_ErrorStack', '_handleError')); -?> \ No newline at end of file diff --git a/3rdparty/PEAR/Exception.php b/3rdparty/PEAR/Exception.php deleted file mode 100644 index c735c16b39..0000000000 --- a/3rdparty/PEAR/Exception.php +++ /dev/null @@ -1,359 +0,0 @@ - | -// | Hans Lellelid | -// | Bertrand Mansion | -// | Greg Beaver | -// +----------------------------------------------------------------------+ -// -// $Id: Exception.php,v 1.4.2.2 2004/12/31 19:01:52 cellog Exp $ - - -/** - * Base PEAR_Exception Class - * - * WARNING: This code should be considered stable, but the API is - * subject to immediate and drastic change, so API stability is - * at best alpha - * - * 1) Features: - * - * - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception)) - * - Definable triggers, shot when exceptions occur - * - Pretty and informative error messages - * - Added more context info available (like class, method or cause) - * - cause can be a PEAR_Exception or an array of mixed - * PEAR_Exceptions/PEAR_ErrorStack warnings - * - callbacks for specific exception classes and their children - * - * 2) Ideas: - * - * - Maybe a way to define a 'template' for the output - * - * 3) Inherited properties from PHP Exception Class: - * - * protected $message - * protected $code - * protected $line - * protected $file - * private $trace - * - * 4) Inherited methods from PHP Exception Class: - * - * __clone - * __construct - * getMessage - * getCode - * getFile - * getLine - * getTraceSafe - * getTraceSafeAsString - * __toString - * - * 5) Usage example - * - * - * require_once 'PEAR/Exception.php'; - * - * class Test { - * function foo() { - * throw new PEAR_Exception('Error Message', ERROR_CODE); - * } - * } - * - * function myLogger($pear_exception) { - * echo $pear_exception->getMessage(); - * } - * // each time a exception is thrown the 'myLogger' will be called - * // (its use is completely optional) - * PEAR_Exception::addObserver('myLogger'); - * $test = new Test; - * try { - * $test->foo(); - * } catch (PEAR_Exception $e) { - * print $e; - * } - * - * - * @since PHP 5 - * @package PEAR - * @version $Revision: 1.4.2.2 $ - * @author Tomas V.V.Cox - * @author Hans Lellelid - * @author Bertrand Mansion - * - */ -class PEAR_Exception extends Exception -{ - const OBSERVER_PRINT = -2; - const OBSERVER_TRIGGER = -4; - const OBSERVER_DIE = -8; - protected $cause; - private static $_observers = array(); - private static $_uniqueid = 0; - private $_trace; - - /** - * Supported signatures: - * PEAR_Exception(string $message); - * PEAR_Exception(string $message, int $code); - * PEAR_Exception(string $message, Exception $cause); - * PEAR_Exception(string $message, Exception $cause, int $code); - * PEAR_Exception(string $message, array $causes); - * PEAR_Exception(string $message, array $causes, int $code); - */ - public function __construct($message, $p2 = null, $p3 = null) - { - if (is_int($p2)) { - $code = $p2; - $this->cause = null; - } elseif ($p2 instanceof Exception || is_array($p2)) { - $code = $p3; - if (is_array($p2) && isset($p2['message'])) { - // fix potential problem of passing in a single warning - $p2 = array($p2); - } - $this->cause = $p2; - } else { - $code = null; - $this->cause = null; - } - parent::__construct($message, $code); - $this->signal(); - } - - /** - * @param mixed $callback - A valid php callback, see php func is_callable() - * - A PEAR_Exception::OBSERVER_* constant - * - An array(const PEAR_Exception::OBSERVER_*, - * mixed $options) - * @param string $label The name of the observer. Use this if you want - * to remove it later with removeObserver() - */ - public static function addObserver($callback, $label = 'default') - { - self::$_observers[$label] = $callback; - } - - public static function removeObserver($label = 'default') - { - unset(self::$_observers[$label]); - } - - /** - * @return int unique identifier for an observer - */ - public static function getUniqueId() - { - return self::$_uniqueid++; - } - - private function signal() - { - foreach (self::$_observers as $func) { - if (is_callable($func)) { - call_user_func($func, $this); - continue; - } - settype($func, 'array'); - switch ($func[0]) { - case self::OBSERVER_PRINT : - $f = (isset($func[1])) ? $func[1] : '%s'; - printf($f, $this->getMessage()); - break; - case self::OBSERVER_TRIGGER : - $f = (isset($func[1])) ? $func[1] : E_USER_NOTICE; - trigger_error($this->getMessage(), $f); - break; - case self::OBSERVER_DIE : - $f = (isset($func[1])) ? $func[1] : '%s'; - die(printf($f, $this->getMessage())); - break; - default: - trigger_error('invalid observer type', E_USER_WARNING); - } - } - } - - /** - * Return specific error information that can be used for more detailed - * error messages or translation. - * - * This method may be overridden in child exception classes in order - * to add functionality not present in PEAR_Exception and is a placeholder - * to define API - * - * The returned array must be an associative array of parameter => value like so: - *
-     * array('name' => $name, 'context' => array(...))
-     * 
- * @return array - */ - public function getErrorData() - { - return array(); - } - - /** - * Returns the exception that caused this exception to be thrown - * @access public - * @return Exception|array The context of the exception - */ - public function getCause() - { - return $this->cause; - } - - /** - * Function must be public to call on caused exceptions - * @param array - */ - public function getCauseMessage(&$causes) - { - $trace = $this->getTraceSafe(); - $cause = array('class' => get_class($this), - 'message' => $this->message, - 'file' => 'unknown', - 'line' => 'unknown'); - if (isset($trace[0])) { - if (isset($trace[0]['file'])) { - $cause['file'] = $trace[0]['file']; - $cause['line'] = $trace[0]['line']; - } - } - if ($this->cause instanceof PEAR_Exception) { - $this->cause->getCauseMessage($causes); - } - if (is_array($this->cause)) { - foreach ($this->cause as $cause) { - if ($cause instanceof PEAR_Exception) { - $cause->getCauseMessage($causes); - } elseif (is_array($cause) && isset($cause['message'])) { - // PEAR_ErrorStack warning - $causes[] = array( - 'class' => $cause['package'], - 'message' => $cause['message'], - 'file' => isset($cause['context']['file']) ? - $cause['context']['file'] : - 'unknown', - 'line' => isset($cause['context']['line']) ? - $cause['context']['line'] : - 'unknown', - ); - } - } - } - } - - public function getTraceSafe() - { - if (!isset($this->_trace)) { - $this->_trace = $this->getTrace(); - if (empty($this->_trace)) { - $backtrace = debug_backtrace(); - $this->_trace = array($backtrace[count($backtrace)-1]); - } - } - return $this->_trace; - } - - public function getErrorClass() - { - $trace = $this->getTraceSafe(); - return $trace[0]['class']; - } - - public function getErrorMethod() - { - $trace = $this->getTraceSafe(); - return $trace[0]['function']; - } - - public function __toString() - { - if (isset($_SERVER['REQUEST_URI'])) { - return $this->toHtml(); - } - return $this->toText(); - } - - public function toHtml() - { - $trace = $this->getTraceSafe(); - $causes = array(); - $this->getCauseMessage($causes); - $html = '' . "\n"; - foreach ($causes as $i => $cause) { - $html .= '\n"; - } - $html .= '' . "\n" - . '' - . '' - . '' . "\n"; - - foreach ($trace as $k => $v) { - $html .= '' - . '' - . '' . "\n"; - } - $html .= '' - . '' - . '' . "\n" - . '
' - . str_repeat('-', $i) . ' ' . $cause['class'] . ': ' - . htmlspecialchars($cause['message']) . ' in ' . $cause['file'] . ' ' - . 'on line ' . $cause['line'] . '' - . "
Exception trace
#FunctionLocation
' . $k . ''; - if (!empty($v['class'])) { - $html .= $v['class'] . $v['type']; - } - $html .= $v['function']; - $args = array(); - if (!empty($v['args'])) { - foreach ($v['args'] as $arg) { - if (is_null($arg)) $args[] = 'null'; - elseif (is_array($arg)) $args[] = 'Array'; - elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')'; - elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false'; - elseif (is_int($arg) || is_double($arg)) $args[] = $arg; - else { - $arg = (string)$arg; - $str = htmlspecialchars(substr($arg, 0, 16)); - if (strlen($arg) > 16) $str .= '…'; - $args[] = "'" . $str . "'"; - } - } - } - $html .= '(' . implode(', ',$args) . ')' - . '' . $v['file'] . ':' . $v['line'] . '
' . ($k+1) . '{main} 
'; - return $html; - } - - public function toText() - { - $causes = array(); - $this->getCauseMessage($causes); - $causeMsg = ''; - foreach ($causes as $i => $cause) { - $causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': ' - . $cause['message'] . ' in ' . $cause['file'] - . ' on line ' . $cause['line'] . "\n"; - } - return $causeMsg . $this->getTraceAsString(); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/PEAR/Frontend/CLI.php b/3rdparty/PEAR/Frontend/CLI.php deleted file mode 100644 index 832ddf09b3..0000000000 --- a/3rdparty/PEAR/Frontend/CLI.php +++ /dev/null @@ -1,509 +0,0 @@ - | - +----------------------------------------------------------------------+ - - $Id: CLI.php,v 1.41 2004/02/17 05:49:16 ssb Exp $ -*/ - -require_once "PEAR.php"; - -class PEAR_Frontend_CLI extends PEAR -{ - // {{{ properties - - /** - * What type of user interface this frontend is for. - * @var string - * @access public - */ - var $type = 'CLI'; - var $lp = ''; // line prefix - - var $params = array(); - var $term = array( - 'bold' => '', - 'normal' => '', - ); - - // }}} - - // {{{ constructor - - function PEAR_Frontend_CLI() - { - parent::PEAR(); - $term = getenv('TERM'); //(cox) $_ENV is empty for me in 4.1.1 - if (function_exists('posix_isatty') && !posix_isatty(1)) { - // output is being redirected to a file or through a pipe - } elseif ($term) { - // XXX can use ncurses extension here, if available - if (preg_match('/^(xterm|vt220|linux)/', $term)) { - $this->term['bold'] = sprintf("%c%c%c%c", 27, 91, 49, 109); - $this->term['normal']=sprintf("%c%c%c", 27, 91, 109); - } elseif (preg_match('/^vt100/', $term)) { - $this->term['bold'] = sprintf("%c%c%c%c%c%c", 27, 91, 49, 109, 0, 0); - $this->term['normal']=sprintf("%c%c%c%c%c", 27, 91, 109, 0, 0); - } - } elseif (OS_WINDOWS) { - // XXX add ANSI codes here - } - } - - // }}} - - // {{{ displayLine(text) - - function displayLine($text) - { - trigger_error("PEAR_Frontend_CLI::displayLine deprecated", E_USER_ERROR); - } - - function _displayLine($text) - { - print "$this->lp$text\n"; - } - - // }}} - // {{{ display(text) - - function display($text) - { - trigger_error("PEAR_Frontend_CLI::display deprecated", E_USER_ERROR); - } - - function _display($text) - { - print $text; - } - - // }}} - // {{{ displayError(eobj) - - /** - * @param object PEAR_Error object - */ - function displayError($eobj) - { - return $this->_displayLine($eobj->getMessage()); - } - - // }}} - // {{{ displayFatalError(eobj) - - /** - * @param object PEAR_Error object - */ - function displayFatalError($eobj) - { - $this->displayError($eobj); - exit(1); - } - - // }}} - // {{{ displayHeading(title) - - function displayHeading($title) - { - trigger_error("PEAR_Frontend_CLI::displayHeading deprecated", E_USER_ERROR); - } - - function _displayHeading($title) - { - print $this->lp.$this->bold($title)."\n"; - print $this->lp.str_repeat("=", strlen($title))."\n"; - } - - // }}} - // {{{ userDialog(prompt, [type], [default]) - - function userDialog($command, $prompts, $types = array(), $defaults = array()) - { - $result = array(); - if (is_array($prompts)) { - $fp = fopen("php://stdin", "r"); - foreach ($prompts as $key => $prompt) { - $type = $types[$key]; - $default = @$defaults[$key]; - if ($type == 'password') { - system('stty -echo'); - } - print "$this->lp$prompt "; - if ($default) { - print "[$default] "; - } - print ": "; - $line = fgets($fp, 2048); - if ($type == 'password') { - system('stty echo'); - print "\n"; - } - if ($default && trim($line) == "") { - $result[$key] = $default; - } else { - $result[$key] = $line; - } - } - fclose($fp); - } - return $result; - } - - // }}} - // {{{ userConfirm(prompt, [default]) - - function userConfirm($prompt, $default = 'yes') - { - trigger_error("PEAR_Frontend_CLI::userConfirm not yet converted", E_USER_ERROR); - static $positives = array('y', 'yes', 'on', '1'); - static $negatives = array('n', 'no', 'off', '0'); - print "$this->lp$prompt [$default] : "; - $fp = fopen("php://stdin", "r"); - $line = fgets($fp, 2048); - fclose($fp); - $answer = strtolower(trim($line)); - if (empty($answer)) { - $answer = $default; - } - if (in_array($answer, $positives)) { - return true; - } - if (in_array($answer, $negatives)) { - return false; - } - if (in_array($default, $positives)) { - return true; - } - return false; - } - - // }}} - // {{{ startTable([params]) - - function startTable($params = array()) - { - trigger_error("PEAR_Frontend_CLI::startTable deprecated", E_USER_ERROR); - } - - function _startTable($params = array()) - { - $params['table_data'] = array(); - $params['widest'] = array(); // indexed by column - $params['highest'] = array(); // indexed by row - $params['ncols'] = 0; - $this->params = $params; - } - - // }}} - // {{{ tableRow(columns, [rowparams], [colparams]) - - function tableRow($columns, $rowparams = array(), $colparams = array()) - { - trigger_error("PEAR_Frontend_CLI::tableRow deprecated", E_USER_ERROR); - } - - function _tableRow($columns, $rowparams = array(), $colparams = array()) - { - $highest = 1; - for ($i = 0; $i < sizeof($columns); $i++) { - $col = &$columns[$i]; - if (isset($colparams[$i]) && !empty($colparams[$i]['wrap'])) { - $col = wordwrap($col, $colparams[$i]['wrap'], "\n", 0); - } - if (strpos($col, "\n") !== false) { - $multiline = explode("\n", $col); - $w = 0; - foreach ($multiline as $n => $line) { - if (strlen($line) > $w) { - $w = strlen($line); - } - } - $lines = sizeof($multiline); - } else { - $w = strlen($col); - } - if ($w > @$this->params['widest'][$i]) { - $this->params['widest'][$i] = $w; - } - $tmp = count_chars($columns[$i], 1); - // handle unix, mac and windows formats - $lines = (isset($tmp[10]) ? $tmp[10] : @$tmp[13]) + 1; - if ($lines > $highest) { - $highest = $lines; - } - } - if (sizeof($columns) > $this->params['ncols']) { - $this->params['ncols'] = sizeof($columns); - } - $new_row = array( - 'data' => $columns, - 'height' => $highest, - 'rowparams' => $rowparams, - 'colparams' => $colparams, - ); - $this->params['table_data'][] = $new_row; - } - - // }}} - // {{{ endTable() - - function endTable() - { - trigger_error("PEAR_Frontend_CLI::endTable deprecated", E_USER_ERROR); - } - - function _endTable() - { - extract($this->params); - if (!empty($caption)) { - $this->_displayHeading($caption); - } - if (count($table_data) == 0) { - return; - } - if (!isset($width)) { - $width = $widest; - } else { - for ($i = 0; $i < $ncols; $i++) { - if (!isset($width[$i])) { - $width[$i] = $widest[$i]; - } - } - } - $border = false; - if (empty($border)) { - $cellstart = ''; - $cellend = ' '; - $rowend = ''; - $padrowend = false; - $borderline = ''; - } else { - $cellstart = '| '; - $cellend = ' '; - $rowend = '|'; - $padrowend = true; - $borderline = '+'; - foreach ($width as $w) { - $borderline .= str_repeat('-', $w + strlen($cellstart) + strlen($cellend) - 1); - $borderline .= '+'; - } - } - if ($borderline) { - $this->_displayLine($borderline); - } - for ($i = 0; $i < sizeof($table_data); $i++) { - extract($table_data[$i]); - if (!is_array($rowparams)) { - $rowparams = array(); - } - if (!is_array($colparams)) { - $colparams = array(); - } - $rowlines = array(); - if ($height > 1) { - for ($c = 0; $c < sizeof($data); $c++) { - $rowlines[$c] = preg_split('/(\r?\n|\r)/', $data[$c]); - if (sizeof($rowlines[$c]) < $height) { - $rowlines[$c] = array_pad($rowlines[$c], $height, ''); - } - } - } else { - for ($c = 0; $c < sizeof($data); $c++) { - $rowlines[$c] = array($data[$c]); - } - } - for ($r = 0; $r < $height; $r++) { - $rowtext = ''; - for ($c = 0; $c < sizeof($data); $c++) { - if (isset($colparams[$c])) { - $attribs = array_merge($rowparams, $colparams); - } else { - $attribs = $rowparams; - } - $w = isset($width[$c]) ? $width[$c] : 0; - //$cell = $data[$c]; - $cell = $rowlines[$c][$r]; - $l = strlen($cell); - if ($l > $w) { - $cell = substr($cell, 0, $w); - } - if (isset($attribs['bold'])) { - $cell = $this->bold($cell); - } - if ($l < $w) { - // not using str_pad here because we may - // add bold escape characters to $cell - $cell .= str_repeat(' ', $w - $l); - } - - $rowtext .= $cellstart . $cell . $cellend; - } - if (!$border) { - $rowtext = rtrim($rowtext); - } - $rowtext .= $rowend; - $this->_displayLine($rowtext); - } - } - if ($borderline) { - $this->_displayLine($borderline); - } - } - - // }}} - // {{{ outputData() - - function outputData($data, $command = '_default') - { - switch ($command) { - case 'install': - case 'upgrade': - case 'upgrade-all': - if (isset($data['release_warnings'])) { - $this->_displayLine(''); - $this->_startTable(array( - 'border' => false, - 'caption' => 'Release Warnings' - )); - $this->_tableRow(array($data['release_warnings']), null, array(1 => array('wrap' => 55))); - $this->_endTable(); - $this->_displayLine(''); - } - $this->_displayLine($data['data']); - break; - case 'search': - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55))); - } - - foreach($data['data'] as $category) { - foreach($category as $pkg) { - $this->_tableRow($pkg, null, array(1 => array('wrap' => 55))); - } - }; - $this->_endTable(); - break; - case 'list-all': - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55))); - } - - foreach($data['data'] as $category) { - foreach($category as $pkg) { - unset($pkg[3]); - unset($pkg[4]); - $this->_tableRow($pkg, null, array(1 => array('wrap' => 55))); - } - }; - $this->_endTable(); - break; - case 'config-show': - $data['border'] = false; - $opts = array(0 => array('wrap' => 30), - 1 => array('wrap' => 20), - 2 => array('wrap' => 35)); - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], - array('bold' => true), - $opts); - } - foreach($data['data'] as $group) { - foreach($group as $value) { - if ($value[2] == '') { - $value[2] = ""; - } - $this->_tableRow($value, null, $opts); - } - } - $this->_endTable(); - break; - case 'remote-info': - $data = array( - 'caption' => 'Package details:', - 'border' => false, - 'data' => array( - array("Latest", $data['stable']), - array("Installed", $data['installed']), - array("Package", $data['name']), - array("License", $data['license']), - array("Category", $data['category']), - array("Summary", $data['summary']), - array("Description", $data['description']), - ), - ); - default: { - if (is_array($data)) { - $this->_startTable($data); - $count = count($data['data'][0]); - if ($count == 2) { - $opts = array(0 => array('wrap' => 25), - 1 => array('wrap' => 48) - ); - } elseif ($count == 3) { - $opts = array(0 => array('wrap' => 30), - 1 => array('wrap' => 20), - 2 => array('wrap' => 35) - ); - } else { - $opts = null; - } - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], - array('bold' => true), - $opts); - } - foreach($data['data'] as $row) { - $this->_tableRow($row, null, $opts); - } - $this->_endTable(); - } else { - $this->_displayLine($data); - } - } - } - } - - // }}} - // {{{ log(text) - - - function log($text, $append_crlf = true) - { - if ($append_crlf) { - return $this->_displayLine($text); - } - return $this->_display($text); - } - - - // }}} - // {{{ bold($text) - - function bold($text) - { - if (empty($this->term['bold'])) { - return strtoupper($text); - } - return $this->term['bold'] . $text . $this->term['normal']; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Installer.php b/3rdparty/PEAR/Installer.php deleted file mode 100644 index 31e2cff81e..0000000000 --- a/3rdparty/PEAR/Installer.php +++ /dev/null @@ -1,1068 +0,0 @@ - | -// | Tomas V.V.Cox | -// | Martin Jansen | -// +----------------------------------------------------------------------+ -// -// $Id: Installer.php,v 1.150.2.2 2005/02/17 17:47:55 cellog Exp $ - -require_once 'PEAR/Downloader.php'; - -/** - * Administration class used to install PEAR packages and maintain the - * installed package database. - * - * TODO: - * - Check dependencies break on package uninstall (when no force given) - * - add a guessInstallDest() method with the code from _installFile() and - * use that method in Registry::_rebuildFileMap() & Command_Registry::doList(), - * others.. - * - * @since PHP 4.0.2 - * @author Stig Bakken - * @author Martin Jansen - * @author Greg Beaver - */ -class PEAR_Installer extends PEAR_Downloader -{ - // {{{ properties - - /** name of the package directory, for example Foo-1.0 - * @var string - */ - var $pkgdir; - - /** directory where PHP code files go - * @var string - */ - var $phpdir; - - /** directory where PHP extension files go - * @var string - */ - var $extdir; - - /** directory where documentation goes - * @var string - */ - var $docdir; - - /** installation root directory (ala PHP's INSTALL_ROOT or - * automake's DESTDIR - * @var string - */ - var $installroot = ''; - - /** debug level - * @var int - */ - var $debug = 1; - - /** temporary directory - * @var string - */ - var $tmpdir; - - /** PEAR_Registry object used by the installer - * @var object - */ - var $registry; - - /** List of file transactions queued for an install/upgrade/uninstall. - * - * Format: - * array( - * 0 => array("rename => array("from-file", "to-file")), - * 1 => array("delete" => array("file-to-delete")), - * ... - * ) - * - * @var array - */ - var $file_operations = array(); - - // }}} - - // {{{ constructor - - /** - * PEAR_Installer constructor. - * - * @param object $ui user interface object (instance of PEAR_Frontend_*) - * - * @access public - */ - function PEAR_Installer(&$ui) - { - parent::PEAR_Common(); - $this->setFrontendObject($ui); - $this->debug = $this->config->get('verbose'); - //$this->registry = &new PEAR_Registry($this->config->get('php_dir')); - } - - // }}} - - // {{{ _deletePackageFiles() - - /** - * Delete a package's installed files, does not remove empty directories. - * - * @param string $package package name - * - * @return bool TRUE on success, or a PEAR error on failure - * - * @access private - */ - function _deletePackageFiles($package) - { - if (!strlen($package)) { - return $this->raiseError("No package to uninstall given"); - } - $filelist = $this->registry->packageInfo($package, 'filelist'); - if ($filelist == null) { - return $this->raiseError("$package not installed"); - } - foreach ($filelist as $file => $props) { - if (empty($props['installed_as'])) { - continue; - } - $path = $this->_prependPath($props['installed_as'], $this->installroot); - $this->addFileOperation('delete', array($path)); - } - return true; - } - - // }}} - // {{{ _installFile() - - /** - * @param string filename - * @param array attributes from tag in package.xml - * @param string path to install the file in - * @param array options from command-line - * @access private - */ - function _installFile($file, $atts, $tmp_path, $options) - { - // {{{ return if this file is meant for another platform - static $os; - if (isset($atts['platform'])) { - if (empty($os)) { - include_once "OS/Guess.php"; - $os = new OS_Guess(); - } - if (strlen($atts['platform']) && $atts['platform']{0} == '!') { - $negate = true; - $platform = substr($atts['platform'], 1); - } else { - $negate = false; - $platform = $atts['platform']; - } - if ((bool) $os->matchSignature($platform) === $negate) { - $this->log(3, "skipped $file (meant for $atts[platform], we are ".$os->getSignature().")"); - return PEAR_INSTALLER_SKIPPED; - } - } - // }}} - - // {{{ assemble the destination paths - switch ($atts['role']) { - case 'doc': - case 'data': - case 'test': - $dest_dir = $this->config->get($atts['role'] . '_dir') . - DIRECTORY_SEPARATOR . $this->pkginfo['package']; - unset($atts['baseinstalldir']); - break; - case 'ext': - case 'php': - $dest_dir = $this->config->get($atts['role'] . '_dir'); - break; - case 'script': - $dest_dir = $this->config->get('bin_dir'); - break; - case 'src': - case 'extsrc': - $this->source_files++; - return; - default: - return $this->raiseError("Invalid role `$atts[role]' for file $file"); - } - $save_destdir = $dest_dir; - if (!empty($atts['baseinstalldir'])) { - $dest_dir .= DIRECTORY_SEPARATOR . $atts['baseinstalldir']; - } - if (dirname($file) != '.' && empty($atts['install-as'])) { - $dest_dir .= DIRECTORY_SEPARATOR . dirname($file); - } - if (empty($atts['install-as'])) { - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . basename($file); - } else { - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . $atts['install-as']; - } - $orig_file = $tmp_path . DIRECTORY_SEPARATOR . $file; - - // Clean up the DIRECTORY_SEPARATOR mess - $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR; - list($dest_file, $orig_file) = preg_replace(array('!\\\\+!', '!/!', "!$ds2+!"), - DIRECTORY_SEPARATOR, - array($dest_file, $orig_file)); - $installed_as = $dest_file; - $final_dest_file = $this->_prependPath($dest_file, $this->installroot); - $dest_dir = dirname($final_dest_file); - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . '.tmp' . basename($final_dest_file); - // }}} - - if (!@is_dir($dest_dir)) { - if (!$this->mkDirHier($dest_dir)) { - return $this->raiseError("failed to mkdir $dest_dir", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ mkdir $dest_dir"); - } - if (empty($atts['replacements'])) { - if (!file_exists($orig_file)) { - return $this->raiseError("file does not exist", - PEAR_INSTALLER_FAILED); - } - if (!@copy($orig_file, $dest_file)) { - return $this->raiseError("failed to write $dest_file", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ cp $orig_file $dest_file"); - if (isset($atts['md5sum'])) { - $md5sum = md5_file($dest_file); - } - } else { - // {{{ file with replacements - if (!file_exists($orig_file)) { - return $this->raiseError("file does not exist", - PEAR_INSTALLER_FAILED); - } - $fp = fopen($orig_file, "r"); - $contents = fread($fp, filesize($orig_file)); - fclose($fp); - if (isset($atts['md5sum'])) { - $md5sum = md5($contents); - } - $subst_from = $subst_to = array(); - foreach ($atts['replacements'] as $a) { - $to = ''; - if ($a['type'] == 'php-const') { - if (preg_match('/^[a-z0-9_]+$/i', $a['to'])) { - eval("\$to = $a[to];"); - } else { - $this->log(0, "invalid php-const replacement: $a[to]"); - continue; - } - } elseif ($a['type'] == 'pear-config') { - $to = $this->config->get($a['to']); - if (is_null($to)) { - $this->log(0, "invalid pear-config replacement: $a[to]"); - continue; - } - } elseif ($a['type'] == 'package-info') { - if (isset($this->pkginfo[$a['to']]) && is_string($this->pkginfo[$a['to']])) { - $to = $this->pkginfo[$a['to']]; - } else { - $this->log(0, "invalid package-info replacement: $a[to]"); - continue; - } - } - if (!is_null($to)) { - $subst_from[] = $a['from']; - $subst_to[] = $to; - } - } - $this->log(3, "doing ".sizeof($subst_from)." substitution(s) for $final_dest_file"); - if (sizeof($subst_from)) { - $contents = str_replace($subst_from, $subst_to, $contents); - } - $wp = @fopen($dest_file, "wb"); - if (!is_resource($wp)) { - return $this->raiseError("failed to create $dest_file: $php_errormsg", - PEAR_INSTALLER_FAILED); - } - if (!fwrite($wp, $contents)) { - return $this->raiseError("failed writing to $dest_file: $php_errormsg", - PEAR_INSTALLER_FAILED); - } - fclose($wp); - // }}} - } - // {{{ check the md5 - if (isset($md5sum)) { - if (strtolower($md5sum) == strtolower($atts['md5sum'])) { - $this->log(2, "md5sum ok: $final_dest_file"); - } else { - if (empty($options['force'])) { - // delete the file - @unlink($dest_file); - return $this->raiseError("bad md5sum for file $final_dest_file", - PEAR_INSTALLER_FAILED); - } else { - $this->log(0, "warning : bad md5sum for file $final_dest_file"); - } - } - } - // }}} - // {{{ set file permissions - if (!OS_WINDOWS) { - if ($atts['role'] == 'script') { - $mode = 0777 & ~(int)octdec($this->config->get('umask')); - $this->log(3, "+ chmod +x $dest_file"); - } else { - $mode = 0666 & ~(int)octdec($this->config->get('umask')); - } - $this->addFileOperation("chmod", array($mode, $dest_file)); - if (!@chmod($dest_file, $mode)) { - $this->log(0, "failed to change mode of $dest_file"); - } - } - // }}} - $this->addFileOperation("rename", array($dest_file, $final_dest_file)); - // Store the full path where the file was installed for easy unistall - $this->addFileOperation("installed_as", array($file, $installed_as, - $save_destdir, dirname(substr($dest_file, strlen($save_destdir))))); - - //$this->log(2, "installed: $dest_file"); - return PEAR_INSTALLER_OK; - } - - // }}} - // {{{ addFileOperation() - - /** - * Add a file operation to the current file transaction. - * - * @see startFileTransaction() - * @var string $type This can be one of: - * - rename: rename a file ($data has 2 values) - * - chmod: change permissions on a file ($data has 2 values) - * - delete: delete a file ($data has 1 value) - * - rmdir: delete a directory if empty ($data has 1 value) - * - installed_as: mark a file as installed ($data has 4 values). - * @var array $data For all file operations, this array must contain the - * full path to the file or directory that is being operated on. For - * the rename command, the first parameter must be the file to rename, - * the second its new name. - * - * The installed_as operation contains 4 elements in this order: - * 1. Filename as listed in the filelist element from package.xml - * 2. Full path to the installed file - * 3. Full path from the php_dir configuration variable used in this - * installation - * 4. Relative path from the php_dir that this file is installed in - */ - function addFileOperation($type, $data) - { - if (!is_array($data)) { - return $this->raiseError('Internal Error: $data in addFileOperation' - . ' must be an array, was ' . gettype($data)); - } - if ($type == 'chmod') { - $octmode = decoct($data[0]); - $this->log(3, "adding to transaction: $type $octmode $data[1]"); - } else { - $this->log(3, "adding to transaction: $type " . implode(" ", $data)); - } - $this->file_operations[] = array($type, $data); - } - - // }}} - // {{{ startFileTransaction() - - function startFileTransaction($rollback_in_case = false) - { - if (count($this->file_operations) && $rollback_in_case) { - $this->rollbackFileTransaction(); - } - $this->file_operations = array(); - } - - // }}} - // {{{ commitFileTransaction() - - function commitFileTransaction() - { - $n = count($this->file_operations); - $this->log(2, "about to commit $n file operations"); - // {{{ first, check permissions and such manually - $errors = array(); - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - if (!file_exists($data[0])) { - $errors[] = "cannot rename file $data[0], doesn't exist"; - } - // check that dest dir. is writable - if (!is_writable(dirname($data[1]))) { - $errors[] = "permission denied ($type): $data[1]"; - } - break; - case 'chmod': - // check that file is writable - if (!is_writable($data[1])) { - $errors[] = "permission denied ($type): $data[1] " . decoct($data[0]); - } - break; - case 'delete': - if (!file_exists($data[0])) { - $this->log(2, "warning: file $data[0] doesn't exist, can't be deleted"); - } - // check that directory is writable - if (file_exists($data[0]) && !is_writable(dirname($data[0]))) { - $errors[] = "permission denied ($type): $data[0]"; - } - break; - } - - } - // }}} - $m = sizeof($errors); - if ($m > 0) { - foreach ($errors as $error) { - $this->log(1, $error); - } - return false; - } - // {{{ really commit the transaction - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - @unlink($data[1]); - @rename($data[0], $data[1]); - $this->log(3, "+ mv $data[0] $data[1]"); - break; - case 'chmod': - @chmod($data[1], $data[0]); - $octmode = decoct($data[0]); - $this->log(3, "+ chmod $octmode $data[1]"); - break; - case 'delete': - @unlink($data[0]); - $this->log(3, "+ rm $data[0]"); - break; - case 'rmdir': - @rmdir($data[0]); - $this->log(3, "+ rmdir $data[0]"); - break; - case 'installed_as': - $this->pkginfo['filelist'][$data[0]]['installed_as'] = $data[1]; - if (!isset($this->pkginfo['filelist']['dirtree'][dirname($data[1])])) { - $this->pkginfo['filelist']['dirtree'][dirname($data[1])] = true; - while(!empty($data[3]) && $data[3] != '/' && $data[3] != '\\' - && $data[3] != '.') { - $this->pkginfo['filelist']['dirtree'] - [$this->_prependPath($data[3], $data[2])] = true; - $data[3] = dirname($data[3]); - } - } - break; - } - } - // }}} - $this->log(2, "successfully committed $n file operations"); - $this->file_operations = array(); - return true; - } - - // }}} - // {{{ rollbackFileTransaction() - - function rollbackFileTransaction() - { - $n = count($this->file_operations); - $this->log(2, "rolling back $n file operations"); - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - @unlink($data[0]); - $this->log(3, "+ rm $data[0]"); - break; - case 'mkdir': - @rmdir($data[0]); - $this->log(3, "+ rmdir $data[0]"); - break; - case 'chmod': - break; - case 'delete': - break; - case 'installed_as': - if (isset($this->pkginfo['filelist'])) { - unset($this->pkginfo['filelist'][$data[0]]['installed_as']); - } - if (isset($this->pkginfo['filelist']['dirtree'][dirname($data[1])])) { - unset($this->pkginfo['filelist']['dirtree'][dirname($data[1])]); - while(!empty($data[3]) && $data[3] != '/' && $data[3] != '\\' - && $data[3] != '.') { - unset($this->pkginfo['filelist']['dirtree'] - [$this->_prependPath($data[3], $data[2])]); - $data[3] = dirname($data[3]); - } - } - if (isset($this->pkginfo['filelist']['dirtree']) - && !count($this->pkginfo['filelist']['dirtree'])) { - unset($this->pkginfo['filelist']['dirtree']); - } - break; - } - } - $this->file_operations = array(); - } - - // }}} - // {{{ mkDirHier($dir) - - function mkDirHier($dir) - { - $this->addFileOperation('mkdir', array($dir)); - return parent::mkDirHier($dir); - } - - // }}} - // {{{ download() - - /** - * Download any files and their dependencies, if necessary - * - * @param array a mixed list of package names, local files, or package.xml - * @param PEAR_Config - * @param array options from the command line - * @param array this is the array that will be populated with packages to - * install. Format of each entry: - * - * - * array('pkg' => 'package_name', 'file' => '/path/to/local/file', - * 'info' => array() // parsed package.xml - * ); - * - * @param array this will be populated with any error messages - * @param false private recursion variable - * @param false private recursion variable - * @param false private recursion variable - * @deprecated in favor of PEAR_Downloader - */ - function download($packages, $options, &$config, &$installpackages, - &$errors, $installed = false, $willinstall = false, $state = false) - { - // trickiness: initialize here - parent::PEAR_Downloader($this->ui, $options, $config); - $ret = parent::download($packages); - $errors = $this->getErrorMsgs(); - $installpackages = $this->getDownloadedPackages(); - trigger_error("PEAR Warning: PEAR_Installer::download() is deprecated " . - "in favor of PEAR_Downloader class", E_USER_WARNING); - return $ret; - } - - // }}} - // {{{ install() - - /** - * Installs the files within the package file specified. - * - * @param string $pkgfile path to the package file - * @param array $options - * recognized options: - * - installroot : optional prefix directory for installation - * - force : force installation - * - register-only : update registry but don't install files - * - upgrade : upgrade existing install - * - soft : fail silently - * - nodeps : ignore dependency conflicts/missing dependencies - * - alldeps : install all dependencies - * - onlyreqdeps : install only required dependencies - * - * @return array|PEAR_Error package info if successful - */ - - function install($pkgfile, $options = array()) - { - $php_dir = $this->config->get('php_dir'); - if (isset($options['installroot'])) { - if (substr($options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $options['installroot'] = substr($options['installroot'], 0, -1); - } - $php_dir = $this->_prependPath($php_dir, $options['installroot']); - $this->installroot = $options['installroot']; - } else { - $this->installroot = ''; - } - $this->registry = &new PEAR_Registry($php_dir); - // ==> XXX should be removed later on - $flag_old_format = false; - - if (substr($pkgfile, -4) == '.xml') { - $descfile = $pkgfile; - } else { - // {{{ Decompress pack in tmp dir ------------------------------------- - - // To allow relative package file names - $pkgfile = realpath($pkgfile); - - if (PEAR::isError($tmpdir = System::mktemp('-d'))) { - return $tmpdir; - } - $this->log(3, '+ tmp dir created at ' . $tmpdir); - - $tar = new Archive_Tar($pkgfile); - if (!@$tar->extract($tmpdir)) { - return $this->raiseError("unable to unpack $pkgfile"); - } - - // {{{ Look for existing package file - $descfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml'; - - if (!is_file($descfile)) { - // ----- Look for old package archive format - // In this format the package.xml file was inside the - // Package-n.n directory - $dp = opendir($tmpdir); - do { - $pkgdir = readdir($dp); - } while ($pkgdir{0} == '.'); - - $descfile = $tmpdir . DIRECTORY_SEPARATOR . $pkgdir . DIRECTORY_SEPARATOR . 'package.xml'; - $flag_old_format = true; - $this->log(0, "warning : you are using an archive with an old format"); - } - // }}} - // <== XXX This part should be removed later on - // }}} - } - - if (!is_file($descfile)) { - return $this->raiseError("no package.xml file after extracting the archive"); - } - - // Parse xml file ----------------------------------------------- - $pkginfo = $this->infoFromDescriptionFile($descfile); - if (PEAR::isError($pkginfo)) { - return $pkginfo; - } - $this->validatePackageInfo($pkginfo, $errors, $warnings); - // XXX We allow warnings, do we have to do it? - if (count($errors)) { - if (empty($options['force'])) { - return $this->raiseError("The following errors where found (use force option to install anyway):\n". - implode("\n", $errors)); - } else { - $this->log(0, "warning : the following errors were found:\n". - implode("\n", $errors)); - } - } - - $pkgname = $pkginfo['package']; - - // {{{ Check dependencies ------------------------------------------- - if (isset($pkginfo['release_deps']) && empty($options['nodeps'])) { - $dep_errors = ''; - $error = $this->checkDeps($pkginfo, $dep_errors); - if ($error == true) { - if (empty($options['soft'])) { - $this->log(0, substr($dep_errors, 1)); - } - return $this->raiseError("$pkgname: Dependencies failed"); - } else if (!empty($dep_errors)) { - // Print optional dependencies - if (empty($options['soft'])) { - $this->log(0, $dep_errors); - } - } - } - // }}} - - // {{{ checks to do when not in "force" mode - if (empty($options['force'])) { - $test = $this->registry->checkFileMap($pkginfo); - if (sizeof($test)) { - $tmp = $test; - foreach ($tmp as $file => $pkg) { - if ($pkg == $pkgname) { - unset($test[$file]); - } - } - if (sizeof($test)) { - $msg = "$pkgname: conflicting files found:\n"; - $longest = max(array_map("strlen", array_keys($test))); - $fmt = "%${longest}s (%s)\n"; - foreach ($test as $file => $pkg) { - $msg .= sprintf($fmt, $file, $pkg); - } - return $this->raiseError($msg); - } - } - } - // }}} - - $this->startFileTransaction(); - - if (empty($options['upgrade'])) { - // checks to do only when installing new packages - if (empty($options['force']) && $this->registry->packageExists($pkgname)) { - return $this->raiseError("$pkgname already installed"); - } - } else { - if ($this->registry->packageExists($pkgname)) { - $v1 = $this->registry->packageInfo($pkgname, 'version'); - $v2 = $pkginfo['version']; - $cmp = version_compare("$v1", "$v2", 'gt'); - if (empty($options['force']) && !version_compare("$v2", "$v1", 'gt')) { - return $this->raiseError("upgrade to a newer version ($v2 is not newer than $v1)"); - } - if (empty($options['register-only'])) { - // when upgrading, remove old release's files first: - if (PEAR::isError($err = $this->_deletePackageFiles($pkgname))) { - return $this->raiseError($err); - } - } - } - } - - // {{{ Copy files to dest dir --------------------------------------- - - // info from the package it self we want to access from _installFile - $this->pkginfo = &$pkginfo; - // used to determine whether we should build any C code - $this->source_files = 0; - - if (empty($options['register-only'])) { - if (!is_dir($php_dir)) { - return $this->raiseError("no script destination directory\n", - null, PEAR_ERROR_DIE); - } - - $tmp_path = dirname($descfile); - if (substr($pkgfile, -4) != '.xml') { - $tmp_path .= DIRECTORY_SEPARATOR . $pkgname . '-' . $pkginfo['version']; - } - - // ==> XXX This part should be removed later on - if ($flag_old_format) { - $tmp_path = dirname($descfile); - } - // <== XXX This part should be removed later on - - // {{{ install files - foreach ($pkginfo['filelist'] as $file => $atts) { - $this->expectError(PEAR_INSTALLER_FAILED); - $res = $this->_installFile($file, $atts, $tmp_path, $options); - $this->popExpect(); - if (PEAR::isError($res)) { - if (empty($options['ignore-errors'])) { - $this->rollbackFileTransaction(); - if ($res->getMessage() == "file does not exist") { - $this->raiseError("file $file in package.xml does not exist"); - } - return $this->raiseError($res); - } else { - $this->log(0, "Warning: " . $res->getMessage()); - } - } - if ($res != PEAR_INSTALLER_OK) { - // Do not register files that were not installed - unset($pkginfo['filelist'][$file]); - } - } - // }}} - - // {{{ compile and install source files - if ($this->source_files > 0 && empty($options['nobuild'])) { - $this->log(1, "$this->source_files source files, building"); - $bob = &new PEAR_Builder($this->ui); - $bob->debug = $this->debug; - $built = $bob->build($descfile, array(&$this, '_buildCallback')); - if (PEAR::isError($built)) { - $this->rollbackFileTransaction(); - return $built; - } - $this->log(1, "\nBuild process completed successfully"); - foreach ($built as $ext) { - $bn = basename($ext['file']); - list($_ext_name, $_ext_suff) = explode('.', $bn); - if ($_ext_suff == '.so' || $_ext_suff == '.dll') { - if (extension_loaded($_ext_name)) { - $this->raiseError("Extension '$_ext_name' already loaded. " . - 'Please unload it in your php.ini file ' . - 'prior to install or upgrade'); - } - $role = 'ext'; - } else { - $role = 'src'; - } - $dest = $ext['dest']; - $this->log(1, "Installing '$ext[file]'"); - $copyto = $this->_prependPath($dest, $this->installroot); - $copydir = dirname($copyto); - if (!@is_dir($copydir)) { - if (!$this->mkDirHier($copydir)) { - return $this->raiseError("failed to mkdir $copydir", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ mkdir $copydir"); - } - if (!@copy($ext['file'], $copyto)) { - return $this->raiseError("failed to write $copyto", PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ cp $ext[file] $copyto"); - if (!OS_WINDOWS) { - $mode = 0666 & ~(int)octdec($this->config->get('umask')); - $this->addFileOperation('chmod', array($mode, $copyto)); - if (!@chmod($copyto, $mode)) { - $this->log(0, "failed to change mode of $copyto"); - } - } - $this->addFileOperation('rename', array($ext['file'], $copyto)); - - $pkginfo['filelist'][$bn] = array( - 'role' => $role, - 'installed_as' => $dest, - 'php_api' => $ext['php_api'], - 'zend_mod_api' => $ext['zend_mod_api'], - 'zend_ext_api' => $ext['zend_ext_api'], - ); - } - } - // }}} - } - - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - return $this->raiseError("commit failed", PEAR_INSTALLER_FAILED); - } - // }}} - - $ret = false; - // {{{ Register that the package is installed ----------------------- - if (empty($options['upgrade'])) { - // if 'force' is used, replace the info in registry - if (!empty($options['force']) && $this->registry->packageExists($pkgname)) { - $this->registry->deletePackage($pkgname); - } - $ret = $this->registry->addPackage($pkgname, $pkginfo); - } else { - // new: upgrade installs a package if it isn't installed - if (!$this->registry->packageExists($pkgname)) { - $ret = $this->registry->addPackage($pkgname, $pkginfo); - } else { - $ret = $this->registry->updatePackage($pkgname, $pkginfo, false); - } - } - if (!$ret) { - return $this->raiseError("Adding package $pkgname to registry failed"); - } - // }}} - return $pkginfo; - } - - // }}} - // {{{ uninstall() - - /** - * Uninstall a package - * - * This method removes all files installed by the application, and then - * removes any empty directories. - * @param string package name - * @param array Command-line options. Possibilities include: - * - * - installroot: base installation dir, if not the default - * - nodeps: do not process dependencies of other packages to ensure - * uninstallation does not break things - */ - function uninstall($package, $options = array()) - { - $php_dir = $this->config->get('php_dir'); - if (isset($options['installroot'])) { - if (substr($options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $options['installroot'] = substr($options['installroot'], 0, -1); - } - $this->installroot = $options['installroot']; - $php_dir = $this->_prependPath($php_dir, $this->installroot); - } else { - $this->installroot = ''; - } - $this->registry = &new PEAR_Registry($php_dir); - $filelist = $this->registry->packageInfo($package, 'filelist'); - if ($filelist == null) { - return $this->raiseError("$package not installed"); - } - if (empty($options['nodeps'])) { - $depchecker = &new PEAR_Dependency($this->registry); - $error = $depchecker->checkPackageUninstall($errors, $warning, $package); - if ($error) { - return $this->raiseError($errors . 'uninstall failed'); - } - if ($warning) { - $this->log(0, $warning); - } - } - // {{{ Delete the files - $this->startFileTransaction(); - if (PEAR::isError($err = $this->_deletePackageFiles($package))) { - $this->rollbackFileTransaction(); - return $this->raiseError($err); - } - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - return $this->raiseError("uninstall failed"); - } else { - $this->startFileTransaction(); - if (!isset($filelist['dirtree']) || !count($filelist['dirtree'])) { - return $this->registry->deletePackage($package); - } - // attempt to delete empty directories - uksort($filelist['dirtree'], array($this, '_sortDirs')); - foreach($filelist['dirtree'] as $dir => $notused) { - $this->addFileOperation('rmdir', array($dir)); - } - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - } - } - // }}} - - // Register that the package is no longer installed - return $this->registry->deletePackage($package); - } - - // }}} - // {{{ _sortDirs() - function _sortDirs($a, $b) - { - if (strnatcmp($a, $b) == -1) return 1; - if (strnatcmp($a, $b) == 1) return -1; - return 0; - } - - // }}} - // {{{ checkDeps() - - /** - * Check if the package meets all dependencies - * - * @param array Package information (passed by reference) - * @param string Error message (passed by reference) - * @return boolean False when no error occured, otherwise true - */ - function checkDeps(&$pkginfo, &$errors) - { - if (empty($this->registry)) { - $this->registry = &new PEAR_Registry($this->config->get('php_dir')); - } - $depchecker = &new PEAR_Dependency($this->registry); - $error = $errors = ''; - $failed_deps = $optional_deps = array(); - if (is_array($pkginfo['release_deps'])) { - foreach($pkginfo['release_deps'] as $dep) { - $code = $depchecker->callCheckMethod($error, $dep); - if ($code) { - if (isset($dep['optional']) && $dep['optional'] == 'yes') { - $optional_deps[] = array($dep, $code, $error); - } else { - $failed_deps[] = array($dep, $code, $error); - } - } - } - // {{{ failed dependencies - $n = count($failed_deps); - if ($n > 0) { - for ($i = 0; $i < $n; $i++) { - if (isset($failed_deps[$i]['type'])) { - $type = $failed_deps[$i]['type']; - } else { - $type = 'pkg'; - } - switch ($failed_deps[$i][1]) { - case PEAR_DEPENDENCY_MISSING: - if ($type == 'pkg') { - // install - } - $errors .= "\n" . $failed_deps[$i][2]; - break; - case PEAR_DEPENDENCY_UPGRADE_MINOR: - if ($type == 'pkg') { - // upgrade - } - $errors .= "\n" . $failed_deps[$i][2]; - break; - default: - $errors .= "\n" . $failed_deps[$i][2]; - break; - } - } - return true; - } - // }}} - - // {{{ optional dependencies - $count_optional = count($optional_deps); - if ($count_optional > 0) { - $errors = "Optional dependencies:"; - - for ($i = 0; $i < $count_optional; $i++) { - if (isset($optional_deps[$i]['type'])) { - $type = $optional_deps[$i]['type']; - } else { - $type = 'pkg'; - } - switch ($optional_deps[$i][1]) { - case PEAR_DEPENDENCY_MISSING: - case PEAR_DEPENDENCY_UPGRADE_MINOR: - default: - $errors .= "\n" . $optional_deps[$i][2]; - break; - } - } - return false; - } - // }}} - } - return false; - } - - // }}} - // {{{ _buildCallback() - - function _buildCallback($what, $data) - { - if (($what == 'cmdoutput' && $this->debug > 1) || - ($what == 'output' && $this->debug > 0)) { - $this->ui->outputData(rtrim($data), 'build'); - } - } - - // }}} -} - -// {{{ md5_file() utility function -if (!function_exists("md5_file")) { - function md5_file($filename) { - $fp = fopen($filename, "r"); - if (!$fp) return null; - $contents = fread($fp, filesize($filename)); - fclose($fp); - return md5($contents); - } -} -// }}} - -?> diff --git a/3rdparty/PEAR/Packager.php b/3rdparty/PEAR/Packager.php deleted file mode 100644 index 3ed209be8b..0000000000 --- a/3rdparty/PEAR/Packager.php +++ /dev/null @@ -1,165 +0,0 @@ - | -// | Tomas V.V.Cox | -// +----------------------------------------------------------------------+ -// -// $Id: Packager.php,v 1.53 2004/06/13 14:06:01 pajoye Exp $ - -require_once 'PEAR/Common.php'; -require_once 'System.php'; - -/** - * Administration class used to make a PEAR release tarball. - * - * TODO: - * - add an extra param the dir where to place the created package - * - * @since PHP 4.0.2 - * @author Stig Bakken - */ -class PEAR_Packager extends PEAR_Common -{ - // {{{ constructor - - function PEAR_Packager() - { - parent::PEAR_Common(); - } - - // }}} - // {{{ destructor - - function _PEAR_Packager() - { - parent::_PEAR_Common(); - } - - // }}} - - // {{{ package() - - function package($pkgfile = null, $compress = true) - { - // {{{ validate supplied package.xml file - if (empty($pkgfile)) { - $pkgfile = 'package.xml'; - } - // $this->pkginfo gets populated inside - $pkginfo = $this->infoFromDescriptionFile($pkgfile); - if (PEAR::isError($pkginfo)) { - return $this->raiseError($pkginfo); - } - - $pkgdir = dirname(realpath($pkgfile)); - $pkgfile = basename($pkgfile); - - $errors = $warnings = array(); - $this->validatePackageInfo($pkginfo, $errors, $warnings, $pkgdir); - foreach ($warnings as $w) { - $this->log(1, "Warning: $w"); - } - foreach ($errors as $e) { - $this->log(0, "Error: $e"); - } - if (sizeof($errors) > 0) { - return $this->raiseError('Errors in package'); - } - // }}} - - $pkgver = $pkginfo['package'] . '-' . $pkginfo['version']; - - // {{{ Create the package file list - $filelist = array(); - $i = 0; - - foreach ($pkginfo['filelist'] as $fname => $atts) { - $file = $pkgdir . DIRECTORY_SEPARATOR . $fname; - if (!file_exists($file)) { - return $this->raiseError("File does not exist: $fname"); - } else { - $filelist[$i++] = $file; - if (empty($pkginfo['filelist'][$fname]['md5sum'])) { - $md5sum = md5_file($file); - $pkginfo['filelist'][$fname]['md5sum'] = $md5sum; - } - $this->log(2, "Adding file $fname"); - } - } - // }}} - - // {{{ regenerate package.xml - $new_xml = $this->xmlFromInfo($pkginfo); - if (PEAR::isError($new_xml)) { - return $this->raiseError($new_xml); - } - if (!($tmpdir = System::mktemp(array('-d')))) { - return $this->raiseError("PEAR_Packager: mktemp failed"); - } - $newpkgfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml'; - $np = @fopen($newpkgfile, 'wb'); - if (!$np) { - return $this->raiseError("PEAR_Packager: unable to rewrite $pkgfile as $newpkgfile"); - } - fwrite($np, $new_xml); - fclose($np); - // }}} - - // {{{ TAR the Package ------------------------------------------- - $ext = $compress ? '.tgz' : '.tar'; - $dest_package = getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext; - $tar =& new Archive_Tar($dest_package, $compress); - $tar->setErrorHandling(PEAR_ERROR_RETURN); // XXX Don't print errors - // ----- Creates with the package.xml file - $ok = $tar->createModify(array($newpkgfile), '', $tmpdir); - if (PEAR::isError($ok)) { - return $this->raiseError($ok); - } elseif (!$ok) { - return $this->raiseError('PEAR_Packager: tarball creation failed'); - } - // ----- Add the content of the package - if (!$tar->addModify($filelist, $pkgver, $pkgdir)) { - return $this->raiseError('PEAR_Packager: tarball creation failed'); - } - $this->log(1, "Package $dest_package done"); - if (file_exists("$pkgdir/CVS/Root")) { - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $pkginfo['version']); - $cvstag = "RELEASE_$cvsversion"; - $this->log(1, "Tag the released code with `pear cvstag $pkgfile'"); - $this->log(1, "(or set the CVS tag $cvstag by hand)"); - } - // }}} - - return $dest_package; - } - - // }}} -} - -// {{{ md5_file() utility function -if (!function_exists('md5_file')) { - function md5_file($file) { - if (!$fd = @fopen($file, 'r')) { - return false; - } - $md5 = md5(fread($fd, filesize($file))); - fclose($fd); - return $md5; - } -} -// }}} - -?> diff --git a/3rdparty/PEAR/Registry.php b/3rdparty/PEAR/Registry.php deleted file mode 100644 index f2510a38f1..0000000000 --- a/3rdparty/PEAR/Registry.php +++ /dev/null @@ -1,538 +0,0 @@ - | -// | Tomas V.V.Cox | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Registry.php,v 1.50.4.3 2004/10/26 19:19:56 cellog Exp $ - -/* -TODO: - - Transform into singleton() - - Add application level lock (avoid change the registry from the cmdline - while using the GTK interface, for ex.) -*/ -require_once "System.php"; -require_once "PEAR.php"; - -define('PEAR_REGISTRY_ERROR_LOCK', -2); -define('PEAR_REGISTRY_ERROR_FORMAT', -3); -define('PEAR_REGISTRY_ERROR_FILE', -4); - -/** - * Administration class used to maintain the installed package database. - */ -class PEAR_Registry extends PEAR -{ - // {{{ properties - - /** Directory where registry files are stored. - * @var string - */ - var $statedir = ''; - - /** File where the file map is stored - * @var string - */ - var $filemap = ''; - - /** Name of file used for locking the registry - * @var string - */ - var $lockfile = ''; - - /** File descriptor used during locking - * @var resource - */ - var $lock_fp = null; - - /** Mode used during locking - * @var int - */ - var $lock_mode = 0; // XXX UNUSED - - /** Cache of package information. Structure: - * array( - * 'package' => array('id' => ... ), - * ... ) - * @var array - */ - var $pkginfo_cache = array(); - - /** Cache of file map. Structure: - * array( '/path/to/file' => 'package', ... ) - * @var array - */ - var $filemap_cache = array(); - - // }}} - - // {{{ constructor - - /** - * PEAR_Registry constructor. - * - * @param string (optional) PEAR install directory (for .php files) - * - * @access public - */ - function PEAR_Registry($pear_install_dir = PEAR_INSTALL_DIR) - { - parent::PEAR(); - $ds = DIRECTORY_SEPARATOR; - $this->install_dir = $pear_install_dir; - $this->statedir = $pear_install_dir.$ds.'.registry'; - $this->filemap = $pear_install_dir.$ds.'.filemap'; - $this->lockfile = $pear_install_dir.$ds.'.lock'; - - // XXX Compatibility code should be removed in the future - // rename all registry files if any to lowercase - if (!OS_WINDOWS && $handle = @opendir($this->statedir)) { - $dest = $this->statedir . DIRECTORY_SEPARATOR; - while (false !== ($file = readdir($handle))) { - if (preg_match('/^.*[A-Z].*\.reg$/', $file)) { - rename($dest . $file, $dest . strtolower($file)); - } - } - closedir($handle); - } - if (!file_exists($this->filemap)) { - $this->rebuildFileMap(); - } - } - - // }}} - // {{{ destructor - - /** - * PEAR_Registry destructor. Makes sure no locks are forgotten. - * - * @access private - */ - function _PEAR_Registry() - { - parent::_PEAR(); - if (is_resource($this->lock_fp)) { - $this->_unlock(); - } - } - - // }}} - - // {{{ _assertStateDir() - - /** - * Make sure the directory where we keep registry files exists. - * - * @return bool TRUE if directory exists, FALSE if it could not be - * created - * - * @access private - */ - function _assertStateDir() - { - if (!@is_dir($this->statedir)) { - if (!System::mkdir(array('-p', $this->statedir))) { - return $this->raiseError("could not create directory '{$this->statedir}'"); - } - } - return true; - } - - // }}} - // {{{ _packageFileName() - - /** - * Get the name of the file where data for a given package is stored. - * - * @param string package name - * - * @return string registry file name - * - * @access public - */ - function _packageFileName($package) - { - return $this->statedir . DIRECTORY_SEPARATOR . strtolower($package) . '.reg'; - } - - // }}} - // {{{ _openPackageFile() - - function _openPackageFile($package, $mode) - { - $this->_assertStateDir(); - $file = $this->_packageFileName($package); - $fp = @fopen($file, $mode); - if (!$fp) { - return null; - } - return $fp; - } - - // }}} - // {{{ _closePackageFile() - - function _closePackageFile($fp) - { - fclose($fp); - } - - // }}} - // {{{ rebuildFileMap() - - function rebuildFileMap() - { - $packages = $this->listPackages(); - $files = array(); - foreach ($packages as $package) { - $version = $this->packageInfo($package, 'version'); - $filelist = $this->packageInfo($package, 'filelist'); - if (!is_array($filelist)) { - continue; - } - foreach ($filelist as $name => $attrs) { - if (isset($attrs['role']) && $attrs['role'] != 'php') { - continue; - } - if (isset($attrs['baseinstalldir'])) { - $file = $attrs['baseinstalldir'].DIRECTORY_SEPARATOR.$name; - } else { - $file = $name; - } - $file = preg_replace(',^/+,', '', $file); - $files[$file] = $package; - } - } - $this->_assertStateDir(); - $fp = @fopen($this->filemap, 'wb'); - if (!$fp) { - return false; - } - $this->filemap_cache = $files; - fwrite($fp, serialize($files)); - fclose($fp); - return true; - } - - // }}} - // {{{ readFileMap() - - function readFileMap() - { - $fp = @fopen($this->filemap, 'r'); - if (!$fp) { - return $this->raiseError('PEAR_Registry: could not open filemap', PEAR_REGISTRY_ERROR_FILE, null, null, $php_errormsg); - } - $fsize = filesize($this->filemap); - $rt = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - $data = fread($fp, $fsize); - set_magic_quotes_runtime($rt); - fclose($fp); - $tmp = unserialize($data); - if (!$tmp && $fsize > 7) { - return $this->raiseError('PEAR_Registry: invalid filemap data', PEAR_REGISTRY_ERROR_FORMAT, null, null, $data); - } - $this->filemap_cache = $tmp; - return true; - } - - // }}} - // {{{ _lock() - - /** - * Lock the registry. - * - * @param integer lock mode, one of LOCK_EX, LOCK_SH or LOCK_UN. - * See flock manual for more information. - * - * @return bool TRUE on success, FALSE if locking failed, or a - * PEAR error if some other error occurs (such as the - * lock file not being writable). - * - * @access private - */ - function _lock($mode = LOCK_EX) - { - if (!eregi('Windows 9', php_uname())) { - if ($mode != LOCK_UN && is_resource($this->lock_fp)) { - // XXX does not check type of lock (LOCK_SH/LOCK_EX) - return true; - } - if (PEAR::isError($err = $this->_assertStateDir())) { - return $err; - } - $open_mode = 'w'; - // XXX People reported problems with LOCK_SH and 'w' - if ($mode === LOCK_SH || $mode === LOCK_UN) { - if (@!is_file($this->lockfile)) { - touch($this->lockfile); - } - $open_mode = 'r'; - } - - if (!is_resource($this->lock_fp)) { - $this->lock_fp = @fopen($this->lockfile, $open_mode); - } - - if (!is_resource($this->lock_fp)) { - return $this->raiseError("could not create lock file" . - (isset($php_errormsg) ? ": " . $php_errormsg : "")); - } - if (!(int)flock($this->lock_fp, $mode)) { - switch ($mode) { - case LOCK_SH: $str = 'shared'; break; - case LOCK_EX: $str = 'exclusive'; break; - case LOCK_UN: $str = 'unlock'; break; - default: $str = 'unknown'; break; - } - return $this->raiseError("could not acquire $str lock ($this->lockfile)", - PEAR_REGISTRY_ERROR_LOCK); - } - } - return true; - } - - // }}} - // {{{ _unlock() - - function _unlock() - { - $ret = $this->_lock(LOCK_UN); - if (is_resource($this->lock_fp)) { - fclose($this->lock_fp); - } - $this->lock_fp = null; - return $ret; - } - - // }}} - // {{{ _packageExists() - - function _packageExists($package) - { - return file_exists($this->_packageFileName($package)); - } - - // }}} - // {{{ _packageInfo() - - function _packageInfo($package = null, $key = null) - { - if ($package === null) { - return array_map(array($this, '_packageInfo'), - $this->_listPackages()); - } - $fp = $this->_openPackageFile($package, 'r'); - if ($fp === null) { - return null; - } - $rt = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - $data = fread($fp, filesize($this->_packageFileName($package))); - set_magic_quotes_runtime($rt); - $this->_closePackageFile($fp); - $data = unserialize($data); - if ($key === null) { - return $data; - } - if (isset($data[$key])) { - return $data[$key]; - } - return null; - } - - // }}} - // {{{ _listPackages() - - function _listPackages() - { - $pkglist = array(); - $dp = @opendir($this->statedir); - if (!$dp) { - return $pkglist; - } - while ($ent = readdir($dp)) { - if ($ent{0} == '.' || substr($ent, -4) != '.reg') { - continue; - } - $pkglist[] = substr($ent, 0, -4); - } - return $pkglist; - } - - // }}} - - // {{{ packageExists() - - function packageExists($package) - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_packageExists($package); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ packageInfo() - - function packageInfo($package = null, $key = null) - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_packageInfo($package, $key); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ listPackages() - - function listPackages() - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_listPackages(); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ addPackage() - - function addPackage($package, $info) - { - if ($this->packageExists($package)) { - return false; - } - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $fp = $this->_openPackageFile($package, 'wb'); - if ($fp === null) { - $this->_unlock(); - return false; - } - $info['_lastmodified'] = time(); - fwrite($fp, serialize($info)); - $this->_closePackageFile($fp); - $this->_unlock(); - return true; - } - - // }}} - // {{{ deletePackage() - - function deletePackage($package) - { - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $file = $this->_packageFileName($package); - $ret = @unlink($file); - $this->rebuildFileMap(); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ updatePackage() - - function updatePackage($package, $info, $merge = true) - { - $oldinfo = $this->packageInfo($package); - if (empty($oldinfo)) { - return false; - } - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $fp = $this->_openPackageFile($package, 'w'); - if ($fp === null) { - $this->_unlock(); - return false; - } - $info['_lastmodified'] = time(); - if ($merge) { - fwrite($fp, serialize(array_merge($oldinfo, $info))); - } else { - fwrite($fp, serialize($info)); - } - $this->_closePackageFile($fp); - if (isset($info['filelist'])) { - $this->rebuildFileMap(); - } - $this->_unlock(); - return true; - } - - // }}} - // {{{ checkFileMap() - - /** - * Test whether a file belongs to a package. - * - * @param string $path file path, absolute or relative to the pear - * install dir - * - * @return string which package the file belongs to, or an empty - * string if the file does not belong to an installed package - * - * @access public - */ - function checkFileMap($path) - { - if (is_array($path)) { - static $notempty; - if (empty($notempty)) { - $notempty = create_function('$a','return !empty($a);'); - } - $pkgs = array(); - foreach ($path as $name => $attrs) { - if (is_array($attrs) && isset($attrs['baseinstalldir'])) { - $name = $attrs['baseinstalldir'].DIRECTORY_SEPARATOR.$name; - } - $pkgs[$name] = $this->checkFileMap($name); - } - return array_filter($pkgs, $notempty); - } - if (empty($this->filemap_cache) && PEAR::isError($this->readFileMap())) { - return $err; - } - if (isset($this->filemap_cache[$path])) { - return $this->filemap_cache[$path]; - } - $l = strlen($this->install_dir); - if (substr($path, 0, $l) == $this->install_dir) { - $path = preg_replace('!^'.DIRECTORY_SEPARATOR.'+!', '', substr($path, $l)); - } - if (isset($this->filemap_cache[$path])) { - return $this->filemap_cache[$path]; - } - return ''; - } - - // }}} - -} - -?> diff --git a/3rdparty/PEAR/Remote.php b/3rdparty/PEAR/Remote.php deleted file mode 100644 index 7b1e314f90..0000000000 --- a/3rdparty/PEAR/Remote.php +++ /dev/null @@ -1,394 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Remote.php,v 1.50 2004/06/08 18:03:46 cellog Exp $ - -require_once 'PEAR.php'; -require_once 'PEAR/Config.php'; - -/** - * This is a class for doing remote operations against the central - * PEAR database. - * - * @nodep XML_RPC_Value - * @nodep XML_RPC_Message - * @nodep XML_RPC_Client - */ -class PEAR_Remote extends PEAR -{ - // {{{ properties - - var $config = null; - var $cache = null; - - // }}} - - // {{{ PEAR_Remote(config_object) - - function PEAR_Remote(&$config) - { - $this->PEAR(); - $this->config = &$config; - } - - // }}} - - // {{{ getCache() - - - function getCache($args) - { - $id = md5(serialize($args)); - $cachedir = $this->config->get('cache_dir'); - $filename = $cachedir . DIRECTORY_SEPARATOR . 'xmlrpc_cache_' . $id; - if (!file_exists($filename)) { - return null; - }; - - $fp = fopen($filename, 'rb'); - if (!$fp) { - return null; - } - $content = fread($fp, filesize($filename)); - fclose($fp); - $result = array( - 'age' => time() - filemtime($filename), - 'lastChange' => filemtime($filename), - 'content' => unserialize($content), - ); - return $result; - } - - // }}} - - // {{{ saveCache() - - function saveCache($args, $data) - { - $id = md5(serialize($args)); - $cachedir = $this->config->get('cache_dir'); - if (!file_exists($cachedir)) { - System::mkdir(array('-p', $cachedir)); - } - $filename = $cachedir.'/xmlrpc_cache_'.$id; - - $fp = @fopen($filename, "wb"); - if ($fp) { - fwrite($fp, serialize($data)); - fclose($fp); - }; - } - - // }}} - - // {{{ call(method, [args...]) - - function call($method) - { - $_args = $args = func_get_args(); - - $this->cache = $this->getCache($args); - $cachettl = $this->config->get('cache_ttl'); - // If cache is newer than $cachettl seconds, we use the cache! - if ($this->cache !== null && $this->cache['age'] < $cachettl) { - return $this->cache['content']; - }; - - if (extension_loaded("xmlrpc")) { - $result = call_user_func_array(array(&$this, 'call_epi'), $args); - if (!PEAR::isError($result)) { - $this->saveCache($_args, $result); - }; - return $result; - } - if (!@include_once("XML/RPC.php")) { - return $this->raiseError("For this remote PEAR operation you need to install the XML_RPC package"); - } - array_shift($args); - $server_host = $this->config->get('master_server'); - $username = $this->config->get('username'); - $password = $this->config->get('password'); - $eargs = array(); - foreach($args as $arg) $eargs[] = $this->_encode($arg); - $f = new XML_RPC_Message($method, $eargs); - if ($this->cache !== null) { - $maxAge = '?maxAge='.$this->cache['lastChange']; - } else { - $maxAge = ''; - }; - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - if ($proxy = parse_url($this->config->get('http_proxy'))) { - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @urldecode(@$proxy['user']); - $proxy_pass = @urldecode(@$proxy['pass']); - } - $c = new XML_RPC_Client('/xmlrpc.php'.$maxAge, $server_host, 80, $proxy_host, $proxy_port, $proxy_user, $proxy_pass); - if ($username && $password) { - $c->setCredentials($username, $password); - } - if ($this->config->get('verbose') >= 3) { - $c->setDebug(1); - } - $r = $c->send($f); - if (!$r) { - return $this->raiseError("XML_RPC send failed"); - } - $v = $r->value(); - if ($e = $r->faultCode()) { - if ($e == $GLOBALS['XML_RPC_err']['http_error'] && strstr($r->faultString(), '304 Not Modified') !== false) { - return $this->cache['content']; - } - return $this->raiseError($r->faultString(), $e); - } - - $result = XML_RPC_decode($v); - $this->saveCache($_args, $result); - return $result; - } - - // }}} - - // {{{ call_epi(method, [args...]) - - function call_epi($method) - { - do { - if (extension_loaded("xmlrpc")) { - break; - } - if (OS_WINDOWS) { - $ext = 'dll'; - } elseif (PHP_OS == 'HP-UX') { - $ext = 'sl'; - } elseif (PHP_OS == 'AIX') { - $ext = 'a'; - } else { - $ext = 'so'; - } - $ext = OS_WINDOWS ? 'dll' : 'so'; - @dl("xmlrpc-epi.$ext"); - if (extension_loaded("xmlrpc")) { - break; - } - @dl("xmlrpc.$ext"); - if (extension_loaded("xmlrpc")) { - break; - } - return $this->raiseError("unable to load xmlrpc extension"); - } while (false); - $params = func_get_args(); - array_shift($params); - $method = str_replace("_", ".", $method); - $request = xmlrpc_encode_request($method, $params); - $server_host = $this->config->get("master_server"); - if (empty($server_host)) { - return $this->raiseError("PEAR_Remote::call: no master_server configured"); - } - $server_port = 80; - if ($http_proxy = $this->config->get('http_proxy')) { - $proxy = parse_url($http_proxy); - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @urldecode(@$proxy['user']); - $proxy_pass = @urldecode(@$proxy['pass']); - $fp = @fsockopen($proxy_host, $proxy_port); - $use_proxy = true; - } else { - $use_proxy = false; - $fp = @fsockopen($server_host, $server_port); - } - if (!$fp && $http_proxy) { - return $this->raiseError("PEAR_Remote::call: fsockopen(`$proxy_host', $proxy_port) failed"); - } elseif (!$fp) { - return $this->raiseError("PEAR_Remote::call: fsockopen(`$server_host', $server_port) failed"); - } - $len = strlen($request); - $req_headers = "Host: $server_host:$server_port\r\n" . - "Content-type: text/xml\r\n" . - "Content-length: $len\r\n"; - $username = $this->config->get('username'); - $password = $this->config->get('password'); - if ($username && $password) { - $req_headers .= "Cookie: PEAR_USER=$username; PEAR_PW=$password\r\n"; - $tmp = base64_encode("$username:$password"); - $req_headers .= "Authorization: Basic $tmp\r\n"; - } - if ($this->cache !== null) { - $maxAge = '?maxAge='.$this->cache['lastChange']; - } else { - $maxAge = ''; - }; - - if ($use_proxy && $proxy_host != '' && $proxy_user != '') { - $req_headers .= 'Proxy-Authorization: Basic ' - .base64_encode($proxy_user.':'.$proxy_pass) - ."\r\n"; - } - - if ($this->config->get('verbose') > 3) { - print "XMLRPC REQUEST HEADERS:\n"; - var_dump($req_headers); - print "XMLRPC REQUEST BODY:\n"; - var_dump($request); - } - - if ($use_proxy && $proxy_host != '') { - $post_string = "POST http://".$server_host; - if ($proxy_port > '') { - $post_string .= ':'.$server_port; - } - } else { - $post_string = "POST "; - } - - fwrite($fp, ($post_string."/xmlrpc.php$maxAge HTTP/1.0\r\n$req_headers\r\n$request")); - $response = ''; - $line1 = fgets($fp, 2048); - if (!preg_match('!^HTTP/[0-9\.]+ (\d+) (.*)!', $line1, $matches)) { - return $this->raiseError("PEAR_Remote: invalid HTTP response from XML-RPC server"); - } - switch ($matches[1]) { - case "200": // OK - break; - case "304": // Not Modified - return $this->cache['content']; - case "401": // Unauthorized - if ($username && $password) { - return $this->raiseError("PEAR_Remote: authorization failed", 401); - } else { - return $this->raiseError("PEAR_Remote: authorization required, please log in first", 401); - } - default: - return $this->raiseError("PEAR_Remote: unexpected HTTP response", (int)$matches[1], null, null, "$matches[1] $matches[2]"); - } - while (trim(fgets($fp, 2048)) != ''); // skip rest of headers - while ($chunk = fread($fp, 10240)) { - $response .= $chunk; - } - fclose($fp); - if ($this->config->get('verbose') > 3) { - print "XMLRPC RESPONSE:\n"; - var_dump($response); - } - $ret = xmlrpc_decode($response); - if (is_array($ret) && isset($ret['__PEAR_TYPE__'])) { - if ($ret['__PEAR_TYPE__'] == 'error') { - if (isset($ret['__PEAR_CLASS__'])) { - $class = $ret['__PEAR_CLASS__']; - } else { - $class = "PEAR_Error"; - } - if ($ret['code'] === '') $ret['code'] = null; - if ($ret['message'] === '') $ret['message'] = null; - if ($ret['userinfo'] === '') $ret['userinfo'] = null; - if (strtolower($class) == 'db_error') { - $ret = $this->raiseError(PEAR::errorMessage($ret['code']), - $ret['code'], null, null, - $ret['userinfo']); - } else { - $ret = $this->raiseError($ret['message'], $ret['code'], - null, null, $ret['userinfo']); - } - } - } elseif (is_array($ret) && sizeof($ret) == 1 && isset($ret[0]) - && is_array($ret[0]) && - !empty($ret[0]['faultString']) && - !empty($ret[0]['faultCode'])) { - extract($ret[0]); - $faultString = "XML-RPC Server Fault: " . - str_replace("\n", " ", $faultString); - return $this->raiseError($faultString, $faultCode); - } - return $ret; - } - - // }}} - - // {{{ _encode - - // a slightly extended version of XML_RPC_encode - function _encode($php_val) - { - global $XML_RPC_Boolean, $XML_RPC_Int, $XML_RPC_Double; - global $XML_RPC_String, $XML_RPC_Array, $XML_RPC_Struct; - - $type = gettype($php_val); - $xmlrpcval = new XML_RPC_Value; - - switch($type) { - case "array": - reset($php_val); - $firstkey = key($php_val); - end($php_val); - $lastkey = key($php_val); - if ($firstkey === 0 && is_int($lastkey) && - ($lastkey + 1) == count($php_val)) { - $is_continuous = true; - reset($php_val); - $size = count($php_val); - for ($expect = 0; $expect < $size; $expect++, next($php_val)) { - if (key($php_val) !== $expect) { - $is_continuous = false; - break; - } - } - if ($is_continuous) { - reset($php_val); - $arr = array(); - while (list($k, $v) = each($php_val)) { - $arr[$k] = $this->_encode($v); - } - $xmlrpcval->addArray($arr); - break; - } - } - // fall though if not numerical and continuous - case "object": - $arr = array(); - while (list($k, $v) = each($php_val)) { - $arr[$k] = $this->_encode($v); - } - $xmlrpcval->addStruct($arr); - break; - case "integer": - $xmlrpcval->addScalar($php_val, $XML_RPC_Int); - break; - case "double": - $xmlrpcval->addScalar($php_val, $XML_RPC_Double); - break; - case "string": - case "NULL": - $xmlrpcval->addScalar($php_val, $XML_RPC_String); - break; - case "boolean": - $xmlrpcval->addScalar($php_val, $XML_RPC_Boolean); - break; - case "unknown type": - default: - return null; - } - return $xmlrpcval; - } - - // }}} - -} - -?> diff --git a/3rdparty/PEAR/RunTest.php b/3rdparty/PEAR/RunTest.php deleted file mode 100644 index 1aa02aab9d..0000000000 --- a/3rdparty/PEAR/RunTest.php +++ /dev/null @@ -1,363 +0,0 @@ - | -// | Greg Beaver | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: RunTest.php,v 1.3.2.4 2005/02/17 17:47:55 cellog Exp $ -// - -/** - * Simplified version of PHP's test suite - * -- EXPERIMENTAL -- - - Try it with: - - $ php -r 'include "../PEAR/RunTest.php"; $t=new PEAR_RunTest; $o=$t->run("./pear_system.phpt");print_r($o);' - - -TODO: - -Actually finish the development and testing - - */ - -require_once 'PEAR.php'; -require_once 'PEAR/Config.php'; - -define('DETAILED', 1); -putenv("PHP_PEAR_RUNTESTS=1"); - -class PEAR_RunTest -{ - var $_logger; - - /** - * An object that supports the PEAR_Common->log() signature, or null - * @param PEAR_Common|null - */ - function PEAR_RunTest($logger = null) - { - $this->_logger = $logger; - } - - // - // Run an individual test case. - // - - function run($file, $ini_settings = '') - { - $cwd = getcwd(); - $conf = &PEAR_Config::singleton(); - $php = $conf->get('php_bin'); - //var_dump($php);exit; - global $log_format, $info_params, $ini_overwrites; - - $info_params = ''; - $log_format = 'LEOD'; - - // Load the sections of the test file. - $section_text = array( - 'TEST' => '(unnamed test)', - 'SKIPIF' => '', - 'GET' => '', - 'ARGS' => '', - ); - - if (!is_file($file) || !$fp = fopen($file, "r")) { - return PEAR::raiseError("Cannot open test file: $file"); - } - - $section = ''; - while (!feof($fp)) { - $line = fgets($fp); - - // Match the beginning of a section. - if (ereg('^--([A-Z]+)--',$line,$r)) { - $section = $r[1]; - $section_text[$section] = ''; - continue; - } - - // Add to the section text. - $section_text[$section] .= $line; - } - fclose($fp); - - $shortname = str_replace($cwd.'/', '', $file); - $tested = trim($section_text['TEST'])." [$shortname]"; - - $tmp = realpath(dirname($file)); - $tmp_skipif = $tmp . uniqid('/phpt.'); - $tmp_file = ereg_replace('\.phpt$','.php',$file); - $tmp_post = $tmp . uniqid('/phpt.'); - - @unlink($tmp_skipif); - @unlink($tmp_file); - @unlink($tmp_post); - - // unlink old test results - @unlink(ereg_replace('\.phpt$','.diff',$file)); - @unlink(ereg_replace('\.phpt$','.log',$file)); - @unlink(ereg_replace('\.phpt$','.exp',$file)); - @unlink(ereg_replace('\.phpt$','.out',$file)); - - // Check if test should be skipped. - $info = ''; - $warn = false; - if (array_key_exists('SKIPIF', $section_text)) { - if (trim($section_text['SKIPIF'])) { - $this->save_text($tmp_skipif, $section_text['SKIPIF']); - //$extra = substr(PHP_OS, 0, 3) !== "WIN" ? - // "unset REQUEST_METHOD;": ""; - - //$output = `$extra $php $info_params -f $tmp_skipif`; - $output = `$php $info_params -f $tmp_skipif`; - unlink($tmp_skipif); - if (eregi("^skip", trim($output))) { - $skipreason = "SKIP $tested"; - $reason = (eregi("^skip[[:space:]]*(.+)\$", trim($output))) ? eregi_replace("^skip[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE; - if ($reason) { - $skipreason .= " (reason: $reason)"; - } - $this->_logger->log(0, $skipreason); - if (isset($old_php)) { - $php = $old_php; - } - return 'SKIPPED'; - } - if (eregi("^info", trim($output))) { - $reason = (ereg("^info[[:space:]]*(.+)\$", trim($output))) ? ereg_replace("^info[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE; - if ($reason) { - $info = " (info: $reason)"; - } - } - if (eregi("^warn", trim($output))) { - $reason = (ereg("^warn[[:space:]]*(.+)\$", trim($output))) ? ereg_replace("^warn[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE; - if ($reason) { - $warn = true; /* only if there is a reason */ - $info = " (warn: $reason)"; - } - } - } - } - - // We've satisfied the preconditions - run the test! - $this->save_text($tmp_file,$section_text['FILE']); - - $args = $section_text['ARGS'] ? ' -- '.$section_text['ARGS'] : ''; - - $cmd = "$php$ini_settings -f $tmp_file$args 2>&1"; - if (isset($this->_logger)) { - $this->_logger->log(2, 'Running command "' . $cmd . '"'); - } - - $savedir = getcwd(); // in case the test moves us around - if (isset($section_text['RETURNS'])) { - ob_start(); - system($cmd, $return_value); - $out = ob_get_contents(); - ob_end_clean(); - @unlink($tmp_post); - $section_text['RETURNS'] = (int) trim($section_text['RETURNS']); - $returnfail = ($return_value != $section_text['RETURNS']); - } else { - $out = `$cmd`; - $returnfail = false; - } - chdir($savedir); - // Does the output match what is expected? - $output = trim($out); - $output = preg_replace('/\r\n/', "\n", $output); - - if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) { - if (isset($section_text['EXPECTF'])) { - $wanted = trim($section_text['EXPECTF']); - } else { - $wanted = trim($section_text['EXPECTREGEX']); - } - $wanted_re = preg_replace('/\r\n/',"\n",$wanted); - if (isset($section_text['EXPECTF'])) { - $wanted_re = preg_quote($wanted_re, '/'); - // Stick to basics - $wanted_re = str_replace("%s", ".+?", $wanted_re); //not greedy - $wanted_re = str_replace("%i", "[+\-]?[0-9]+", $wanted_re); - $wanted_re = str_replace("%d", "[0-9]+", $wanted_re); - $wanted_re = str_replace("%x", "[0-9a-fA-F]+", $wanted_re); - $wanted_re = str_replace("%f", "[+\-]?\.?[0-9]+\.?[0-9]*(E-?[0-9]+)?", $wanted_re); - $wanted_re = str_replace("%c", ".", $wanted_re); - // %f allows two points "-.0.0" but that is the best *simple* expression - } - /* DEBUG YOUR REGEX HERE - var_dump($wanted_re); - print(str_repeat('=', 80) . "\n"); - var_dump($output); - */ - if (!$returnfail && preg_match("/^$wanted_re\$/s", $output)) { - @unlink($tmp_file); - $this->_logger->log(0, "PASS $tested$info"); - if (isset($old_php)) { - $php = $old_php; - } - return 'PASSED'; - } - - } else { - $wanted = trim($section_text['EXPECT']); - $wanted = preg_replace('/\r\n/',"\n",$wanted); - // compare and leave on success - $ok = (0 == strcmp($output,$wanted)); - if (!$returnfail && $ok) { - @unlink($tmp_file); - $this->_logger->log(0, "PASS $tested$info"); - if (isset($old_php)) { - $php = $old_php; - } - return 'PASSED'; - } - } - - // Test failed so we need to report details. - if ($warn) { - $this->_logger->log(0, "WARN $tested$info"); - } else { - $this->_logger->log(0, "FAIL $tested$info"); - } - - if (isset($section_text['RETURNS'])) { - $GLOBALS['__PHP_FAILED_TESTS__'][] = array( - 'name' => $file, - 'test_name' => $tested, - 'output' => ereg_replace('\.phpt$','.log', $file), - 'diff' => ereg_replace('\.phpt$','.diff', $file), - 'info' => $info, - 'return' => $return_value - ); - } else { - $GLOBALS['__PHP_FAILED_TESTS__'][] = array( - 'name' => $file, - 'test_name' => $tested, - 'output' => ereg_replace('\.phpt$','.log', $file), - 'diff' => ereg_replace('\.phpt$','.diff', $file), - 'info' => $info, - ); - } - - // write .exp - if (strpos($log_format,'E') !== FALSE) { - $logname = ereg_replace('\.phpt$','.exp',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log,$wanted); - fclose($log); - } - - // write .out - if (strpos($log_format,'O') !== FALSE) { - $logname = ereg_replace('\.phpt$','.out',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log,$output); - fclose($log); - } - - // write .diff - if (strpos($log_format,'D') !== FALSE) { - $logname = ereg_replace('\.phpt$','.diff',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log, $this->generate_diff($wanted, $output, - isset($section_text['RETURNS']) ? array(trim($section_text['RETURNS']), - $return_value) : null)); - fclose($log); - } - - // write .log - if (strpos($log_format,'L') !== FALSE) { - $logname = ereg_replace('\.phpt$','.log',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log," ----- EXPECTED OUTPUT -$wanted ----- ACTUAL OUTPUT -$output ----- FAILED -"); - if ($returnfail) { - fwrite($log," ----- EXPECTED RETURN -$section_text[RETURNS] ----- ACTUAL RETURN -$return_value -"); - } - fclose($log); - //error_report($file,$logname,$tested); - } - - if (isset($old_php)) { - $php = $old_php; - } - - return $warn ? 'WARNED' : 'FAILED'; - } - - function generate_diff($wanted, $output, $return_value) - { - $w = explode("\n", $wanted); - $o = explode("\n", $output); - $w1 = array_diff_assoc($w,$o); - $o1 = array_diff_assoc($o,$w); - $w2 = array(); - $o2 = array(); - foreach($w1 as $idx => $val) $w2[sprintf("%03d<",$idx)] = sprintf("%03d- ", $idx+1).$val; - foreach($o1 as $idx => $val) $o2[sprintf("%03d>",$idx)] = sprintf("%03d+ ", $idx+1).$val; - $diff = array_merge($w2, $o2); - ksort($diff); - if ($return_value) { - $extra = "##EXPECTED: $return_value[0]\r\n##RETURNED: $return_value[1]"; - } else { - $extra = ''; - } - return implode("\r\n", $diff) . $extra; - } - - // - // Write the given text to a temporary file, and return the filename. - // - - function save_text($filename, $text) - { - if (!$fp = fopen($filename, 'w')) { - return PEAR::raiseError("Cannot open file '" . $filename . "' (save_text)"); - } - fwrite($fp,$text); - fclose($fp); - if (1 < DETAILED) echo " -FILE $filename {{{ -$text -}}} -"; - } - -} -?> \ No newline at end of file diff --git a/3rdparty/README b/3rdparty/README new file mode 100644 index 0000000000..e577d414ad --- /dev/null +++ b/3rdparty/README @@ -0,0 +1,2 @@ +the 3rdparty libraries are now located in a seperate repository. just copy https://gitorious.org/owncloud/3rdparty into this directory and everything will work + diff --git a/3rdparty/Sabre.includes.php b/3rdparty/Sabre.includes.php deleted file mode 100644 index d41b287b77..0000000000 --- a/3rdparty/Sabre.includes.php +++ /dev/null @@ -1,127 +0,0 @@ - array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param string $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) { - - return false; - - } - - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @return void - */ - abstract function deleteCalendar($calendarId); - - /** - * Returns all calendar objects within a calendar. - * - * Every item contains an array with the following keys: - * * id - unique identifier which will be used for subsequent updates - * * calendardata - The iCalendar-compatible calnedar data - * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. - * * lastmodified - a timestamp of the last modification time - * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: - * ' "abcdef"') - * * calendarid - The calendarid as it was passed to this function. - * - * Note that the etag is optional, but it's highly encouraged to return for - * speed reasons. - * - * The calendardata is also optional. If it's not returned - * 'getCalendarObject' will be called later, which *is* expected to return - * calendardata. - * - * @param string $calendarId - * @return array - */ - abstract function getCalendarObjects($calendarId); - - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @return array - */ - abstract function getCalendarObject($calendarId,$objectUri); - - /** - * Creates a new calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - abstract function createCalendarObject($calendarId,$objectUri,$calendarData); - - /** - * Updates an existing calendarobject, based on it's uri. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - abstract function updateCalendarObject($calendarId,$objectUri,$calendarData); - - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @return void - */ - abstract function deleteCalendarObject($calendarId,$objectUri); - -} diff --git a/3rdparty/Sabre/CalDAV/Backend/PDO.php b/3rdparty/Sabre/CalDAV/Backend/PDO.php deleted file mode 100644 index 7b1b33b912..0000000000 --- a/3rdparty/Sabre/CalDAV/Backend/PDO.php +++ /dev/null @@ -1,386 +0,0 @@ - 'displayname', - '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', - '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', - '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', - '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', - ); - - /** - * Creates the backend - * - * @param PDO $pdo - */ - public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') { - - $this->pdo = $pdo; - $this->calendarTableName = $calendarTableName; - $this->calendarObjectTableName = $calendarObjectTableName; - - } - - /** - * Returns a list of calendars for a principal. - * - * Every project is an array with the following keys: - * * id, a unique id that will be used by other functions to modify the - * calendar. This can be the same as the uri or a database key. - * * uri, which the basename of the uri with which the calendar is - * accessed. - * * principalUri. The owner of the calendar. Almost always the same as - * principalUri passed to this method. - * - * Furthermore it can contain webdav properties in clark notation. A very - * common one is '{DAV:}displayname'. - * - * @param string $principalUri - * @return array - */ - public function getCalendarsForUser($principalUri) { - - $fields = array_values($this->propertyMap); - $fields[] = 'id'; - $fields[] = 'uri'; - $fields[] = 'ctag'; - $fields[] = 'components'; - $fields[] = 'principaluri'; - - // Making fields a comma-delimited list - $fields = implode(', ', $fields); - $stmt = $this->pdo->prepare("SELECT " . $fields . " FROM `".$this->calendarTableName."` WHERE principaluri = ?"); - $stmt->execute(array($principalUri)); - - $calendars = array(); - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $components = explode(',',$row['components']); - - $calendar = array( - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $row['principaluri'], - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag']?$row['ctag']:'0', - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), - ); - - - foreach($this->propertyMap as $xmlName=>$dbName) { - $calendar[$xmlName] = $row[$dbName]; - } - - $calendars[] = $calendar; - - } - - return $calendars; - - } - - /** - * Creates a new calendar for a principal. - * - * If the creation was a success, an id must be returned that can be used to reference - * this calendar in other methods, such as updateCalendar - * - * @param string $principalUri - * @param string $calendarUri - * @param array $properties - */ - public function createCalendar($principalUri,$calendarUri, array $properties) { - - $fieldNames = array( - 'principaluri', - 'uri', - 'ctag', - ); - $values = array( - ':principaluri' => $principalUri, - ':uri' => $calendarUri, - ':ctag' => 1, - ); - - // Default value - $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; - $fieldNames[] = 'components'; - if (!isset($properties[$sccs])) { - $values[':components'] = 'VEVENT,VTODO'; - } else { - if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) { - throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); - } - $values[':components'] = implode(',',$properties[$sccs]->getValue()); - } - - foreach($this->propertyMap as $xmlName=>$dbName) { - if (isset($properties[$xmlName])) { - - $myValue = $properties[$xmlName]; - $values[':' . $dbName] = $properties[$xmlName]; - $fieldNames[] = $dbName; - } - } - - $stmt = $this->pdo->prepare("INSERT INTO `".$this->calendarTableName."` (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")"); - $stmt->execute($values); - - return $this->pdo->lastInsertId(); - - } - - /** - * Updates properties for a calendar. - * - * The mutations array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param string $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) { - - $newValues = array(); - $result = array( - 200 => array(), // Ok - 403 => array(), // Forbidden - 424 => array(), // Failed Dependency - ); - - $hasError = false; - - foreach($mutations as $propertyName=>$propertyValue) { - - // We don't know about this property. - if (!isset($this->propertyMap[$propertyName])) { - $hasError = true; - $result[403][$propertyName] = null; - unset($mutations[$propertyName]); - continue; - } - - $fieldName = $this->propertyMap[$propertyName]; - $newValues[$fieldName] = $propertyValue; - - } - - // If there were any errors we need to fail the request - if ($hasError) { - // Properties has the remaining properties - foreach($mutations as $propertyName=>$propertyValue) { - $result[424][$propertyName] = null; - } - - // Removing unused statuscodes for cleanliness - foreach($result as $status=>$properties) { - if (is_array($properties) && count($properties)===0) unset($result[$status]); - } - - return $result; - - } - - // Success - - // Now we're generating the sql query. - $valuesSql = array(); - foreach($newValues as $fieldName=>$value) { - $valuesSql[] = $fieldName . ' = ?'; - } - $valuesSql[] = 'ctag = ctag + 1'; - - $stmt = $this->pdo->prepare("UPDATE `" . $this->calendarTableName . "` SET " . implode(', ',$valuesSql) . " WHERE id = ?"); - $newValues['id'] = $calendarId; - $stmt->execute(array_values($newValues)); - - return true; - - } - - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @return void - */ - public function deleteCalendar($calendarId) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ?'); - $stmt->execute(array($calendarId)); - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarTableName.'` WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Returns all calendar objects within a calendar. - * - * Every item contains an array with the following keys: - * * id - unique identifier which will be used for subsequent updates - * * calendardata - The iCalendar-compatible calnedar data - * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. - * * lastmodified - a timestamp of the last modification time - * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: - * ' "abcdef"') - * * calendarid - The calendarid as it was passed to this function. - * - * Note that the etag is optional, but it's highly encouraged to return for - * speed reasons. - * - * The calendardata is also optional. If it's not returned - * 'getCalendarObject' will be called later, which *is* expected to return - * calendardata. - * - * @param string $calendarId - * @return array - */ - public function getCalendarObjects($calendarId) { - - $stmt = $this->pdo->prepare('SELECT * FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ?'); - $stmt->execute(array($calendarId)); - return $stmt->fetchAll(); - - } - - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @return array - */ - public function getCalendarObject($calendarId,$objectUri) { - - $stmt = $this->pdo->prepare('SELECT * FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarId, $objectUri)); - return $stmt->fetch(); - - } - - /** - * Creates a new calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - public function createCalendarObject($calendarId,$objectUri,$calendarData) { - - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->calendarObjectTableName.'` (calendarid, uri, calendardata, lastmodified) VALUES (?,?,?,?)'); - $stmt->execute(array($calendarId,$objectUri,$calendarData,time())); - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarTableName.'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Updates an existing calendarobject, based on it's uri. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - public function updateCalendarObject($calendarId,$objectUri,$calendarData) { - - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarObjectTableName.'` SET calendardata = ?, lastmodified = ? WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarData,time(),$calendarId,$objectUri)); - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarTableName.'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @return void - */ - public function deleteCalendarObject($calendarId,$objectUri) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarId,$objectUri)); - $stmt = $this->pdo->prepare('UPDATE `'. $this->calendarTableName .'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - -} diff --git a/3rdparty/Sabre/CalDAV/Calendar.php b/3rdparty/Sabre/CalDAV/Calendar.php deleted file mode 100644 index 0d2b387577..0000000000 --- a/3rdparty/Sabre/CalDAV/Calendar.php +++ /dev/null @@ -1,318 +0,0 @@ -caldavBackend = $caldavBackend; - $this->principalBackend = $principalBackend; - $this->calendarInfo = $calendarInfo; - - - } - - /** - * Returns the name of the calendar - * - * @return string - */ - public function getName() { - - return $this->calendarInfo['uri']; - - } - - /** - * Updates properties such as the display name and description - * - * @param array $mutations - * @return array - */ - public function updateProperties($mutations) { - - return $this->caldavBackend->updateCalendar($this->calendarInfo['id'],$mutations); - - } - - /** - * Returns the list of properties - * - * @param array $properties - * @return array - */ - public function getProperties($requestedProperties) { - - $response = array(); - - foreach($requestedProperties as $prop) switch($prop) { - - case '{urn:ietf:params:xml:ns:caldav}supported-calendar-data' : - $response[$prop] = new Sabre_CalDAV_Property_SupportedCalendarData(); - break; - case '{urn:ietf:params:xml:ns:caldav}supported-collation-set' : - $response[$prop] = new Sabre_CalDAV_Property_SupportedCollationSet(); - break; - case '{DAV:}owner' : - $response[$prop] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF,$this->calendarInfo['principaluri']); - break; - default : - if (isset($this->calendarInfo[$prop])) $response[$prop] = $this->calendarInfo[$prop]; - break; - - } - return $response; - - } - - /** - * Returns a calendar object - * - * The contained calendar objects are for example Events or Todo's. - * - * @param string $name - * @return Sabre_DAV_ICalendarObject - */ - public function getChild($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_FileNotFound('Calendar object not found'); - return new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); - - } - - /** - * Returns the full list of calendar objects - * - * @return array - */ - public function getChildren() { - - $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); - $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); - } - return $children; - - } - - /** - * Checks if a child-node exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) - return false; - else - return true; - - } - - /** - * Creates a new directory - * - * We actually block this, as subdirectories are not allowed in calendars. - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in calendar objects is not allowed'); - - } - - /** - * Creates a new file - * - * The contents of the new file must be a valid ICalendar string. - * - * @param string $name - * @param resource $calendarData - * @return void - */ - public function createFile($name,$calendarData = null) { - - $calendarData = stream_get_contents($calendarData); - // Converting to UTF-8, if needed - $calendarData = Sabre_DAV_StringUtil::ensureUTF8($calendarData); - - $supportedComponents = $this->calendarInfo['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set']; - if ($supportedComponents) { - $supportedComponents = $supportedComponents->getValue(); - } else { - $supportedComponents = null; - } - Sabre_CalDAV_ICalendarUtil::validateICalendarObject($calendarData, $supportedComponents); - - $this->caldavBackend->createCalendarObject($this->calendarInfo['id'],$name,$calendarData); - - } - - /** - * Deletes the calendar. - * - * @return void - */ - public function delete() { - - $this->caldavBackend->deleteCalendar($this->calendarInfo['id']); - - } - - /** - * Renames the calendar. Note that most calendars use the - * {DAV:}displayname to display a name to display a name. - * - * @param string $newName - * @return void - */ - public function setName($newName) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming calendars is not yet supported'); - - } - - /** - * Returns the last modification date as a unix timestamp. - * - * @return void - */ - public function getLastModified() { - - return null; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->calendarInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CalDAV/CalendarObject.php b/3rdparty/Sabre/CalDAV/CalendarObject.php deleted file mode 100644 index 0c99f18deb..0000000000 --- a/3rdparty/Sabre/CalDAV/CalendarObject.php +++ /dev/null @@ -1,260 +0,0 @@ -caldavBackend = $caldavBackend; - - if (!isset($objectData['calendarid'])) { - throw new InvalidArgumentException('The objectData argument must contain a \'calendarid\' property'); - } - if (!isset($objectData['uri'])) { - throw new InvalidArgumentException('The objectData argument must contain an \'uri\' property'); - } - - $this->calendarInfo = $calendarInfo; - $this->objectData = $objectData; - - } - - /** - * Returns the uri for this object - * - * @return string - */ - public function getName() { - - return $this->objectData['uri']; - - } - - /** - * Returns the ICalendar-formatted object - * - * @return string - */ - public function get() { - - // Pre-populating the 'calendardata' is optional, if we don't have it - // already we fetch it from the backend. - if (!isset($this->objectData['calendardata'])) { - $this->objectData = $this->caldavBackend->getCalendarObject($this->objectData['calendarid'], $this->objectData['uri']); - } - return $this->objectData['calendardata']; - - } - - /** - * Updates the ICalendar-formatted object - * - * @param string $calendarData - * @return void - */ - public function put($calendarData) { - - if (is_resource($calendarData)) - $calendarData = stream_get_contents($calendarData); - - // Converting to UTF-8, if needed - $calendarData = Sabre_DAV_StringUtil::ensureUTF8($calendarData); - - $supportedComponents = $this->calendarInfo['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set']; - if ($supportedComponents) { - $supportedComponents = $supportedComponents->getValue(); - } else { - $supportedComponents = null; - } - Sabre_CalDAV_ICalendarUtil::validateICalendarObject($calendarData, $supportedComponents); - - $this->caldavBackend->updateCalendarObject($this->calendarInfo['id'],$this->objectData['uri'],$calendarData); - $this->objectData['calendardata'] = $calendarData; - - } - - /** - * Deletes the calendar object - * - * @return void - */ - public function delete() { - - $this->caldavBackend->deleteCalendarObject($this->calendarInfo['id'],$this->objectData['uri']); - - } - - /** - * Returns the mime content-type - * - * @return string - */ - public function getContentType() { - - return 'text/calendar'; - - } - - /** - * Returns an ETag for this object. - * - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * @return string - */ - public function getETag() { - - if (isset($this->objectData['etag'])) { - return $this->objectData['etag']; - } else { - return '"' . md5($this->get()). '"'; - } - - } - - /** - * Returns the last modification date as a unix timestamp - * - * @return time - */ - public function getLastModified() { - - return $this->objectData['lastmodified']; - - } - - /** - * Returns the size of this object in bytes - * - * @return int - */ - public function getSize() { - - return strlen($this->objectData['calendardata']); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->calendarInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - -} - diff --git a/3rdparty/Sabre/CalDAV/CalendarRootNode.php b/3rdparty/Sabre/CalDAV/CalendarRootNode.php deleted file mode 100644 index 69669a9d7f..0000000000 --- a/3rdparty/Sabre/CalDAV/CalendarRootNode.php +++ /dev/null @@ -1,75 +0,0 @@ -caldavBackend = $caldavBackend; - - } - - /** - * Returns the nodename - * - * We're overriding this, because the default will be the 'principalPrefix', - * and we want it to be Sabre_CalDAV_Plugin::CALENDAR_ROOT - * - * @return void - */ - public function getName() { - - return Sabre_CalDAV_Plugin::CALENDAR_ROOT; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAV_INode - */ - public function getChildForPrincipal(array $principal) { - - return new Sabre_CalDAV_UserCalendars($this->principalBackend, $this->caldavBackend, $principal['uri']); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php b/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php deleted file mode 100644 index 656b7286a6..0000000000 --- a/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php +++ /dev/null @@ -1,18 +0,0 @@ -server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - - } - - /** - * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?export - * - * @param string $method - * @param string $uri - * @return void - */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='export') return; - - // splitting uri - list($uri) = explode('?',$uri,2); - - $node = $this->server->tree->getNodeForPath($uri); - - if (!($node instanceof Sabre_CalDAV_Calendar)) return; - - $this->server->httpResponse->setHeader('Content-Type','text/calendar'); - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->sendBody($this->generateICS($this->server->tree->getChildren($uri))); - - // Returning false to break the event chain - return false; - - } - - /** - * Merges all calendar objects, and builds one big ics export - * - * @param array $nodes - * @return void - */ - public function generateICS(array $nodes) { - - $calendar = new Sabre_VObject_Component('vcalendar'); - $calendar->version = '2.0'; - $calendar->prodid = '-//SabreDAV//SabreDAV ' . Sabre_DAV_Version::VERSION . '//EN'; - $calendar->calscale = 'GREGORIAN'; - - $collectedTimezones = array(); - - $timezones = array(); - $objects = array(); - - foreach($nodes as $node) { - - $nodeData = $node->get(); - $nodeComp = Sabre_VObject_Reader::read($nodeData); - - foreach($nodeComp->children() as $child) { - - switch($child->name) { - case 'VEVENT' : - case 'VTODO' : - case 'VJOURNAL' : - $objects[] = $child; - break; - - // VTIMEZONE is special, because we need to filter out the duplicates - case 'VTIMEZONE' : - // Naively just checking tzid. - if (in_array((string)$child->TZID, $collectedTimezones)) continue; - - $timezones[] = $child; - $collectedTimezones[] = $child->TZID; - break; - - - } - - - } - - - } - - foreach($timezones as $tz) $calendar->add($tz); - foreach($objects as $obj) $calendar->add($obj); - - return $calendar->serialize(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/ICalendar.php b/3rdparty/Sabre/CalDAV/ICalendar.php deleted file mode 100644 index 8193dff3a8..0000000000 --- a/3rdparty/Sabre/CalDAV/ICalendar.php +++ /dev/null @@ -1,18 +0,0 @@ -registerXPathNameSpace('cal','urn:ietf:params:xml:ns:xcal'); - - // Check if there's only 1 component - $components = array('vevent','vtodo','vjournal','vfreebusy'); - $componentsFound = array(); - - foreach($components as $component) { - $test = $xcal->xpath('/cal:iCalendar/cal:vcalendar/cal:' . $component); - if (is_array($test)) $componentsFound = array_merge($componentsFound, $test); - } - if (count($componentsFound)<1) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject('One VEVENT, VTODO, VJOURNAL or VFREEBUSY must be specified. 0 found.'); - } - $component = $componentsFound[0]; - - if (is_null($allowedComponents)) return true; - - // Check if the component is allowed - $name = $component->getName(); - if (!in_array(strtoupper($name),$allowedComponents)) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject(strtoupper($name) . ' is not allowed in this calendar.'); - } - - if (count($xcal->xpath('/cal:iCalendar/cal:vcalendar/cal:method'))>0) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject('The METHOD property is not allowed in calendar objects'); - } - - return true; - - } - - /** - * Converts ICalendar data to XML. - * - * Properties are converted to lowercase xml elements. Parameters are; - * converted to attributes. BEGIN:VEVENT is converted to and - * END:VEVENT as well as other components. - * - * It's a very loose parser. If any line does not conform to the spec, it - * will simply be ignored. It will try to detect if \r\n or \n line endings - * are used. - * - * @todo Currently quoted attributes are not parsed correctly. - * @see http://tools.ietf.org/html/draft-royer-calsch-xcal-03 - * @param string $icalData - * @return string. - */ - static function toXCAL($icalData) { - - // Detecting line endings - $lb="\r\n"; - if (strpos($icalData,"\r\n")!==false) $lb = "\r\n"; - elseif (strpos($icalData,"\n")!==false) $lb = "\n"; - - // Splitting up items per line - $lines = explode($lb,$icalData); - - // Properties can be folded over 2 lines. In this case the second - // line will be preceeded by a space or tab. - $lines2 = array(); - foreach($lines as $line) { - - if (!$line) continue; - if ($line[0]===" " || $line[0]==="\t") { - $lines2[count($lines2)-1].=substr($line,1); - continue; - } - - $lines2[]=$line; - - } - - $xml = '' . "\n"; - $xml.= "\n"; - - $spaces = 2; - foreach($lines2 as $line) { - - $matches = array(); - // This matches PROPERTYNAME;ATTRIBUTES:VALUE - if (!preg_match('/^([^:^;]*)(?:;([^:]*))?:(.*)$/',$line,$matches)) - continue; - - $propertyName = strtolower($matches[1]); - $attributes = $matches[2]; - $value = $matches[3]; - - // If the line was in the format BEGIN:COMPONENT or END:COMPONENT, we need to special case it. - if ($propertyName === 'begin') { - $xml.=str_repeat(" ",$spaces); - $xml.='<' . strtolower($value) . ">\n"; - $spaces+=2; - continue; - } elseif ($propertyName === 'end') { - $spaces-=2; - $xml.=str_repeat(" ",$spaces); - $xml.='\n"; - continue; - } - - $xml.=str_repeat(" ",$spaces); - $xml.='<' . $propertyName; - if ($attributes) { - // There can be multiple attributes - $attributes = explode(';',$attributes); - foreach($attributes as $att) { - - list($attName,$attValue) = explode('=',$att,2); - $attName = strtolower($attName); - if ($attName === 'language') $attName='xml:lang'; - $xml.=' ' . $attName . '="' . htmlspecialchars($attValue) . '"'; - - } - } - - $xml.='>'. htmlspecialchars(trim($value)) . '\n"; - - } - $xml.=""; - return $xml; - - } - -} - diff --git a/3rdparty/Sabre/CalDAV/Plugin.php b/3rdparty/Sabre/CalDAV/Plugin.php deleted file mode 100644 index 02747c8395..0000000000 --- a/3rdparty/Sabre/CalDAV/Plugin.php +++ /dev/null @@ -1,788 +0,0 @@ -server->tree->getNodeForPath($parent); - - if ($node instanceof Sabre_DAV_IExtendedCollection) { - try { - $node->getChild($name); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - return array('MKCALENDAR'); - } - } - return array(); - - } - - /** - * Returns a list of features for the DAV: HTTP header. - * - * @return array - */ - public function getFeatures() { - - return array('calendar-access', 'calendar-proxy'); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'caldav'; - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_CalDAV_ICalendar || $node instanceof Sabre_CalDAV_ICalendarObject) { - return array( - '{' . self::NS_CALDAV . '}calendar-multiget', - '{' . self::NS_CALDAV . '}calendar-query', - ); - } - return array(); - - } - - /** - * Initializes the plugin - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - //$server->subscribeEvent('unknownMethod',array($this,'unknownMethod2'),1000); - $server->subscribeEvent('report',array($this,'report')); - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); - - $server->xmlNamespaces[self::NS_CALDAV] = 'cal'; - $server->xmlNamespaces[self::NS_CALENDARSERVER] = 'cs'; - - $server->propertyMap['{' . self::NS_CALDAV . '}supported-calendar-component-set'] = 'Sabre_CalDAV_Property_SupportedCalendarComponentSet'; - - $server->resourceTypeMapping['Sabre_CalDAV_ICalendar'] = '{urn:ietf:params:xml:ns:caldav}calendar'; - $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyRead'] = '{http://calendarserver.org/ns/}calendar-proxy-read'; - $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyWrite'] = '{http://calendarserver.org/ns/}calendar-proxy-write'; - - array_push($server->protectedProperties, - - '{' . self::NS_CALDAV . '}supported-calendar-component-set', - '{' . self::NS_CALDAV . '}supported-calendar-data', - '{' . self::NS_CALDAV . '}max-resource-size', - '{' . self::NS_CALDAV . '}min-date-time', - '{' . self::NS_CALDAV . '}max-date-time', - '{' . self::NS_CALDAV . '}max-instances', - '{' . self::NS_CALDAV . '}max-attendees-per-instance', - '{' . self::NS_CALDAV . '}calendar-home-set', - '{' . self::NS_CALDAV . '}supported-collation-set', - '{' . self::NS_CALDAV . '}calendar-data', - - // scheduling extension - '{' . self::NS_CALDAV . '}calendar-user-address-set', - - // CalendarServer extensions - '{' . self::NS_CALENDARSERVER . '}getctag', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for' - - ); - } - - /** - * This function handles support for the MKCALENDAR method - * - * @param string $method - * @return bool - */ - public function unknownMethod($method, $uri) { - - if ($method!=='MKCALENDAR') return; - - $this->httpMkCalendar($uri); - // false is returned to stop the unknownMethod event - return false; - - } - - /** - * This functions handles REPORT requests specific to CalDAV - * - * @param string $reportName - * @param DOMNode $dom - * @return bool - */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CALDAV.'}calendar-multiget' : - $this->calendarMultiGetReport($dom); - return false; - case '{'.self::NS_CALDAV.'}calendar-query' : - $this->calendarQueryReport($dom); - return false; - - } - - - } - - /** - * This function handles the MKCALENDAR HTTP method, which creates - * a new calendar. - * - * @param string $uri - * @return void - */ - public function httpMkCalendar($uri) { - - // Due to unforgivable bugs in iCal, we're completely disabling MKCALENDAR support - // for clients matching iCal in the user agent - //$ua = $this->server->httpRequest->getHeader('User-Agent'); - //if (strpos($ua,'iCal/')!==false) { - // throw new Sabre_DAV_Exception_Forbidden('iCal has major bugs in it\'s RFC3744 support. Therefore we are left with no other choice but disabling this feature.'); - //} - - $body = $this->server->httpRequest->getBody(true); - $properties = array(); - - if ($body) { - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - foreach($dom->firstChild->childNodes as $child) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($child)!=='{DAV:}set') continue; - foreach(Sabre_DAV_XMLUtil::parseProperties($child,$this->server->propertyMap) as $k=>$prop) { - $properties[$k] = $prop; - } - - } - } - - $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:caldav}calendar'); - - $this->server->createCollection($uri,$resourceType,$properties); - - $this->server->httpResponse->sendStatus(201); - $this->server->httpResponse->setHeader('Content-Length',0); - } - - /** - * beforeGetProperties - * - * This method handler is invoked before any after properties for a - * resource are fetched. This allows us to add in any CalDAV specific - * properties. - * - * @param string $path - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void - */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { - - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - // calendar-home-set property - $calHome = '{' . self::NS_CALDAV . '}calendar-home-set'; - if (in_array($calHome,$requestedProperties)) { - $principalId = $node->getName(); - $calendarHomePath = self::CALENDAR_ROOT . '/' . $principalId . '/'; - unset($requestedProperties[$calHome]); - $returnedProperties[200][$calHome] = new Sabre_DAV_Property_Href($calendarHomePath); - } - - // calendar-user-address-set property - $calProp = '{' . self::NS_CALDAV . '}calendar-user-address-set'; - if (in_array($calProp,$requestedProperties)) { - - $addresses = $node->getAlternateUriSet(); - $addresses[] = $this->server->getBaseUri() . $node->getPrincipalUrl(); - unset($requestedProperties[$calProp]); - $returnedProperties[200][$calProp] = new Sabre_DAV_Property_HrefList($addresses, false); - - } - - // These two properties are shortcuts for ical to easily find - // other principals this principal has access to. - $propRead = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for'; - $propWrite = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for'; - if (in_array($propRead,$requestedProperties) || in_array($propWrite,$requestedProperties)) { - - $membership = $node->getGroupMembership(); - $readList = array(); - $writeList = array(); - - foreach($membership as $group) { - - $groupNode = $this->server->tree->getNodeForPath($group); - - // If the node is either ap proxy-read or proxy-write - // group, we grab the parent principal and add it to the - // list. - if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyRead) { - list($readList[]) = Sabre_DAV_URLUtil::splitPath($group); - } - if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyWrite) { - list($writeList[]) = Sabre_DAV_URLUtil::splitPath($group); - } - - } - if (in_array($propRead,$requestedProperties)) { - unset($requestedProperties[$propRead]); - $returnedProperties[200][$propRead] = new Sabre_DAV_Property_HrefList($readList); - } - if (in_array($propWrite,$requestedProperties)) { - unset($requestedProperties[$propWrite]); - $returnedProperties[200][$propWrite] = new Sabre_DAV_Property_HrefList($writeList); - } - - } - - } // instanceof IPrincipal - - - if ($node instanceof Sabre_CalDAV_ICalendarObject) { - // The calendar-data property is not supposed to be a 'real' - // property, but in large chunks of the spec it does act as such. - // Therefore we simply expose it as a property. - $calDataProp = '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'; - if (in_array($calDataProp, $requestedProperties)) { - unset($requestedProperties[$calDataProp]); - $val = $node->get(); - if (is_resource($val)) - $val = stream_get_contents($val); - - // Taking out \r to not screw up the xml output - $returnedProperties[200][$calDataProp] = str_replace("\r","", $val); - - } - } - - } - - /** - * This function handles the calendar-multiget REPORT. - * - * This report is used by the client to fetch the content of a series - * of urls. Effectively avoiding a lot of redundant requests. - * - * @param DOMNode $dom - * @return void - */ - public function calendarMultiGetReport($dom) { - - $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); - foreach($hrefElems as $elem) { - $uri = $this->server->calculateUri($elem->nodeValue); - list($objProps) = $this->server->getPropertiesForPath($uri,$properties); - $propertyList[]=$objProps; - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - - } - - /** - * This function handles the calendar-query REPORT - * - * This report is used by clients to request calendar objects based on - * complex conditions. - * - * @param DOMNode $dom - * @return void - */ - public function calendarQueryReport($dom) { - - $requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $filterNode = $dom->getElementsByTagNameNS('urn:ietf:params:xml:ns:caldav','filter'); - if ($filterNode->length!==1) { - throw new Sabre_DAV_Exception_BadRequest('The calendar-query report must have a filter element'); - } - $filters = Sabre_CalDAV_XMLUtil::parseCalendarQueryFilters($filterNode->item(0)); - - $requestedCalendarData = true; - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar-data', $requestedProperties)) { - // We always retrieve calendar-data, as we need it for filtering. - $requestedProperties[] = '{urn:ietf:params:xml:ns:caldav}calendar-data'; - - // If calendar-data wasn't explicitly requested, we need to remove - // it after processing. - $requestedCalendarData = false; - } - - // These are the list of nodes that potentially match the requirement - $candidateNodes = $this->server->getPropertiesForPath($this->server->getRequestUri(),$requestedProperties,$this->server->getHTTPDepth(0)); - - $verifiedNodes = array(); - - foreach($candidateNodes as $node) { - - // If the node didn't have a calendar-data property, it must not be a calendar object - if (!isset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'])) continue; - - if ($this->validateFilters($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'],$filters)) { - - if (!$requestedCalendarData) { - unset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); - } - $verifiedNodes[] = $node; - } - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($verifiedNodes)); - - } - - - /** - * Verify if a list of filters applies to the calendar data object - * - * The calendarData object must be a valid iCalendar blob. The list of - * filters must be formatted as parsed by Sabre_CalDAV_Plugin::parseCalendarQueryFilters - * - * @param string $calendarData - * @param array $filters - * @return bool - */ - public function validateFilters($calendarData,$filters) { - - // We are converting the calendar object to an XML structure - // This makes it far easier to parse - $xCalendarData = Sabre_CalDAV_ICalendarUtil::toXCal($calendarData); - $xml = simplexml_load_string($xCalendarData); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:xcal'); - - foreach($filters as $xpath=>$filter) { - - // if-not-defined comes first - if (isset($filter['is-not-defined'])) { - if (!$xml->xpath($xpath)) - continue; - else - return false; - - } - - $elem = $xml->xpath($xpath); - - if (!$elem) return false; - $elem = $elem[0]; - - if (isset($filter['time-range'])) { - - switch($elem->getName()) { - case 'vevent' : - $result = $this->validateTimeRangeFilterForEvent($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vtodo' : - $result = $this->validateTimeRangeFilterForTodo($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vjournal' : - case 'vfreebusy' : - case 'valarm' : - // TODO: not implemented - break; - - /* - - case 'vjournal' : - $result = $this->validateTimeRangeFilterForJournal($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vfreebusy' : - $result = $this->validateTimeRangeFilterForFreeBusy($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'valarm' : - $result = $this->validateTimeRangeFilterForAlarm($xml,$xpath,$filter); - if ($result===false) return false; - break; - - */ - - } - - } - - if (isset($filter['text-match'])) { - $currentString = (string)$elem; - - $isMatching = Sabre_DAV_StringUtil::textMatch($currentString, $filter['text-match']['value'], $filter['text-match']['collation']); - if ($filter['text-match']['negate-condition'] && $isMatching) return false; - if (!$filter['text-match']['negate-condition'] && !$isMatching) return false; - - } - - } - return true; - - } - - /** - * Checks whether a time-range filter matches an event. - * - * @param SimpleXMLElement $xml Event as xml object - * @param string $currentXPath XPath to check - * @param array $currentFilter Filter information - * @return void - */ - private function validateTimeRangeFilterForEvent(SimpleXMLElement $xml,$currentXPath,array $currentFilter) { - - // Grabbing the DTSTART property - $xdtstart = $xml->xpath($currentXPath.'/c:dtstart'); - if (!count($xdtstart)) { - throw new Sabre_DAV_Exception_BadRequest('DTSTART property missing from calendar object'); - } - - // The dtstart can be both a date, or datetime property - if ((string)$xdtstart[0]['value']==='DATE' || strlen((string)$xdtstart[0])===8) { - $isDateTime = false; - } else { - $isDateTime = true; - } - - // Determining the timezone - if ($tzid = (string)$xdtstart[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $dtstart = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdtstart[0],$tz); - } else { - $dtstart = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdtstart[0]); - } - - - // Grabbing the DTEND property - $xdtend = $xml->xpath($currentXPath.'/c:dtend'); - $dtend = null; - - if (count($xdtend)) { - // Determining the timezone - if ($tzid = (string)$xdtend[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - - // Since the VALUE prameter of both DTSTART and DTEND must be the same - // we can assume we don't need to check the VALUE paramter of DTEND. - if ($isDateTime) { - $dtend = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdtend[0],$tz); - } else { - $dtend = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdtend[0],$tz); - } - - } - - if (is_null($dtend)) { - // The DTEND property was not found. We will first see if the event has a duration - // property - - $xduration = $xml->xpath($currentXPath.'/c:duration'); - if (count($xduration)) { - $duration = Sabre_CalDAV_XMLUtil::parseICalendarDuration((string)$xduration[0]); - - // Making sure that the duration is bigger than 0 seconds. - $tempDT = clone $dtstart; - $tempDT->modify($duration); - if ($tempDT > $dtstart) { - - // use DTEND = DTSTART + DURATION - $dtend = $tempDT; - } else { - // use DTEND = DTSTART - $dtend = $dtstart; - } - - } - } - - if (is_null($dtend)) { - if ($isDateTime) { - // DTEND = DTSTART - $dtend = $dtstart; - } else { - // DTEND = DTSTART + 1 DAY - $dtend = clone $dtstart; - $dtend->modify('+1 day'); - } - } - // TODO: we need to properly parse RRULE's, but it's very difficult. - // For now, we're always returning events if they have an RRULE at all. - $rrule = $xml->xpath($currentXPath.'/c:rrule'); - $hasRrule = (count($rrule))>0; - - if (!is_null($currentFilter['time-range']['start']) && $currentFilter['time-range']['start'] >= $dtend) return false; - if (!is_null($currentFilter['time-range']['end']) && $currentFilter['time-range']['end'] <= $dtstart && !$hasRrule) return false; - return true; - - } - - private function validateTimeRangeFilterForTodo(SimpleXMLElement $xml,$currentXPath,array $filter) { - - // Gathering all relevant elements - - $dtStart = null; - $duration = null; - $due = null; - $completed = null; - $created = null; - - $xdt = $xml->xpath($currentXPath.'/c:dtstart'); - if (count($xdt)) { - // The dtstart can be both a date, or datetime property - if ((string)$xdt[0]['value']==='DATE') { - $isDateTime = false; - } else { - $isDateTime = true; - } - - // Determining the timezone - if ($tzid = (string)$xdt[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $dtStart = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0],$tz); - } else { - $dtStart = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdt[0]); - } - } - - // Only need to grab duration if dtStart is set - if (!is_null($dtStart)) { - - $xduration = $xml->xpath($currentXPath.'/c:duration'); - if (count($xduration)) { - $duration = Sabre_CalDAV_XMLUtil::parseICalendarDuration((string)$xduration[0]); - } - - } - - if (!is_null($dtStart) && !is_null($duration)) { - - // Comparision from RFC 4791: - // (start <= DTSTART+DURATION) AND ((end > DTSTART) OR (end >= DTSTART+DURATION)) - - $end = clone $dtStart; - $end->modify($duration); - - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $end) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $dtStart || $filter['time-range']['end'] >= $end) ) { - return true; - } else { - return false; - } - - } - - // Need to grab the DUE property - $xdt = $xml->xpath($currentXPath.'/c:due'); - if (count($xdt)) { - // The due property can be both a date, or datetime property - if ((string)$xdt[0]['value']==='DATE') { - $isDateTime = false; - } else { - $isDateTime = true; - } - // Determining the timezone - if ($tzid = (string)$xdt[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $due = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0],$tz); - } else { - $due = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdt[0]); - } - } - - if (!is_null($dtStart) && !is_null($due)) { - - // Comparision from RFC 4791: - // ((start < DUE) OR (start <= DTSTART)) AND ((end > DTSTART) OR (end >= DUE)) - - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] < $due || $filter['time-range']['start'] < $dtstart) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $due) ) { - return true; - } else { - return false; - } - - } - - if (!is_null($dtStart)) { - - // Comparision from RFC 4791 - // (start <= DTSTART) AND (end > DTSTART) - if ( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $dtStart) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $dtStart) ) { - return true; - } else { - return false; - } - - } - - if (!is_null($due)) { - - // Comparison from RFC 4791 - // (start < DUE) AND (end >= DUE) - if ( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] < $due) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $due) ) { - return true; - } else { - return false; - } - - } - // Need to grab the COMPLETED property - $xdt = $xml->xpath($currentXPath.'/c:completed'); - if (count($xdt)) { - $completed = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0]); - } - // Need to grab the CREATED property - $xdt = $xml->xpath($currentXPath.'/c:created'); - if (count($xdt)) { - $created = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0]); - } - - if (!is_null($completed) && !is_null($created)) { - // Comparison from RFC 4791 - // ((start <= CREATED) OR (start <= COMPLETED)) AND ((end >= CREATED) OR (end >= COMPLETED)) - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $created || $filter['time-range']['start'] <= $completed) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $created || $filter['time-range']['end'] >= $completed)) { - return true; - } else { - return false; - } - } - - if (!is_null($completed)) { - // Comparison from RFC 4791 - // (start <= COMPLETED) AND (end >= COMPLETED) - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $completed) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $completed)) { - return true; - } else { - return false; - } - } - - if (!is_null($created)) { - // Comparison from RFC 4791 - // (end > CREATED) - if( (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $created) ) { - return true; - } else { - return false; - } - } - - // Everything else is TRUE - return true; - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/Collection.php b/3rdparty/Sabre/CalDAV/Principal/Collection.php deleted file mode 100644 index 13435b2448..0000000000 --- a/3rdparty/Sabre/CalDAV/Principal/Collection.php +++ /dev/null @@ -1,31 +0,0 @@ -principalBackend, $principalInfo); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php b/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php deleted file mode 100644 index f531d85d1f..0000000000 --- a/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php +++ /dev/null @@ -1,178 +0,0 @@ -principalInfo = $principalInfo; - $this->principalBackend = $principalBackend; - - } - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - return 'calendar-proxy-read'; - - } - - /** - * Returns the last modification time - * - * @return null - */ - public function getLastModified() { - - return null; - - } - - /** - * Deletes the current node - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - - } - - /** - * Renames the node - * - * @throws Sabre_DAV_Exception_Forbidden - * @param string $name The new name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - - } - - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - return array(); - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - - } - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $principals) { - - $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - - } - - /** - * Returns the displayname - * - * This should be a human readable name for the principal. - * If none is available, return the nodename. - * - * @return string - */ - public function getDisplayName() { - - return $this->getName(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php b/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php deleted file mode 100644 index 4d8face206..0000000000 --- a/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php +++ /dev/null @@ -1,178 +0,0 @@ -principalInfo = $principalInfo; - $this->principalBackend = $principalBackend; - - } - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - return 'calendar-proxy-write'; - - } - - /** - * Returns the last modification time - * - * @return null - */ - public function getLastModified() { - - return null; - - } - - /** - * Deletes the current node - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - - } - - /** - * Renames the node - * - * @throws Sabre_DAV_Exception_Forbidden - * @param string $name The new name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - - } - - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - return array(); - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - - } - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $principals) { - - $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - - } - - /** - * Returns the displayname - * - * This should be a human readable name for the principal. - * If none is available, return the nodename. - * - * @return string - */ - public function getDisplayName() { - - return $this->getName(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/User.php b/3rdparty/Sabre/CalDAV/Principal/User.php deleted file mode 100644 index 034629b89b..0000000000 --- a/3rdparty/Sabre/CalDAV/Principal/User.php +++ /dev/null @@ -1,122 +0,0 @@ -principalBackend, $this->principalProperties); - - if ($name === 'calendar-proxy-write') - return new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties); - - throw new Sabre_DAV_Exception_FileNotFound('Node with name ' . $name . ' was not found'); - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - return array( - new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties), - new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties), - ); - - } - - /** - * Checks if a child-node with the specified name exists - * - * @return bool - */ - public function childExists($name) { - - return $name === 'calendar-proxy-read' || $name === 'calendar-proxy-write'; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-read', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - ); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php deleted file mode 100644 index 1bbaca6b8a..0000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php +++ /dev/null @@ -1,85 +0,0 @@ -components = $components; - - } - - /** - * Returns the list of supported components - * - * @return array - */ - public function getValue() { - - return $this->components; - - } - - /** - * Serializes the property in a DOMDocument - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->components as $component) { - - $xcomp = $doc->createElement('cal:comp'); - $xcomp->setAttribute('name',$component); - $node->appendChild($xcomp); - - } - - } - - /** - * Unserializes the DOMElement back into a Property class. - * - * @param DOMElement $node - * @return void - */ - static function unserialize(DOMElement $node) { - - $components = array(); - foreach($node->childNodes as $childNode) { - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)==='{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}comp') { - $components[] = $childNode->getAttribute('name'); - } - } - return new self($components); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php deleted file mode 100644 index 5010ee6d52..0000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php +++ /dev/null @@ -1,38 +0,0 @@ -ownerDocument; - - $prefix = isset($server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV])?$server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV]:'cal'; - - $caldata = $doc->createElement($prefix . ':calendar-data'); - $caldata->setAttribute('content-type','text/calendar'); - $caldata->setAttribute('version','2.0'); - - $node->appendChild($caldata); - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php deleted file mode 100644 index e585e9db3d..0000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php +++ /dev/null @@ -1,44 +0,0 @@ -ownerDocument; - - $prefix = $node->lookupPrefix('urn:ietf:params:xml:ns:caldav'); - if (!$prefix) $prefix = 'cal'; - - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;ascii-casemap') - ); - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;octet') - ); - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;unicode-casemap') - ); - - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Server.php b/3rdparty/Sabre/CalDAV/Server.php deleted file mode 100644 index 969d69c627..0000000000 --- a/3rdparty/Sabre/CalDAV/Server.php +++ /dev/null @@ -1,65 +0,0 @@ -authRealm); - $this->addPlugin($authPlugin); - - $aclPlugin = new Sabre_DAVACL_Plugin(); - $this->addPlugin($aclPlugin); - - $caldavPlugin = new Sabre_CalDAV_Plugin(); - $this->addPlugin($caldavPlugin); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/UserCalendars.php b/3rdparty/Sabre/CalDAV/UserCalendars.php deleted file mode 100644 index f52d65e9a7..0000000000 --- a/3rdparty/Sabre/CalDAV/UserCalendars.php +++ /dev/null @@ -1,280 +0,0 @@ -principalBackend = $principalBackend; - $this->caldavBackend = $caldavBackend; - $this->principalInfo = $principalBackend->getPrincipalByPath($userUri); - - } - - /** - * Returns the name of this object - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); - return $name; - - } - - /** - * Updates the name of this object - * - * @param string $name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden(); - - } - - /** - * Deletes this object - * - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden(); - - } - - /** - * Returns the last modification date - * - * @return int - */ - public function getLastModified() { - - return null; - - } - - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @return void - */ - public function createFile($filename, $data=null) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - - } - - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @return void - */ - public function createDirectory($filename) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - - } - - /** - * Returns a single calendar, by name - * - * @param string $name - * @todo needs optimizing - * @return Sabre_CalDAV_Calendar - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('Calendar with name \'' . $name . '\' could not be found'); - - } - - /** - * Checks if a calendar exists. - * - * @param string $name - * @todo needs optimizing - * @return bool - */ - public function childExists($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return true; - - } - return false; - - } - - /** - * Returns a list of calendars - * - * @return array - */ - public function getChildren() { - - $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']); - $objs = array(); - foreach($calendars as $calendar) { - $objs[] = new Sabre_CalDAV_Calendar($this->principalBackend, $this->caldavBackend, $calendar); - } - return $objs; - - } - - /** - * Creates a new calendar - * - * @param string $name - * @param string $properties - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar',$resourceType) || count($resourceType)!==2) { - throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); - } - $this->caldavBackend->createCalendar($this->principalInfo['uri'], $name, $properties); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalInfo['uri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CalDAV/Version.php b/3rdparty/Sabre/CalDAV/Version.php deleted file mode 100644 index df8fe1f6bd..0000000000 --- a/3rdparty/Sabre/CalDAV/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -childNodes as $child) { - - switch(Sabre_DAV_XMLUtil::toClarkNotation($child)) { - - case '{urn:ietf:params:xml:ns:caldav}comp-filter' : - case '{urn:ietf:params:xml:ns:caldav}prop-filter' : - - $filterName = $basePath . '/' . 'c:' . strtolower($child->getAttribute('name')); - $filters[$filterName] = array(); - - self::parseCalendarQueryFilters($child, $filterName,$filters); - break; - - case '{urn:ietf:params:xml:ns:caldav}time-range' : - - if ($start = $child->getAttribute('start')) { - $start = self::parseICalendarDateTime($start); - } else { - $start = null; - } - if ($end = $child->getAttribute('end')) { - $end = self::parseICalendarDateTime($end); - } else { - $end = null; - } - - if (!is_null($start) && !is_null($end) && $end <= $start) { - throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the time-range filter'); - } - - $filters[$basePath]['time-range'] = array( - 'start' => $start, - 'end' => $end - ); - break; - - case '{urn:ietf:params:xml:ns:caldav}is-not-defined' : - $filters[$basePath]['is-not-defined'] = true; - break; - - case '{urn:ietf:params:xml:ns:caldav}param-filter' : - - $filterName = $basePath . '/@' . strtolower($child->getAttribute('name')); - $filters[$filterName] = array(); - self::parseCalendarQueryFilters($child, $filterName, $filters); - break; - - case '{urn:ietf:params:xml:ns:caldav}text-match' : - - $collation = $child->getAttribute('collation'); - if (!$collation) $collation = 'i;ascii-casemap'; - - $filters[$basePath]['text-match'] = array( - 'collation' => ($collation == 'default'?'i;ascii-casemap':$collation), - 'negate-condition' => $child->getAttribute('negate-condition')==='yes', - 'value' => $child->nodeValue, - ); - break; - - } - - } - - return $filters; - - } - - /** - * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object - * - * Specifying a reference timezone is optional. It will only be used - * if the non-UTC format is used. The argument is used as a reference, the - * returned DateTime object will still be in the UTC timezone. - * - * @param string $dt - * @param DateTimeZone $tz - * @return DateTime - */ - static public function parseICalendarDateTime($dt,DateTimeZone $tz = null) { - - // Format is YYYYMMDD + "T" + hhmmss - $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])T([0-2][0-9])([0-5][0-9])([0-5][0-9])([Z]?)$/',$dt,$matches); - - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar datetime value is incorrect: ' . $dt); - } - - if ($matches[7]==='Z' || is_null($tz)) { - $tz = new DateTimeZone('UTC'); - } - $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3] . ' ' . $matches[4] . ':' . $matches[5] .':' . $matches[6], $tz); - - // Still resetting the timezone, to normalize everything to UTC - $date->setTimeZone(new DateTimeZone('UTC')); - return $date; - - } - - /** - * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object - * - * @param string $date - * @param DateTimeZone $tz - * @return DateTime - */ - static public function parseICalendarDate($date) { - - // Format is YYYYMMDD - $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])$/',$date,$matches); - - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar date value is incorrect: ' . $date); - } - - $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3], new DateTimeZone('UTC')); - return $date; - - } - - /** - * Parses an iCalendar (RFC5545) formatted duration and returns a string suitable - * for strtotime or DateTime::modify. - * - * NOTE: When we require PHP 5.3 this can be replaced by the DateTimeInterval object, which - * supports ISO 8601 Intervals, which is a superset of ICalendar durations. - * - * For now though, we're just gonna live with this messy system - * - * @param string $duration - * @return string - */ - static public function parseICalendarDuration($duration) { - - $result = preg_match('/^(?P\+|-)?P((?P\d+)W)?((?P\d+)D)?(T((?P\d+)H)?((?P\d+)M)?((?P\d+)S)?)?$/', $duration, $matches); - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar duration value is incorrect: ' . $duration); - } - - $parts = array( - 'week', - 'day', - 'hour', - 'minute', - 'second', - ); - - $newDur = ''; - foreach($parts as $part) { - if (isset($matches[$part]) && $matches[$part]) { - $newDur.=' '.$matches[$part] . ' ' . $part . 's'; - } - } - - $newDur = ($matches['plusminus']==='-'?'-':'+') . trim($newDur); - return $newDur; - - } - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBook.php b/3rdparty/Sabre/CardDAV/AddressBook.php deleted file mode 100644 index 471ca7b338..0000000000 --- a/3rdparty/Sabre/CardDAV/AddressBook.php +++ /dev/null @@ -1,293 +0,0 @@ -carddavBackend = $carddavBackend; - $this->addressBookInfo = $addressBookInfo; - - } - - /** - * Returns the name of the addressbook - * - * @return string - */ - public function getName() { - - return $this->addressBookInfo['uri']; - - } - - /** - * Returns a card - * - * @param string $name - * @return Sabre_DAV_Card - */ - public function getChild($name) { - - $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_FileNotFound('Card not found'); - return new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); - - } - - /** - * Returns the full list of cards - * - * @return array - */ - public function getChildren() { - - $objs = $this->carddavBackend->getCards($this->addressBookInfo['id']); - $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); - } - return $children; - - } - - /** - * Creates a new directory - * - * We actually block this, as subdirectories are not allowed in addressbooks. - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in addressbooks is not allowed'); - - } - - /** - * Creates a new file - * - * The contents of the new file must be a valid VCARD - * - * @param string $name - * @param resource $vcardData - * @return void - */ - public function createFile($name,$vcardData = null) { - - $vcardData = stream_get_contents($vcardData); - // Converting to UTF-8, if needed - $vcardData = Sabre_DAV_StringUtil::ensureUTF8($vcardData); - - $this->carddavBackend->createCard($this->addressBookInfo['id'],$name,$vcardData); - - } - - /** - * Deletes the entire addressbook. - * - * @return void - */ - public function delete() { - - $this->carddavBackend->deleteAddressBook($this->addressBookInfo['id']); - - } - - /** - * Renames the addressbook - * - * @param string $newName - * @return void - */ - public function setName($newName) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming addressbooks is not yet supported'); - - } - - /** - * Returns the last modification date as a unix timestamp. - * - * @return void - */ - public function getLastModified() { - - return null; - - } - - /** - * Updates properties on this node, - * - * The properties array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param array $mutations - * @return bool|array - */ - public function updateProperties($mutations) { - - return $this->carddavBackend->updateAddressBook($this->addressBookInfo['id'], $mutations); - - } - - /** - * Returns a list of properties for this nodes. - * - * The properties list is a list of propertynames the client requested, - * encoded in clark-notation {xmlnamespace}tagname - * - * If the array is empty, it means 'all properties' were requested. - * - * @param array $properties - * @return void - */ - public function getProperties($properties) { - - $response = array(); - foreach($properties as $propertyName) { - - if (isset($this->addressBookInfo[$propertyName])) { - - $response[$propertyName] = $this->addressBookInfo[$propertyName]; - - } - - } - - return $response; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->addressBookInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php b/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php deleted file mode 100644 index 08adc3b815..0000000000 --- a/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php +++ /dev/null @@ -1,211 +0,0 @@ -dom = $dom; - - $this->xpath = new DOMXPath($dom); - $this->xpath->registerNameSpace('card',Sabre_CardDAV_Plugin::NS_CARDDAV); - - } - - /** - * Parses the request. - * - * @param DOMNode $dom - * @return void - */ - public function parse() { - - $filterNode = null; - - $limit = $this->xpath->evaluate('number(/card:addressbook-query/card:limit/card:nresults)'); - if (is_nan($limit)) $limit = null; - - $filter = $this->xpath->query('/card:addressbook-query/card:filter'); - if ($filter->length !== 1) { - throw new Sabre_DAV_Exception_BadRequest('Only one filter element is allowed'); - } - - $filter = $filter->item(0); - $test = $this->xpath->evaluate('string(@test)', $filter); - if (!$test) $test = self::TEST_ANYOF; - if ($test !== self::TEST_ANYOF && $test !== self::TEST_ALLOF) { - throw new Sabre_DAV_Exception_BadRequest('The test attribute must either hold "anyof" or "allof"'); - } - - $propFilters = array(); - - $propFilterNodes = $this->xpath->query('card:prop-filter', $filter); - for($ii=0; $ii < $propFilterNodes->length; $ii++) { - - $propFilters[] = $this->parsePropFilterNode($propFilterNodes->item($ii)); - - - } - - $this->filters = $propFilters; - $this->limit = $limit; - $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild)); - $this->test = $test; - - } - - /** - * Parses the prop-filter xml element - * - * @param DOMElement $propFilterNode - * @return array - */ - protected function parsePropFilterNode(DOMElement $propFilterNode) { - - $propFilter = array(); - $propFilter['name'] = $propFilterNode->getAttribute('name'); - $propFilter['test'] = $propFilterNode->getAttribute('test'); - if (!$propFilter['test']) $propFilter['test'] = 'anyof'; - - $propFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $propFilterNode)->length>0; - - $paramFilterNodes = $this->xpath->query('card:param-filter', $propFilterNode); - - $propFilter['param-filters'] = array(); - - - for($ii=0;$ii<$paramFilterNodes->length;$ii++) { - - $propFilter['param-filters'][] = $this->parseParamFilterNode($paramFilterNodes->item($ii)); - - } - $propFilter['text-matches'] = array(); - $textMatchNodes = $this->xpath->query('card:text-match', $propFilterNode); - - for($ii=0;$ii<$textMatchNodes->length;$ii++) { - - $propFilter['text-matches'][] = $this->parseTextMatchNode($textMatchNodes->item($ii)); - - } - - return $propFilter; - - } - - /** - * Parses the param-filter element - * - * @param DOMElement $paramFilterNode - * @return array - */ - public function parseParamFilterNode(DOMElement $paramFilterNode) { - - $paramFilter = array(); - $paramFilter['name'] = $paramFilterNode->getAttribute('name'); - $paramFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $paramFilterNode)->length>0; - $paramFilter['text-match'] = null; - - $textMatch = $this->xpath->query('card:text-match', $paramFilterNode); - if ($textMatch->length>0) { - $paramFilter['text-match'] = $this->parseTextMatchNode($textMatch->item(0)); - } - - return $paramFilter; - - } - - /** - * Text match - * - * @param DOMElement $textMatchNode - * @return void - */ - public function parseTextMatchNode(DOMElement $textMatchNode) { - - $matchType = $textMatchNode->getAttribute('match-type'); - if (!$matchType) $matchType = 'contains'; - - if (!in_array($matchType, array('contains', 'equals', 'starts-with', 'ends-with'))) { - throw new Sabre_DAV_Exception_BadRequest('Unknown match-type: ' . $matchType); - } - - $negateCondition = $textMatchNode->getAttribute('negate-condition'); - $negateCondition = $negateCondition==='yes'; - $collation = $textMatchNode->getAttribute('collation'); - if (!$collation) $collation = 'i;unicode-casemap'; - - return array( - 'negate-condition' => $negateCondition, - 'collation' => $collation, - 'match-type' => $matchType, - 'value' => $textMatchNode->nodeValue - ); - - - } - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBookRoot.php b/3rdparty/Sabre/CardDAV/AddressBookRoot.php deleted file mode 100644 index 1a80efba35..0000000000 --- a/3rdparty/Sabre/CardDAV/AddressBookRoot.php +++ /dev/null @@ -1,78 +0,0 @@ -carddavBackend = $carddavBackend; - parent::__construct($principalBackend, $principalPrefix); - - } - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - - return Sabre_CardDAV_Plugin::ADDRESSBOOK_ROOT; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAV_INode - */ - public function getChildForPrincipal(array $principal) { - - return new Sabre_CardDAV_UserAddressBooks($this->carddavBackend, $principal['uri']); - - } - -} diff --git a/3rdparty/Sabre/CardDAV/Backend/Abstract.php b/3rdparty/Sabre/CardDAV/Backend/Abstract.php deleted file mode 100644 index 1f0253ddab..0000000000 --- a/3rdparty/Sabre/CardDAV/Backend/Abstract.php +++ /dev/null @@ -1,121 +0,0 @@ -pdo = $pdo; - $this->addressBooksTableName = $addressBooksTableName; - $this->cardsTableName = $cardsTableName; - - } - - /** - * Returns the list of addressbooks for a specific user. - * - * @param string $principalUri - * @return array - */ - public function getAddressBooksForUser($principalUri) { - - $stmt = $this->pdo->prepare('SELECT id, uri, displayname, principaluri, description, ctag FROM `'.$this->addressBooksTableName.'` WHERE principaluri = ?'); - $result = $stmt->execute(array($principalUri)); - - $addressBooks = array(); - - foreach($stmt->fetchAll() as $row) { - - $addressBooks[] = array( - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $row['principaluri'], - '{DAV:}displayname' => $row['displayname'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], - '{http://calendarserver.org/ns/}getctag' => $row['ctag'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => - new Sabre_CardDAV_Property_SupportedAddressData(), - ); - - } - - return $addressBooks; - - } - - - /** - * Updates an addressbook's properties - * - * See Sabre_DAV_IProperties for a description of the mutations array, as - * well as the return value. - * - * @param mixed $addressBookId - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateAddressBook($addressBookId, array $mutations) { - - $updates = array(); - - foreach($mutations as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : - $updates['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $updates['description'] = $newValue; - break; - default : - // If any unsupported values were being updated, we must - // let the entire request fail. - return false; - } - - } - - // No values are being updated? - if (!$updates) { - return false; - } - - $query = 'UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 '; - foreach($updates as $key=>$value) { - $query.=', `' . $key . '` = :' . $key . ' '; - } - $query.=' WHERE id = :addressbookid'; - - $stmt = $this->pdo->prepare($query); - $updates['addressbookid'] = $addressBookId; - - $stmt->execute($updates); - - return true; - - } - - /** - * Creates a new address book - * - * @param string $principalUri - * @param string $url Just the 'basename' of the url. - * @param array $properties - * @return void - */ - public function createAddressBook($principalUri, $url, array $properties) { - - $values = array( - 'displayname' => null, - 'description' => null, - 'principaluri' => $principalUri, - 'uri' => $url, - ); - - foreach($properties as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : - $values['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $values['description'] = $newValue; - break; - default : - throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property); - } - - } - - $query = 'INSERT INTO `' . $this->addressBooksTableName . '` (uri, displayname, description, principaluri, ctag) VALUES (:uri, :displayname, :description, :principaluri, 1)'; - $stmt = $this->pdo->prepare($query); - $stmt->execute($values); - - } - - /** - * Deletes an entire addressbook and all its contents - * - * @param int $addressBookId - * @return void - */ - public function deleteAddressBook($addressBookId) { - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->cardsTableName . '` WHERE addressbookid = ?'); - $stmt->execute(array($addressBookId)); - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->addressBooksTableName . '` WHERE id = ?'); - $stmt->execute(array($addressBookId)); - - } - - /** - * Returns all cards for a specific addressbook id. - * - * @param mixed $addressbookId - * @return array - */ - public function getCards($addressbookId) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM `' . $this->cardsTableName . '` WHERE addressbookid = ?'); - $stmt->execute(array($addressbookId)); - - return $stmt->fetchAll(PDO::FETCH_ASSOC); - - - } - /** - * Returns a specfic card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return array - */ - public function getCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM `' . $this->cardsTableName . '` WHERE addressbookid = ? AND uri = ? LIMIT 1'); - $stmt->execute(array($addressBookId, $cardUri)); - - $result = $stmt->fetchAll(PDO::FETCH_ASSOC); - - return (count($result)>0?$result[0]:false); - - } - - /** - * Creates a new card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - public function createCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('INSERT INTO `' . $this->cardsTableName . '` (carddata, uri, lastmodified, addressbookid) VALUES (?, ?, ?, ?)'); - - $result = $stmt->execute(array($cardData, $cardUri, time(), $addressBookId)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $result; - - } - - /** - * Updates a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - public function updateCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('UPDATE `' . $this->cardsTableName . '` SET carddata = ?, lastmodified = ? WHERE uri = ? AND addressbookid =?'); - $result = $stmt->execute(array($cardData, time(), $cardUri, $addressBookId)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $stmt->rowCount()===1; - - } - - /** - * Deletes a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return bool - */ - public function deleteCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->cardsTableName . '` WHERE addressbookid = ? AND uri = ?'); - $stmt->execute(array($addressBookId, $cardUri)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $stmt->rowCount()===1; - - } -} diff --git a/3rdparty/Sabre/CardDAV/Card.php b/3rdparty/Sabre/CardDAV/Card.php deleted file mode 100644 index 2844eaf7ed..0000000000 --- a/3rdparty/Sabre/CardDAV/Card.php +++ /dev/null @@ -1,220 +0,0 @@ -carddavBackend = $carddavBackend; - $this->addressBookInfo = $addressBookInfo; - $this->cardData = $cardData; - - } - - /** - * Returns the uri for this object - * - * @return string - */ - public function getName() { - - return $this->cardData['uri']; - - } - - /** - * Returns the VCard-formatted object - * - * @return string - */ - public function get() { - - $cardData = $this->cardData['carddata']; - $s = fopen('php://temp','r+'); - fwrite($s, $cardData); - rewind($s); - return $s; - - } - - /** - * Updates the VCard-formatted object - * - * @param string $cardData - * @return void - */ - public function put($cardData) { - - if (is_resource($cardData)) - $cardData = stream_get_contents($cardData); - - // Converting to UTF-8, if needed - $cardData = Sabre_DAV_StringUtil::ensureUTF8($cardData); - - $this->carddavBackend->updateCard($this->addressBookInfo['id'],$this->cardData['uri'],$cardData); - $this->cardData['carddata'] = $cardData; - - } - - /** - * Deletes the card - * - * @return void - */ - public function delete() { - - $this->carddavBackend->deleteCard($this->addressBookInfo['id'],$this->cardData['uri']); - - } - - /** - * Returns the mime content-type - * - * @return string - */ - public function getContentType() { - - return 'text/x-vcard'; - - } - - /** - * Returns an ETag for this object - * - * @return string - */ - public function getETag() { - - return '"' . md5($this->cardData['carddata']) . '"'; - - } - - /** - * Returns the last modification date as a unix timestamp - * - * @return time - */ - public function getLastModified() { - - return isset($this->cardData['lastmodified'])?$this->cardData['lastmodified']:null; - - } - - /** - * Returns the size of this object in bytes - * - * @return int - */ - public function getSize() { - - return strlen($this->cardData['carddata']); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->addressBookInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - -} - diff --git a/3rdparty/Sabre/CardDAV/IAddressBook.php b/3rdparty/Sabre/CardDAV/IAddressBook.php deleted file mode 100644 index a0dffb30ae..0000000000 --- a/3rdparty/Sabre/CardDAV/IAddressBook.php +++ /dev/null @@ -1,18 +0,0 @@ -subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); - $server->subscribeEvent('report', array($this,'report')); - - /* Namespaces */ - $server->xmlNamespaces[self::NS_CARDDAV] = 'card'; - - /* Mapping Interfaces to {DAV:}resourcetype values */ - $server->resourceTypeMapping['Sabre_CardDAV_IAddressBook'] = '{' . self::NS_CARDDAV . '}addressbook'; - $server->resourceTypeMapping['Sabre_CardDAV_IDirectory'] = '{' . self::NS_CARDDAV . '}directory'; - - /* Adding properties that may never be changed */ - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-address-data'; - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}max-resource-size'; - - - $this->server = $server; - - } - - /** - * Returns a list of supported features. - * - * This is used in the DAV: header in the OPTIONS and PROPFIND requests. - * - * @return array - */ - public function getFeatures() { - - return array('addressbook'); - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_CardDAV_IAddressBook || $node instanceof Sabre_CardDAV_ICard) { - return array( - '{' . self::NS_CARDDAV . '}addressbook-multiget', - '{' . self::NS_CARDDAV . '}addressbook-query', - ); - } - return array(); - - } - - - /** - * Adds all CardDAV-specific properties - * - * @param string $path - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void - */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, array &$requestedProperties, array &$returnedProperties) { - - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - // calendar-home-set property - $addHome = '{' . self::NS_CARDDAV . '}addressbook-home-set'; - if (in_array($addHome,$requestedProperties)) { - $principalId = $node->getName(); - $addressbookHomePath = self::ADDRESSBOOK_ROOT . '/' . $principalId . '/'; - unset($requestedProperties[array_search($addHome, $requestedProperties)]); - $returnedProperties[200][$addHome] = new Sabre_DAV_Property_Href($addressbookHomePath); - } - - $directories = '{' . self::NS_CARDDAV . '}directory-gateway'; - if ($this->directories && in_array($directories, $requestedProperties)) { - unset($requestedProperties[array_search($directories, $requestedProperties)]); - $returnedProperties[200][$directories] = new Sabre_DAV_Property_HrefList($this->directories); - } - - } - - if ($node instanceof Sabre_CardDAV_ICard) { - - // The address-data property is not supposed to be a 'real' - // property, but in large chunks of the spec it does act as such. - // Therefore we simply expose it as a property. - $addressDataProp = '{' . self::NS_CARDDAV . '}address-data'; - if (in_array($addressDataProp, $requestedProperties)) { - unset($requestedProperties[$addressDataProp]); - $val = $node->get(); - if (is_resource($val)) - $val = stream_get_contents($val); - - // Taking out \r to not screw up the xml output - $returnedProperties[200][$addressDataProp] = str_replace("\r","", $val); - - } - } - - } - - /** - * This functions handles REPORT requests specific to CardDAV - * - * @param string $reportName - * @param DOMNode $dom - * @return bool - */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CARDDAV.'}addressbook-multiget' : - $this->addressbookMultiGetReport($dom); - return false; - case '{'.self::NS_CARDDAV.'}addressbook-query' : - $this->addressBookQueryReport($dom); - return false; - default : - return; - - } - - - } - - /** - * This function handles the addressbook-multiget REPORT. - * - * This report is used by the client to fetch the content of a series - * of urls. Effectively avoiding a lot of redundant requests. - * - * @param DOMNode $dom - * @return void - */ - public function addressbookMultiGetReport($dom) { - - $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); - $propertyList = array(); - - foreach($hrefElems as $elem) { - - $uri = $this->server->calculateUri($elem->nodeValue); - list($propertyList[]) = $this->server->getPropertiesForPath($uri,$properties); - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - - } - - /** - * This function handles the addressbook-query REPORT - * - * This report is used by the client to filter an addressbook based on a - * complex query. - * - * @param DOMNode $dom - * @return void - */ - protected function addressbookQueryReport($dom) { - - $query = new Sabre_CardDAV_AddressBookQueryParser($dom); - $query->parse(); - - $depth = $this->server->getHTTPDepth(0); - - if ($depth==0) { - $candidateNodes = array( - $this->server->tree->getNodeForPath($this->server->getRequestUri()) - ); - } else { - $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); - } - - $validNodes = array(); - foreach($candidateNodes as $node) { - - if (!$node instanceof Sabre_CardDAV_ICard) - continue; - - $blob = $node->get(); - if (is_resource($blob)) { - $blob = stream_get_contents($blob); - } - - if (!$this->validateFilters($blob, $query->filters, $query->test)) { - continue; - } - - $validNodes[] = $node; - - if ($query->limit && $query->limit <= count($validNodes)) { - // We hit the maximum number of items, we can stop now. - break; - } - - } - - $result = array(); - foreach($validNodes as $validNode) { - if ($depth==0) { - $href = $this->server->getRequestUri(); - } else { - $href = $this->server->getRequestUri() . '/' . $validNode->getName(); - } - - list($result[]) = $this->server->getPropertiesForPath($href, $query->requestedProperties, 0); - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($result)); - - } - - /** - * Validates if a vcard makes it throught a list of filters. - * - * @param string $vcardData - * @param array $filters - * @param string $test anyof or allof (which means OR or AND) - * @return bool - */ - public function validateFilters($vcardData, array $filters, $test) { - - $vcard = Sabre_VObject_Reader::read($vcardData); - - $success = true; - - foreach($filters as $filter) { - - $isDefined = isset($vcard->{$filter['name']}); - if ($filter['is-not-defined']) { - if ($isDefined) { - $success = false; - } else { - $success = true; - } - } elseif ((!$filter['param-filters'] && !$filter['text-matches']) || !$isDefined) { - - // We only need to check for existence - $success = $isDefined; - - } else { - - $vProperties = $vcard->select($filter['name']); - - $results = array(); - if ($filter['param-filters']) { - $results[] = $this->validateParamFilters($vProperties, $filter['param-filters'], $filter['test']); - } - if ($filter['text-matches']) { - $texts = array(); - foreach($vProperties as $vProperty) - $texts[] = $vProperty->value; - - $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']); - } - - if (count($results)===1) { - $success = $results[0]; - } else { - if ($filter['test'] === 'anyof') { - $success = $results[0] || $results[1]; - } else { - $success = $results[0] && $results[1]; - } - } - - } // else - - // There are two conditions where we can already determine wether - // or not this filter succeeds. - if ($test==='anyof' && $success) { - return true; - } - if ($test==='allof' && !$success) { - return false; - } - - } // foreach - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - /** - * Validates if a param-filter can be applied to a specific property. - * - * @todo currently we're only validating the first parameter of the passed - * property. Any subsequence parameters with the same name are - * ignored. - * @param Sabre_VObject_Property $vProperty - * @param array $filters - * @param string $test - * @return bool - */ - protected function validateParamFilters(array $vProperties, array $filters, $test) { - - $success = false; - foreach($filters as $filter) { - - $isDefined = false; - foreach($vProperties as $vProperty) { - $isDefined = isset($vProperty[$filter['name']]); - if ($isDefined) break; - } - - if ($filter['is-not-defined']) { - if ($isDefined) { - $success = false; - } else { - $success = true; - } - - // If there's no text-match, we can just check for existence - } elseif (!$filter['text-match'] || !$isDefined) { - - $success = $isDefined; - - } else { - - $texts = array(); - $success = false; - foreach($vProperties as $vProperty) { - // If we got all the way here, we'll need to validate the - // text-match filter. - $success = Sabre_DAV_StringUtil::textMatch($vProperty[$filter['name']]->value, $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']); - if ($success) break; - } - if ($filter['text-match']['negate-condition']) { - $success = !$success; - } - - } // else - - // There are two conditions where we can already determine wether - // or not this filter succeeds. - if ($test==='anyof' && $success) { - return true; - } - if ($test==='allof' && !$success) { - return false; - } - - } - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - /** - * Validates if a text-filter can be applied to a specific property. - * - * @param array $texts - * @param array $filters - * @param string $test - * @return bool - */ - protected function validateTextMatches(array $texts, array $filters, $test) { - - foreach($filters as $filter) { - - $success = false; - foreach($texts as $haystack) { - $success = Sabre_DAV_StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']); - - // Breaking on the first match - if ($success) break; - } - if ($filter['negate-condition']) { - $success = !$success; - } - - if ($success && $test==='anyof') - return true; - - if (!$success && $test=='allof') - return false; - - - } - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - -} diff --git a/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php b/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php deleted file mode 100644 index d57d3a6e7b..0000000000 --- a/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php +++ /dev/null @@ -1,69 +0,0 @@ - 'text/vcard', 'version' => '3.0'), - array('contentType' => 'text/vcard', 'version' => '4.0'), - ); - } - - $this->supportedData = $supportedData; - - } - - /** - * Serializes the property in a DOMDocument - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - - $prefix = - isset($server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV]) ? - $server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV] : - 'card'; - - foreach($this->supportedData as $supported) { - - $caldata = $doc->createElementNS(Sabre_CardDAV_Plugin::NS_CARDDAV, $prefix . ':address-data-type'); - $caldata->setAttribute('content-type',$supported['contentType']); - $caldata->setAttribute('version',$supported['version']); - $node->appendChild($caldata); - - } - - } - -} diff --git a/3rdparty/Sabre/CardDAV/UserAddressBooks.php b/3rdparty/Sabre/CardDAV/UserAddressBooks.php deleted file mode 100644 index e9f2de7f74..0000000000 --- a/3rdparty/Sabre/CardDAV/UserAddressBooks.php +++ /dev/null @@ -1,240 +0,0 @@ -carddavBackend = $carddavBackend; - $this->principalUri = $principalUri; - - } - - /** - * Returns the name of this object - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); - return $name; - - } - - /** - * Updates the name of this object - * - * @param string $name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed(); - - } - - /** - * Deletes this object - * - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_MethodNotAllowed(); - - } - - /** - * Returns the last modification date - * - * @return int - */ - public function getLastModified() { - - return null; - - } - - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @return void - */ - public function createFile($filename, $data=null) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - - } - - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @return void - */ - public function createDirectory($filename) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - - } - - /** - * Returns a single calendar, by name - * - * @param string $name - * @todo needs optimizing - * @return Sabre_CardDAV_AddressBook - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('Addressbook with name \'' . $name . '\' could not be found'); - - } - - /** - * Returns a list of addressbooks - * - * @return array - */ - public function getChildren() { - - $addressbooks = $this->carddavBackend->getAddressbooksForUser($this->principalUri); - $objs = array(); - foreach($addressbooks as $addressbook) { - $objs[] = new Sabre_CardDAV_AddressBook($this->carddavBackend, $addressbook); - } - return $objs; - - } - - /** - * Creates a new addressbook - * - * @param string $name - * @param array $resourceType - * @param array $properties - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook',$resourceType) || count($resourceType)!==2) { - throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); - } - $this->carddavBackend->createAddressBook($this->principalUri, $name, $properties); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalUri; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalUri, - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalUri, - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - -} diff --git a/3rdparty/Sabre/CardDAV/Version.php b/3rdparty/Sabre/CardDAV/Version.php deleted file mode 100644 index 900fbf5e75..0000000000 --- a/3rdparty/Sabre/CardDAV/Version.php +++ /dev/null @@ -1,26 +0,0 @@ -currentUser; - } - - - /** - * Authenticates the user based on the current request. - * - * If authentication is succesful, true must be returned. - * If authentication fails, an exception must be thrown. - * - * @throws Sabre_DAV_Exception_NotAuthenticated - * @return bool - */ - public function authenticate(Sabre_DAV_Server $server,$realm) { - - $auth = new Sabre_HTTP_BasicAuth(); - $auth->setHTTPRequest($server->httpRequest); - $auth->setHTTPResponse($server->httpResponse); - $auth->setRealm($realm); - $userpass = $auth->getUserPass(); - if (!$userpass) { - $auth->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('No basic authentication headers were found'); - } - - // Authenticates the user - if (!$this->validateUserPass($userpass[0],$userpass[1])) { - $auth->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('Username or password does not match'); - } - $this->currentUser = $userpass[0]; - return true; - } - - -} - diff --git a/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php b/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php deleted file mode 100644 index 5bdc72753e..0000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php +++ /dev/null @@ -1,96 +0,0 @@ -setHTTPRequest($server->httpRequest); - $digest->setHTTPResponse($server->httpResponse); - - $digest->setRealm($realm); - $digest->init(); - - $username = $digest->getUsername(); - - // No username was given - if (!$username) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('No digest authentication headers were found'); - } - - $hash = $this->getDigestHash($realm, $username); - // If this was false, the user account didn't exist - if ($hash===false || is_null($hash)) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('The supplied username was not on file'); - } - if (!is_string($hash)) { - throw new Sabre_DAV_Exception('The returned value from getDigestHash must be a string or null'); - } - - // If this was false, the password or part of the hash was incorrect. - if (!$digest->validateA1($hash)) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('Incorrect username'); - } - - $this->currentUser = $username; - return true; - - } - - /** - * Returns the currently logged in username. - * - * @return string|null - */ - public function getCurrentUser() { - - return $this->currentUser; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/Apache.php b/3rdparty/Sabre/DAV/Auth/Backend/Apache.php deleted file mode 100644 index 6bcd76bdcb..0000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/Apache.php +++ /dev/null @@ -1,60 +0,0 @@ -httpRequest->getRawServerValue('REMOTE_USER'); - if (is_null($remoteUser)) { - throw new Sabre_DAV_Exception('We did not receive the $_SERVER[REMOTE_USER] property. This means that apache might have been misconfigured'); - } - - $this->remoteUser = $remoteUser; - return true; - - } - - /** - * Returns information about the currently logged in user. - * - * If nobody is currently logged in, this method should return null. - * - * @return array|null - */ - public function getCurrentUser() { - - return $this->remoteUser; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Auth/Backend/File.php b/3rdparty/Sabre/DAV/Auth/Backend/File.php deleted file mode 100644 index db1f04c477..0000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/File.php +++ /dev/null @@ -1,76 +0,0 @@ -loadFile($filename); - - } - - /** - * Loads an htdigest-formatted file. This method can be called multiple times if - * more than 1 file is used. - * - * @param string $filename - * @return void - */ - public function loadFile($filename) { - - foreach(file($filename,FILE_IGNORE_NEW_LINES) as $line) { - - if (substr_count($line, ":") !== 2) - throw new Sabre_DAV_Exception('Malformed htdigest file. Every line should contain 2 colons'); - - list($username,$realm,$A1) = explode(':',$line); - - if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) - throw new Sabre_DAV_Exception('Malformed htdigest file. Invalid md5 hash'); - - $this->users[$realm . ':' . $username] = $A1; - - } - - } - - /** - * Returns a users' information - * - * @param string $realm - * @param string $username - * @return string - */ - public function getDigestHash($realm, $username) { - - return isset($this->users[$realm . ':' . $username])?$this->users[$realm . ':' . $username]:false; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/PDO.php b/3rdparty/Sabre/DAV/Auth/Backend/PDO.php deleted file mode 100644 index 0301503601..0000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/PDO.php +++ /dev/null @@ -1,66 +0,0 @@ -pdo = $pdo; - $this->tableName = $tableName; - - } - - /** - * Returns the digest hash for a user. - * - * @param string $realm - * @param string $username - * @return string|null - */ - public function getDigestHash($realm,$username) { - - $stmt = $this->pdo->prepare('SELECT username, digesta1 FROM `'.$this->tableName.'` WHERE username = ?'); - $stmt->execute(array($username)); - $result = $stmt->fetchAll(); - - if (!count($result)) return; - - return $result[0]['digesta1']; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/IBackend.php b/3rdparty/Sabre/DAV/Auth/IBackend.php deleted file mode 100644 index 1f67af4c2d..0000000000 --- a/3rdparty/Sabre/DAV/Auth/IBackend.php +++ /dev/null @@ -1,34 +0,0 @@ -authBackend = $authBackend; - $this->realm = $realm; - - } - - /** - * Initializes the plugin. This function is automatically called by the server - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),10); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'auth'; - - } - - /** - * Returns the current users' principal uri. - * - * If nobody is logged in, this will return null. - * - * @return string|null - */ - public function getCurrentUser() { - - $userInfo = $this->authBackend->getCurrentUser(); - if (!$userInfo) return null; - - return $userInfo; - - } - - /** - * This method is called before any HTTP method and forces users to be authenticated - * - * @param string $method - * @throws Sabre_DAV_Exception_NotAuthenticated - * @return bool - */ - public function beforeMethod($method, $uri) { - - $this->authBackend->authenticate($this->server,$this->realm); - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/GuessContentType.php b/3rdparty/Sabre/DAV/Browser/GuessContentType.php deleted file mode 100644 index ee8c698d78..0000000000 --- a/3rdparty/Sabre/DAV/Browser/GuessContentType.php +++ /dev/null @@ -1,97 +0,0 @@ - 'image/jpeg', - 'gif' => 'image/gif', - 'png' => 'image/png', - - // groupware - 'ics' => 'text/calendar', - 'vcf' => 'text/x-vcard', - - // text - 'txt' => 'text/plain', - - ); - - /** - * Initializes the plugin - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - // Using a relatively low priority (200) to allow other extensions - // to set the content-type first. - $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties'),200); - - } - - /** - * Handler for teh afterGetProperties event - * - * @param string $path - * @param array $properties - * @return void - */ - public function afterGetProperties($path, &$properties) { - - if (array_key_exists('{DAV:}getcontenttype', $properties[404])) { - - list(, $fileName) = Sabre_DAV_URLUtil::splitPath($path); - $contentType = $this->getContentType($fileName); - - if ($contentType) { - $properties[200]['{DAV:}getcontenttype'] = $contentType; - unset($properties[404]['{DAV:}getcontenttype']); - } - - } - - } - - /** - * Simple method to return the contenttype - * - * @param string $fileName - * @return string - */ - protected function getContentType($fileName) { - - // Just grabbing the extension - $extension = strtolower(substr($fileName,strrpos($fileName,'.')+1)); - if (isset($this->extensionMap[$extension])) - return $this->extensionMap[$extension]; - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php b/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php deleted file mode 100644 index a66b57a3a9..0000000000 --- a/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php +++ /dev/null @@ -1,54 +0,0 @@ -server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); - } - - /** - * This method intercepts GET requests to non-files, and changes it into an HTTP PROPFIND request - * - * @param string $method - * @return bool - */ - public function httpGetInterceptor($method, $uri) { - - if ($method!='GET') return true; - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_IFile) return; - - $this->server->invokeMethod('PROPFIND',$uri); - return false; - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/Plugin.php b/3rdparty/Sabre/DAV/Browser/Plugin.php deleted file mode 100644 index cd5617babb..0000000000 --- a/3rdparty/Sabre/DAV/Browser/Plugin.php +++ /dev/null @@ -1,285 +0,0 @@ -enablePost = $enablePost; - - } - - /** - * Initializes the plugin and subscribes to events - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); - if ($this->enablePost) $this->server->subscribeEvent('unknownMethod',array($this,'httpPOSTHandler')); - } - - /** - * This method intercepts GET requests to collections and returns the html - * - * @param string $method - * @return bool - */ - public function httpGetInterceptor($method, $uri) { - - if ($method!='GET') return true; - - try { - $node = $this->server->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // We're simply stopping when the file isn't found to not interfere - // with other plugins. - return; - } - if ($node instanceof Sabre_DAV_IFile) - return; - - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','text/html; charset=utf-8'); - - $this->server->httpResponse->sendBody( - $this->generateDirectoryIndex($uri) - ); - - return false; - - } - - /** - * Handles POST requests for tree operations - * - * This method is not yet used. - * - * @param string $method - * @return bool - */ - public function httpPOSTHandler($method, $uri) { - - if ($method!='POST') return true; - if (isset($_POST['sabreAction'])) switch($_POST['sabreAction']) { - - case 'mkcol' : - if (isset($_POST['name']) && trim($_POST['name'])) { - // Using basename() because we won't allow slashes - list(, $folderName) = Sabre_DAV_URLUtil::splitPath(trim($_POST['name'])); - $this->server->createDirectory($uri . '/' . $folderName); - } - break; - case 'put' : - if ($_FILES) $file = current($_FILES); - else break; - $newName = trim($file['name']); - list(, $newName) = Sabre_DAV_URLUtil::splitPath(trim($file['name'])); - if (isset($_POST['name']) && trim($_POST['name'])) - $newName = trim($_POST['name']); - - // Making sure we only have a 'basename' component - list(, $newName) = Sabre_DAV_URLUtil::splitPath($newName); - - - if (is_uploaded_file($file['tmp_name'])) { - $parent = $this->server->tree->getNodeForPath(trim($uri,'/')); - $parent->createFile($newName,fopen($file['tmp_name'],'r')); - } - - } - $this->server->httpResponse->setHeader('Location',$this->server->httpRequest->getUri()); - return false; - - } - - /** - * Escapes a string for html. - * - * @param string $value - * @return void - */ - public function escapeHTML($value) { - - return htmlspecialchars($value,ENT_QUOTES,'UTF-8'); - - } - - /** - * Generates the html directory index for a given url - * - * @param string $path - * @return string - */ - public function generateDirectoryIndex($path) { - - $html = " - - Index for " . $this->escapeHTML($path) . "/ - SabreDAV " . Sabre_DAV_Version::VERSION . " - - - -

Index for " . $this->escapeHTML($path) . "/

- - - "; - - $files = $this->server->getPropertiesForPath($path,array( - '{DAV:}displayname', - '{DAV:}resourcetype', - '{DAV:}getcontenttype', - '{DAV:}getcontentlength', - '{DAV:}getlastmodified', - ),1); - - $parent = $this->server->tree->getNodeForPath($path); - - - if ($path) { - - list($parentUri) = Sabre_DAV_URLUtil::splitPath($path); - $fullPath = Sabre_DAV_URLUtil::encodePath($this->server->getBaseUri() . $parentUri); - - $html.= " - - - - -"; - - } - - foreach($files as $k=>$file) { - - // This is the current directory, we can skip it - if (rtrim($file['href'],'/')==$path) continue; - - list(, $name) = Sabre_DAV_URLUtil::splitPath($file['href']); - - $type = null; - - - if (isset($file[200]['{DAV:}resourcetype'])) { - $type = $file[200]['{DAV:}resourcetype']->getValue(); - - // resourcetype can have multiple values - if (!is_array($type)) $type = array($type); - - foreach($type as $k=>$v) { - - // Some name mapping is preferred - switch($v) { - case '{DAV:}collection' : - $type[$k] = 'Collection'; - break; - case '{DAV:}principal' : - $type[$k] = 'Principal'; - break; - case '{urn:ietf:params:xml:ns:carddav}addressbook' : - $type[$k] = 'Addressbook'; - break; - case '{urn:ietf:params:xml:ns:caldav}calendar' : - $type[$k] = 'Calendar'; - break; - } - - } - $type = implode(', ', $type); - } - - // If no resourcetype was found, we attempt to use - // the contenttype property - if (!$type && isset($file[200]['{DAV:}getcontenttype'])) { - $type = $file[200]['{DAV:}getcontenttype']; - } - if (!$type) $type = 'Unknown'; - - $size = isset($file[200]['{DAV:}getcontentlength'])?(int)$file[200]['{DAV:}getcontentlength']:''; - $lastmodified = isset($file[200]['{DAV:}getlastmodified'])?$file[200]['{DAV:}getlastmodified']->getTime()->format(DateTime::ATOM):''; - - $fullPath = Sabre_DAV_URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path?$path . '/':'') . $name,'/')); - - $displayName = isset($file[200]['{DAV:}displayname'])?$file[200]['{DAV:}displayname']:$name; - - $name = $this->escapeHTML($name); - $displayName = $this->escapeHTML($displayName); - $type = $this->escapeHTML($type); - - $html.= " - - - - -"; - - } - - $html.= ""; - - if ($this->enablePost && $parent instanceof Sabre_DAV_ICollection) { - $html.= ''; - } - - $html.= "
NameTypeSizeLast modified

..[parent]
{$displayName}{$type}{$size}{$lastmodified}

-

Create new folder

- - Name:
- -
-
-

Upload file

- - Name (optional):
- File:
- -
-
-
Generated by SabreDAV " . Sabre_DAV_Version::VERSION ."-". Sabre_DAV_Version::STABILITY . " (c)2007-2011 http://code.google.com/p/sabredav/
- -"; - - return $html; - - } - -} diff --git a/3rdparty/Sabre/DAV/Client.php b/3rdparty/Sabre/DAV/Client.php deleted file mode 100644 index fc6a6fff08..0000000000 --- a/3rdparty/Sabre/DAV/Client.php +++ /dev/null @@ -1,431 +0,0 @@ -$validSetting = $settings[$validSetting]; - } - } - - $this->propertyMap['{DAV:}resourcetype'] = 'Sabre_DAV_Property_ResourceType'; - - } - - /** - * Does a PROPFIND request - * - * The list of requested properties must be specified as an array, in clark - * notation. - * - * The returned array will contain a list of filenames as keys, and - * properties as values. - * - * The properties array will contain the list of properties. Only properties - * that are actually returned from the server (without error) will be - * returned, anything else is discarded. - * - * Depth should be either 0 or 1. A depth of 1 will cause a request to be - * made to the server to also return all child resources. - * - * @param string $url - * @param array $properties - * @param int $depth - * @return array - */ - public function propFind($url, array $properties, $depth = 0) { - - $body = '' . "\n"; - $body.= '' . "\n"; - $body.= ' ' . "\n"; - - foreach($properties as $property) { - - list( - $namespace, - $elementName - ) = Sabre_DAV_XMLUtil::parseClarkNotation($property); - - if ($namespace === 'DAV:') { - $body.=' ' . "\n"; - } else { - $body.=" \n"; - } - - } - - $body.= ' ' . "\n"; - $body.= ''; - - $response = $this->request('PROPFIND', $url, $body, array( - 'Depth' => $depth, - 'Content-Type' => 'application/xml' - )); - - $result = $this->parseMultiStatus($response['body']); - - // If depth was 0, we only return the top item - if ($depth===0) { - reset($result); - $result = current($result); - return $result[200]; - } - - $newResult = array(); - foreach($result as $href => $statusList) { - - $newResult[$href] = $statusList[200]; - - } - - return $newResult; - - } - - /** - * Updates a list of properties on the server - * - * The list of properties must have clark-notation properties for the keys, - * and the actual (string) value for the value. If the value is null, an - * attempt is made to delete the property. - * - * @todo Must be building the request using the DOM, and does not yet - * support complex properties. - * @param string $url - * @param array $properties - * @return void - */ - public function propPatch($url, array $properties) { - - $body = '' . "\n"; - $body.= '' . "\n"; - - foreach($properties as $propName => $propValue) { - - list( - $namespace, - $elementName - ) = Sabre_DAV_XMLUtil::parseClarkNotation($propName); - - if ($propValue === null) { - - $body.="\n"; - - if ($namespace === 'DAV:') { - $body.=' ' . "\n"; - } else { - $body.=" \n"; - } - - $body.="\n"; - - } else { - - $body.="\n"; - if ($namespace === 'DAV:') { - $body.=' '; - } else { - $body.=" "; - } - // Shitty.. i know - $body.=htmlspecialchars($propValue, ENT_NOQUOTES, 'UTF-8'); - if ($namespace === 'DAV:') { - $body.='' . "\n"; - } else { - $body.="\n"; - } - $body.="\n"; - - } - - } - - $body.= ''; - - $response = $this->request('PROPPATCH', $url, $body, array( - 'Content-Type' => 'application/xml' - )); - - } - - /** - * Performs an HTTP options request - * - * This method returns all the features from the 'DAV:' header as an array. - * If there was no DAV header, or no contents this method will return an - * empty array. - * - * @return array - */ - public function options() { - - $result = $this->request('OPTIONS'); - if (!isset($result['headers']['dav'])) { - return array(); - } - - $features = explode(',', $result['headers']['dav']); - foreach($features as &$v) { - $v = trim($v); - } - return $features; - - } - - /** - * Performs an actual HTTP request, and returns the result. - * - * If the specified url is relative, it will be expanded based on the base - * url. - * - * The returned array contains 3 keys: - * * body - the response body - * * httpCode - a HTTP code (200, 404, etc) - * * headers - a list of response http headers. The header names have - * been lowercased. - * - * @param string $method - * @param string $url - * @param string $body - * @param array $headers - * @return array - */ - public function request($method, $url = '', $body = null, $headers = array()) { - - $url = $this->getAbsoluteUrl($url); - - $curlSettings = array( - CURLOPT_RETURNTRANSFER => true, - CURLOPT_CUSTOMREQUEST => $method, - CURLOPT_POSTFIELDS => $body, - // Return headers as part of the response - CURLOPT_HEADER => true - ); - - // Adding HTTP headers - $nHeaders = array(); - foreach($headers as $key=>$value) { - - $nHeaders[] = $key . ': ' . $value; - - } - $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders; - - if ($this->proxy) { - $curlSettings[CURLOPT_PROXY] = $this->proxy; - } - - if ($this->userName) { - $curlSettings[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC | CURLAUTH_DIGEST; - $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password; - } - - list( - $response, - $curlInfo, - $curlErrNo, - $curlError - ) = $this->curlRequest($url, $curlSettings); - - $headerBlob = substr($response, 0, $curlInfo['header_size']); - $response = substr($response, $curlInfo['header_size']); - - // In the case of 100 Continue, or redirects we'll have multiple lists - // of headers for each separate HTTP response. We can easily split this - // because they are separated by \r\n\r\n - $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n")); - - // We only care about the last set of headers - $headerBlob = $headerBlob[count($headerBlob)-1]; - - // Splitting headers - $headerBlob = explode("\r\n", $headerBlob); - - $headers = array(); - foreach($headerBlob as $header) { - $parts = explode(':', $header, 2); - if (count($parts)==2) { - $headers[strtolower(trim($parts[0]))] = trim($parts[1]); - } - } - - $response = array( - 'body' => $response, - 'statusCode' => $curlInfo['http_code'], - 'headers' => $headers - ); - - if ($curlErrNo) { - throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')'); - } - - if ($response['statusCode']>=400) { - throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')'); - } - - return $response; - - } - - /** - * Wrapper for all curl functions. - * - * The only reason this was split out in a separate method, is so it - * becomes easier to unittest. - * - * @param string $url - * @param array $settings - * @return - */ - protected function curlRequest($url, $settings) { - - $curl = curl_init($url); - curl_setopt_array($curl, $settings); - - return array( - curl_exec($curl), - curl_getinfo($curl), - curl_errno($curl), - curl_error($curl) - ); - - } - - /** - * Returns the full url based on the given url (which may be relative). All - * urls are expanded based on the base url as given by the server. - * - * @param string $url - * @return string - */ - protected function getAbsoluteUrl($url) { - - // If the url starts with http:// or https://, the url is already absolute. - if (preg_match('/^http(s?):\/\//', $url)) { - return $url; - } - - // If the url starts with a slash, we must calculate the url based off - // the root of the base url. - if (strpos($url,'/') === 0) { - $parts = parse_url($this->baseUri); - return $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port'])?':' . $parts['port']:'') . $url; - } - - // Otherwise... - return $this->baseUri . $url; - - } - - /** - * Parses a WebDAV multistatus response body - * - * This method returns an array with the following structure - * - * array( - * 'url/to/resource' => array( - * '200' => array( - * '{DAV:}property1' => 'value1', - * '{DAV:}property2' => 'value2', - * ), - * '404' => array( - * '{DAV:}property1' => null, - * '{DAV:}property2' => null, - * ), - * ) - * 'url/to/resource2' => array( - * .. etc .. - * ) - * ) - * - * - * @param string $body xml body - * @return array - */ - public function parseMultiStatus($body) { - - $body = Sabre_DAV_XMLUtil::convertDAVNamespace($body); - - $responseXML = simplexml_load_string($body, null, LIBXML_NOBLANKS | LIBXML_NOCDATA); - if ($responseXML===false) { - throw new InvalidArgumentException('The passed data is not valid XML'); - } - - $responseXML->registerXPathNamespace('d','DAV:'); - - $propResult = array(); - - foreach($responseXML->xpath('d:response') as $response) { - - $response->registerXPathNamespace('d','DAV:'); - $href = $response->xpath('d:href'); - $href = (string)$href[0]; - - $properties = array(); - - foreach($response->xpath('d:propstat') as $propStat) { - - $propStat->registerXPathNamespace('d','DAV:'); - $status = $propStat->xpath('d:status'); - list($httpVersion, $statusCode, $message) = explode(' ', (string)$status[0],3); - - $properties[$statusCode] = Sabre_DAV_XMLUtil::parseProperties(dom_import_simplexml($propStat), $this->propertyMap); - - } - - $propResult[$href] = $properties; - - } - - return $propResult; - - } - -} diff --git a/3rdparty/Sabre/DAV/Collection.php b/3rdparty/Sabre/DAV/Collection.php deleted file mode 100644 index 9da04c1279..0000000000 --- a/3rdparty/Sabre/DAV/Collection.php +++ /dev/null @@ -1,90 +0,0 @@ -getChildren() as $child) { - - if ($child->getName()==$name) return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('File not found: ' . $name); - - } - - /** - * Checks is a child-node exists. - * - * It is generally a good idea to try and override this. Usually it can be optimized. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - try { - - $this->getChild($name); - return true; - - } catch(Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Creates a new file in the directory - * - * @param string $name Name of the file - * @param resource $data Initial payload, passed as a readable stream resource. - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createFile($name, $data = null) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create file (filename ' . $name . ')'); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create directory'); - - } - - -} - diff --git a/3rdparty/Sabre/DAV/Directory.php b/3rdparty/Sabre/DAV/Directory.php deleted file mode 100644 index 86af4827b3..0000000000 --- a/3rdparty/Sabre/DAV/Directory.php +++ /dev/null @@ -1,17 +0,0 @@ -lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:no-conflicting-lock'); - $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/FileNotFound.php b/3rdparty/Sabre/DAV/Exception/FileNotFound.php deleted file mode 100644 index b20e4a2fb3..0000000000 --- a/3rdparty/Sabre/DAV/Exception/FileNotFound.php +++ /dev/null @@ -1,28 +0,0 @@ -ownerDocument->createElementNS('DAV:','d:valid-resourcetype'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php b/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php deleted file mode 100644 index 47032cffc7..0000000000 --- a/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php +++ /dev/null @@ -1,39 +0,0 @@ -message = 'The locktoken supplied does not match any locks on this entity'; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-matches-request-uri'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/Locked.php b/3rdparty/Sabre/DAV/Exception/Locked.php deleted file mode 100644 index b4bb2e0378..0000000000 --- a/3rdparty/Sabre/DAV/Exception/Locked.php +++ /dev/null @@ -1,67 +0,0 @@ -lock = $lock; - - } - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 423; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - if ($this->lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-submitted'); - $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php b/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php deleted file mode 100644 index 02c145ffeb..0000000000 --- a/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php +++ /dev/null @@ -1,44 +0,0 @@ -getAllowedMethods($server->getRequestUri()); - - return array( - 'Allow' => strtoupper(implode(', ',$methods)), - ); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php b/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php deleted file mode 100644 index 1faffddfa0..0000000000 --- a/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php +++ /dev/null @@ -1,28 +0,0 @@ -header = $header; - - } - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 412; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - if ($this->header) { - $prop = $errorNode->ownerDocument->createElement('s:header'); - $prop->nodeValue = $this->header; - $errorNode->appendChild($prop); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php b/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php deleted file mode 100644 index e4ed601b16..0000000000 --- a/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php +++ /dev/null @@ -1,30 +0,0 @@ -ownerDocument->createElementNS('DAV:','d:supported-report'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php b/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php deleted file mode 100644 index 37abbd729d..0000000000 --- a/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php +++ /dev/null @@ -1,29 +0,0 @@ -path . '/' . $name; - file_put_contents($newPath,$data); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - $newPath = $this->path . '/' . $name; - mkdir($newPath); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File with name ' . $path . ' could not be located'); - - if (is_dir($path)) { - - return new Sabre_DAV_FS_Directory($path); - - } else { - - return new Sabre_DAV_FS_File($path); - - } - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..') $nodes[] = $this->getChild($node); - return $nodes; - - } - - /** - * Checks if a child exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - $path = $this->path . '/' . $name; - return file_exists($path); - - } - - /** - * Deletes all files in this directory, and then itself - * - * @return void - */ - public function delete() { - - foreach($this->getChildren() as $child) $child->delete(); - rmdir($this->path); - - } - - /** - * Returns available diskspace information - * - * @return array - */ - public function getQuotaInfo() { - - return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) - ); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FS/File.php b/3rdparty/Sabre/DAV/FS/File.php deleted file mode 100644 index 262187d7e8..0000000000 --- a/3rdparty/Sabre/DAV/FS/File.php +++ /dev/null @@ -1,89 +0,0 @@ -path,$data); - - } - - /** - * Returns the data - * - * @return string - */ - public function get() { - - return fopen($this->path,'r'); - - } - - /** - * Delete the current file - * - * @return void - */ - public function delete() { - - unlink($this->path); - - } - - /** - * Returns the size of the node, in bytes - * - * @return int - */ - public function getSize() { - - return filesize($this->path); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - * - * @return mixed - */ - public function getETag() { - - return null; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - * - * @return mixed - */ - public function getContentType() { - - return null; - - } - -} - diff --git a/3rdparty/Sabre/DAV/FS/Node.php b/3rdparty/Sabre/DAV/FS/Node.php deleted file mode 100644 index b8d7bcfe84..0000000000 --- a/3rdparty/Sabre/DAV/FS/Node.php +++ /dev/null @@ -1,81 +0,0 @@ -path = $path; - - } - - - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - - list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); - return $name; - - } - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - - $newPath = $parentPath . '/' . $newName; - rename($this->path,$newPath); - - $this->path = $newPath; - - } - - - - /** - * Returns the last modification time, as a unix timestamp - * - * @return int - */ - public function getLastModified() { - - return filemtime($this->path); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/Directory.php b/3rdparty/Sabre/DAV/FSExt/Directory.php deleted file mode 100644 index c43d4385ac..0000000000 --- a/3rdparty/Sabre/DAV/FSExt/Directory.php +++ /dev/null @@ -1,135 +0,0 @@ -path . '/' . $name; - file_put_contents($newPath,$data); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - // We're not allowing dots - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - $newPath = $this->path . '/' . $name; - mkdir($newPath); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File could not be located'); - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - - if (is_dir($path)) { - - return new Sabre_DAV_FSExt_Directory($path); - - } else { - - return new Sabre_DAV_FSExt_File($path); - - } - - } - - /** - * Checks if a child exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - if ($name=='.' || $name=='..') - throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - - $path = $this->path . '/' . $name; - return file_exists($path); - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..' && $node!='.sabredav') $nodes[] = $this->getChild($node); - return $nodes; - - } - - /** - * Deletes all files in this directory, and then itself - * - * @return void - */ - public function delete() { - - // Deleting all children - foreach($this->getChildren() as $child) $child->delete(); - - // Removing resource info, if its still around - if (file_exists($this->path . '/.sabredav')) unlink($this->path . '/.sabredav'); - - // Removing the directory itself - rmdir($this->path); - - return parent::delete(); - - } - - /** - * Returns available diskspace information - * - * @return array - */ - public function getQuotaInfo() { - - return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) - ); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/File.php b/3rdparty/Sabre/DAV/FSExt/File.php deleted file mode 100644 index 7a8e7a11f2..0000000000 --- a/3rdparty/Sabre/DAV/FSExt/File.php +++ /dev/null @@ -1,88 +0,0 @@ -path,$data); - - } - - /** - * Returns the data - * - * @return string - */ - public function get() { - - return fopen($this->path,'r'); - - } - - /** - * Delete the current file - * - * @return void - */ - public function delete() { - - unlink($this->path); - return parent::delete(); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - */ - public function getETag() { - - return '"' . md5_file($this->path). '"'; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - */ - public function getContentType() { - - return null; - - } - - /** - * Returns the size of the file, in bytes - * - * @return int - */ - public function getSize() { - - return filesize($this->path); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/Node.php b/3rdparty/Sabre/DAV/FSExt/Node.php deleted file mode 100644 index 9e36222bfd..0000000000 --- a/3rdparty/Sabre/DAV/FSExt/Node.php +++ /dev/null @@ -1,276 +0,0 @@ -getResourceData(); - $locks = $resourceData['locks']; - foreach($locks as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($locks[$k]); - } - return $locks; - - } - - /** - * Locks this node - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - function lock(Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - - $resourceData = $this->getResourceData(); - if (!isset($resourceData['locks'])) $resourceData['locks'] = array(); - $current = null; - foreach($resourceData['locks'] as $k=>$lock) { - if ($lock->token === $lockInfo->token) $current = $k; - } - if (!is_null($current)) $resourceData['locks'][$current] = $lockInfo; - else $resourceData['locks'][] = $lockInfo; - - $this->putResourceData($resourceData); - - } - - /** - * Removes a lock from this node - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - function unlock(Sabre_DAV_Locks_LockInfo $lockInfo) { - - //throw new Sabre_DAV_Exception('bla'); - $resourceData = $this->getResourceData(); - foreach($resourceData['locks'] as $k=>$lock) { - - if ($lock->token === $lockInfo->token) { - - unset($resourceData['locks'][$k]); - $this->putResourceData($resourceData); - return true; - - } - } - return false; - - } - - /** - * Updates properties on this node, - * - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateProperties($properties) { - - $resourceData = $this->getResourceData(); - - $result = array(); - - foreach($properties as $propertyName=>$propertyValue) { - - // If it was null, we need to delete the property - if (is_null($propertyValue)) { - if (isset($resourceData['properties'][$propertyName])) { - unset($resourceData['properties'][$propertyName]); - } - } else { - $resourceData['properties'][$propertyName] = $propertyValue; - } - - } - - $this->putResourceData($resourceData); - return true; - } - - /** - * Returns a list of properties for this nodes.; - * - * The properties list is a list of propertynames the client requested, encoded as xmlnamespace#tagName, for example: http://www.example.org/namespace#author - * If the array is empty, all properties should be returned - * - * @param array $properties - * @return void - */ - function getProperties($properties) { - - $resourceData = $this->getResourceData(); - - // if the array was empty, we need to return everything - if (!$properties) return $resourceData['properties']; - - $props = array(); - foreach($properties as $property) { - if (isset($resourceData['properties'][$property])) $props[$property] = $resourceData['properties'][$property]; - } - - return $props; - - } - - /** - * Returns the path to the resource file - * - * @return string - */ - protected function getResourceInfoPath() { - - list($parentDir) = Sabre_DAV_URLUtil::splitPath($this->path); - return $parentDir . '/.sabredav'; - - } - - /** - * Returns all the stored resource information - * - * @return array - */ - protected function getResourceData() { - - $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return array('locks'=>array(), 'properties' => array()); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); - $data = ''; - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!isset($data[$this->getName()])) { - return array('locks'=>array(), 'properties' => array()); - } - - $data = $data[$this->getName()]; - if (!isset($data['locks'])) $data['locks'] = array(); - if (!isset($data['properties'])) $data['properties'] = array(); - return $data; - - } - - /** - * Updates the resource information - * - * @param array $newData - * @return void - */ - protected function putResourceData(array $newData) { - - $path = $this->getResourceInfoPath(); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - $data = ''; - - rewind($handle); - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - $data[$this->getName()] = $newData; - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($data)); - fclose($handle); - - } - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - $newPath = $parentPath . '/' . $newName; - - // We're deleting the existing resourcedata, and recreating it - // for the new path. - $resourceData = $this->getResourceData(); - $this->deleteResourceData(); - - rename($this->path,$newPath); - $this->path = $newPath; - $this->putResourceData($resourceData); - - - } - - public function deleteResourceData() { - - // When we're deleting this node, we also need to delete any resource information - $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return true; - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - $data = ''; - - rewind($handle); - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (isset($data[$this->getName()])) unset($data[$this->getName()]); - ftruncate($handle,0); - rewind($handle); - fwrite($handle,serialize($data)); - fclose($handle); - - } - - public function delete() { - - return $this->deleteResourceData(); - - } - -} - diff --git a/3rdparty/Sabre/DAV/File.php b/3rdparty/Sabre/DAV/File.php deleted file mode 100644 index b74bd9525b..0000000000 --- a/3rdparty/Sabre/DAV/File.php +++ /dev/null @@ -1,81 +0,0 @@ - array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param array $mutations - * @return bool|array - */ - function updateProperties($mutations); - - /** - * Returns a list of properties for this nodes. - * - * The properties list is a list of propertynames the client requested, - * encoded in clark-notation {xmlnamespace}tagname - * - * If the array is empty, it means 'all properties' were requested. - * - * @param array $properties - * @return void - */ - function getProperties($properties); - -} - diff --git a/3rdparty/Sabre/DAV/IQuota.php b/3rdparty/Sabre/DAV/IQuota.php deleted file mode 100644 index 8ff1a4597f..0000000000 --- a/3rdparty/Sabre/DAV/IQuota.php +++ /dev/null @@ -1,27 +0,0 @@ -dataDir = $dataDir; - - } - - protected function getFileNameForUri($uri) { - - return $this->dataDir . '/sabredav_' . md5($uri) . '.locks'; - - } - - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - $lockList = array(); - $currentPath = ''; - - foreach(explode('/',$uri) as $uriPart) { - - // weird algorithm that can probably be improved, but we're traversing the path top down - if ($currentPath) $currentPath.='/'; - $currentPath.=$uriPart; - - $uriLocks = $this->getData($currentPath); - - foreach($uriLocks as $uriLock) { - - // Unless we're on the leaf of the uri-tree we should ingore locks with depth 0 - if($uri==$currentPath || $uriLock->depth!=0) { - $uriLock->uri = $currentPath; - $lockList[] = $uriLock; - } - - } - - } - - // Checking if we can remove any of these locks - foreach($lockList as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($lockList[$k]); - } - return $lockList; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) unset($locks[$k]); - } - $locks[] = $lockInfo; - $this->putData($uri,$locks); - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - - if ($lock->token == $lockInfo->token) { - - unset($locks[$k]); - $this->putData($uri,$locks); - return true; - - } - } - return false; - - } - - /** - * Returns the stored data for a uri - * - * @param string $uri - * @return array - */ - protected function getData($uri) { - - $path = $this->getFilenameForUri($uri); - if (!file_exists($path)) return array(); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); - $data = ''; - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!$data) return array(); - return $data; - - } - - /** - * Updates the lock information - * - * @param string $uri - * @param array $newData - * @return void - */ - protected function putData($uri,array $newData) { - - $path = $this->getFileNameForUri($uri); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($newData)); - fclose($handle); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/File.php b/3rdparty/Sabre/DAV/Locks/Backend/File.php deleted file mode 100644 index f65b20c430..0000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/File.php +++ /dev/null @@ -1,175 +0,0 @@ -locksFile = $locksFile; - - } - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - $newLocks = array(); - $currentPath = ''; - - $locks = $this->getData(); - foreach($locks as $lock) { - - if ($lock->uri === $uri || - //deep locks on parents - ($lock->depth!=0 && strpos($uri, $lock->uri . '/')===0) || - - // locks on children - ($returnChildLocks && (strpos($lock->uri, $uri . '/')===0)) ) { - - $newLocks[] = $lock; - - } - - } - - // Checking if we can remove any of these locks - foreach($newLocks as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($newLocks[$k]); - } - return $newLocks; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - $lockInfo->uri = $uri; - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) unset($locks[$k]); - } - $locks[] = $lockInfo; - $this->putData($locks); - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - - if ($lock->token == $lockInfo->token) { - - unset($locks[$k]); - $this->putData($locks); - return true; - - } - } - return false; - - } - - /** - * Loads the lockdata from the filesystem. - * - * @return array - */ - protected function getData() { - - if (!file_exists($this->locksFile)) return array(); - - // opening up the file, and creating a shared lock - $handle = fopen($this->locksFile,'r'); - flock($handle,LOCK_SH); - - // Reading data until the eof - $data = stream_get_contents($handle); - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!$data) return array(); - return $data; - - } - - /** - * Saves the lockdata - * - * @param array $newData - * @return void - */ - protected function putData(array $newData) { - - // opening up the file, and creating an exclusive lock - $handle = fopen($this->locksFile,'a+'); - flock($handle,LOCK_EX); - - // We can only truncate and rewind once the lock is acquired. - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($newData)); - fclose($handle); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/PDO.php b/3rdparty/Sabre/DAV/Locks/Backend/PDO.php deleted file mode 100644 index c3923af19d..0000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/PDO.php +++ /dev/null @@ -1,165 +0,0 @@ -pdo = $pdo; - $this->tableName = $tableName; - - } - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - // NOTE: the following 10 lines or so could be easily replaced by - // pure sql. MySQL's non-standard string concatination prevents us - // from doing this though. - $query = 'SELECT owner, token, timeout, created, scope, depth, uri FROM `'.$this->tableName.'` WHERE ((created + timeout) > CAST(? AS UNSIGNED INTEGER)) AND ((uri = ?)'; - $params = array(time(),$uri); - - // We need to check locks for every part in the uri. - $uriParts = explode('/',$uri); - - // We already covered the last part of the uri - array_pop($uriParts); - - $currentPath=''; - - foreach($uriParts as $part) { - - if ($currentPath) $currentPath.='/'; - $currentPath.=$part; - - $query.=' OR (depth!=0 AND uri = ?)'; - $params[] = $currentPath; - - } - - if ($returnChildLocks) { - - $query.=' OR (uri LIKE ?)'; - $params[] = $uri . '/%'; - - } - $query.=')'; - - $stmt = $this->pdo->prepare($query); - $stmt->execute($params); - $result = $stmt->fetchAll(); - - $lockList = array(); - foreach($result as $row) { - - $lockInfo = new Sabre_DAV_Locks_LockInfo(); - $lockInfo->owner = $row['owner']; - $lockInfo->token = $row['token']; - $lockInfo->timeout = $row['timeout']; - $lockInfo->created = $row['created']; - $lockInfo->scope = $row['scope']; - $lockInfo->depth = $row['depth']; - $lockInfo->uri = $row['uri']; - $lockList[] = $lockInfo; - - } - - return $lockList; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 30*60; - $lockInfo->created = time(); - $lockInfo->uri = $uri; - - $locks = $this->getLocks($uri,false); - $exists = false; - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) $exists = true; - } - - if ($exists) { - $stmt = $this->pdo->prepare('UPDATE `'.$this->tableName.'` SET owner = ?, timeout = ?, scope = ?, depth = ?, uri = ?, created = ? WHERE token = ?'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); - } else { - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->tableName.'` (owner,timeout,scope,depth,uri,created,token) VALUES (?,?,?,?,?,?,?)'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); - } - - return true; - - } - - - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->tableName.'` WHERE uri = ? AND token = ?'); - $stmt->execute(array($uri,$lockInfo->token)); - - return $stmt->rowCount()===1; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/LockInfo.php b/3rdparty/Sabre/DAV/Locks/LockInfo.php deleted file mode 100644 index 6a064466f4..0000000000 --- a/3rdparty/Sabre/DAV/Locks/LockInfo.php +++ /dev/null @@ -1,81 +0,0 @@ -addPlugin($lockPlugin); - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * locksBackend - * - * @var Sabre_DAV_Locks_Backend_Abstract - */ - private $locksBackend; - - /** - * server - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * __construct - * - * @param Sabre_DAV_Locks_Backend_Abstract $locksBackend - * @return void - */ - public function __construct(Sabre_DAV_Locks_Backend_Abstract $locksBackend = null) { - - $this->locksBackend = $locksBackend; - - } - - /** - * Initializes the plugin - * - * This method is automatically called by the Server class after addPlugin. - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),50); - $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties')); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'locks'; - - } - - /** - * This method is called by the Server if the user used an HTTP method - * the server didn't recognize. - * - * This plugin intercepts the LOCK and UNLOCK methods. - * - * @param string $method - * @return bool - */ - public function unknownMethod($method, $uri) { - - switch($method) { - - case 'LOCK' : $this->httpLock($uri); return false; - case 'UNLOCK' : $this->httpUnlock($uri); return false; - - } - - } - - /** - * This method is called after most properties have been found - * it allows us to add in any Lock-related properties - * - * @param string $path - * @param array $properties - * @return bool - */ - public function afterGetProperties($path,&$newProperties) { - - foreach($newProperties[404] as $propName=>$discard) { - - $node = null; - - switch($propName) { - - case '{DAV:}supportedlock' : - $val = false; - if ($this->locksBackend) $val = true; - else { - if (!$node) $node = $this->server->tree->getNodeForPath($path); - if ($node instanceof Sabre_DAV_ILockable) $val = true; - } - $newProperties[200][$propName] = new Sabre_DAV_Property_SupportedLock($val); - unset($newProperties[404][$propName]); - break; - - case '{DAV:}lockdiscovery' : - $newProperties[200][$propName] = new Sabre_DAV_Property_LockDiscovery($this->getLocks($path)); - unset($newProperties[404][$propName]); - break; - - } - - - } - return true; - - } - - - /** - * This method is called before the logic for any HTTP method is - * handled. - * - * This plugin uses that feature to intercept access to locked resources. - * - * @param string $method - * @param string $uri - * @return bool - */ - public function beforeMethod($method, $uri) { - - switch($method) { - - case 'DELETE' : - $lastLock = null; - if (!$this->validateLock($uri,$lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'MKCOL' : - case 'PROPPATCH' : - case 'PUT' : - $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'MOVE' : - $lastLock = null; - if (!$this->validateLock(array( - $uri, - $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - ),$lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'COPY' : - $lastLock = null; - if (!$this->validateLock( - $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - $lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - } - - return true; - - } - - /** - * Use this method to tell the server this plugin defines additional - * HTTP methods. - * - * This method is passed a uri. It should only return HTTP methods that are - * available for the specified uri. - * - * @param string $uri - * @return array - */ - public function getHTTPMethods($uri) { - - if ($this->locksBackend || - $this->server->tree->getNodeForPath($uri) instanceof Sabre_DAV_ILocks) { - return array('LOCK','UNLOCK'); - } - return array(); - - } - - /** - * Returns a list of features for the HTTP OPTIONS Dav: header. - * - * In this case this is only the number 2. The 2 in the Dav: header - * indicates the server supports locks. - * - * @return array - */ - public function getFeatures() { - - return array(2); - - } - - /** - * Returns all lock information on a particular uri - * - * This function should return an array with Sabre_DAV_Locks_LockInfo objects. If there are no locks on a file, return an empty array. - * - * Additionally there is also the possibility of locks on parent nodes, so we'll need to traverse every part of the tree - * If the $returnChildLocks argument is set to true, we'll also traverse all the children of the object - * for any possible locks and return those as well. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks = false) { - - $lockList = array(); - $currentPath = ''; - foreach(explode('/',$uri) as $uriPart) { - - $uriLocks = array(); - if ($currentPath) $currentPath.='/'; - $currentPath.=$uriPart; - - try { - - $node = $this->server->tree->getNodeForPath($currentPath); - if ($node instanceof Sabre_DAV_ILockable) $uriLocks = $node->getLocks(); - - } catch (Sabre_DAV_Exception_FileNotFound $e){ - // In case the node didn't exist, this could be a lock-null request - } - - foreach($uriLocks as $uriLock) { - - // Unless we're on the leaf of the uri-tree we should ignore locks with depth 0 - if($uri==$currentPath || $uriLock->depth!=0) { - $uriLock->uri = $currentPath; - $lockList[] = $uriLock; - } - - } - - } - if ($this->locksBackend) - $lockList = array_merge($lockList,$this->locksBackend->getLocks($uri, $returnChildLocks)); - - return $lockList; - - } - - /** - * Locks an uri - * - * The WebDAV lock request can be operated to either create a new lock on a file, or to refresh an existing lock - * If a new lock is created, a full XML body should be supplied, containing information about the lock such as the type - * of lock (shared or exclusive) and the owner of the lock - * - * If a lock is to be refreshed, no body should be supplied and there should be a valid If header containing the lock - * - * Additionally, a lock can be requested for a non-existant file. In these case we're obligated to create an empty file as per RFC4918:S7.3 - * - * @param string $uri - * @return void - */ - protected function httpLock($uri) { - - $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) { - - // If the existing lock was an exclusive lock, we need to fail - if (!$lastLock || $lastLock->scope == Sabre_DAV_Locks_LockInfo::EXCLUSIVE) { - //var_dump($lastLock); - throw new Sabre_DAV_Exception_ConflictingLock($lastLock); - } - - } - - if ($body = $this->server->httpRequest->getBody(true)) { - // This is a new lock request - $lockInfo = $this->parseLockRequest($body); - $lockInfo->depth = $this->server->getHTTPDepth(); - $lockInfo->uri = $uri; - if($lastLock && $lockInfo->scope != Sabre_DAV_Locks_LockInfo::SHARED) throw new Sabre_DAV_Exception_ConflictingLock($lastLock); - - } elseif ($lastLock) { - - // This must have been a lock refresh - $lockInfo = $lastLock; - - // The resource could have been locked through another uri. - if ($uri!=$lockInfo->uri) $uri = $lockInfo->uri; - - } else { - - // There was neither a lock refresh nor a new lock request - throw new Sabre_DAV_Exception_BadRequest('An xml body is required for lock requests'); - - } - - if ($timeout = $this->getTimeoutHeader()) $lockInfo->timeout = $timeout; - - $newFile = false; - - // If we got this far.. we should go check if this node actually exists. If this is not the case, we need to create it first - try { - $node = $this->server->tree->getNodeForPath($uri); - - // We need to call the beforeWriteContent event for RFC3744 - $this->server->broadcastEvent('beforeWriteContent',array($uri)); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // It didn't, lets create it - $this->server->createFile($uri,fopen('php://memory','r')); - $newFile = true; - - } - - $this->lockNode($uri,$lockInfo); - - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->setHeader('Lock-Token','token . '>'); - $this->server->httpResponse->sendStatus($newFile?201:200); - $this->server->httpResponse->sendBody($this->generateLockResponse($lockInfo)); - - } - - /** - * Unlocks a uri - * - * This WebDAV method allows you to remove a lock from a node. The client should provide a valid locktoken through the Lock-token http header - * The server should return 204 (No content) on success - * - * @param string $uri - * @return void - */ - protected function httpUnlock($uri) { - - $lockToken = $this->server->httpRequest->getHeader('Lock-Token'); - - // If the locktoken header is not supplied, we need to throw a bad request exception - if (!$lockToken) throw new Sabre_DAV_Exception_BadRequest('No lock token was supplied'); - - $locks = $this->getLocks($uri); - - // Windows sometimes forgets to include < and > in the Lock-Token - // header - if ($lockToken[0]!=='<') $lockToken = '<' . $lockToken . '>'; - - foreach($locks as $lock) { - - if ('token . '>' == $lockToken) { - - $this->server->broadcastEvent('beforeUnlock',array($uri, $lock)); - $this->unlockNode($uri,$lock); - $this->server->httpResponse->setHeader('Content-Length','0'); - $this->server->httpResponse->sendStatus(204); - return; - - } - - } - - // If we got here, it means the locktoken was invalid - throw new Sabre_DAV_Exception_LockTokenMatchesRequestUri(); - - } - - /** - * Locks a uri - * - * All the locking information is supplied in the lockInfo object. The object has a suggested timeout, but this can be safely ignored - * It is important that if the existing timeout is ignored, the property is overwritten, as this needs to be sent back to the client - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - public function lockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - if (!$this->server->broadcastEvent('beforeLock',array($uri,$lockInfo))) return; - - try { - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_ILockable) return $node->lock($lockInfo); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // In case the node didn't exist, this could be a lock-null request - } - if ($this->locksBackend) return $this->locksBackend->lock($uri,$lockInfo); - throw new Sabre_DAV_Exception_MethodNotAllowed('Locking support is not enabled for this resource. No Locking backend was found so if you didn\'t expect this error, please check your configuration.'); - - } - - /** - * Unlocks a uri - * - * This method removes a lock from a uri. It is assumed all the supplied information is correct and verified - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - public function unlockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - if (!$this->server->broadcastEvent('beforeUnlock',array($uri,$lockInfo))) return; - try { - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_ILockable) return $node->unlock($lockInfo); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // In case the node didn't exist, this could be a lock-null request - } - - if ($this->locksBackend) return $this->locksBackend->unlock($uri,$lockInfo); - - } - - - /** - * Returns the contents of the HTTP Timeout header. - * - * The method formats the header into an integer. - * - * @return int - */ - public function getTimeoutHeader() { - - $header = $this->server->httpRequest->getHeader('Timeout'); - - if ($header) { - - if (stripos($header,'second-')===0) $header = (int)(substr($header,7)); - else if (strtolower($header)=='infinite') $header=Sabre_DAV_Locks_LockInfo::TIMEOUT_INFINITE; - else throw new Sabre_DAV_Exception_BadRequest('Invalid HTTP timeout header'); - - } else { - - $header = 0; - - } - - return $header; - - } - - /** - * Generates the response for successfull LOCK requests - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return string - */ - protected function generateLockResponse(Sabre_DAV_Locks_LockInfo $lockInfo) { - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - - $prop = $dom->createElementNS('DAV:','d:prop'); - $dom->appendChild($prop); - - $lockDiscovery = $dom->createElementNS('DAV:','d:lockdiscovery'); - $prop->appendChild($lockDiscovery); - - $lockObj = new Sabre_DAV_Property_LockDiscovery(array($lockInfo),true); - $lockObj->serialize($this->server,$lockDiscovery); - - return $dom->saveXML(); - - } - - /** - * validateLock should be called when a write operation is about to happen - * It will check if the requested url is locked, and see if the correct lock tokens are passed - * - * @param mixed $urls List of relevant urls. Can be an array, a string or nothing at all for the current request uri - * @param mixed $lastLock This variable will be populated with the last checked lock object (Sabre_DAV_Locks_LockInfo) - * @param bool $checkChildLocks If set to true, this function will also look for any locks set on child resources of the supplied urls. This is needed for for example deletion of entire trees. - * @return bool - */ - protected function validateLock($urls = null,&$lastLock = null, $checkChildLocks = false) { - - if (is_null($urls)) { - $urls = array($this->server->getRequestUri()); - } elseif (is_string($urls)) { - $urls = array($urls); - } elseif (!is_array($urls)) { - throw new Sabre_DAV_Exception('The urls parameter should either be null, a string or an array'); - } - - $conditions = $this->getIfConditions(); - - // We're going to loop through the urls and make sure all lock conditions are satisfied - foreach($urls as $url) { - - $locks = $this->getLocks($url, $checkChildLocks); - - // If there were no conditions, but there were locks, we fail - if (!$conditions && $locks) { - reset($locks); - $lastLock = current($locks); - return false; - } - - // If there were no locks or conditions, we go to the next url - if (!$locks && !$conditions) continue; - - foreach($conditions as $condition) { - - if (!$condition['uri']) { - $conditionUri = $this->server->getRequestUri(); - } else { - $conditionUri = $this->server->calculateUri($condition['uri']); - } - - // If the condition has a url, and it isn't part of the affected url at all, check the next condition - if ($conditionUri && strpos($url,$conditionUri)!==0) continue; - - // The tokens array contians arrays with 2 elements. 0=true/false for normal/not condition, 1=locktoken - // At least 1 condition has to be satisfied - foreach($condition['tokens'] as $conditionToken) { - - $etagValid = true; - $lockValid = true; - - // key 2 can contain an etag - if ($conditionToken[2]) { - - $uri = $conditionUri?$conditionUri:$this->server->getRequestUri(); - $node = $this->server->tree->getNodeForPath($uri); - $etagValid = $node->getETag()==$conditionToken[2]; - - } - - // key 1 can contain a lock token - if ($conditionToken[1]) { - - $lockValid = false; - // Match all the locks - foreach($locks as $lockIndex=>$lock) { - - $lockToken = 'opaquelocktoken:' . $lock->token; - - // Checking NOT - if (!$conditionToken[0] && $lockToken != $conditionToken[1]) { - - // Condition valid, onto the next - $lockValid = true; - break; - } - if ($conditionToken[0] && $lockToken == $conditionToken[1]) { - - $lastLock = $lock; - // Condition valid and lock matched - unset($locks[$lockIndex]); - $lockValid = true; - break; - - } - - } - - } - - // If, after checking both etags and locks they are stil valid, - // we can continue with the next condition. - if ($etagValid && $lockValid) continue 2; - } - // No conditions matched, so we fail - throw new Sabre_DAV_Exception_PreconditionFailed('The tokens provided in the if header did not match','If'); - } - - // Conditions were met, we'll also need to check if all the locks are gone - if (count($locks)) { - - reset($locks); - - // There's still locks, we fail - $lastLock = current($locks); - return false; - - } - - - } - - // We got here, this means every condition was satisfied - return true; - - } - - /** - * This method is created to extract information from the WebDAV HTTP 'If:' header - * - * The If header can be quite complex, and has a bunch of features. We're using a regex to extract all relevant information - * The function will return an array, containg structs with the following keys - * - * * uri - the uri the condition applies to. If this is returned as an - * empty string, this implies it's referring to the request url. - * * tokens - The lock token. another 2 dimensional array containg 2 elements (0 = true/false.. If this is a negative condition its set to false, 1 = the actual token) - * * etag - an etag, if supplied - * - * @return void - */ - public function getIfConditions() { - - $header = $this->server->httpRequest->getHeader('If'); - if (!$header) return array(); - - $matches = array(); - - $regex = '/(?:\<(?P.*?)\>\s)?\((?PNot\s)?(?:\<(?P[^\>]*)\>)?(?:\s?)(?:\[(?P[^\]]*)\])?\)/im'; - preg_match_all($regex,$header,$matches,PREG_SET_ORDER); - - $conditions = array(); - - foreach($matches as $match) { - - $condition = array( - 'uri' => $match['uri'], - 'tokens' => array( - array($match['not']?0:1,$match['token'],isset($match['etag'])?$match['etag']:'') - ), - ); - - if (!$condition['uri'] && count($conditions)) $conditions[count($conditions)-1]['tokens'][] = array( - $match['not']?0:1, - $match['token'], - isset($match['etag'])?$match['etag']:'' - ); - else { - $conditions[] = $condition; - } - - } - - return $conditions; - - } - - /** - * Parses a webdav lock xml body, and returns a new Sabre_DAV_Locks_LockInfo object - * - * @param string $body - * @return Sabre_DAV_Locks_LockInfo - */ - protected function parseLockRequest($body) { - - $xml = simplexml_load_string($body,null,LIBXML_NOWARNING); - $xml->registerXPathNamespace('d','DAV:'); - $lockInfo = new Sabre_DAV_Locks_LockInfo(); - - $children = $xml->children("DAV:"); - $lockInfo->owner = (string)$children->owner; - - $lockInfo->token = Sabre_DAV_UUIDUtil::getUUID(); - $lockInfo->scope = count($xml->xpath('d:lockscope/d:exclusive'))>0?Sabre_DAV_Locks_LockInfo::EXCLUSIVE:Sabre_DAV_Locks_LockInfo::SHARED; - - return $lockInfo; - - } - - -} diff --git a/3rdparty/Sabre/DAV/Mount/Plugin.php b/3rdparty/Sabre/DAV/Mount/Plugin.php deleted file mode 100644 index f93a1aa25a..0000000000 --- a/3rdparty/Sabre/DAV/Mount/Plugin.php +++ /dev/null @@ -1,79 +0,0 @@ -server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - - } - - /** - * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?mount - * - * @param string $method - * @return void - */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='mount') return; - - $currentUri = $this->server->httpRequest->getAbsoluteUri(); - - // Stripping off everything after the ? - list($currentUri) = explode('?',$currentUri); - - $this->davMount($currentUri); - - // Returning false to break the event chain - return false; - - } - - /** - * Generates the davmount response - * - * @param string $uri absolute uri - * @return void - */ - public function davMount($uri) { - - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','application/davmount+xml'); - ob_start(); - echo '', "\n"; - echo "\n"; - echo " ", htmlspecialchars($uri, ENT_NOQUOTES, 'UTF-8'), "\n"; - echo ""; - $this->server->httpResponse->sendBody(ob_get_clean()); - - } - - -} diff --git a/3rdparty/Sabre/DAV/Node.php b/3rdparty/Sabre/DAV/Node.php deleted file mode 100644 index 0510df5fdf..0000000000 --- a/3rdparty/Sabre/DAV/Node.php +++ /dev/null @@ -1,55 +0,0 @@ -rootNode = $rootNode; - - } - - /** - * Returns the INode object for the requested path - * - * @param string $path - * @return Sabre_DAV_INode - */ - public function getNodeForPath($path) { - - $path = trim($path,'/'); - if (isset($this->cache[$path])) return $this->cache[$path]; - - //if (!$path || $path=='.') return $this->rootNode; - $currentNode = $this->rootNode; - $i=0; - // We're splitting up the path variable into folder/subfolder components and traverse to the correct node.. - foreach(explode('/',$path) as $pathPart) { - - // If this part of the path is just a dot, it actually means we can skip it - if ($pathPart=='.' || $pathPart=='') continue; - - if (!($currentNode instanceof Sabre_DAV_ICollection)) - throw new Sabre_DAV_Exception_FileNotFound('Could not find node at path: ' . $path); - - $currentNode = $currentNode->getChild($pathPart); - - } - - $this->cache[$path] = $currentNode; - return $currentNode; - - } - - /** - * This function allows you to check if a node exists. - * - * @param string $path - * @return bool - */ - public function nodeExists($path) { - - try { - - // The root always exists - if ($path==='') return true; - - list($parent, $base) = Sabre_DAV_URLUtil::splitPath($path); - - $parentNode = $this->getNodeForPath($parent); - if (!$parentNode instanceof Sabre_DAV_ICollection) return false; - return $parentNode->childExists($base); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Returns a list of childnodes for a given path. - * - * @param string $path - * @return array - */ - public function getChildren($path) { - - $node = $this->getNodeForPath($path); - $children = $node->getChildren(); - foreach($children as $child) { - - $this->cache[trim($path,'/') . '/' . $child->getName()] = $child; - - } - return $children; - - } - - /** - * This method is called with every tree update - * - * Examples of tree updates are: - * * node deletions - * * node creations - * * copy - * * move - * * renaming nodes - * - * If Tree classes implement a form of caching, this will allow - * them to make sure caches will be expired. - * - * If a path is passed, it is assumed that the entire subtree is dirty - * - * @param string $path - * @return void - */ - public function markDirty($path) { - - // We don't care enough about sub-paths - // flushing the entire cache - $path = trim($path,'/'); - foreach($this->cache as $nodePath=>$node) { - if ($nodePath == $path || strpos($nodePath,$path.'/')===0) - unset($this->cache[$nodePath]); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property.php b/3rdparty/Sabre/DAV/Property.php deleted file mode 100644 index 577535b012..0000000000 --- a/3rdparty/Sabre/DAV/Property.php +++ /dev/null @@ -1,25 +0,0 @@ -time = $time; - } elseif (is_int($time) || ctype_digit($time)) { - $this->time = new DateTime('@' . $time); - } else { - $this->time = new DateTime($time); - } - - // Setting timezone to UTC - $this->time->setTimezone(new DateTimeZone('UTC')); - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { - - $doc = $prop->ownerDocument; - $prop->setAttribute('xmlns:b','urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/'); - $prop->setAttribute('b:dt','dateTime.rfc1123'); - $prop->nodeValue = $this->time->format(DateTime::RFC1123); - - } - - /** - * getTime - * - * @return DateTime - */ - public function getTime() { - - return $this->time; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/Href.php b/3rdparty/Sabre/DAV/Property/Href.php deleted file mode 100644 index 3294ff2ac6..0000000000 --- a/3rdparty/Sabre/DAV/Property/Href.php +++ /dev/null @@ -1,91 +0,0 @@ -href = $href; - $this->autoPrefix = $autoPrefix; - - } - - /** - * Returns the uri - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Serializes this property. - * - * It will additionally prepend the href property with the server's base uri. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $prefix = $server->xmlNamespaces['DAV:']; - - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $this->href; - $dom->appendChild($elem); - - } - - /** - * Unserializes this property from a DOM Element - * - * This method returns an instance of this class. - * It will only decode {DAV:}href values. For non-compatible elements null will be returned. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Href - */ - static function unserialize(DOMElement $dom) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)==='{DAV:}href') { - return new self($dom->firstChild->textContent,false); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/HrefList.php b/3rdparty/Sabre/DAV/Property/HrefList.php deleted file mode 100644 index 76a5512901..0000000000 --- a/3rdparty/Sabre/DAV/Property/HrefList.php +++ /dev/null @@ -1,96 +0,0 @@ -hrefs = $hrefs; - $this->autoPrefix = $autoPrefix; - - } - - /** - * Returns the uris - * - * @return array - */ - public function getHrefs() { - - return $this->hrefs; - - } - - /** - * Serializes this property. - * - * It will additionally prepend the href property with the server's base uri. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $prefix = $server->xmlNamespaces['DAV:']; - - foreach($this->hrefs as $href) { - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $href; - $dom->appendChild($elem); - } - - } - - /** - * Unserializes this property from a DOM Element - * - * This method returns an instance of this class. - * It will only decode {DAV:}href values. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Href - */ - static function unserialize(DOMElement $dom) { - - $hrefs = array(); - foreach($dom->childNodes as $child) { - if (Sabre_DAV_XMLUtil::toClarkNotation($child)==='{DAV:}href') { - $hrefs[] = $child->textContent; - } - } - return new self($hrefs, false); - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/IHref.php b/3rdparty/Sabre/DAV/Property/IHref.php deleted file mode 100644 index 29d76a44fc..0000000000 --- a/3rdparty/Sabre/DAV/Property/IHref.php +++ /dev/null @@ -1,25 +0,0 @@ -locks = $locks; - $this->revealLockToken = $revealLockToken; - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $doc = $prop->ownerDocument; - - foreach($this->locks as $lock) { - - $activeLock = $doc->createElementNS('DAV:','d:activelock'); - $prop->appendChild($activeLock); - - $lockScope = $doc->createElementNS('DAV:','d:lockscope'); - $activeLock->appendChild($lockScope); - - $lockScope->appendChild($doc->createElementNS('DAV:','d:' . ($lock->scope==Sabre_DAV_Locks_LockInfo::EXCLUSIVE?'exclusive':'shared'))); - - $lockType = $doc->createElementNS('DAV:','d:locktype'); - $activeLock->appendChild($lockType); - - $lockType->appendChild($doc->createElementNS('DAV:','d:write')); - - /* {DAV:}lockroot */ - if (!self::$hideLockRoot) { - $lockRoot = $doc->createElementNS('DAV:','d:lockroot'); - $activeLock->appendChild($lockRoot); - $href = $doc->createElementNS('DAV:','d:href'); - $href->appendChild($doc->createTextNode($server->getBaseUri() . $lock->uri)); - $lockRoot->appendChild($href); - } - - $activeLock->appendChild($doc->createElementNS('DAV:','d:depth',($lock->depth == Sabre_DAV_Server::DEPTH_INFINITY?'infinity':$lock->depth))); - $activeLock->appendChild($doc->createElementNS('DAV:','d:timeout','Second-' . $lock->timeout)); - - if ($this->revealLockToken) { - $lockToken = $doc->createElementNS('DAV:','d:locktoken'); - $activeLock->appendChild($lockToken); - $lockToken->appendChild($doc->createElementNS('DAV:','d:href','opaquelocktoken:' . $lock->token)); - } - - $activeLock->appendChild($doc->createElementNS('DAV:','d:owner',$lock->owner)); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/ResourceType.php b/3rdparty/Sabre/DAV/Property/ResourceType.php deleted file mode 100644 index 2c606c22d6..0000000000 --- a/3rdparty/Sabre/DAV/Property/ResourceType.php +++ /dev/null @@ -1,125 +0,0 @@ -resourceType = array(); - elseif ($resourceType === Sabre_DAV_Server::NODE_DIRECTORY) - $this->resourceType = array('{DAV:}collection'); - elseif (is_array($resourceType)) - $this->resourceType = $resourceType; - else - $this->resourceType = array($resourceType); - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $propName = null; - $rt = $this->resourceType; - - foreach($rt as $resourceType) { - if (preg_match('/^{([^}]*)}(.*)$/',$resourceType,$propName)) { - - if (isset($server->xmlNamespaces[$propName[1]])) { - $prop->appendChild($prop->ownerDocument->createElement($server->xmlNamespaces[$propName[1]] . ':' . $propName[2])); - } else { - $prop->appendChild($prop->ownerDocument->createElementNS($propName[1],'custom:' . $propName[2])); - } - - } - } - - } - - /** - * Returns the values in clark-notation - * - * For example array('{DAV:}collection') - * - * @return array - */ - public function getValue() { - - return $this->resourceType; - - } - - /** - * Checks if the principal contains a certain value - * - * @param string $type - * @return bool - */ - public function is($type) { - - return in_array($type, $this->resourceType); - - } - - /** - * Adds a resourcetype value to this property - * - * @param string $type - * @return void - */ - public function add($type) { - - $this->resourceType[] = $type; - $this->resourceType = array_unique($this->resourceType); - - } - - /** - * Unserializes a DOM element into a ResourceType property. - * - * @param DOMElement $dom - * @return void - */ - static public function unserialize(DOMElement $dom) { - - $value = array(); - foreach($dom->childNodes as $child) { - - $value[] = Sabre_DAV_XMLUtil::toClarkNotation($child); - - } - - return new self($value); - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/Response.php b/3rdparty/Sabre/DAV/Property/Response.php deleted file mode 100644 index 7d3a2db038..0000000000 --- a/3rdparty/Sabre/DAV/Property/Response.php +++ /dev/null @@ -1,156 +0,0 @@ -href = $href; - $this->responseProperties = $responseProperties; - - } - - /** - * Returns the url - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Returns the property list - * - * @return array - */ - public function getResponseProperties() { - - return $this->responseProperties; - - } - - /** - * serialize - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $document = $dom->ownerDocument; - $properties = $this->responseProperties; - - $xresponse = $document->createElement('d:response'); - $dom->appendChild($xresponse); - - $uri = Sabre_DAV_URLUtil::encodePath($this->href); - - // Adding the baseurl to the beginning of the url - $uri = $server->getBaseUri() . $uri; - - $xresponse->appendChild($document->createElement('d:href',$uri)); - - // The properties variable is an array containing properties, grouped by - // HTTP status - foreach($properties as $httpStatus=>$propertyGroup) { - - // The 'href' is also in this array, and it's special cased. - // We will ignore it - if ($httpStatus=='href') continue; - - // If there are no properties in this group, we can also just carry on - if (!count($propertyGroup)) continue; - - $xpropstat = $document->createElement('d:propstat'); - $xresponse->appendChild($xpropstat); - - $xprop = $document->createElement('d:prop'); - $xpropstat->appendChild($xprop); - - $nsList = $server->xmlNamespaces; - - foreach($propertyGroup as $propertyName=>$propertyValue) { - - $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); - - // special case for empty namespaces - if ($propName[1]=='') { - - $currentProperty = $document->createElement($propName[2]); - $xprop->appendChild($currentProperty); - $currentProperty->setAttribute('xmlns',''); - - } else { - - if (!isset($nsList[$propName[1]])) { - $nsList[$propName[1]] = 'x' . count($nsList); - } - - // If the namespace was defined in the top-level xml namespaces, it means - // there was already a namespace declaration, and we don't have to worry about it. - if (isset($server->xmlNamespaces[$propName[1]])) { - $currentProperty = $document->createElement($nsList[$propName[1]] . ':' . $propName[2]); - } else { - $currentProperty = $document->createElementNS($propName[1],$nsList[$propName[1]].':' . $propName[2]); - } - $xprop->appendChild($currentProperty); - - } - - if (is_scalar($propertyValue)) { - $text = $document->createTextNode($propertyValue); - $currentProperty->appendChild($text); - } elseif ($propertyValue instanceof Sabre_DAV_Property) { - $propertyValue->serialize($server,$currentProperty); - } elseif (!is_null($propertyValue)) { - throw new Sabre_DAV_Exception('Unknown property value type: ' . gettype($propertyValue) . ' for property: ' . $propertyName); - } - - } - - $xpropstat->appendChild($document->createElement('d:status',$server->httpResponse->getStatusMessage($httpStatus))); - - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/ResponseList.php b/3rdparty/Sabre/DAV/Property/ResponseList.php deleted file mode 100644 index cd70b12861..0000000000 --- a/3rdparty/Sabre/DAV/Property/ResponseList.php +++ /dev/null @@ -1,58 +0,0 @@ -responses = $responses; - - } - - /** - * serialize - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - foreach($this->responses as $response) { - $response->serialize($server, $dom); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/SupportedLock.php b/3rdparty/Sabre/DAV/Property/SupportedLock.php deleted file mode 100644 index 01e63f58d9..0000000000 --- a/3rdparty/Sabre/DAV/Property/SupportedLock.php +++ /dev/null @@ -1,76 +0,0 @@ -supportsLocks = $supportsLocks; - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $doc = $prop->ownerDocument; - - if (!$this->supportsLocks) return null; - - $lockEntry1 = $doc->createElementNS('DAV:','d:lockentry'); - $lockEntry2 = $doc->createElementNS('DAV:','d:lockentry'); - - $prop->appendChild($lockEntry1); - $prop->appendChild($lockEntry2); - - $lockScope1 = $doc->createElementNS('DAV:','d:lockscope'); - $lockScope2 = $doc->createElementNS('DAV:','d:lockscope'); - $lockType1 = $doc->createElementNS('DAV:','d:locktype'); - $lockType2 = $doc->createElementNS('DAV:','d:locktype'); - - $lockEntry1->appendChild($lockScope1); - $lockEntry1->appendChild($lockType1); - $lockEntry2->appendChild($lockScope2); - $lockEntry2->appendChild($lockType2); - - $lockScope1->appendChild($doc->createElementNS('DAV:','d:exclusive')); - $lockScope2->appendChild($doc->createElementNS('DAV:','d:shared')); - - $lockType1->appendChild($doc->createElementNS('DAV:','d:write')); - $lockType2->appendChild($doc->createElementNS('DAV:','d:write')); - - //$frag->appendXML(''); - //$frag->appendXML(''); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/SupportedReportSet.php b/3rdparty/Sabre/DAV/Property/SupportedReportSet.php deleted file mode 100644 index acd9219c0f..0000000000 --- a/3rdparty/Sabre/DAV/Property/SupportedReportSet.php +++ /dev/null @@ -1,110 +0,0 @@ -addReport($reports); - - } - - /** - * Adds a report to this property - * - * The report must be a string in clark-notation. - * Multiple reports can be specified as an array. - * - * @param mixed $report - * @return void - */ - public function addReport($report) { - - if (!is_array($report)) $report = array($report); - - foreach($report as $r) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$r)) - throw new Sabre_DAV_Exception('Reportname must be in clark-notation'); - - $this->reports[] = $r; - - } - - } - - /** - * Returns the list of supported reports - * - * @return array - */ - public function getValue() { - - return $this->reports; - - } - - /** - * Serializes the node - * - * @param Sabre_DAV_Server $server - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - foreach($this->reports as $reportName) { - - $supportedReport = $prop->ownerDocument->createElement('d:supported-report'); - $prop->appendChild($supportedReport); - - $report = $prop->ownerDocument->createElement('d:report'); - $supportedReport->appendChild($report); - - preg_match('/^{([^}]*)}(.*)$/',$reportName,$matches); - - list(, $namespace, $element) = $matches; - - $prefix = isset($server->xmlNamespaces[$namespace])?$server->xmlNamespaces[$namespace]:null; - - if ($prefix) { - $report->appendChild($prop->ownerDocument->createElement($prefix . ':' . $element)); - } else { - $report->appendChild($prop->ownerDocument->createElementNS($namespace, 'x:' . $element)); - } - - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Server.php b/3rdparty/Sabre/DAV/Server.php deleted file mode 100644 index 3d76d4f191..0000000000 --- a/3rdparty/Sabre/DAV/Server.php +++ /dev/null @@ -1,1941 +0,0 @@ - 'd', - 'http://sabredav.org/ns' => 's', - ); - - /** - * The propertymap can be used to map properties from - * requests to property classes. - * - * @var array - */ - public $propertyMap = array( - '{DAV:}resourcetype' => 'Sabre_DAV_Property_ResourceType', - ); - - public $protectedProperties = array( - // RFC4918 - '{DAV:}getcontentlength', - '{DAV:}getetag', - '{DAV:}getlastmodified', - '{DAV:}lockdiscovery', - '{DAV:}resourcetype', - '{DAV:}supportedlock', - - // RFC4331 - '{DAV:}quota-available-bytes', - '{DAV:}quota-used-bytes', - - // RFC3744 - '{DAV:}supported-privilege-set', - '{DAV:}current-user-privilege-set', - '{DAV:}acl', - '{DAV:}acl-restrictions', - '{DAV:}inherited-acl-set', - - ); - - /** - * This is a flag that allow or not showing file, line and code - * of the exception in the returned XML - * - * @var bool - */ - public $debugExceptions = false; - - /** - * This property allows you to automatically add the 'resourcetype' value - * based on a node's classname or interface. - * - * The preset ensures that {DAV:}collection is automaticlly added for nodes - * implementing Sabre_DAV_ICollection. - * - * @var array - */ - public $resourceTypeMapping = array( - 'Sabre_DAV_ICollection' => '{DAV:}collection', - ); - - - /** - * Sets up the server - * - * If a Sabre_DAV_Tree object is passed as an argument, it will - * use it as the directory tree. If a Sabre_DAV_INode is passed, it - * will create a Sabre_DAV_ObjectTree and use the node as the root. - * - * If nothing is passed, a Sabre_DAV_SimpleCollection is created in - * a Sabre_DAV_ObjectTree. - * - * If an array is passed, we automatically create a root node, and use - * the nodes in the array as top-level children. - * - * @param Sabre_DAV_Tree $tree The tree object - * @return void - */ - public function __construct($treeOrNode = null) { - - if ($treeOrNode instanceof Sabre_DAV_Tree) { - $this->tree = $treeOrNode; - } elseif ($treeOrNode instanceof Sabre_DAV_INode) { - $this->tree = new Sabre_DAV_ObjectTree($treeOrNode); - } elseif (is_array($treeOrNode)) { - - // If it's an array, a list of nodes was passed, and we need to - // create the root node. - foreach($treeOrNode as $node) { - if (!($node instanceof Sabre_DAV_INode)) { - throw new Sabre_DAV_Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre_DAV_INode'); - } - } - - $root = new Sabre_DAV_SimpleCollection('root', $treeOrNode); - $this->tree = new Sabre_DAV_ObjectTree($root); - - } elseif (is_null($treeOrNode)) { - $root = new Sabre_DAV_SimpleCollection('root'); - $this->tree = new Sabre_DAV_ObjectTree($root); - } else { - throw new Sabre_DAV_Exception('Invalid argument passed to constructor. Argument must either be an instance of Sabre_DAV_Tree, Sabre_DAV_INode, an array or null'); - } - $this->httpResponse = new Sabre_HTTP_Response(); - $this->httpRequest = new Sabre_HTTP_Request(); - - } - - /** - * Starts the DAV Server - * - * @return void - */ - public function exec() { - - try { - - $this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri()); - - } catch (Exception $e) { - - $DOM = new DOMDocument('1.0','utf-8'); - $DOM->formatOutput = true; - - $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s',self::NS_SABREDAV); - $DOM->appendChild($error); - - $error->appendChild($DOM->createElement('s:exception',get_class($e))); - $error->appendChild($DOM->createElement('s:message',$e->getMessage())); - if ($this->debugExceptions) { - $error->appendChild($DOM->createElement('s:file',$e->getFile())); - $error->appendChild($DOM->createElement('s:line',$e->getLine())); - $error->appendChild($DOM->createElement('s:code',$e->getCode())); - $error->appendChild($DOM->createElement('s:stacktrace',$e->getTraceAsString())); - - } - $error->appendChild($DOM->createElement('s:sabredav-version',Sabre_DAV_Version::VERSION)); - - if($e instanceof Sabre_DAV_Exception) { - - $httpCode = $e->getHTTPCode(); - $e->serialize($this,$error); - $headers = $e->getHTTPHeaders($this); - - } else { - - $httpCode = 500; - $headers = array(); - - } - $headers['Content-Type'] = 'application/xml; charset=utf-8'; - - $this->httpResponse->sendStatus($httpCode); - $this->httpResponse->setHeaders($headers); - $this->httpResponse->sendBody($DOM->saveXML()); - - } - - } - - /** - * Sets the base server uri - * - * @param string $uri - * @return void - */ - public function setBaseUri($uri) { - - // If the baseUri does not end with a slash, we must add it - if ($uri[strlen($uri)-1]!=='/') - $uri.='/'; - - $this->baseUri = $uri; - - } - - /** - * Returns the base responding uri - * - * @return string - */ - public function getBaseUri() { - - if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri(); - return $this->baseUri; - - } - - /** - * This method attempts to detect the base uri. - * Only the PATH_INFO variable is considered. - * - * If this variable is not set, the root (/) is assumed. - * - * @return void - */ - public function guessBaseUri() { - - $pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO'); - $uri = $this->httpRequest->getRawServerValue('REQUEST_URI'); - - // If PATH_INFO is found, we can assume it's accurate. - if (!empty($pathInfo)) { - - // We need to make sure we ignore the QUERY_STRING part - if ($pos = strpos($uri,'?')) - $uri = substr($uri,0,$pos); - - // PATH_INFO is only set for urls, such as: /example.php/path - // in that case PATH_INFO contains '/path'. - // Note that REQUEST_URI is percent encoded, while PATH_INFO is - // not, Therefore they are only comparable if we first decode - // REQUEST_INFO as well. - $decodedUri = Sabre_DAV_URLUtil::decodePath($uri); - - // A simple sanity check: - if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) { - $baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo)); - return rtrim($baseUri,'/') . '/'; - } - - throw new Sabre_DAV_Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.'); - - } - - // The last fallback is that we're just going to assume the server root. - return '/'; - - } - - /** - * Adds a plugin to the server - * - * For more information, console the documentation of Sabre_DAV_ServerPlugin - * - * @param Sabre_DAV_ServerPlugin $plugin - * @return void - */ - public function addPlugin(Sabre_DAV_ServerPlugin $plugin) { - - $this->plugins[$plugin->getPluginName()] = $plugin; - $plugin->initialize($this); - - } - - /** - * Returns an initialized plugin by it's name. - * - * This function returns null if the plugin was not found. - * - * @param string $name - * @return Sabre_DAV_ServerPlugin - */ - public function getPlugin($name) { - - if (isset($this->plugins[$name])) - return $this->plugins[$name]; - - // This is a fallback and deprecated. - foreach($this->plugins as $plugin) { - if (get_class($plugin)===$name) return $plugin; - } - - return null; - - } - - /** - * Returns all plugins - * - * @return array - */ - public function getPlugins() { - - return $this->plugins; - - } - - - - /** - * Subscribe to an event. - * - * When the event is triggered, we'll call all the specified callbacks. - * It is possible to control the order of the callbacks through the - * priority argument. - * - * This is for example used to make sure that the authentication plugin - * is triggered before anything else. If it's not needed to change this - * number, it is recommended to ommit. - * - * @param string $event - * @param callback $callback - * @param int $priority - * @return void - */ - public function subscribeEvent($event, $callback, $priority = 100) { - - if (!isset($this->eventSubscriptions[$event])) { - $this->eventSubscriptions[$event] = array(); - } - while(isset($this->eventSubscriptions[$event][$priority])) $priority++; - $this->eventSubscriptions[$event][$priority] = $callback; - ksort($this->eventSubscriptions[$event]); - - } - - /** - * Broadcasts an event - * - * This method will call all subscribers. If one of the subscribers returns false, the process stops. - * - * The arguments parameter will be sent to all subscribers - * - * @param string $eventName - * @param array $arguments - * @return bool - */ - public function broadcastEvent($eventName,$arguments = array()) { - - if (isset($this->eventSubscriptions[$eventName])) { - - foreach($this->eventSubscriptions[$eventName] as $subscriber) { - - $result = call_user_func_array($subscriber,$arguments); - if ($result===false) return false; - - } - - } - - return true; - - } - - /** - * Handles a http request, and execute a method based on its name - * - * @param string $method - * @param string $uri - * @return void - */ - public function invokeMethod($method, $uri) { - - $method = strtoupper($method); - - if (!$this->broadcastEvent('beforeMethod',array($method, $uri))) return; - - // Make sure this is a HTTP method we support - $internalMethods = array( - 'OPTIONS', - 'GET', - 'HEAD', - 'DELETE', - 'PROPFIND', - 'MKCOL', - 'PUT', - 'PROPPATCH', - 'COPY', - 'MOVE', - 'REPORT' - ); - - if (in_array($method,$internalMethods)) { - - call_user_func(array($this,'http' . $method), $uri); - - } else { - - if ($this->broadcastEvent('unknownMethod',array($method, $uri))) { - // Unsupported method - throw new Sabre_DAV_Exception_NotImplemented(); - } - - } - - } - - // {{{ HTTP Method implementations - - /** - * HTTP OPTIONS - * - * @param string $uri - * @return void - */ - protected function httpOptions($uri) { - - $methods = $this->getAllowedMethods($uri); - - $this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods))); - $features = array('1','3', 'extended-mkcol'); - - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - - $this->httpResponse->setHeader('DAV',implode(', ',$features)); - $this->httpResponse->setHeader('MS-Author-Via','DAV'); - $this->httpResponse->setHeader('Accept-Ranges','bytes'); - $this->httpResponse->setHeader('X-Sabre-Version',Sabre_DAV_Version::VERSION); - $this->httpResponse->setHeader('Content-Length',0); - $this->httpResponse->sendStatus(200); - - } - - /** - * HTTP GET - * - * This method simply fetches the contents of a uri, like normal - * - * @param string $uri - * @return void - */ - protected function httpGet($uri) { - - $node = $this->tree->getNodeForPath($uri,0); - - if (!$this->checkPreconditions(true)) return false; - - if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_NotImplemented('GET is only implemented on File objects'); - $body = $node->get(); - - // Converting string into stream, if needed. - if (is_string($body)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$body); - rewind($stream); - $body = $stream; - } - - /* - * TODO: getetag, getlastmodified, getsize should also be used using - * this method - */ - $httpHeaders = $this->getHTTPHeaders($uri); - - /* ContentType needs to get a default, because many webservers will otherwise - * default to text/html, and we don't want this for security reasons. - */ - if (!isset($httpHeaders['Content-Type'])) { - $httpHeaders['Content-Type'] = 'application/octet-stream'; - } - - - if (isset($httpHeaders['Content-Length'])) { - - $nodeSize = $httpHeaders['Content-Length']; - - // Need to unset Content-Length, because we'll handle that during figuring out the range - unset($httpHeaders['Content-Length']); - - } else { - $nodeSize = null; - } - - $this->httpResponse->setHeaders($httpHeaders); - - $range = $this->getHTTPRange(); - $ifRange = $this->httpRequest->getHeader('If-Range'); - $ignoreRangeHeader = false; - - // If ifRange is set, and range is specified, we first need to check - // the precondition. - if ($nodeSize && $range && $ifRange) { - - // if IfRange is parsable as a date we'll treat it as a DateTime - // otherwise, we must treat it as an etag. - try { - $ifRangeDate = new DateTime($ifRange); - - // It's a date. We must check if the entity is modified since - // the specified date. - if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true; - else { - $modified = new DateTime($httpHeaders['Last-Modified']); - if($modified > $ifRangeDate) $ignoreRangeHeader = true; - } - - } catch (Exception $e) { - - // It's an entity. We can do a simple comparison. - if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true; - elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true; - } - } - - // We're only going to support HTTP ranges if the backend provided a filesize - if (!$ignoreRangeHeader && $nodeSize && $range) { - - // Determining the exact byte offsets - if (!is_null($range[0])) { - - $start = $range[0]; - $end = $range[1]?$range[1]:$nodeSize-1; - if($start >= $nodeSize) - throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')'); - - if($end < $start) throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')'); - if($end >= $nodeSize) $end = $nodeSize-1; - - } else { - - $start = $nodeSize-$range[1]; - $end = $nodeSize-1; - - if ($start<0) $start = 0; - - } - - // New read/write stream - $newStream = fopen('php://temp','r+'); - - stream_copy_to_stream($body, $newStream, $end-$start+1, $start); - rewind($newStream); - - $this->httpResponse->setHeader('Content-Length', $end-$start+1); - $this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize); - $this->httpResponse->sendStatus(206); - $this->httpResponse->sendBody($newStream); - - - } else { - - if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize); - $this->httpResponse->sendStatus(200); - $this->httpResponse->sendBody($body); - - } - - } - - /** - * HTTP HEAD - * - * This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body - * This is used by clients to determine if a remote file was changed, so they can use a local cached version, instead of downloading it again - * - * @param string $uri - * @return void - */ - protected function httpHead($uri) { - - $node = $this->tree->getNodeForPath($uri); - /* This information is only collection for File objects. - * Ideally we want to throw 405 Method Not Allowed for every - * non-file, but MS Office does not like this - */ - if ($node instanceof Sabre_DAV_IFile) { - $headers = $this->getHTTPHeaders($this->getRequestUri()); - if (!isset($headers['Content-Type'])) { - $headers['Content-Type'] = 'application/octet-stream'; - } - $this->httpResponse->setHeaders($headers); - } - $this->httpResponse->sendStatus(200); - - } - - /** - * HTTP Delete - * - * The HTTP delete method, deletes a given uri - * - * @param string $uri - * @return void - */ - protected function httpDelete($uri) { - - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; - $this->tree->delete($uri); - - $this->httpResponse->sendStatus(204); - $this->httpResponse->setHeader('Content-Length','0'); - - } - - - /** - * WebDAV PROPFIND - * - * This WebDAV method requests information about an uri resource, or a list of resources - * If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value - * If the value is 1, it means that it also expects a list of sub-resources (e.g.: files in a directory) - * - * The request body contains an XML data structure that has a list of properties the client understands - * The response body is also an xml document, containing information about every uri resource and the requested properties - * - * It has to return a HTTP 207 Multi-status status code - * - * @param string $uri - * @return void - */ - protected function httpPropfind($uri) { - - // $xml = new Sabre_DAV_XMLReader(file_get_contents('php://input')); - $requestedProperties = $this->parsePropfindRequest($this->httpRequest->getBody(true)); - - $depth = $this->getHTTPDepth(1); - // The only two options for the depth of a propfind is 0 or 1 - if ($depth!=0) $depth = 1; - - $newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth); - - // This is a multi-status response - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - // Normally this header is only needed for OPTIONS responses, however.. - // iCal seems to also depend on these being set for PROPFIND. Since - // this is not harmful, we'll add it. - $features = array('1','3', 'extended-mkcol'); - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - $this->httpResponse->setHeader('DAV',implode(', ',$features)); - - $data = $this->generateMultiStatus($newProperties); - $this->httpResponse->sendBody($data); - - } - - /** - * WebDAV PROPPATCH - * - * This method is called to update properties on a Node. The request is an XML body with all the mutations. - * In this XML body it is specified which properties should be set/updated and/or deleted - * - * @param string $uri - * @return void - */ - protected function httpPropPatch($uri) { - - $newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true)); - - $result = $this->updateProperties($uri, $newProperties); - - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - $this->httpResponse->sendBody( - $this->generateMultiStatus(array($result)) - ); - - } - - /** - * HTTP PUT method - * - * This HTTP method updates a file, or creates a new one. - * - * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 200 Ok - * - * @param string $uri - * @return void - */ - protected function httpPut($uri) { - - $body = $this->httpRequest->getBody(); - - // Intercepting Content-Range - if ($this->httpRequest->getHeader('Content-Range')) { - /** - Content-Range is dangerous for PUT requests: PUT per definition - stores a full resource. draft-ietf-httpbis-p2-semantics-15 says - in section 7.6: - An origin server SHOULD reject any PUT request that contains a - Content-Range header field, since it might be misinterpreted as - partial content (or might be partial content that is being mistakenly - PUT as a full representation). Partial content updates are possible - by targeting a separately identified resource with state that - overlaps a portion of the larger resource, or by using a different - method that has been specifically defined for partial updates (for - example, the PATCH method defined in [RFC5789]). - This clarifies RFC2616 section 9.6: - The recipient of the entity MUST NOT ignore any Content-* - (e.g. Content-Range) headers that it does not understand or implement - and MUST return a 501 (Not Implemented) response in such cases. - OTOH is a PUT request with a Content-Range currently the only way to - continue an aborted upload request and is supported by curl, mod_dav, - Tomcat and others. Since some clients do use this feature which results - in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject - all PUT requests with a Content-Range for now. - */ - - throw new Sabre_DAV_Exception_NotImplemented('PUT with Content-Range is not allowed.'); - } - - // Intercepting the Finder problem - if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) { - - /** - Many webservers will not cooperate well with Finder PUT requests, - because it uses 'Chunked' transfer encoding for the request body. - - The symptom of this problem is that Finder sends files to the - server, but they arrive as 0-lenght files in PHP. - - If we don't do anything, the user might think they are uploading - files successfully, but they end up empty on the server. Instead, - we throw back an error if we detect this. - - The reason Finder uses Chunked, is because it thinks the files - might change as it's being uploaded, and therefore the - Content-Length can vary. - - Instead it sends the X-Expected-Entity-Length header with the size - of the file at the very start of the request. If this header is set, - but we don't get a request body we will fail the request to - protect the end-user. - */ - - // Only reading first byte - $firstByte = fread($body,1); - if (strlen($firstByte)!==1) { - throw new Sabre_DAV_Exception_Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.'); - } - - // The body needs to stay intact, so we copy everything to a - // temporary stream. - - $newBody = fopen('php://temp','r+'); - fwrite($newBody,$firstByte); - stream_copy_to_stream($body, $newBody); - rewind($newBody); - - $body = $newBody; - - } - - if ($this->tree->nodeExists($uri)) { - - $node = $this->tree->getNodeForPath($uri); - - // Checking If-None-Match and related headers. - if (!$this->checkPreconditions()) return; - - // If the node is a collection, we'll deny it - if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_Conflict('PUT is not allowed on non-files.'); - if (!$this->broadcastEvent('beforeWriteContent',array($this->getRequestUri()))) return false; - - $node->put($body); - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(204); - - } else { - - // If we got here, the resource didn't exist yet. - if (!$this->createFile($this->getRequestUri(),$body)) { - // For one reason or another the file was not created. - return; - } - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(201); - - } - - } - - - /** - * WebDAV MKCOL - * - * The MKCOL method is used to create a new collection (directory) on the server - * - * @param string $uri - * @return void - */ - protected function httpMkcol($uri) { - - $requestBody = $this->httpRequest->getBody(true); - - if ($requestBody) { - - $contentType = $this->httpRequest->getHeader('Content-Type'); - if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) { - - // We must throw 415 for unsupport mkcol bodies - throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type'); - - } - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($requestBody); - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') { - - // We must throw 415 for unsupport mkcol bodies - throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.'); - - } - - $properties = array(); - foreach($dom->firstChild->childNodes as $childNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue; - $properties = array_merge($properties, Sabre_DAV_XMLUtil::parseProperties($childNode, $this->propertyMap)); - - } - if (!isset($properties['{DAV:}resourcetype'])) - throw new Sabre_DAV_Exception_BadRequest('The mkcol request must include a {DAV:}resourcetype property'); - - $resourceType = $properties['{DAV:}resourcetype']->getValue(); - unset($properties['{DAV:}resourcetype']); - - } else { - - $properties = array(); - $resourceType = array('{DAV:}collection'); - - } - - $result = $this->createCollection($uri, $resourceType, $properties); - - if (is_array($result)) { - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - $this->httpResponse->sendBody( - $this->generateMultiStatus(array($result)) - ); - - } else { - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(201); - } - - } - - /** - * WebDAV HTTP MOVE method - * - * This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo - * - * @param string $uri - * @return void - */ - protected function httpMove($uri) { - - $moveInfo = $this->getCopyAndMoveInfo(); - - // If the destination is part of the source tree, we must fail - if ($moveInfo['destination']==$uri) - throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); - - if ($moveInfo['destinationExists']) { - - if (!$this->broadcastEvent('beforeUnbind',array($moveInfo['destination']))) return false; - $this->tree->delete($moveInfo['destination']); - - } - - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return false; - if (!$this->broadcastEvent('beforeBind',array($moveInfo['destination']))) return false; - $this->tree->move($uri,$moveInfo['destination']); - $this->broadcastEvent('afterBind',array($moveInfo['destination'])); - - // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201); - - } - - /** - * WebDAV HTTP COPY method - * - * This method copies one uri to a different uri, and works much like the MOVE request - * A lot of the actual request processing is done in getCopyMoveInfo - * - * @param string $uri - * @return void - */ - protected function httpCopy($uri) { - - $copyInfo = $this->getCopyAndMoveInfo(); - // If the destination is part of the source tree, we must fail - if ($copyInfo['destination']==$uri) - throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); - - if ($copyInfo['destinationExists']) { - if (!$this->broadcastEvent('beforeUnbind',array($copyInfo['destination']))) return false; - $this->tree->delete($copyInfo['destination']); - - } - if (!$this->broadcastEvent('beforeBind',array($copyInfo['destination']))) return false; - $this->tree->copy($uri,$copyInfo['destination']); - $this->broadcastEvent('afterBind',array($copyInfo['destination'])); - - // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201); - - } - - - - /** - * HTTP REPORT method implementation - * - * Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253) - * It's used in a lot of extensions, so it made sense to implement it into the core. - * - * @param string $uri - * @return void - */ - protected function httpReport($uri) { - - $body = $this->httpRequest->getBody(true); - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $reportName = Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild); - - if ($this->broadcastEvent('report',array($reportName,$dom, $uri))) { - - // If broadcastEvent returned true, it means the report was not supported - throw new Sabre_DAV_Exception_ReportNotImplemented(); - - } - - } - - // }}} - // {{{ HTTP/WebDAV protocol helpers - - /** - * Returns an array with all the supported HTTP methods for a specific uri. - * - * @param string $uri - * @return array - */ - public function getAllowedMethods($uri) { - - $methods = array( - 'OPTIONS', - 'GET', - 'HEAD', - 'DELETE', - 'PROPFIND', - 'PUT', - 'PROPPATCH', - 'COPY', - 'MOVE', - 'REPORT' - ); - - // The MKCOL is only allowed on an unmapped uri - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - $methods[] = 'MKCOL'; - } - - // We're also checking if any of the plugins register any new methods - foreach($this->plugins as $plugin) $methods = array_merge($methods,$plugin->getHTTPMethods($uri)); - array_unique($methods); - - return $methods; - - } - - /** - * Gets the uri for the request, keeping the base uri into consideration - * - * @return string - */ - public function getRequestUri() { - - return $this->calculateUri($this->httpRequest->getUri()); - - } - - /** - * Calculates the uri for a request, making sure that the base uri is stripped out - * - * @param string $uri - * @throws Sabre_DAV_Exception_Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri - * @return string - */ - public function calculateUri($uri) { - - if ($uri[0]!='/' && strpos($uri,'://')) { - - $uri = parse_url($uri,PHP_URL_PATH); - - } - - $uri = str_replace('//','/',$uri); - - if (strpos($uri,$this->getBaseUri())===0) { - - return trim(Sabre_DAV_URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/'); - - // A special case, if the baseUri was accessed without a trailing - // slash, we'll accept it as well. - } elseif ($uri.'/' === $this->getBaseUri()) { - - return ''; - - } else { - - throw new Sabre_DAV_Exception_Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')'); - - } - - } - - /** - * Returns the HTTP depth header - * - * This method returns the contents of the HTTP depth request header. If the depth header was 'infinity' it will return the Sabre_DAV_Server::DEPTH_INFINITY object - * It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existant - * - * @param mixed $default - * @return int - */ - public function getHTTPDepth($default = self::DEPTH_INFINITY) { - - // If its not set, we'll grab the default - $depth = $this->httpRequest->getHeader('Depth'); - - if (is_null($depth)) return $default; - - if ($depth == 'infinity') return self::DEPTH_INFINITY; - - - // If its an unknown value. we'll grab the default - if (!ctype_digit($depth)) return $default; - - return (int)$depth; - - } - - /** - * Returns the HTTP range header - * - * This method returns null if there is no well-formed HTTP range request - * header or array($start, $end). - * - * The first number is the offset of the first byte in the range. - * The second number is the offset of the last byte in the range. - * - * If the second offset is null, it should be treated as the offset of the last byte of the entity - * If the first offset is null, the second offset should be used to retrieve the last x bytes of the entity - * - * return $mixed - */ - public function getHTTPRange() { - - $range = $this->httpRequest->getHeader('range'); - if (is_null($range)) return null; - - // Matching "Range: bytes=1234-5678: both numbers are optional - - if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null; - - if ($matches[1]==='' && $matches[2]==='') return null; - - return array( - $matches[1]!==''?$matches[1]:null, - $matches[2]!==''?$matches[2]:null, - ); - - } - - - /** - * Returns information about Copy and Move requests - * - * This function is created to help getting information about the source and the destination for the - * WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions - * - * The returned value is an array with the following keys: - * * destination - Destination path - * * destinationExists - Wether or not the destination is an existing url (and should therefore be overwritten) - * - * @return array - */ - public function getCopyAndMoveInfo() { - - // Collecting the relevant HTTP headers - if (!$this->httpRequest->getHeader('Destination')) throw new Sabre_DAV_Exception_BadRequest('The destination header was not supplied'); - $destination = $this->calculateUri($this->httpRequest->getHeader('Destination')); - $overwrite = $this->httpRequest->getHeader('Overwrite'); - if (!$overwrite) $overwrite = 'T'; - if (strtoupper($overwrite)=='T') $overwrite = true; - elseif (strtoupper($overwrite)=='F') $overwrite = false; - // We need to throw a bad request exception, if the header was invalid - else throw new Sabre_DAV_Exception_BadRequest('The HTTP Overwrite header should be either T or F'); - - list($destinationDir) = Sabre_DAV_URLUtil::splitPath($destination); - - try { - $destinationParent = $this->tree->getNodeForPath($destinationDir); - if (!($destinationParent instanceof Sabre_DAV_ICollection)) throw new Sabre_DAV_Exception_UnsupportedMediaType('The destination node is not a collection'); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // If the destination parent node is not found, we throw a 409 - throw new Sabre_DAV_Exception_Conflict('The destination node is not found'); - } - - try { - - $destinationNode = $this->tree->getNodeForPath($destination); - - // If this succeeded, it means the destination already exists - // we'll need to throw precondition failed in case overwrite is false - if (!$overwrite) throw new Sabre_DAV_Exception_PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite'); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // Destination didn't exist, we're all good - $destinationNode = false; - - - - } - - // These are the three relevant properties we need to return - return array( - 'destination' => $destination, - 'destinationExists' => $destinationNode==true, - 'destinationNode' => $destinationNode, - ); - - } - - /** - * Returns a list of properties for a path - * - * This is a simplified version getPropertiesForPath. - * if you aren't interested in status codes, but you just - * want to have a flat list of properties. Use this method. - * - * @param string $path - * @param array $propertyNames - */ - public function getProperties($path, $propertyNames) { - - $result = $this->getPropertiesForPath($path,$propertyNames,0); - return $result[0][200]; - - } - - /** - * Returns a list of HTTP headers for a particular resource - * - * The generated http headers are based on properties provided by the - * resource. The method basically provides a simple mapping between - * DAV property and HTTP header. - * - * The headers are intended to be used for HEAD and GET requests. - * - * @param string $path - */ - public function getHTTPHeaders($path) { - - $propertyMap = array( - '{DAV:}getcontenttype' => 'Content-Type', - '{DAV:}getcontentlength' => 'Content-Length', - '{DAV:}getlastmodified' => 'Last-Modified', - '{DAV:}getetag' => 'ETag', - ); - - $properties = $this->getProperties($path,array_keys($propertyMap)); - - $headers = array(); - foreach($propertyMap as $property=>$header) { - if (!isset($properties[$property])) continue; - - if (is_scalar($properties[$property])) { - $headers[$header] = $properties[$property]; - - // GetLastModified gets special cased - } elseif ($properties[$property] instanceof Sabre_DAV_Property_GetLastModified) { - $headers[$header] = $properties[$property]->getTime()->format(DateTime::RFC1123); - } - - } - - return $headers; - - } - - /** - * Returns a list of properties for a given path - * - * The path that should be supplied should have the baseUrl stripped out - * The list of properties should be supplied in Clark notation. If the list is empty - * 'allprops' is assumed. - * - * If a depth of 1 is requested child elements will also be returned. - * - * @param string $path - * @param array $propertyNames - * @param int $depth - * @return array - */ - public function getPropertiesForPath($path,$propertyNames = array(),$depth = 0) { - - if ($depth!=0) $depth = 1; - - $returnPropertyList = array(); - - $parentNode = $this->tree->getNodeForPath($path); - $nodes = array( - $path => $parentNode - ); - if ($depth==1 && $parentNode instanceof Sabre_DAV_ICollection) { - foreach($this->tree->getChildren($path) as $childNode) - $nodes[$path . '/' . $childNode->getName()] = $childNode; - } - - // If the propertyNames array is empty, it means all properties are requested. - // We shouldn't actually return everything we know though, and only return a - // sensible list. - $allProperties = count($propertyNames)==0; - - foreach($nodes as $myPath=>$node) { - - $currentPropertyNames = $propertyNames; - - $newProperties = array( - '200' => array(), - '404' => array(), - ); - - if ($allProperties) { - // Default list of propertyNames, when all properties were requested. - $currentPropertyNames = array( - '{DAV:}getlastmodified', - '{DAV:}getcontentlength', - '{DAV:}resourcetype', - '{DAV:}quota-used-bytes', - '{DAV:}quota-available-bytes', - '{DAV:}getetag', - '{DAV:}getcontenttype', - ); - } - - // If the resourceType was not part of the list, we manually add it - // and mark it for removal. We need to know the resourcetype in order - // to make certain decisions about the entry. - // WebDAV dictates we should add a / and the end of href's for collections - $removeRT = false; - if (!in_array('{DAV:}resourcetype',$currentPropertyNames)) { - $currentPropertyNames[] = '{DAV:}resourcetype'; - $removeRT = true; - } - - $result = $this->broadcastEvent('beforeGetProperties',array($myPath, $node, &$currentPropertyNames, &$newProperties)); - // If this method explicitly returned false, we must ignore this - // node as it is inacessible. - if ($result===false) continue; - - if (count($currentPropertyNames) > 0) { - - if ($node instanceof Sabre_DAV_IProperties) - $newProperties['200'] = $newProperties[200] + $node->getProperties($currentPropertyNames); - - } - - - foreach($currentPropertyNames as $prop) { - - if (isset($newProperties[200][$prop])) continue; - - switch($prop) { - case '{DAV:}getlastmodified' : if ($node->getLastModified()) $newProperties[200][$prop] = new Sabre_DAV_Property_GetLastModified($node->getLastModified()); break; - case '{DAV:}getcontentlength' : if ($node instanceof Sabre_DAV_IFile) $newProperties[200][$prop] = (int)$node->getSize(); break; - case '{DAV:}quota-used-bytes' : - if ($node instanceof Sabre_DAV_IQuota) { - $quotaInfo = $node->getQuotaInfo(); - $newProperties[200][$prop] = $quotaInfo[0]; - } - break; - case '{DAV:}quota-available-bytes' : - if ($node instanceof Sabre_DAV_IQuota) { - $quotaInfo = $node->getQuotaInfo(); - $newProperties[200][$prop] = $quotaInfo[1]; - } - break; - case '{DAV:}getetag' : if ($node instanceof Sabre_DAV_IFile && $etag = $node->getETag()) $newProperties[200][$prop] = $etag; break; - case '{DAV:}getcontenttype' : if ($node instanceof Sabre_DAV_IFile && $ct = $node->getContentType()) $newProperties[200][$prop] = $ct; break; - case '{DAV:}supported-report-set' : - $reports = array(); - foreach($this->plugins as $plugin) { - $reports = array_merge($reports, $plugin->getSupportedReportSet($myPath)); - } - $newProperties[200][$prop] = new Sabre_DAV_Property_SupportedReportSet($reports); - break; - case '{DAV:}resourcetype' : - $newProperties[200]['{DAV:}resourcetype'] = new Sabre_DAV_Property_ResourceType(); - foreach($this->resourceTypeMapping as $className => $resourceType) { - if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType); - } - break; - - } - - // If we were unable to find the property, we will list it as 404. - if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null; - - } - - $this->broadcastEvent('afterGetProperties',array(trim($myPath,'/'),&$newProperties)); - - $newProperties['href'] = trim($myPath,'/'); - - // Its is a WebDAV recommendation to add a trailing slash to collectionnames. - // Apple's iCal also requires a trailing slash for principals (rfc 3744). - // Therefore we add a trailing / for any non-file. This might need adjustments - // if we find there are other edge cases. - if ($myPath!='' && isset($newProperties[200]['{DAV:}resourcetype']) && count($newProperties[200]['{DAV:}resourcetype']->getValue())>0) $newProperties['href'] .='/'; - - // If the resourcetype property was manually added to the requested property list, - // we will remove it again. - if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']); - - $returnPropertyList[] = $newProperties; - - } - - return $returnPropertyList; - - } - - /** - * This method is invoked by sub-systems creating a new file. - * - * Currently this is done by HTTP PUT and HTTP LOCK (in the Locks_Plugin). - * It was important to get this done through a centralized function, - * allowing plugins to intercept this using the beforeCreateFile event. - * - * This method will return true if the file was actually created - * - * @param string $uri - * @param resource $data - * @return bool - */ - public function createFile($uri,$data) { - - list($dir,$name) = Sabre_DAV_URLUtil::splitPath($uri); - - if (!$this->broadcastEvent('beforeBind',array($uri))) return false; - if (!$this->broadcastEvent('beforeCreateFile',array($uri,$data))) return false; - - $parent = $this->tree->getNodeForPath($dir); - $parent->createFile($name,$data); - $this->tree->markDirty($dir); - - $this->broadcastEvent('afterBind',array($uri)); - - return true; - } - - /** - * This method is invoked by sub-systems creating a new directory. - * - * @param string $uri - * @return void - */ - public function createDirectory($uri) { - - $this->createCollection($uri,array('{DAV:}collection'),array()); - - } - - /** - * Use this method to create a new collection - * - * The {DAV:}resourcetype is specified using the resourceType array. - * At the very least it must contain {DAV:}collection. - * - * The properties array can contain a list of additional properties. - * - * @param string $uri The new uri - * @param array $resourceType The resourceType(s) - * @param array $properties A list of properties - * @return void - */ - public function createCollection($uri, array $resourceType, array $properties) { - - list($parentUri,$newName) = Sabre_DAV_URLUtil::splitPath($uri); - - // Making sure {DAV:}collection was specified as resourceType - if (!in_array('{DAV:}collection', $resourceType)) { - throw new Sabre_DAV_Exception_InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection'); - } - - - // Making sure the parent exists - try { - - $parent = $this->tree->getNodeForPath($parentUri); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - throw new Sabre_DAV_Exception_Conflict('Parent node does not exist'); - - } - - // Making sure the parent is a collection - if (!$parent instanceof Sabre_DAV_ICollection) { - throw new Sabre_DAV_Exception_Conflict('Parent node is not a collection'); - } - - - - // Making sure the child does not already exist - try { - $parent->getChild($newName); - - // If we got here.. it means there's already a node on that url, and we need to throw a 405 - throw new Sabre_DAV_Exception_MethodNotAllowed('The resource you tried to create already exists'); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // This is correct - } - - - if (!$this->broadcastEvent('beforeBind',array($uri))) return; - - // There are 2 modes of operation. The standard collection - // creates the directory, and then updates properties - // the extended collection can create it directly. - if ($parent instanceof Sabre_DAV_IExtendedCollection) { - - $parent->createExtendedCollection($newName, $resourceType, $properties); - - } else { - - // No special resourcetypes are supported - if (count($resourceType)>1) { - throw new Sabre_DAV_Exception_InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.'); - } - - $parent->createDirectory($newName); - $rollBack = false; - $exception = null; - $errorResult = null; - - if (count($properties)>0) { - - try { - - $errorResult = $this->updateProperties($uri, $properties); - if (!isset($errorResult[200])) { - $rollBack = true; - } - - } catch (Sabre_DAV_Exception $e) { - - $rollBack = true; - $exception = $e; - - } - - } - - if ($rollBack) { - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; - $this->tree->delete($uri); - - // Re-throwing exception - if ($exception) throw $exception; - - return $errorResult; - } - - } - $this->tree->markDirty($parentUri); - $this->broadcastEvent('afterBind',array($uri)); - - } - - /** - * This method updates a resource's properties - * - * The properties array must be a list of properties. Array-keys are - * property names in clarknotation, array-values are it's values. - * If a property must be deleted, the value should be null. - * - * Note that this request should either completely succeed, or - * completely fail. - * - * The response is an array with statuscodes for keys, which in turn - * contain arrays with propertynames. This response can be used - * to generate a multistatus body. - * - * @param string $uri - * @param array $properties - * @return array - */ - public function updateProperties($uri, array $properties) { - - // we'll start by grabbing the node, this will throw the appropriate - // exceptions if it doesn't. - $node = $this->tree->getNodeForPath($uri); - - $result = array( - 200 => array(), - 403 => array(), - 424 => array(), - ); - $remainingProperties = $properties; - $hasError = false; - - // Running through all properties to make sure none of them are protected - if (!$hasError) foreach($properties as $propertyName => $value) { - if(in_array($propertyName, $this->protectedProperties)) { - $result[403][$propertyName] = null; - unset($remainingProperties[$propertyName]); - $hasError = true; - } - } - - if (!$hasError) { - // Allowing plugins to take care of property updating - $hasError = !$this->broadcastEvent('updateProperties',array( - &$remainingProperties, - &$result, - $node - )); - } - - // If the node is not an instance of Sabre_DAV_IProperties, every - // property is 403 Forbidden - if (!$hasError && count($remainingProperties) && !($node instanceof Sabre_DAV_IProperties)) { - $hasError = true; - foreach($properties as $propertyName=> $value) { - $result[403][$propertyName] = null; - } - $remainingProperties = array(); - } - - // Only if there were no errors we may attempt to update the resource - if (!$hasError) { - - if (count($remainingProperties)>0) { - - $updateResult = $node->updateProperties($remainingProperties); - - if ($updateResult===true) { - // success - foreach($remainingProperties as $propertyName=>$value) { - $result[200][$propertyName] = null; - } - - } elseif ($updateResult===false) { - // The node failed to update the properties for an - // unknown reason - foreach($remainingProperties as $propertyName=>$value) { - $result[403][$propertyName] = null; - } - - } elseif (is_array($updateResult)) { - - // The node has detailed update information - // We need to merge the results with the earlier results. - foreach($updateResult as $status => $props) { - if (is_array($props)) { - if (!isset($result[$status])) - $result[$status] = array(); - - $result[$status] = array_merge($result[$status], $updateResult[$status]); - } - } - - } else { - throw new Sabre_DAV_Exception('Invalid result from updateProperties'); - } - $remainingProperties = array(); - } - - } - - foreach($remainingProperties as $propertyName=>$value) { - // if there are remaining properties, it must mean - // there's a dependency failure - $result[424][$propertyName] = null; - } - - // Removing empty array values - foreach($result as $status=>$props) { - - if (count($props)===0) unset($result[$status]); - - } - $result['href'] = $uri; - return $result; - - } - - /** - * This method checks the main HTTP preconditions. - * - * Currently these are: - * * If-Match - * * If-None-Match - * * If-Modified-Since - * * If-Unmodified-Since - * - * The method will return true if all preconditions are met - * The method will return false, or throw an exception if preconditions - * failed. If false is returned the operation should be aborted, and - * the appropriate HTTP response headers are already set. - * - * Normally this method will throw 412 Precondition Failed for failures - * related to If-None-Match, If-Match and If-Unmodified Since. It will - * set the status to 304 Not Modified for If-Modified_since. - * - * If the $handleAsGET argument is set to true, it will also return 304 - * Not Modified for failure of the If-None-Match precondition. This is the - * desired behaviour for HTTP GET and HTTP HEAD requests. - * - * @return bool - */ - public function checkPreconditions($handleAsGET = false) { - - $uri = $this->getRequestUri(); - $node = null; - $lastMod = null; - $etag = null; - - if ($ifMatch = $this->httpRequest->getHeader('If-Match')) { - - // If-Match contains an entity tag. Only if the entity-tag - // matches we are allowed to make the request succeed. - // If the entity-tag is '*' we are only allowed to make the - // request succeed if a resource exists at that url. - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match'); - } - - // Only need to check entity tags if they are not * - if ($ifMatch!=='*') { - - // There can be multiple etags - $ifMatch = explode(',',$ifMatch); - $haveMatch = false; - foreach($ifMatch as $ifMatchItem) { - - // Stripping any extra spaces - $ifMatchItem = trim($ifMatchItem,' '); - - $etag = $node->getETag(); - if ($etag===$ifMatchItem) { - $haveMatch = true; - } - } - if (!$haveMatch) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match'); - } - } - } - - if ($ifNoneMatch = $this->httpRequest->getHeader('If-None-Match')) { - - // The If-None-Match header contains an etag. - // Only if the ETag does not match the current ETag, the request will succeed - // The header can also contain *, in which case the request - // will only succeed if the entity does not exist at all. - $nodeExists = true; - if (!$node) { - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - $nodeExists = false; - } - } - if ($nodeExists) { - $haveMatch = false; - if ($ifNoneMatch==='*') $haveMatch = true; - else { - - // There might be multiple etags - $ifNoneMatch = explode(',', $ifNoneMatch); - $etag = $node->getETag(); - - foreach($ifNoneMatch as $ifNoneMatchItem) { - - // Stripping any extra spaces - $ifNoneMatchItem = trim($ifNoneMatchItem,' '); - - if ($etag===$ifNoneMatchItem) $haveMatch = true; - - } - - } - - if ($haveMatch) { - if ($handleAsGET) { - $this->httpResponse->sendStatus(304); - return false; - } else { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match'); - } - } - } - - } - - if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) { - - // The If-Modified-Since header contains a date. We - // will only return the entity if it has been changed since - // that date. If it hasn't been changed, we return a 304 - // header - // Note that this header only has to be checked if there was no If-None-Match header - // as per the HTTP spec. - $date = Sabre_HTTP_Util::parseHTTPDate($ifModifiedSince); - - if ($date) { - if (is_null($node)) { - $node = $this->tree->getNodeForPath($uri); - } - $lastMod = $node->getLastModified(); - if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); - if ($lastMod <= $date) { - $this->httpResponse->sendStatus(304); - return false; - } - } - } - } - - if ($ifUnmodifiedSince = $this->httpRequest->getHeader('If-Unmodified-Since')) { - - // The If-Unmodified-Since will allow allow the request if the - // entity has not changed since the specified date. - $date = Sabre_HTTP_Util::parseHTTPDate($ifUnmodifiedSince); - - // We must only check the date if it's valid - if ($date) { - if (is_null($node)) { - $node = $this->tree->getNodeForPath($uri); - } - $lastMod = $node->getLastModified(); - if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); - if ($lastMod > $date) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since'); - } - } - } - - } - return true; - - } - - // }}} - // {{{ XML Readers & Writers - - - /** - * Generates a WebDAV propfind response body based on a list of nodes - * - * @param array $fileProperties The list with nodes - * @param array $requestedProperties The properties that should be returned - * @return string - */ - public function generateMultiStatus(array $fileProperties) { - - $dom = new DOMDocument('1.0','utf-8'); - //$dom->formatOutput = true; - $multiStatus = $dom->createElement('d:multistatus'); - $dom->appendChild($multiStatus); - - // Adding in default namespaces - foreach($this->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - - } - - foreach($fileProperties as $entry) { - - $href = $entry['href']; - unset($entry['href']); - - $response = new Sabre_DAV_Property_Response($href,$entry); - $response->serialize($this,$multiStatus); - - } - - return $dom->saveXML(); - - } - - /** - * This method parses a PropPatch request - * - * PropPatch changes the properties for a resource. This method - * returns a list of properties. - * - * The keys in the returned array contain the property name (e.g.: {DAV:}displayname, - * and the value contains the property value. If a property is to be removed the value - * will be null. - * - * @param string $body xml body - * @return array list of properties in need of updating or deletion - */ - public function parsePropPatchRequest($body) { - - //We'll need to change the DAV namespace declaration to something else in order to make it parsable - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $newProperties = array(); - - foreach($dom->firstChild->childNodes as $child) { - - if ($child->nodeType !== XML_ELEMENT_NODE) continue; - - $operation = Sabre_DAV_XMLUtil::toClarkNotation($child); - - if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue; - - $innerProperties = Sabre_DAV_XMLUtil::parseProperties($child, $this->propertyMap); - - foreach($innerProperties as $propertyName=>$propertyValue) { - - if ($operation==='{DAV:}remove') { - $propertyValue = null; - } - - $newProperties[$propertyName] = $propertyValue; - - } - - } - - return $newProperties; - - } - - /** - * This method parses the PROPFIND request and returns its information - * - * This will either be a list of properties, or an empty array; in which case - * an {DAV:}allprop was requested. - * - * @param string $body - * @return array - */ - public function parsePropFindRequest($body) { - - // If the propfind body was empty, it means IE is requesting 'all' properties - if (!$body) return array(); - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - $elem = $dom->getElementsByTagNameNS('urn:DAV','propfind')->item(0); - return array_keys(Sabre_DAV_XMLUtil::parseProperties($elem)); - - } - - // }}} - -} - diff --git a/3rdparty/Sabre/DAV/ServerPlugin.php b/3rdparty/Sabre/DAV/ServerPlugin.php deleted file mode 100644 index 6909f600c2..0000000000 --- a/3rdparty/Sabre/DAV/ServerPlugin.php +++ /dev/null @@ -1,90 +0,0 @@ -name = $name; - foreach($children as $child) { - - if (!($child instanceof Sabre_DAV_INode)) throw new Sabre_DAV_Exception('Only instances of Sabre_DAV_INode are allowed to be passed in the children argument'); - $this->addChild($child); - - } - - } - - /** - * Adds a new childnode to this collection - * - * @param Sabre_DAV_INode $child - * @return void - */ - public function addChild(Sabre_DAV_INode $child) { - - $this->children[$child->getName()] = $child; - - } - - /** - * Returns the name of the collection - * - * @return string - */ - public function getName() { - - return $this->name; - - } - - /** - * Returns a child object, by its name. - * - * This method makes use of the getChildren method to grab all the child nodes, and compares the name. - * Generally its wise to override this, as this can usually be optimized - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - if (isset($this->children[$name])) return $this->children[$name]; - throw new Sabre_DAV_Exception_FileNotFound('File not found: ' . $name . ' in \'' . $this->getName() . '\''); - - } - - /** - * Returns a list of children for this collection - * - * @return array - */ - public function getChildren() { - - return array_values($this->children); - - } - - -} - diff --git a/3rdparty/Sabre/DAV/SimpleDirectory.php b/3rdparty/Sabre/DAV/SimpleDirectory.php deleted file mode 100644 index 516a3aa907..0000000000 --- a/3rdparty/Sabre/DAV/SimpleDirectory.php +++ /dev/null @@ -1,21 +0,0 @@ -name = $name; - $this->contents = $contents; - $this->mimeType = $mimeType; - - } - - /** - * Returns the node name for this file. - * - * This name is used to construct the url. - * - * @return string - */ - public function getName() { - - return $this->name; - - } - - /** - * Returns the data - * - * This method may either return a string or a readable stream resource - * - * @return mixed - */ - public function get() { - - return $this->contents; - - } - - /** - * Returns the size of the file, in bytes. - * - * @return int - */ - public function getSize() { - - return strlen($this->contents); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - */ - public function getETag() { - - return '"' . md5($this->contents) . '"'; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - */ - public function getContentType() { - - return $this->mimeType; - - } - -} - -?> diff --git a/3rdparty/Sabre/DAV/StringUtil.php b/3rdparty/Sabre/DAV/StringUtil.php deleted file mode 100644 index 440cf6866c..0000000000 --- a/3rdparty/Sabre/DAV/StringUtil.php +++ /dev/null @@ -1,91 +0,0 @@ -dataDir = $dataDir; - - } - - /** - * Initialize the plugin - * - * This is called automatically be the Server class after this plugin is - * added with Sabre_DAV_Server::addPlugin() - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod')); - $server->subscribeEvent('beforeCreateFile',array($this,'beforeCreateFile')); - - } - - /** - * This method is called before any HTTP method handler - * - * This method intercepts any GET, DELETE, PUT and PROPFIND calls to - * filenames that are known to match the 'temporary file' regex. - * - * @param string $method - * @return bool - */ - public function beforeMethod($method, $uri) { - - if (!$tempLocation = $this->isTempFile($uri)) - return true; - - switch($method) { - case 'GET' : - return $this->httpGet($tempLocation); - case 'PUT' : - return $this->httpPut($tempLocation); - case 'PROPFIND' : - return $this->httpPropfind($tempLocation, $uri); - case 'DELETE' : - return $this->httpDelete($tempLocation); - } - return true; - - } - - /** - * This method is invoked if some subsystem creates a new file. - * - * This is used to deal with HTTP LOCK requests which create a new - * file. - * - * @param string $uri - * @param resource $data - * @return bool - */ - public function beforeCreateFile($uri,$data) { - - if ($tempPath = $this->isTempFile($uri)) { - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - file_put_contents($tempPath,$data); - return false; - } - return true; - - } - - /** - * This method will check if the url matches the temporary file pattern - * if it does, it will return an path based on $this->dataDir for the - * temporary file storage. - * - * @param string $path - * @return boolean|string - */ - protected function isTempFile($path) { - - // We're only interested in the basename. - list(, $tempPath) = Sabre_DAV_URLUtil::splitPath($path); - - foreach($this->temporaryFilePatterns as $tempFile) { - - if (preg_match($tempFile,$tempPath)) { - return $this->dataDir . '/sabredav_' . md5($path) . '.tempfile'; - } - - } - - return false; - - } - - - /** - * This method handles the GET method for temporary files. - * If the file doesn't exist, it will return false which will kick in - * the regular system for the GET method. - * - * @param string $tempLocation - * @return bool - */ - public function httpGet($tempLocation) { - - if (!file_exists($tempLocation)) return true; - - $hR = $this->server->httpResponse; - $hR->setHeader('Content-Type','application/octet-stream'); - $hR->setHeader('Content-Length',filesize($tempLocation)); - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(200); - $hR->sendBody(fopen($tempLocation,'r')); - return false; - - } - - /** - * This method handles the PUT method. - * - * @param string $tempLocation - * @return bool - */ - public function httpPut($tempLocation) { - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - - $newFile = !file_exists($tempLocation); - - if (!$newFile && ($this->server->httpRequest->getHeader('If-None-Match'))) { - throw new Sabre_DAV_Exception_PreconditionFailed('The resource already exists, and an If-None-Match header was supplied'); - } - - file_put_contents($tempLocation,$this->server->httpRequest->getBody()); - $hR->sendStatus($newFile?201:200); - return false; - - } - - /** - * This method handles the DELETE method. - * - * If the file didn't exist, it will return false, which will make the - * standard HTTP DELETE handler kick in. - * - * @param string $tempLocation - * @return bool - */ - public function httpDelete($tempLocation) { - - if (!file_exists($tempLocation)) return true; - - unlink($tempLocation); - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(204); - return false; - - } - - /** - * This method handles the PROPFIND method. - * - * It's a very lazy method, it won't bother checking the request body - * for which properties were requested, and just sends back a default - * set of properties. - * - * @param string $tempLocation - * @return void - */ - public function httpPropfind($tempLocation, $uri) { - - if (!file_exists($tempLocation)) return true; - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(207); - $hR->setHeader('Content-Type','application/xml; charset=utf-8'); - - $requestedProps = $this->server->parsePropFindRequest($this->server->httpRequest->getBody(true)); - - $properties = array( - 'href' => $uri, - 200 => array( - '{DAV:}getlastmodified' => new Sabre_DAV_Property_GetLastModified(filemtime($tempLocation)), - '{DAV:}getcontentlength' => filesize($tempLocation), - '{DAV:}resourcetype' => new Sabre_DAV_Property_ResourceType(null), - '{'.Sabre_DAV_Server::NS_SABREDAV.'}tempFile' => true, - - ), - ); - - $data = $this->server->generateMultiStatus(array($properties)); - $hR->sendBody($data); - return false; - - } - - -} diff --git a/3rdparty/Sabre/DAV/Tree.php b/3rdparty/Sabre/DAV/Tree.php deleted file mode 100644 index 98e6f62c9e..0000000000 --- a/3rdparty/Sabre/DAV/Tree.php +++ /dev/null @@ -1,192 +0,0 @@ -getNodeForPath($path); - return true; - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Copies a file from path to another - * - * @param string $sourcePath The source location - * @param string $destinationPath The full destination path - * @return void - */ - public function copy($sourcePath, $destinationPath) { - - $sourceNode = $this->getNodeForPath($sourcePath); - - // grab the dirname and basename components - list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); - - $destinationParent = $this->getNodeForPath($destinationDir); - $this->copyNode($sourceNode,$destinationParent,$destinationName); - - $this->markDirty($destinationDir); - - } - - /** - * Moves a file from one location to another - * - * @param string $sourcePath The path to the file which should be moved - * @param string $destinationPath The full destination path, so not just the destination parent node - * @return int - */ - public function move($sourcePath, $destinationPath) { - - list($sourceDir, $sourceName) = Sabre_DAV_URLUtil::splitPath($sourcePath); - list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); - - if ($sourceDir===$destinationDir) { - $renameable = $this->getNodeForPath($sourcePath); - $renameable->setName($destinationName); - } else { - $this->copy($sourcePath,$destinationPath); - $this->getNodeForPath($sourcePath)->delete(); - } - $this->markDirty($sourceDir); - $this->markDirty($destinationDir); - - } - - /** - * Deletes a node from the tree - * - * @param string $path - * @return void - */ - public function delete($path) { - - $node = $this->getNodeForPath($path); - $node->delete(); - - list($parent) = Sabre_DAV_URLUtil::splitPath($path); - $this->markDirty($parent); - - } - - /** - * Returns a list of childnodes for a given path. - * - * @param string $path - * @return array - */ - public function getChildren($path) { - - $node = $this->getNodeForPath($path); - return $node->getChildren(); - - } - - /** - * This method is called with every tree update - * - * Examples of tree updates are: - * * node deletions - * * node creations - * * copy - * * move - * * renaming nodes - * - * If Tree classes implement a form of caching, this will allow - * them to make sure caches will be expired. - * - * If a path is passed, it is assumed that the entire subtree is dirty - * - * @param string $path - * @return void - */ - public function markDirty($path) { - - - } - - /** - * copyNode - * - * @param Sabre_DAV_INode $source - * @param Sabre_DAV_ICollection $destination - * @return void - */ - protected function copyNode(Sabre_DAV_INode $source,Sabre_DAV_ICollection $destinationParent,$destinationName = null) { - - if (!$destinationName) $destinationName = $source->getName(); - - if ($source instanceof Sabre_DAV_IFile) { - - $data = $source->get(); - - // If the body was a string, we need to convert it to a stream - if (is_string($data)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$data); - rewind($stream); - $data = $stream; - } - $destinationParent->createFile($destinationName,$data); - $destination = $destinationParent->getChild($destinationName); - - } elseif ($source instanceof Sabre_DAV_ICollection) { - - $destinationParent->createDirectory($destinationName); - - $destination = $destinationParent->getChild($destinationName); - foreach($source->getChildren() as $child) { - - $this->copyNode($child,$destination); - - } - - } - if ($source instanceof Sabre_DAV_IProperties && $destination instanceof Sabre_DAV_IProperties) { - - $props = $source->getProperties(array()); - $destination->updateProperties($props); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Tree/Filesystem.php b/3rdparty/Sabre/DAV/Tree/Filesystem.php deleted file mode 100644 index 5c611047e0..0000000000 --- a/3rdparty/Sabre/DAV/Tree/Filesystem.php +++ /dev/null @@ -1,124 +0,0 @@ -basePath = $basePath; - - } - - /** - * Returns a new node for the given path - * - * @param string $path - * @return void - */ - public function getNodeForPath($path) { - - $realPath = $this->getRealPath($path); - if (!file_exists($realPath)) throw new Sabre_DAV_Exception_FileNotFound('File at location ' . $realPath . ' not found'); - if (is_dir($realPath)) { - return new Sabre_DAV_FS_Directory($path); - } else { - return new Sabre_DAV_FS_File($path); - } - - } - - /** - * Returns the real filesystem path for a webdav url. - * - * @param string $publicPath - * @return string - */ - protected function getRealPath($publicPath) { - - return rtrim($this->basePath,'/') . '/' . trim($publicPath,'/'); - - } - - /** - * Copies a file or directory. - * - * This method must work recursively and delete the destination - * if it exists - * - * @param string $source - * @param string $destination - * @return void - */ - public function copy($source,$destination) { - - $source = $this->getRealPath($source); - $destination = $this->getRealPath($destination); - $this->realCopy($source,$destination); - - } - - /** - * Used by self::copy - * - * @param string $source - * @param string $destination - * @return void - */ - protected function realCopy($source,$destination) { - - if (is_file($source)) { - copy($source,$destination); - } else { - mkdir($destination); - foreach(scandir($source) as $subnode) { - - if ($subnode=='.' || $subnode=='..') continue; - $this->realCopy($source.'/'.$subnode,$destination.'/'.$subnode); - - } - } - - } - - /** - * Moves a file or directory recursively. - * - * If the destination exists, delete it first. - * - * @param string $source - * @param string $destination - * @return void - */ - public function move($source,$destination) { - - $source = $this->getRealPath($source); - $destination = $this->getRealPath($destination); - rename($source,$destination); - - } - -} - diff --git a/3rdparty/Sabre/DAV/URLUtil.php b/3rdparty/Sabre/DAV/URLUtil.php deleted file mode 100644 index 8f38749264..0000000000 --- a/3rdparty/Sabre/DAV/URLUtil.php +++ /dev/null @@ -1,125 +0,0 @@ - - * will be returned as: - * {http://www.example.org}myelem - * - * This format is used throughout the SabreDAV sourcecode. - * Elements encoded with the urn:DAV namespace will - * be returned as if they were in the DAV: namespace. This is to avoid - * compatibility problems. - * - * This function will return null if a nodetype other than an Element is passed. - * - * @param DOMElement $dom - * @return string - */ - static function toClarkNotation(DOMNode $dom) { - - if ($dom->nodeType !== XML_ELEMENT_NODE) return null; - - // Mapping back to the real namespace, in case it was dav - if ($dom->namespaceURI=='urn:DAV') $ns = 'DAV:'; else $ns = $dom->namespaceURI; - - // Mapping to clark notation - return '{' . $ns . '}' . $dom->localName; - - } - - /** - * Parses a clark-notation string, and returns the namespace and element - * name components. - * - * If the string was invalid, it will throw an InvalidArgumentException. - * - * @param string $str - * @throws InvalidArgumentException - * @return array - */ - static function parseClarkNotation($str) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$str,$matches)) { - throw new InvalidArgumentException('\'' . $str . '\' is not a valid clark-notation formatted string'); - } - - return array( - $matches[1], - $matches[2] - ); - - } - - /** - * This method takes an XML document (as string) and converts all instances of the - * DAV: namespace to urn:DAV - * - * This is unfortunately needed, because the DAV: namespace violates the xml namespaces - * spec, and causes the DOM to throw errors - */ - static function convertDAVNamespace($xmlDocument) { - - // This is used to map the DAV: namespace to urn:DAV. This is needed, because the DAV: - // namespace is actually a violation of the XML namespaces specification, and will cause errors - return preg_replace("/xmlns(:[A-Za-z0-9_]*)?=(\"|\')DAV:(\\2)/","xmlns\\1=\\2urn:DAV\\2",$xmlDocument); - - } - - /** - * This method provides a generic way to load a DOMDocument for WebDAV use. - * - * This method throws a Sabre_DAV_Exception_BadRequest exception for any xml errors. - * It does not preserve whitespace, and it converts the DAV: namespace to urn:DAV. - * - * @param string $xml - * @throws Sabre_DAV_Exception_BadRequest - * @return DOMDocument - */ - static function loadDOMDocument($xml) { - - if (empty($xml)) - throw new Sabre_DAV_Exception_BadRequest('Empty XML document sent'); - - // The BitKinex client sends xml documents as UTF-16. PHP 5.3.1 (and presumably lower) - // does not support this, so we must intercept this and convert to UTF-8. - if (substr($xml,0,12) === "\x3c\x00\x3f\x00\x78\x00\x6d\x00\x6c\x00\x20\x00") { - - // Note: the preceeding byte sequence is "]*)encoding="UTF-16"([^>]*)>|u','',$xml); - - } - - // Retaining old error setting - $oldErrorSetting = libxml_use_internal_errors(true); - - // Clearing any previous errors - libxml_clear_errors(); - - $dom = new DOMDocument(); - $dom->loadXML(self::convertDAVNamespace($xml),LIBXML_NOWARNING | LIBXML_NOERROR); - - // We don't generally care about any whitespace - $dom->preserveWhiteSpace = false; - - if ($error = libxml_get_last_error()) { - libxml_clear_errors(); - throw new Sabre_DAV_Exception_BadRequest('The request body had an invalid XML body. (message: ' . $error->message . ', errorcode: ' . $error->code . ', line: ' . $error->line . ')'); - } - - // Restoring old mechanism for error handling - if ($oldErrorSetting===false) libxml_use_internal_errors(false); - - return $dom; - - } - - /** - * Parses all WebDAV properties out of a DOM Element - * - * Generally WebDAV properties are encloded in {DAV:}prop elements. This - * method helps by going through all these and pulling out the actual - * propertynames, making them array keys and making the property values, - * well.. the array values. - * - * If no value was given (self-closing element) null will be used as the - * value. This is used in for example PROPFIND requests. - * - * Complex values are supported through the propertyMap argument. The - * propertyMap should have the clark-notation properties as it's keys, and - * classnames as values. - * - * When any of these properties are found, the unserialize() method will be - * (statically) called. The result of this method is used as the value. - * - * @param DOMElement $parentNode - * @param array $propertyMap - * @return array - */ - static function parseProperties(DOMElement $parentNode, array $propertyMap = array()) { - - $propList = array(); - foreach($parentNode->childNodes as $propNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($propNode)!=='{DAV:}prop') continue; - - foreach($propNode->childNodes as $propNodeData) { - - /* If there are no elements in here, we actually get 1 text node, this special case is dedicated to netdrive */ - if ($propNodeData->nodeType != XML_ELEMENT_NODE) continue; - - $propertyName = Sabre_DAV_XMLUtil::toClarkNotation($propNodeData); - if (isset($propertyMap[$propertyName])) { - $propList[$propertyName] = call_user_func(array($propertyMap[$propertyName],'unserialize'),$propNodeData); - } else { - $propList[$propertyName] = $propNodeData->textContent; - } - } - - - } - return $propList; - - } - -} diff --git a/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php b/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php deleted file mode 100644 index a361e05461..0000000000 --- a/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php +++ /dev/null @@ -1,121 +0,0 @@ -principalPrefix = $principalPrefix; - $this->principalBackend = $principalBackend; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principalInfo - * @return Sabre_DAVACL_IPrincipal - */ - abstract function getChildForPrincipal(array $principalInfo); - - /** - * Returns the name of this collection. - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalPrefix); - return $name; - - } - - /** - * Return the list of users - * - * @return void - */ - public function getChildren() { - - if ($this->disableListing) - throw new Sabre_DAV_Exception_MethodNotAllowed('Listing members of this collection is disabled'); - - $children = array(); - foreach($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { - - $children[] = $this->getChildForPrincipal($principalInfo); - - - } - return $children; - - } - - /** - * Returns a child object, by its name. - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_IPrincipal - */ - public function getChild($name) { - - $principalInfo = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/' . $name); - if (!$principalInfo) throw new Sabre_DAV_Exception_FileNotFound('Principal with name ' . $name . ' not found'); - return $this->getChildForPrincipal($principalInfo); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Exception/AceConflict.php b/3rdparty/Sabre/DAVACL/Exception/AceConflict.php deleted file mode 100644 index d10aeb4345..0000000000 --- a/3rdparty/Sabre/DAVACL/Exception/AceConflict.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:no-ace-conflict'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php b/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php deleted file mode 100644 index 024ab6641f..0000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php +++ /dev/null @@ -1,80 +0,0 @@ -uri = $uri; - $this->privileges = $privileges; - - } - - /** - * Adds in extra information in the xml response. - * - * This method adds the {DAV:}need-privileges element as defined in rfc3744 - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $doc = $errorNode->ownerDocument; - - $np = $doc->createElementNS('DAV:','d:need-privileges'); - $errorNode->appendChild($np); - - foreach($this->privileges as $privilege) { - - $resource = $doc->createElementNS('DAV:','d:resource'); - $np->appendChild($resource); - - $resource->appendChild($doc->createElementNS('DAV:','d:href',$server->getBaseUri() . $this->uri)); - - $priv = $doc->createElementNS('DAV:','d:privilege'); - $resource->appendChild($priv); - - preg_match('/^{([^}]*)}(.*)$/',$privilege,$privilegeParts); - $priv->appendChild($doc->createElementNS($privilegeParts[1],'d:' . $privilegeParts[2])); - - - } - - } - -} - diff --git a/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php b/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php deleted file mode 100644 index 60f49ebff4..0000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:no-abstract'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php b/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php deleted file mode 100644 index e056dc9e4f..0000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:recognized-principal'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php b/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php deleted file mode 100644 index 27db7cdd7d..0000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:not-supported-privilege'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/IACL.php b/3rdparty/Sabre/DAVACL/IACL.php deleted file mode 100644 index 506be4248d..0000000000 --- a/3rdparty/Sabre/DAVACL/IACL.php +++ /dev/null @@ -1,58 +0,0 @@ -getCurrentUserPrivilegeSet($uri); - - if (is_null($acl)) { - if ($this->allowAccessToNodesWithoutACL) { - return true; - } else { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$privileges); - else - return false; - - } - } - - $failed = array(); - foreach($privileges as $priv) { - - if (!in_array($priv, $acl)) { - $failed[] = $priv; - } - - } - - if ($failed) { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$failed); - else - return false; - } - return true; - - } - - /** - * Returns the standard users' principal. - * - * This is one authorative principal url for the current user. - * This method will return null if the user wasn't logged in. - * - * @return string|null - */ - public function getCurrentUserPrincipal() { - - $authPlugin = $this->server->getPlugin('auth'); - if (is_null($authPlugin)) return null; - - $userName = $authPlugin->getCurrentUser(); - if (!$userName) return null; - - return $this->defaultUsernamePath . '/' . $userName; - - } - - /** - * Returns a list of principals that's associated to the current - * user, either directly or through group membership. - * - * @return array - */ - public function getCurrentUserPrincipals() { - - $currentUser = $this->getCurrentUserPrincipal(); - - if (is_null($currentUser)) return array(); - - $check = array($currentUser); - $principals = array($currentUser); - - while(count($check)) { - - $principal = array_shift($check); - - $node = $this->server->tree->getNodeForPath($principal); - if ($node instanceof Sabre_DAVACL_IPrincipal) { - foreach($node->getGroupMembership() as $groupMember) { - - if (!in_array($groupMember, $principals)) { - - $check[] = $groupMember; - $principals[] = $groupMember; - - } - - } - - } - - } - - return $principals; - - } - - /** - * Returns the supported privilege structure for this ACL plugin. - * - * See RFC3744 for more details. Currently we default on a simple, - * standard structure. - * - * @return array - */ - public function getSupportedPrivilegeSet() { - - return array( - 'privilege' => '{DAV:}all', - 'abstract' => true, - 'aggregates' => array( - array( - 'privilege' => '{DAV:}read', - 'aggregates' => array( - array( - 'privilege' => '{DAV:}read-acl', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}read-current-user-privilege-set', - 'abstract' => true, - ), - ), - ), // {DAV:}read - array( - 'privilege' => '{DAV:}write', - 'aggregates' => array( - array( - 'privilege' => '{DAV:}write-acl', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}write-properties', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}write-content', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}bind', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}unbind', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}unlock', - 'abstract' => true, - ), - ), - ), // {DAV:}write - ), - ); // {DAV:}all - - } - - /** - * Returns the supported privilege set as a flat list - * - * This is much easier to parse. - * - * The returned list will be index by privilege name. - * The value is a struct containing the following properties: - * - aggregates - * - abstract - * - concrete - * - * @return array - */ - final public function getFlatPrivilegeSet() { - - $privs = $this->getSupportedPrivilegeSet(); - - $flat = array(); - $this->getFPSTraverse($privs, null, $flat); - - return $flat; - - } - - /** - * Traverses the privilege set tree for reordering - * - * This function is solely used by getFlatPrivilegeSet, and would have been - * a closure if it wasn't for the fact I need to support PHP 5.2. - * - * @return void - */ - final private function getFPSTraverse($priv, $concrete, &$flat) { - - $myPriv = array( - 'privilege' => $priv['privilege'], - 'abstract' => isset($priv['abstract']) && $priv['abstract'], - 'aggregates' => array(), - 'concrete' => isset($priv['abstract']) && $priv['abstract']?$concrete:$priv['privilege'], - ); - - if (isset($priv['aggregates'])) - foreach($priv['aggregates'] as $subPriv) $myPriv['aggregates'][] = $subPriv['privilege']; - - $flat[$priv['privilege']] = $myPriv; - - if (isset($priv['aggregates'])) { - - foreach($priv['aggregates'] as $subPriv) { - - $this->getFPSTraverse($subPriv, $myPriv['concrete'], $flat); - - } - - } - - } - - /** - * Returns the full ACL list. - * - * Either a uri or a Sabre_DAV_INode may be passed. - * - * null will be returned if the node doesn't support ACLs. - * - * @param string|Sabre_DAV_INode $node - * @return array - */ - public function getACL($node) { - - if (is_string($node)) { - $node = $this->server->tree->getNodeForPath($node); - } - if ($node instanceof Sabre_DAVACL_IACL) { - return $node->getACL(); - } - return null; - - } - - /** - * Returns a list of privileges the current user has - * on a particular node. - * - * Either a uri or a Sabre_DAV_INode may be passed. - * - * null will be returned if the node doesn't support ACLs. - * - * @param string|Sabre_DAV_INode $node - * @return array - */ - public function getCurrentUserPrivilegeSet($node) { - - if (is_string($node)) { - $node = $this->server->tree->getNodeForPath($node); - } - - $acl = $this->getACL($node); - if (is_null($acl)) return null; - - $principals = $this->getCurrentUserPrincipals(); - - $collected = array(); - - foreach($acl as $ace) { - - if (in_array($ace['principal'], $principals)) { - $collected[] = $ace; - } - - } - - // Now we deduct all aggregated privileges. - $flat = $this->getFlatPrivilegeSet(); - - $collected2 = array(); - foreach($collected as $privilege) { - - $collected2[] = $privilege['privilege']; - foreach($flat[$privilege['privilege']]['aggregates'] as $subPriv) { - if (!in_array($subPriv, $collected2)) - $collected2[] = $subPriv; - } - - } - - return $collected2; - - } - - /** - * Sets up the plugin - * - * This method is automatically called by the server class. - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); - - $server->subscribeEvent('beforeMethod', array($this,'beforeMethod'),20); - $server->subscribeEvent('beforeBind', array($this,'beforeBind'),20); - $server->subscribeEvent('beforeUnbind', array($this,'beforeUnbind'),20); - $server->subscribeEvent('updateProperties',array($this,'updateProperties')); - $server->subscribeEvent('beforeUnlock', array($this,'beforeUnlock'),20); - $server->subscribeEvent('report',array($this,'report')); - $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); - - array_push($server->protectedProperties, - '{DAV:}alternate-URI-set', - '{DAV:}principal-URL', - '{DAV:}group-membership', - '{DAV:}principal-collection-set', - '{DAV:}current-user-principal', - '{DAV:}supported-privilege-set', - '{DAV:}current-user-privilege-set', - '{DAV:}acl', - '{DAV:}acl-restrictions', - '{DAV:}inherited-acl-set', - '{DAV:}owner', - '{DAV:}group' - ); - - // Automatically mapping nodes implementing IPrincipal to the - // {DAV:}principal resourcetype. - $server->resourceTypeMapping['Sabre_DAVACL_IPrincipal'] = '{DAV:}principal'; - - // Mapping the group-member-set property to the HrefList property - // class. - $server->propertyMap['{DAV:}group-member-set'] = 'Sabre_DAV_Property_HrefList'; - - } - - - /* {{{ Event handlers */ - - /** - * Triggered before any method is handled - * - * @param string $method - * @param string $uri - * @return void - */ - public function beforeMethod($method, $uri) { - - $exists = $this->server->tree->nodeExists($uri); - - // If the node doesn't exists, none of these checks apply - if (!$exists) return; - - switch($method) { - - case 'GET' : - case 'HEAD' : - case 'OPTIONS' : - // For these 3 we only need to know if the node is readable. - $this->checkPrivileges($uri,'{DAV:}read'); - break; - - case 'PUT' : - case 'LOCK' : - case 'UNLOCK' : - // This method requires the write-content priv if the node - // already exists, and bind on the parent if the node is being - // created. - // The bind privilege is handled in the beforeBind event. - $this->checkPrivileges($uri,'{DAV:}write-content'); - break; - - - case 'PROPPATCH' : - $this->checkPrivileges($uri,'{DAV:}write-properties'); - break; - - case 'ACL' : - $this->checkPrivileges($uri,'{DAV:}write-acl'); - break; - - case 'COPY' : - case 'MOVE' : - // Copy requires read privileges on the entire source tree. - // If the target exists write-content normally needs to be - // checked, however, we're deleting the node beforehand and - // creating a new one after, so this is handled by the - // beforeUnbind event. - // - // The creation of the new node is handled by the beforeBind - // event. - // - // If MOVE is used beforeUnbind will also be used to check if - // the sourcenode can be deleted. - $this->checkPrivileges($uri,'{DAV:}read',self::R_RECURSIVE); - - break; - - } - - } - - /** - * Triggered before a new node is created. - * - * This allows us to check permissions for any operation that creates a - * new node, such as PUT, MKCOL, MKCALENDAR, LOCK, COPY and MOVE. - * - * @param string $uri - * @return void - */ - public function beforeBind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}bind'); - - } - - /** - * Triggered before a node is deleted - * - * This allows us to check permissions for any operation that will delete - * an existing node. - * - * @param string $uri - * @return void - */ - public function beforeUnbind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}unbind',self::R_RECURSIVEPARENTS); - - } - - /** - * Triggered before a node is unlocked. - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lock - * @TODO: not yet implemented - * @return void - */ - public function beforeUnlock($uri, Sabre_DAV_Locks_LockInfo $lock) { - - - } - - /** - * Triggered before properties are looked up in specific nodes. - * - * @param string $uri - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @TODO really should be broken into multiple methods, or even a class. - * @return void - */ - public function beforeGetProperties($uri, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { - - // Checking the read permission - if (!$this->checkPrivileges($uri,'{DAV:}read',self::R_PARENT,false)) { - - // User is not allowed to read properties - if ($this->hideNodesFromListings) { - return false; - } - - // Marking all requested properties as '403'. - foreach($requestedProperties as $key=>$requestedProperty) { - unset($requestedProperties[$key]); - $returnedProperties[403][$requestedProperty] = null; - } - return; - - } - - /* Adding principal properties */ - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - if (false !== ($index = array_search('{DAV:}alternate-URI-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}alternate-URI-set'] = new Sabre_DAV_Property_HrefList($node->getAlternateUriSet()); - - } - if (false !== ($index = array_search('{DAV:}principal-URL', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}principal-URL'] = new Sabre_DAV_Property_Href($node->getPrincipalUrl() . '/'); - - } - if (false !== ($index = array_search('{DAV:}group-member-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}group-member-set'] = new Sabre_DAV_Property_HrefList($node->getGroupMemberSet()); - - } - if (false !== ($index = array_search('{DAV:}group-membership', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}group-membership'] = new Sabre_DAV_Property_HrefList($node->getGroupMembership()); - - } - - if (false !== ($index = array_search('{DAV:}displayname', $requestedProperties))) { - - $returnedProperties[200]['{DAV:}displayname'] = $node->getDisplayName(); - - } - - } - if (false !== ($index = array_search('{DAV:}principal-collection-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $val = $this->principalCollectionSet; - // Ensuring all collections end with a slash - foreach($val as $k=>$v) $val[$k] = $v . '/'; - $returnedProperties[200]['{DAV:}principal-collection-set'] = new Sabre_DAV_Property_HrefList($val); - - } - if (false !== ($index = array_search('{DAV:}current-user-principal', $requestedProperties))) { - - unset($requestedProperties[$index]); - if ($url = $this->getCurrentUserPrincipal()) { - $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, $url . '/'); - } else { - $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED); - } - - } - if (false !== ($index = array_search('{DAV:}supported-privilege-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}supported-privilege-set'] = new Sabre_DAVACL_Property_SupportedPrivilegeSet($this->getSupportedPrivilegeSet()); - - } - if (false !== ($index = array_search('{DAV:}current-user-privilege-set', $requestedProperties))) { - - if (!$this->checkPrivileges($uri, '{DAV:}read-current-user-privilege-set', self::R_PARENT, false)) { - $returnedProperties[403]['{DAV:}current-user-privilege-set'] = null; - unset($requestedProperties[$index]); - } else { - $val = $this->getCurrentUserPrivilegeSet($node); - if (!is_null($val)) { - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}current-user-privilege-set'] = new Sabre_DAVACL_Property_CurrentUserPrivilegeSet($val); - } - } - - } - - /* The ACL property contains all the permissions */ - if (false !== ($index = array_search('{DAV:}acl', $requestedProperties))) { - - if (!$this->checkPrivileges($uri, '{DAV:}read-acl', self::R_PARENT, false)) { - - unset($requestedProperties[$index]); - $returnedProperties[403]['{DAV:}acl'] = null; - - } else { - - $acl = $this->getACL($node); - if (!is_null($acl)) { - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}acl'] = new Sabre_DAVACL_Property_Acl($this->getACL($node)); - } - - } - - } - - } - - /** - * This method intercepts PROPPATCH methods and make sure the - * group-member-set is updated correctly. - * - * @param array $propertyDelta - * @param array $result - * @param Sabre_DAV_INode $node - * @return void - */ - public function updateProperties(&$propertyDelta, &$result, Sabre_DAV_INode $node) { - - if (!array_key_exists('{DAV:}group-member-set', $propertyDelta)) - return; - - if (is_null($propertyDelta['{DAV:}group-member-set'])) { - $memberSet = array(); - } elseif ($propertyDelta['{DAV:}group-member-set'] instanceof Sabre_DAV_Property_HrefList) { - $memberSet = $propertyDelta['{DAV:}group-member-set']->getHrefs(); - } else { - throw new Sabre_DAV_Exception('The group-member-set property MUST be an instance of Sabre_DAV_Property_HrefList or null'); - } - - if (!($node instanceof Sabre_DAVACL_IPrincipal)) { - $result[403]['{DAV:}group-member-set'] = null; - unset($propertyDelta['{DAV:}group-member-set']); - - // Returning false will stop the updateProperties process - return false; - } - - $node->setGroupMemberSet($memberSet); - - $result[200]['{DAV:}group-member-set'] = null; - unset($propertyDelta['{DAV:}group-member-set']); - - } - - /** - * This method handels HTTP REPORT requests - * - * @param string $reportName - * @param DOMNode $dom - * @return void - */ - public function report($reportName, $dom) { - - switch($reportName) { - - case '{DAV:}principal-property-search' : - $this->principalPropertySearchReport($dom); - return false; - case '{DAV:}principal-search-property-set' : - $this->principalSearchPropertySetReport($dom); - return false; - case '{DAV:}expand-property' : - $this->expandPropertyReport($dom); - return false; - - } - - } - - /** - * This event is triggered for any HTTP method that is not known by the - * webserver. - * - * @param string $method - * @param string $uri - * @return void - */ - public function unknownMethod($method, $uri) { - - if ($method!=='ACL') return; - - $this->httpACL($uri); - return false; - - } - - /** - * This method is responsible for handling the 'ACL' event. - * - * @param string $uri - * @return void - */ - public function httpACL($uri) { - - $body = $this->server->httpRequest->getBody(true); - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $newAcl = - Sabre_DAVACL_Property_Acl::unserialize($dom->firstChild) - ->getPrivileges(); - - // Normalizing urls - foreach($newAcl as $k=>$newAce) { - $newAcl[$k]['principal'] = $this->server->calculateUri($newAce['principal']); - } - - $node = $this->server->tree->getNodeForPath($uri); - - if (!($node instanceof Sabre_DAVACL_IACL)) { - throw new Sabre_DAV_Exception_MethodNotAllowed('This node does not support the ACL method'); - } - - $oldAcl = $this->getACL($node); - - $supportedPrivileges = $this->getFlatPrivilegeSet(); - - /* Checking if protected principals from the existing principal set are - not overwritten. */ - foreach($oldAcl as $k=>$oldAce) { - - if (!isset($oldAce['protected']) || !$oldAce['protected']) continue; - - $found = false; - foreach($newAcl as $newAce) { - if ( - $newAce['privilege'] === $oldAce['privilege'] && - $newAce['principal'] === $oldAce['principal'] && - $newAce['protected'] - ) - $found = true; - } - - if (!$found) - throw new Sabre_DAVACL_Exception_AceConflict('This resource contained a protected {DAV:}ace, but this privilege did not occur in the ACL request'); - - } - - foreach($newAcl as $k=>$newAce) { - - // Do we recognize the privilege - if (!isset($supportedPrivileges[$newAce['privilege']])) { - throw new Sabre_DAVACL_Exception_NotSupportedPrivilege('The privilege you specified (' . $newAce['privilege'] . ') is not recognized by this server'); - } - - if ($supportedPrivileges[$newAce['privilege']]['abstract']) { - throw new Sabre_DAVACL_Exception_NoAbstract('The privilege you specified (' . $newAce['privilege'] . ') is an abstract privilege'); - } - - // Looking up the principal - try { - $principal = $this->server->tree->getNodeForPath($newAce['principal']); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified principal (' . $newAce['principal'] . ') does not exist'); - } - if (!($principal instanceof Sabre_DAVACL_IPrincipal)) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified uri (' . $newAce['principal'] . ') is not a principal'); - } - - } - $node->setACL($newAcl); - - } - - /* }}} */ - - /* Reports {{{ */ - - /** - * The expand-property report is defined in RFC3253 section 3-8. - * - * This report is very similar to a standard PROPFIND. The difference is - * that it has the additional ability to look at properties containing a - * {DAV:}href element, follow that property and grab additional elements - * there. - * - * Other rfc's, such as ACL rely on this report, so it made sense to put - * it in this plugin. - * - * @param DOMElement $dom - * @return void - */ - protected function expandPropertyReport($dom) { - - $requestedProperties = $this->parseExpandPropertyReportRequest($dom->firstChild->firstChild); - $depth = $this->server->getHTTPDepth(0); - $requestUri = $this->server->getRequestUri(); - - $result = $this->expandProperties($requestUri,$requestedProperties,$depth); - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - $multiStatus = $dom->createElement('d:multistatus'); - $dom->appendChild($multiStatus); - - // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - - } - - foreach($result as $response) { - $response->serialize($this->server, $multiStatus); - } - - $xml = $dom->saveXML(); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->sendBody($xml); - - } - - /** - * This method is used by expandPropertyReport to parse - * out the entire HTTP request. - * - * @param DOMElement $node - * @return array - */ - protected function parseExpandPropertyReportRequest($node) { - - $requestedProperties = array(); - do { - - if (Sabre_DAV_XMLUtil::toClarkNotation($node)!=='{DAV:}property') continue; - - if ($node->firstChild) { - - $children = $this->parseExpandPropertyReportRequest($node->firstChild); - - } else { - - $children = array(); - - } - - $namespace = $node->getAttribute('namespace'); - if (!$namespace) $namespace = 'DAV:'; - - $propName = '{'.$namespace.'}' . $node->getAttribute('name'); - $requestedProperties[$propName] = $children; - - } while ($node = $node->nextSibling); - - return $requestedProperties; - - } - - /** - * This method expands all the properties and returns - * a list with property values - * - * @param array $path - * @param array $requestedProperties the list of required properties - * @param array $depth - */ - protected function expandProperties($path,array $requestedProperties,$depth) { - - $foundProperties = $this->server->getPropertiesForPath($path,array_keys($requestedProperties),$depth); - - $result = array(); - - foreach($foundProperties as $node) { - - foreach($requestedProperties as $propertyName=>$childRequestedProperties) { - - // We're only traversing if sub-properties were requested - if(count($childRequestedProperties)===0) continue; - - // We only have to do the expansion if the property was found - // and it contains an href element. - if (!array_key_exists($propertyName,$node[200])) continue; - - if ($node[200][$propertyName] instanceof Sabre_DAV_Property_IHref) { - $hrefs = array($node[200][$propertyName]->getHref()); - } elseif ($node[200][$propertyName] instanceof Sabre_DAV_Property_HrefList) { - $hrefs = $node[200][$propertyName]->getHrefs(); - } - - $childProps = array(); - foreach($hrefs as $href) { - $childProps = array_merge($childProps, $this->expandProperties($href,$childRequestedProperties,0)); - } - $node[200][$propertyName] = new Sabre_DAV_Property_ResponseList($childProps); - - } - $result[] = new Sabre_DAV_Property_Response($path, $node); - - } - - return $result; - - } - - /** - * principalSearchPropertySetReport - * - * This method responsible for handing the - * {DAV:}principal-search-property-set report. This report returns a list - * of properties the client may search on, using the - * {DAV:}principal-property-search report. - * - * @param DOMDocument $dom - * @return void - */ - protected function principalSearchPropertySetReport(DOMDocument $dom) { - - $searchProperties = array( - '{DAV:}displayname' => 'display name' - ); - - $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { - throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); - } - - if ($dom->firstChild->hasChildNodes()) - throw new Sabre_DAV_Exception_BadRequest('The principal-search-property-set report element is not allowed to have child elements'); - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - $root = $dom->createElement('d:principal-search-property-set'); - $dom->appendChild($root); - // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $root->setAttribute('xmlns:' . $prefix,$namespace); - - } - - $nsList = $this->server->xmlNamespaces; - - foreach($searchProperties as $propertyName=>$description) { - - $psp = $dom->createElement('d:principal-search-property'); - $root->appendChild($psp); - - $prop = $dom->createElement('d:prop'); - $psp->appendChild($prop); - - $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); - - $currentProperty = $dom->createElement($nsList[$propName[1]] . ':' . $propName[2]); - $prop->appendChild($currentProperty); - - $descriptionElem = $dom->createElement('d:description'); - $descriptionElem->setAttribute('xml:lang','en'); - $descriptionElem->appendChild($dom->createTextNode($description)); - $psp->appendChild($descriptionElem); - - - } - - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->sendBody($dom->saveXML()); - - } - - /** - * principalPropertySearchReport - * - * This method is reponsible for handing the - * {DAV:}principal-property-search report. This report can be used for - * clients to search for groups of principals, based on the value of one - * or more properties. - * - * @param DOMDocument $dom - * @return void - */ - protected function principalPropertySearchReport(DOMDocument $dom) { - - $searchableProperties = array( - '{DAV:}displayname' => 'display name' - - ); - - list($searchProperties, $requestedProperties, $applyToPrincipalCollectionSet) = $this->parsePrincipalPropertySearchReportRequest($dom); - - $result = array(); - - if ($applyToPrincipalCollectionSet) { - $uris = array(); - } else { - $uris = array($this->server->getRequestUri()); - } - - $lookupResults = array(); - foreach($uris as $uri) { - - $p = array_keys($searchProperties); - $p[] = '{DAV:}resourcetype'; - $r = $this->server->getPropertiesForPath($uri, $p, 1); - - // The first item in the results is the parent, so we get rid of it. - array_shift($r); - $lookupResults = array_merge($lookupResults, $r); - } - - $matches = array(); - - foreach($lookupResults as $lookupResult) { - - // We're only looking for principals - if (!isset($lookupResult[200]['{DAV:}resourcetype']) || - (!($lookupResult[200]['{DAV:}resourcetype'] instanceof Sabre_DAV_Property_ResourceType)) || - !$lookupResult[200]['{DAV:}resourcetype']->is('{DAV:}principal')) continue; - - foreach($searchProperties as $searchProperty=>$searchValue) { - if (!isset($searchableProperties[$searchProperty])) { - // If a property is not 'searchable', the spec dictates - // this is not a match. - continue; - } - - if (isset($lookupResult[200][$searchProperty]) && - mb_stripos($lookupResult[200][$searchProperty], $searchValue, 0, 'UTF-8')!==false) { - $matches[] = $lookupResult['href']; - } - - } - - } - - $matchProperties = array(); - - foreach($matches as $match) { - - list($result) = $this->server->getPropertiesForPath($match, $requestedProperties, 0); - $matchProperties[] = $result; - - } - - $xml = $this->server->generateMultiStatus($matchProperties); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->sendBody($xml); - - } - - /** - * parsePrincipalPropertySearchReportRequest - * - * This method parses the request body from a - * {DAV:}principal-property-search report. - * - * This method returns an array with two elements: - * 1. an array with properties to search on, and their values - * 2. a list of propertyvalues that should be returned for the request. - * - * @param DOMDocument $dom - * @return array - */ - protected function parsePrincipalPropertySearchReportRequest($dom) { - - $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { - throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); - } - - $searchProperties = array(); - - $applyToPrincipalCollectionSet = false; - - // Parsing the search request - foreach($dom->firstChild->childNodes as $searchNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode) == '{DAV:}apply-to-principal-collection-set') - $applyToPrincipalCollectionSet = true; - - if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode)!=='{DAV:}property-search') - continue; - - $propertyName = null; - $propertyValue = null; - - foreach($searchNode->childNodes as $childNode) { - - switch(Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - - case '{DAV:}prop' : - $property = Sabre_DAV_XMLUtil::parseProperties($searchNode); - reset($property); - $propertyName = key($property); - break; - - case '{DAV:}match' : - $propertyValue = $childNode->textContent; - break; - - } - - - } - - if (is_null($propertyName) || is_null($propertyValue)) - throw new Sabre_DAV_Exception_BadRequest('Invalid search request. propertyname: ' . $propertyName . '. propertvvalue: ' . $propertyValue); - - $searchProperties[$propertyName] = $propertyValue; - - } - - return array($searchProperties, array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)), $applyToPrincipalCollectionSet); - - } - - - /* }}} */ - -} diff --git a/3rdparty/Sabre/DAVACL/Principal.php b/3rdparty/Sabre/DAVACL/Principal.php deleted file mode 100644 index 790603c900..0000000000 --- a/3rdparty/Sabre/DAVACL/Principal.php +++ /dev/null @@ -1,263 +0,0 @@ -principalBackend = $principalBackend; - $this->principalProperties = $principalProperties; - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalProperties['uri']; - - } - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - $uris = array(); - if (isset($this->principalProperties['{DAV:}alternate-URI-set'])) { - - $uris = $this->principalProperties['{DAV:}alternate-URI-set']; - - } - - if (isset($this->principalProperties['{http://sabredav.org/ns}email-address'])) { - $uris[] = 'mailto:' . $this->principalProperties['{http://sabredav.org/ns}email-address']; - } - - return array_unique($uris); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->principalProperties['uri']); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMemberShip($this->principalProperties['uri']); - - } - - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $groupMembers) { - - $this->principalBackend->setGroupMemberSet($this->principalProperties['uri'], $groupMembers); - - } - - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - $uri = $this->principalProperties['uri']; - list(, $name) = Sabre_DAV_URLUtil::splitPath($uri); - - return $name; - - } - - /** - * Returns the name of the user - * - * @return void - */ - public function getDisplayName() { - - if (isset($this->principalProperties['{DAV:}displayname'])) { - return $this->principalProperties['{DAV:}displayname']; - } else { - return $this->getName(); - } - - } - - /** - * Returns a list of properties - * - * @param array $requestedProperties - * @return void - */ - public function getProperties($requestedProperties) { - - $newProperties = array(); - foreach($requestedProperties as $propName) { - - if (isset($this->principalProperties[$propName])) { - $newProperties[$propName] = $this->principalProperties[$propName]; - } - - } - - return $newProperties; - - } - - /** - * Updates this principals properties. - * - * Currently this is not supported - * - * @param array $properties - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateProperties($properties) { - - return false; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalProperties['uri']; - - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'], - 'protected' => true, - ), - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Updating ACLs is not allowed here'); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php b/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php deleted file mode 100644 index 55bd1903c9..0000000000 --- a/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php +++ /dev/null @@ -1,206 +0,0 @@ -pdo = $pdo; - $this->tableName = $tableName; - $this->groupMembersTableName = $groupMembersTableName; - - } - - - /** - * Returns a list of principals based on a prefix. - * - * This prefix will often contain something like 'principals'. You are only - * expected to return principals that are in this base path. - * - * You are expected to return at least a 'uri' for every user, you can - * return any additional properties if you wish so. Common properties are: - * {DAV:}displayname - * {http://sabredav.org/ns}email-address - This is a custom SabreDAV - * field that's actualy injected in a number of other properties. If - * you have an email address, use this property. - * - * @param string $prefixPath - * @return array - */ - public function getPrincipalsByPrefix($prefixPath) { - $result = $this->pdo->query('SELECT uri, email, displayname FROM `'. $this->tableName . '`'); - - $principals = array(); - - while($row = $result->fetch(PDO::FETCH_ASSOC)) { - - // Checking if the principal is in the prefix - list($rowPrefix) = Sabre_DAV_URLUtil::splitPath($row['uri']); - if ($rowPrefix !== $prefixPath) continue; - - $principals[] = array( - 'uri' => $row['uri'], - '{DAV:}displayname' => $row['displayname']?$row['displayname']:basename($row['uri']), - '{http://sabredav.org/ns}email-address' => $row['email'], - ); - - } - - return $principals; - - } - - /** - * Returns a specific principal, specified by it's path. - * The returned structure should be the exact same as from - * getPrincipalsByPrefix. - * - * @param string $path - * @return array - */ - public function getPrincipalByPath($path) { - - $stmt = $this->pdo->prepare('SELECT id, uri, email, displayname FROM `'.$this->tableName.'` WHERE uri = ?'); - $stmt->execute(array($path)); - - $users = array(); - - $row = $stmt->fetch(PDO::FETCH_ASSOC); - if (!$row) return; - - return array( - 'id' => $row['id'], - 'uri' => $row['uri'], - '{DAV:}displayname' => $row['displayname']?$row['displayname']:basename($row['uri']), - '{http://sabredav.org/ns}email-address' => $row['email'], - ); - - } - - /** - * Returns the list of members for a group-principal - * - * @param string $principal - * @return array - */ - public function getGroupMemberSet($principal) { - - $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); - - $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM `'.$this->groupMembersTableName.'` AS groupmembers LEFT JOIN `'.$this->tableName.'` AS principals ON groupmembers.member_id = principals.id WHERE groupmembers.principal_id = ?'); - $stmt->execute(array($principal['id'])); - - $result = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $result[] = $row['uri']; - } - return $result; - - } - - /** - * Returns the list of groups a principal is a member of - * - * @param string $principal - * @return array - */ - public function getGroupMembership($principal) { - - $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); - - $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM `'.$this->groupMembersTableName.'` AS groupmembers LEFT JOIN `'.$this->tableName.'` AS principals ON groupmembers.principal_id = principals.id WHERE groupmembers.member_id = ?'); - $stmt->execute(array($principal['id'])); - - $result = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $result[] = $row['uri']; - } - return $result; - - } - - /** - * Updates the list of group members for a group principal. - * - * The principals should be passed as a list of uri's. - * - * @param string $principal - * @param array $members - * @return void - */ - public function setGroupMemberSet($principal, array $members) { - - // Grabbing the list of principal id's. - $stmt = $this->pdo->prepare('SELECT id, uri FROM `'.$this->tableName.'` WHERE uri IN (? ' . str_repeat(', ? ', count($members)) . ');'); - $stmt->execute(array_merge(array($principal), $members)); - - $memberIds = array(); - $principalId = null; - - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - if ($row['uri'] == $principal) { - $principalId = $row['id']; - } else { - $memberIds[] = $row['id']; - } - } - if (!$principalId) throw new Sabre_DAV_Exception('Principal not found'); - - // Wiping out old members - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->groupMembersTableName.'` WHERE principal_id = ?;'); - $stmt->execute(array($principalId)); - - foreach($memberIds as $memberId) { - - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->groupMembersTableName.'` (principal_id, member_id) VALUES (?, ?);'); - $stmt->execute(array($principalId, $memberId)); - - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/PrincipalCollection.php b/3rdparty/Sabre/DAVACL/PrincipalCollection.php deleted file mode 100644 index 4d22bf8aa7..0000000000 --- a/3rdparty/Sabre/DAVACL/PrincipalCollection.php +++ /dev/null @@ -1,35 +0,0 @@ -principalBackend, $principal); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/Acl.php b/3rdparty/Sabre/DAVACL/Property/Acl.php deleted file mode 100644 index e41e741131..0000000000 --- a/3rdparty/Sabre/DAVACL/Property/Acl.php +++ /dev/null @@ -1,186 +0,0 @@ -privileges = $privileges; - $this->prefixBaseUrl = $prefixBaseUrl; - - } - - /** - * Returns the list of privileges for this property - * - * @return array - */ - public function getPrivileges() { - - return $this->privileges; - - } - - /** - * Serializes the property into a DOMElement - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->privileges as $ace) { - - $this->serializeAce($doc, $node, $ace, $server); - - } - - } - - /** - * Unserializes the {DAV:}acl xml element. - * - * @param DOMElement $dom - * @return Sabre_DAVACL_Property_Acl - */ - static public function unserialize(DOMElement $dom) { - - $privileges = array(); - $xaces = $dom->getElementsByTagNameNS('urn:DAV','ace'); - for($ii=0; $ii < $xaces->length; $ii++) { - - $xace = $xaces->item($ii); - $principal = $xace->getElementsByTagNameNS('urn:DAV','principal'); - if ($principal->length !== 1) { - throw new Sabre_DAV_Exception_BadRequest('Each {DAV:}ace element must have one {DAV:}principal element'); - } - $principal = Sabre_DAVACL_Property_Principal::unserialize($principal->item(0)); - - if ($principal->getType()!==Sabre_DAVACL_Property_Principal::HREF) { - throw new Sabre_DAV_Exception_NotImplemented('Currently only uri based principals are support, {DAV:}all, {DAV:}unauthenticated and {DAV:}authenticated are not implemented yet'); - } - - $principal = $principal->getHref(); - $protected = false; - - if ($xace->getElementsByTagNameNS('urn:DAV','protected')->length > 0) { - $protected = true; - } - - $grants = $xace->getElementsByTagNameNS('urn:DAV','grant'); - if ($grants->length < 1) { - throw new Sabre_DAV_Exception_NotImplemented('Every {DAV:}ace element must have a {DAV:}grant element. {DAV:}deny is not yet supported'); - } - $grant = $grants->item(0); - - $xprivs = $grant->getElementsByTagNameNS('urn:DAV','privilege'); - for($jj=0; $jj<$xprivs->length; $jj++) { - - $xpriv = $xprivs->item($jj); - - $privilegeName = null; - - for ($kk=0;$kk<$xpriv->childNodes->length;$kk++) { - - $childNode = $xpriv->childNodes->item($kk); - if ($t = Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - $privilegeName = $t; - break; - } - } - if (is_null($privilegeName)) { - throw new Sabre_DAV_Exception_BadRequest('{DAV:}privilege elements must have a privilege element contained within them.'); - } - - $privileges[] = array( - 'principal' => $principal, - 'protected' => $protected, - 'privilege' => $privilegeName, - ); - - } - - } - - return new self($privileges); - - } - - /** - * Serializes a single access control entry. - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param array $ace - * @param Sabre_DAV_Server $server - * @return void - */ - private function serializeAce($doc,$node,$ace, $server) { - - $xace = $doc->createElementNS('DAV:','d:ace'); - $node->appendChild($xace); - - $principal = $doc->createElementNS('DAV:','d:principal'); - $xace->appendChild($principal); - $principal->appendChild($doc->createElementNS('DAV:','d:href',($this->prefixBaseUrl?$server->getBaseUri():'') . $ace['principal'] . '/')); - - $grant = $doc->createElementNS('DAV:','d:grant'); - $xace->appendChild($grant); - - $privParts = null; - - preg_match('/^{([^}]*)}(.*)$/',$ace['privilege'],$privParts); - - $xprivilege = $doc->createElementNS('DAV:','d:privilege'); - $grant->appendChild($xprivilege); - - $xprivilege->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - if (isset($ace['protected']) && $ace['protected']) - $xace->appendChild($doc->createElement('d:protected')); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php deleted file mode 100644 index 72274597b3..0000000000 --- a/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php +++ /dev/null @@ -1,75 +0,0 @@ -privileges = $privileges; - - } - - /** - * Serializes the property in the DOM - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->privileges as $privName) { - - $this->serializePriv($doc,$node,$privName); - - } - - } - - /** - * Serializes one privilege - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param string $privName - * @return void - */ - protected function serializePriv($doc,$node,$privName) { - - $xp = $doc->createElementNS('DAV:','d:privilege'); - $node->appendChild($xp); - - $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privName,$privParts); - - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/Principal.php b/3rdparty/Sabre/DAVACL/Property/Principal.php deleted file mode 100644 index dad9a3550f..0000000000 --- a/3rdparty/Sabre/DAVACL/Property/Principal.php +++ /dev/null @@ -1,154 +0,0 @@ -type = $type; - - if ($type===self::HREF && is_null($href)) { - throw new Sabre_DAV_Exception('The href argument must be specified for the HREF principal type.'); - } - $this->href = $href; - - } - - /** - * Returns the principal type - * - * @return int - */ - public function getType() { - - return $this->type; - - } - - /** - * Returns the principal uri. - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Serializes the property into a DOMElement. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server, DOMElement $node) { - - $prefix = $server->xmlNamespaces['DAV:']; - switch($this->type) { - - case self::UNAUTHENTICATED : - $node->appendChild( - $node->ownerDocument->createElement($prefix . ':unauthenticated') - ); - break; - case self::AUTHENTICATED : - $node->appendChild( - $node->ownerDocument->createElement($prefix . ':authenticated') - ); - break; - case self::HREF : - $href = $node->ownerDocument->createElement($prefix . ':href'); - $href->nodeValue = $server->getBaseUri() . $this->href; - $node->appendChild($href); - break; - - } - - } - - /** - * Deserializes a DOM element into a property object. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Principal - */ - static public function unserialize(DOMElement $dom) { - - $parent = $dom->firstChild; - while(!Sabre_DAV_XMLUtil::toClarkNotation($parent)) { - $parent = $parent->nextSibling; - } - - switch(Sabre_DAV_XMLUtil::toClarkNotation($parent)) { - - case '{DAV:}unauthenticated' : - return new self(self::UNAUTHENTICATED); - case '{DAV:}authenticated' : - return new self(self::AUTHENTICATED); - case '{DAV:}href': - return new self(self::HREF, $parent->textContent); - default : - throw new Sabre_DAV_Exception_BadRequest('Unexpected element (' . Sabre_DAV_XMLUtil::toClarkNotation($parent) . '). Could not deserialize'); - - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php deleted file mode 100644 index 93c3895035..0000000000 --- a/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php +++ /dev/null @@ -1,92 +0,0 @@ -privileges = $privileges; - - } - - /** - * Serializes the property into a domdocument. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - $this->serializePriv($doc, $node, $this->privileges); - - } - - /** - * Serializes a property - * - * This is a recursive function. - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param array $privilege - * @return void - */ - private function serializePriv($doc,$node,$privilege) { - - $xsp = $doc->createElementNS('DAV:','d:supported-privilege'); - $node->appendChild($xsp); - - $xp = $doc->createElementNS('DAV:','d:privilege'); - $xsp->appendChild($xp); - - $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privilege['privilege'],$privParts); - - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - if (isset($privilege['abstract']) && $privilege['abstract']) { - $xsp->appendChild($doc->createElementNS('DAV:','d:abstract')); - } - - if (isset($privilege['description'])) { - $xsp->appendChild($doc->createElementNS('DAV:','d:description',$privilege['description'])); - } - - if (isset($privilege['aggregates'])) { - foreach($privilege['aggregates'] as $subPrivilege) { - $this->serializePriv($doc,$xsp,$subPrivilege); - } - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Version.php b/3rdparty/Sabre/DAVACL/Version.php deleted file mode 100644 index 124463e311..0000000000 --- a/3rdparty/Sabre/DAVACL/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -httpRequest->getHeader('Authorization'); - $authHeader = explode(' ',$authHeader); - - if ($authHeader[0]!='AWS' || !isset($authHeader[1])) { - $this->errorCode = self::ERR_NOAWSHEADER; - return false; - } - - list($this->accessKey,$this->signature) = explode(':',$authHeader[1]); - - return true; - - } - - /** - * Returns the username for the request - * - * @return string - */ - public function getAccessKey() { - - return $this->accessKey; - - } - - /** - * Validates the signature based on the secretKey - * - * @return bool - */ - public function validate($secretKey) { - - $contentMD5 = $this->httpRequest->getHeader('Content-MD5'); - - if ($contentMD5) { - // We need to validate the integrity of the request - $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); - - if ($contentMD5!=base64_encode(md5($body,true))) { - // content-md5 header did not match md5 signature of body - $this->errorCode = self::ERR_MD5CHECKSUMWRONG; - return false; - } - - } - - if (!$requestDate = $this->httpRequest->getHeader('x-amz-date')) - $requestDate = $this->httpRequest->getHeader('Date'); - - if (!$this->validateRFC2616Date($requestDate)) - return false; - - $amzHeaders = $this->getAmzHeaders(); - - $signature = base64_encode( - $this->hmacsha1($secretKey, - $this->httpRequest->getMethod() . "\n" . - $contentMD5 . "\n" . - $this->httpRequest->getHeader('Content-type') . "\n" . - $requestDate . "\n" . - $amzHeaders . - $this->httpRequest->getURI() - ) - ); - - if ($this->signature != $signature) { - - $this->errorCode = self::ERR_INVALIDSIGNATURE; - return false; - - } - - return true; - - } - - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','AWS'); - $this->httpResponse->sendStatus(401); - - } - - /** - * Makes sure the supplied value is a valid RFC2616 date. - * - * If we would just use strtotime to get a valid timestamp, we have no way of checking if a - * user just supplied the word 'now' for the date header. - * - * This function also makes sure the Date header is within 15 minutes of the operating - * system date, to prevent replay attacks. - * - * @param string $dateHeader - * @return bool - */ - protected function validateRFC2616Date($dateHeader) { - - $date = Sabre_HTTP_Util::parseHTTPDate($dateHeader); - - // Unknown format - if (!$date) { - $this->errorCode = self::ERR_INVALIDDATEFORMAT; - return false; - } - - $min = new DateTime('-15 minutes'); - $max = new DateTime('+15 minutes'); - - // We allow 15 minutes around the current date/time - if ($date > $max || $date < $min) { - $this->errorCode = self::ERR_REQUESTTIMESKEWED; - return false; - } - - return $date; - - } - - /** - * Returns a list of AMZ headers - * - * @return void - */ - protected function getAmzHeaders() { - - $amzHeaders = array(); - $headers = $this->httpRequest->getHeaders(); - foreach($headers as $headerName => $headerValue) { - if (strpos(strtolower($headerName),'x-amz-')===0) { - $amzHeaders[strtolower($headerName)] = str_replace(array("\r\n"),array(' '),$headerValue) . "\n"; - } - } - ksort($amzHeaders); - - $headerStr = ''; - foreach($amzHeaders as $h=>$v) { - $headerStr.=$h.':'.$v; - } - - return $headerStr; - - } - - /** - * Generates an HMAC-SHA1 signature - * - * @param string $key - * @param string $message - * @return string - */ - private function hmacsha1($key, $message) { - - $blocksize=64; - if (strlen($key)>$blocksize) - $key=pack('H*', sha1($key)); - $key=str_pad($key,$blocksize,chr(0x00)); - $ipad=str_repeat(chr(0x36),$blocksize); - $opad=str_repeat(chr(0x5c),$blocksize); - $hmac = pack('H*',sha1(($key^$opad).pack('H*',sha1(($key^$ipad).$message)))); - return $hmac; - - } - -} diff --git a/3rdparty/Sabre/HTTP/AbstractAuth.php b/3rdparty/Sabre/HTTP/AbstractAuth.php deleted file mode 100644 index eb528f6fde..0000000000 --- a/3rdparty/Sabre/HTTP/AbstractAuth.php +++ /dev/null @@ -1,111 +0,0 @@ -httpResponse = new Sabre_HTTP_Response(); - $this->httpRequest = new Sabre_HTTP_Request(); - - } - - /** - * Sets an alternative HTTP response object - * - * @param Sabre_HTTP_Response $response - * @return void - */ - public function setHTTPResponse(Sabre_HTTP_Response $response) { - - $this->httpResponse = $response; - - } - - /** - * Sets an alternative HTTP request object - * - * @param Sabre_HTTP_Request $request - * @return void - */ - public function setHTTPRequest(Sabre_HTTP_Request $request) { - - $this->httpRequest = $request; - - } - - - /** - * Sets the realm - * - * The realm is often displayed in authentication dialog boxes - * Commonly an application name displayed here - * - * @param string $realm - * @return void - */ - public function setRealm($realm) { - - $this->realm = $realm; - - } - - /** - * Returns the realm - * - * @return string - */ - public function getRealm() { - - return $this->realm; - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - abstract public function requireLogin(); - -} diff --git a/3rdparty/Sabre/HTTP/BasicAuth.php b/3rdparty/Sabre/HTTP/BasicAuth.php deleted file mode 100644 index 35c22d22dc..0000000000 --- a/3rdparty/Sabre/HTTP/BasicAuth.php +++ /dev/null @@ -1,61 +0,0 @@ -httpRequest->getRawServerValue('PHP_AUTH_USER')) && ($pass = $this->httpRequest->getRawServerValue('PHP_AUTH_PW'))) { - - return array($user,$pass); - - } - - // Most other webservers - $auth = $this->httpRequest->getHeader('Authorization'); - - if (!$auth) return false; - - if (strpos(strtolower($auth),'basic')!==0) return false; - - return explode(':', base64_decode(substr($auth, 6))); - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','Basic realm="' . $this->realm . '"'); - $this->httpResponse->sendStatus(401); - - } - -} diff --git a/3rdparty/Sabre/HTTP/DigestAuth.php b/3rdparty/Sabre/HTTP/DigestAuth.php deleted file mode 100644 index 5e75592957..0000000000 --- a/3rdparty/Sabre/HTTP/DigestAuth.php +++ /dev/null @@ -1,234 +0,0 @@ -nonce = uniqid(); - $this->opaque = md5($this->realm); - parent::__construct(); - - } - - /** - * Gathers all information from the headers - * - * This method needs to be called prior to anything else. - * - * @return void - */ - public function init() { - - $digest = $this->getDigest(); - $this->digestParts = $this->parseDigest($digest); - - } - - /** - * Sets the quality of protection value. - * - * Possible values are: - * Sabre_HTTP_DigestAuth::QOP_AUTH - * Sabre_HTTP_DigestAuth::QOP_AUTHINT - * - * Multiple values can be specified using logical OR. - * - * QOP_AUTHINT ensures integrity of the request body, but this is not - * supported by most HTTP clients. QOP_AUTHINT also requires the entire - * request body to be md5'ed, which can put strains on CPU and memory. - * - * @param int $qop - * @return void - */ - public function setQOP($qop) { - - $this->qop = $qop; - - } - - /** - * Validates the user. - * - * The A1 parameter should be md5($username . ':' . $realm . ':' . $password); - * - * @param string $A1 - * @return bool - */ - public function validateA1($A1) { - - $this->A1 = $A1; - return $this->validate(); - - } - - /** - * Validates authentication through a password. The actual password must be provided here. - * It is strongly recommended not store the password in plain-text and use validateA1 instead. - * - * @param string $password - * @return bool - */ - public function validatePassword($password) { - - $this->A1 = md5($this->digestParts['username'] . ':' . $this->realm . ':' . $password); - return $this->validate(); - - } - - /** - * Returns the username for the request - * - * @return string - */ - public function getUsername() { - - return $this->digestParts['username']; - - } - - /** - * Validates the digest challenge - * - * @return bool - */ - protected function validate() { - - $A2 = $this->httpRequest->getMethod() . ':' . $this->digestParts['uri']; - - if ($this->digestParts['qop']=='auth-int') { - // Making sure we support this qop value - if (!($this->qop & self::QOP_AUTHINT)) return false; - // We need to add an md5 of the entire request body to the A2 part of the hash - $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); - $A2 .= ':' . md5($body); - } else { - - // We need to make sure we support this qop value - if (!($this->qop & self::QOP_AUTH)) return false; - } - - $A2 = md5($A2); - - $validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}"); - - return $this->digestParts['response']==$validResponse; - - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $qop = ''; - switch($this->qop) { - case self::QOP_AUTH : $qop = 'auth'; break; - case self::QOP_AUTHINT : $qop = 'auth-int'; break; - case self::QOP_AUTH | self::QOP_AUTHINT : $qop = 'auth,auth-int'; break; - } - - $this->httpResponse->setHeader('WWW-Authenticate','Digest realm="' . $this->realm . '",qop="'.$qop.'",nonce="' . $this->nonce . '",opaque="' . $this->opaque . '"'); - $this->httpResponse->sendStatus(401); - - } - - - /** - * This method returns the full digest string. - * - * It should be compatibile with mod_php format and other webservers. - * - * If the header could not be found, null will be returned - * - * @return mixed - */ - public function getDigest() { - - // mod_php - $digest = $this->httpRequest->getRawServerValue('PHP_AUTH_DIGEST'); - if ($digest) return $digest; - - // most other servers - $digest = $this->httpRequest->getHeader('Authorization'); - - if ($digest && strpos(strtolower($digest),'digest')===0) { - return substr($digest,7); - } else { - return null; - } - - } - - - /** - * Parses the different pieces of the digest string into an array. - * - * This method returns false if an incomplete digest was supplied - * - * @param string $digest - * @return mixed - */ - protected function parseDigest($digest) { - - // protect against missing data - $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); - $data = array(); - - preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER); - - foreach ($matches as $m) { - $data[$m[1]] = $m[2] ? $m[2] : $m[3]; - unset($needed_parts[$m[1]]); - } - - return $needed_parts ? false : $data; - - } - -} diff --git a/3rdparty/Sabre/HTTP/Request.php b/3rdparty/Sabre/HTTP/Request.php deleted file mode 100644 index 95a64171aa..0000000000 --- a/3rdparty/Sabre/HTTP/Request.php +++ /dev/null @@ -1,243 +0,0 @@ -_SERVER = $serverData; - else $this->_SERVER =& $_SERVER; - - } - - /** - * Returns the value for a specific http header. - * - * This method returns null if the header did not exist. - * - * @param string $name - * @return string - */ - public function getHeader($name) { - - $name = strtoupper(str_replace(array('-'),array('_'),$name)); - if (isset($this->_SERVER['HTTP_' . $name])) { - return $this->_SERVER['HTTP_' . $name]; - } - - // There's a few headers that seem to end up in the top-level - // server array. - switch($name) { - case 'CONTENT_TYPE' : - case 'CONTENT_LENGTH' : - if (isset($this->_SERVER[$name])) { - return $this->_SERVER[$name]; - } - break; - - } - return; - - } - - /** - * Returns all (known) HTTP headers. - * - * All headers are converted to lower-case, and additionally all underscores - * are automatically converted to dashes - * - * @return array - */ - public function getHeaders() { - - $hdrs = array(); - foreach($this->_SERVER as $key=>$value) { - - switch($key) { - case 'CONTENT_LENGTH' : - case 'CONTENT_TYPE' : - $hdrs[strtolower(str_replace('_','-',$key))] = $value; - break; - default : - if (strpos($key,'HTTP_')===0) { - $hdrs[substr(strtolower(str_replace('_','-',$key)),5)] = $value; - } - break; - } - - } - - return $hdrs; - - } - - /** - * Returns the HTTP request method - * - * This is for example POST or GET - * - * @return string - */ - public function getMethod() { - - return $this->_SERVER['REQUEST_METHOD']; - - } - - /** - * Returns the requested uri - * - * @return string - */ - public function getUri() { - - return $this->_SERVER['REQUEST_URI']; - - } - - /** - * Will return protocol + the hostname + the uri - * - * @return void - */ - public function getAbsoluteUri() { - - // Checking if the request was made through HTTPS. The last in line is for IIS - $protocol = isset($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']!='off'); - return ($protocol?'https':'http') . '://' . $this->getHeader('Host') . $this->getUri(); - - } - - /** - * Returns everything after the ? from the current url - * - * @return string - */ - public function getQueryString() { - - return isset($this->_SERVER['QUERY_STRING'])?$this->_SERVER['QUERY_STRING']:''; - - } - - /** - * Returns the HTTP request body body - * - * This method returns a readable stream resource. - * If the asString parameter is set to true, a string is sent instead. - * - * @param bool asString - * @return resource - */ - public function getBody($asString = false) { - - if (is_null($this->body)) { - if (!is_null(self::$defaultInputStream)) { - $this->body = self::$defaultInputStream; - } else { - $this->body = fopen('php://input','r'); - self::$defaultInputStream = $this->body; - } - } - if ($asString) { - $body = stream_get_contents($this->body); - return $body; - } else { - return $this->body; - } - - } - - /** - * Sets the contents of the HTTP request body - * - * This method can either accept a string, or a readable stream resource. - * - * If the setAsDefaultInputStream is set to true, it means for this run of the - * script the supplied body will be used instead of php://input. - * - * @param mixed $body - * @param bool $setAsDefaultInputStream - * @return void - */ - public function setBody($body,$setAsDefaultInputStream = false) { - - if(is_resource($body)) { - $this->body = $body; - } else { - - $stream = fopen('php://temp','r+'); - fputs($stream,$body); - rewind($stream); - // String is assumed - $this->body = $stream; - } - if ($setAsDefaultInputStream) { - self::$defaultInputStream = $this->body; - } - - } - - /** - * Returns a specific item from the _SERVER array. - * - * Do not rely on this feature, it is for internal use only. - * - * @param string $field - * @return string - */ - public function getRawServerValue($field) { - - return isset($this->_SERVER[$field])?$this->_SERVER[$field]:null; - - } - -} - diff --git a/3rdparty/Sabre/HTTP/Response.php b/3rdparty/Sabre/HTTP/Response.php deleted file mode 100644 index dce6feac55..0000000000 --- a/3rdparty/Sabre/HTTP/Response.php +++ /dev/null @@ -1,152 +0,0 @@ - 'Continue', - 101 => 'Switching Protocols', - 102 => 'Processing', - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authorative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - 207 => 'Multi-Status', // RFC 4918 - 208 => 'Already Reported', // RFC 5842 - 226 => 'IM Used', // RFC 3229 - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - 306 => 'Reserved', - 307 => 'Temporary Redirect', - 400 => 'Bad request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - 418 => 'I\'m a teapot', // RFC 2324 - 422 => 'Unprocessable Entity', // RFC 4918 - 423 => 'Locked', // RFC 4918 - 424 => 'Failed Dependency', // RFC 4918 - 426 => 'Upgrade required', - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version not supported', - 506 => 'Variant Also Negotiates', - 507 => 'Unsufficient Storage', // RFC 4918 - 508 => 'Loop Detected', // RFC 5842 - 509 => 'Bandwidth Limit Exceeded', // non-standard - 510 => 'Not extended', - ); - - return 'HTTP/1.1 ' . $code . ' ' . $msg[$code]; - - } - - /** - * Sends an HTTP status header to the client - * - * @param int $code HTTP status code - * @return void - */ - public function sendStatus($code) { - - if (!headers_sent()) - return header($this->getStatusMessage($code)); - else return false; - - } - - /** - * Sets an HTTP header for the response - * - * @param string $name - * @param string $value - * @return void - */ - public function setHeader($name, $value, $replace = true) { - - $value = str_replace(array("\r","\n"),array('\r','\n'),$value); - if (!headers_sent()) - return header($name . ': ' . $value, $replace); - else return false; - - } - - /** - * Sets a bunch of HTTP Headers - * - * headersnames are specified as keys, value in the array value - * - * @param array $headers - * @return void - */ - public function setHeaders(array $headers) { - - foreach($headers as $key=>$value) - $this->setHeader($key, $value); - - } - - /** - * Sends the entire response body - * - * This method can accept either an open filestream, or a string. - * - * @param mixed $body - * @return void - */ - public function sendBody($body) { - - if (is_resource($body)) { - - fpassthru($body); - - } else { - - // We assume a string - echo $body; - - } - - } - -} diff --git a/3rdparty/Sabre/HTTP/Util.php b/3rdparty/Sabre/HTTP/Util.php deleted file mode 100644 index 8a6bd7df48..0000000000 --- a/3rdparty/Sabre/HTTP/Util.php +++ /dev/null @@ -1,65 +0,0 @@ -= 0) - return new DateTime('@' . $realDate, new DateTimeZone('UTC')); - - return false; - - } - -} diff --git a/3rdparty/Sabre/HTTP/Version.php b/3rdparty/Sabre/HTTP/Version.php deleted file mode 100644 index 67be232fc2..0000000000 --- a/3rdparty/Sabre/HTTP/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -name = strtoupper($name); - if (!is_null($iterator)) $this->iterator = $iterator; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $str = "BEGIN:" . $this->name . "\r\n"; - foreach($this->children as $child) $str.=$child->serialize(); - $str.= "END:" . $this->name . "\r\n"; - - return $str; - - } - - - /** - * Adds a new componenten or element - * - * You can call this method with the following syntaxes: - * - * add(Sabre_VObject_Element $element) - * add(string $name, $value) - * - * The first version adds an Element - * The second adds a property as a string. - * - * @param mixed $item - * @param mixed $itemValue - * @return void - */ - public function add($item, $itemValue = null) { - - if ($item instanceof Sabre_VObject_Element) { - if (!is_null($itemValue)) { - throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); - } - $item->parent = $this; - $this->children[] = $item; - } elseif(is_string($item)) { - - if (!is_scalar($itemValue)) { - throw new InvalidArgumentException('The second argument must be scalar'); - } - $item = new Sabre_VObject_Property($item,$itemValue); - $item->parent = $this; - $this->children[] = $item; - - } else { - - throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); - - } - - } - - /** - * Returns an iterable list of children - * - * @return Sabre_VObject_ElementList - */ - public function children() { - - return new Sabre_VObject_ElementList($this->children); - - } - - /** - * Returns an array with elements that match the specified name. - * - * This function is also aware of MIME-Directory groups (as they appear in - * vcards). This means that if a property is grouped as "HOME.EMAIL", it - * will also be returned when searching for just "EMAIL". If you want to - * search for a property in a specific group, you can select on the entire - * string ("HOME.EMAIL"). If you want to search on a specific property that - * has not been assigned a group, specify ".EMAIL". - * - * Keys are retained from the 'children' array, which may be confusing in - * certain cases. - * - * @param string $name - * @return array - */ - public function select($name) { - - $group = null; - $name = strtoupper($name); - if (strpos($name,'.')!==false) { - list($group,$name) = explode('.', $name, 2); - } - - $result = array(); - foreach($this->children as $key=>$child) { - - if ( - strtoupper($child->name) === $name && - (is_null($group) || ( $child instanceof Sabre_VObject_Property && strtoupper($child->group) === $group)) - ) { - - $result[$key] = $child; - - } - } - - reset($result); - return $result; - - } - - /* Magic property accessors {{{ */ - - /** - * Using 'get' you will either get a propery or component, - * - * If there were no child-elements found with the specified name, - * null is returned. - * - * @param string $name - * @return void - */ - public function __get($name) { - - $matches = $this->select($name); - if (count($matches)===0) { - return null; - } else { - $firstMatch = current($matches); - $firstMatch->setIterator(new Sabre_VObject_ElementList(array_values($matches))); - return $firstMatch; - } - - } - - /** - * This method checks if a sub-element with the specified name exists. - * - * @param string $name - * @return bool - */ - public function __isset($name) { - - $matches = $this->select($name); - return count($matches)>0; - - } - - /** - * Using the setter method you can add properties or subcomponents - * - * You can either pass a Sabre_VObject_Component, Sabre_VObject_Property - * object, or a string to automatically create a Property. - * - * If the item already exists, it will be removed. If you want to add - * a new item with the same name, always use the add() method. - * - * @param string $name - * @param mixed $value - * @return void - */ - public function __set($name, $value) { - - $matches = $this->select($name); - $overWrite = count($matches)?key($matches):null; - - if ($value instanceof Sabre_VObject_Component || $value instanceof Sabre_VObject_Property) { - $value->parent = $this; - if (!is_null($overWrite)) { - $this->children[$overWrite] = $value; - } else { - $this->children[] = $value; - } - } elseif (is_scalar($value)) { - $property = new Sabre_VObject_Property($name,$value); - $property->parent = $this; - if (!is_null($overWrite)) { - $this->children[$overWrite] = $property; - } else { - $this->children[] = $property; - } - } else { - throw new InvalidArgumentException('You must pass a Sabre_VObject_Component, Sabre_VObject_Property or scalar type'); - } - - } - - /** - * Removes all properties and components within this component. - * - * @param string $name - * @return void - */ - public function __unset($name) { - - $matches = $this->select($name); - foreach($matches as $k=>$child) { - - unset($this->children[$k]); - $child->parent = null; - - } - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Element.php b/3rdparty/Sabre/VObject/Element.php deleted file mode 100644 index 8d2b0aaacd..0000000000 --- a/3rdparty/Sabre/VObject/Element.php +++ /dev/null @@ -1,15 +0,0 @@ -setValue($dt->format('Ymd\\THis')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case self::UTC : - $dt->setTimeZone(new DateTimeZone('UTC')); - $this->setValue($dt->format('Ymd\\THis\\Z')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case self::LOCALTZ : - $this->setValue($dt->format('Ymd\\THis')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - $this->offsetSet('TZID', $dt->getTimeZone()->getName()); - break; - case self::DATE : - $this->setValue($dt->format('Ymd')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE'); - break; - default : - throw new InvalidArgumentException('You must pass a valid dateType constant'); - - } - $this->dateTime = $dt; - $this->dateType = $dateType; - - } - - /** - * Returns the current DateTime value. - * - * If no value was set, this method returns null. - * - * @return DateTime|null - */ - public function getDateTime() { - - if ($this->dateTime) - return $this->dateTime; - - list( - $this->dateType, - $this->dateTime - ) = self::parseData($this->value, $this); - return $this->dateTime; - - } - - /** - * Returns the type of Date format. - * - * This method returns one of the format constants. If no date was set, - * this method will return null. - * - * @return int|null - */ - public function getDateType() { - - if ($this->dateType) - return $this->dateType; - - list( - $this->dateType, - $this->dateTime, - ) = self::parseData($this->value, $this); - return $this->dateType; - - } - - /** - * Parses the internal data structure to figure out what the current date - * and time is. - * - * The returned array contains two elements: - * 1. A 'DateType' constant (as defined on this class), or null. - * 2. A DateTime object (or null) - * - * @param string|null $propertyValue The string to parse (yymmdd or - * ymmddThhmmss, etc..) - * @param Sabre_VObject_Property|null $property The instance of the - * property we're parsing. - * @return array - */ - static public function parseData($propertyValue, Sabre_VObject_Property $property = null) { - - if (is_null($propertyValue)) { - return array(null, null); - } - - $date = '(?P[1-2][0-9]{3})(?P[0-1][0-9])(?P[0-3][0-9])'; - $time = '(?P[0-2][0-9])(?P[0-5][0-9])(?P[0-5][0-9])'; - $regex = "/^$date(T$time(?PZ)?)?$/"; - - if (!preg_match($regex, $propertyValue, $matches)) { - throw new InvalidArgumentException($propertyValue . ' is not a valid DateTime or Date string'); - } - - if (!isset($matches['hour'])) { - // Date-only - return array( - self::DATE, - new DateTime($matches['year'] . '-' . $matches['month'] . '-' . $matches['date'] . ' 00:00:00'), - ); - } - - $dateStr = - $matches['year'] .'-' . - $matches['month'] . '-' . - $matches['date'] . ' ' . - $matches['hour'] . ':' . - $matches['minute'] . ':' . - $matches['second']; - - if (isset($matches['isutc'])) { - $dt = new DateTime($dateStr,new DateTimeZone('UTC')); - $dt->setTimeZone(new DateTimeZone('UTC')); - return array( - self::UTC, - $dt - ); - } - - // Finding the timezone. - $tzid = $property['TZID']; - if (!$tzid) { - return array( - self::LOCAL, - new DateTime($dateStr) - ); - } - - try { - $tz = new DateTimeZone($tzid->value); - } catch (Exception $e) { - - // The id was invalid, we're going to try to find the information - // through the VTIMEZONE object. - - // First we find the root object - $root = $property; - while($root->parent) { - $root = $root->parent; - } - - if (isset($root->VTIMEZONE)) { - foreach($root->VTIMEZONE as $vtimezone) { - if (((string)$vtimezone->TZID) == $tzid) { - if (isset($vtimezone->{'X-LIC-LOCATION'})) { - $tzid = (string)$vtimezone->{'X-LIC-LOCATION'}; - } - } - } - } - - $tz = new DateTimeZone($tzid); - - } - $dt = new DateTime($dateStr, $tz); - $dt->setTimeZone($tz); - - return array( - self::LOCALTZ, - $dt - ); - - } - -} - -?> diff --git a/3rdparty/Sabre/VObject/Element/MultiDateTime.php b/3rdparty/Sabre/VObject/Element/MultiDateTime.php deleted file mode 100644 index dc6ca5abb8..0000000000 --- a/3rdparty/Sabre/VObject/Element/MultiDateTime.php +++ /dev/null @@ -1,168 +0,0 @@ -offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - switch($dateType) { - - case Sabre_VObject_Element_DateTime::LOCAL : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd\\THis'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case Sabre_VObject_Element_DateTime::UTC : - $val = array(); - foreach($dt as $i) { - $i->setTimeZone(new DateTimeZone('UTC')); - $val[] = $i->format('Ymd\\THis\\Z'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case Sabre_VObject_Element_DateTime::LOCALTZ : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd\\THis'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - $this->offsetSet('TZID', $dt[0]->getTimeZone()->getName()); - break; - case Sabre_VObject_Element_DateTime::DATE : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE'); - break; - default : - throw new InvalidArgumentException('You must pass a valid dateType constant'); - - } - $this->dateTimes = $dt; - $this->dateType = $dateType; - - } - - /** - * Returns the current DateTime value. - * - * If no value was set, this method returns null. - * - * @return array|null - */ - public function getDateTimes() { - - if ($this->dateTimes) - return $this->dateTimes; - - $dts = array(); - - if (!$this->value) { - $this->dateTimes = null; - $this->dateType = null; - return null; - } - - foreach(explode(',',$this->value) as $val) { - list( - $type, - $dt - ) = Sabre_VObject_Element_DateTime::parseData($val, $this); - $dts[] = $dt; - $this->dateType = $type; - } - $this->dateTimes = $dts; - return $this->dateTimes; - - } - - /** - * Returns the type of Date format. - * - * This method returns one of the format constants. If no date was set, - * this method will return null. - * - * @return int|null - */ - public function getDateType() { - - if ($this->dateType) - return $this->dateType; - - if (!$this->value) { - $this->dateTimes = null; - $this->dateType = null; - return null; - } - - $dts = array(); - foreach(explode(',',$this->value) as $val) { - list( - $type, - $dt - ) = Sabre_VObject_Element_DateTime::parseData($val, $this); - $dts[] = $dt; - $this->dateType = $type; - } - $this->dateTimes = $dts; - return $this->dateType; - - } - -} - -?> diff --git a/3rdparty/Sabre/VObject/ElementList.php b/3rdparty/Sabre/VObject/ElementList.php deleted file mode 100644 index 9922cd587b..0000000000 --- a/3rdparty/Sabre/VObject/ElementList.php +++ /dev/null @@ -1,172 +0,0 @@ -vevent where there's multiple VEVENT objects. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess { - - /** - * Inner elements - * - * @var array - */ - protected $elements = array(); - - /** - * Creates the element list. - * - * @param array $elements - */ - public function __construct(array $elements) { - - $this->elements = $elements; - - } - - /* {{{ Iterator interface */ - - /** - * Current position - * - * @var int - */ - private $key = 0; - - /** - * Returns current item in iteration - * - * @return Sabre_VObject_Element - */ - public function current() { - - return $this->elements[$this->key]; - - } - - /** - * To the next item in the iterator - * - * @return void - */ - public function next() { - - $this->key++; - - } - - /** - * Returns the current iterator key - * - * @return int - */ - public function key() { - - return $this->key; - - } - - /** - * Returns true if the current position in the iterator is a valid one - * - * @return bool - */ - public function valid() { - - return isset($this->elements[$this->key]); - - } - - /** - * Rewinds the iterator - * - * @return void - */ - public function rewind() { - - $this->key = 0; - - } - - /* }}} */ - - /* {{{ Countable interface */ - - /** - * Returns the number of elements - * - * @return int - */ - public function count() { - - return count($this->elements); - - } - - /* }}} */ - - /* {{{ ArrayAccess Interface */ - - - /** - * Checks if an item exists through ArrayAccess. - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) { - - return isset($this->elements[$offset]); - - } - - /** - * Gets an item through ArrayAccess. - * - * @param int $offset - * @return mixed - */ - public function offsetGet($offset) { - - return $this->elements[$offset]; - - } - - /** - * Sets an item through ArrayAccess. - * - * @param int $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset,$value) { - - throw new LogicException('You can not add new objects to an ElementList'); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return void - */ - public function offsetUnset($offset) { - - throw new LogicException('You can not remove objects from an ElementList'); - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Node.php b/3rdparty/Sabre/VObject/Node.php deleted file mode 100644 index 7100b62f1c..0000000000 --- a/3rdparty/Sabre/VObject/Node.php +++ /dev/null @@ -1,149 +0,0 @@ -iterator)) - return $this->iterator; - - return new Sabre_VObject_ElementList(array($this)); - - } - - /** - * Sets the overridden iterator - * - * Note that this is not actually part of the iterator interface - * - * @param Sabre_VObject_ElementList $iterator - * @return void - */ - public function setIterator(Sabre_VObject_ElementList $iterator) { - - $this->iterator = $iterator; - - } - - /* }}} */ - - /* {{{ Countable interface */ - - /** - * Returns the number of elements - * - * @return int - */ - public function count() { - - $it = $this->getIterator(); - return $it->count(); - - } - - /* }}} */ - - /* {{{ ArrayAccess Interface */ - - - /** - * Checks if an item exists through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetExists($offset); - - } - - /** - * Gets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return mixed - */ - public function offsetGet($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetGet($offset); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset,$value) { - - $iterator = $this->getIterator(); - return $iterator->offsetSet($offset,$value); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return void - */ - public function offsetUnset($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetUnset($offset); - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Parameter.php b/3rdparty/Sabre/VObject/Parameter.php deleted file mode 100644 index 9ebab6ec69..0000000000 --- a/3rdparty/Sabre/VObject/Parameter.php +++ /dev/null @@ -1,81 +0,0 @@ -name = strtoupper($name); - $this->value = $value; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $src = array( - '\\', - "\n", - ';', - ',', - ); - $out = array( - '\\\\', - '\n', - '\;', - '\,', - ); - - return $this->name . '=' . str_replace($src, $out, $this->value); - - } - - /** - * Called when this object is being cast to a string - * - * @return string - */ - public function __toString() { - - return $this->value; - - } - -} diff --git a/3rdparty/Sabre/VObject/ParseException.php b/3rdparty/Sabre/VObject/ParseException.php deleted file mode 100644 index ed4ef2e859..0000000000 --- a/3rdparty/Sabre/VObject/ParseException.php +++ /dev/null @@ -1,12 +0,0 @@ -name = $name; - $this->group = $group; - if (!is_null($iterator)) $this->iterator = $iterator; - $this->setValue($value); - - } - - /** - * Updates the internal value - * - * @param string $value - * @return void - */ - public function setValue($value) { - - $this->value = $value; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $str = $this->name; - if ($this->group) $str = $this->group . '.' . $this->name; - - if (count($this->parameters)) { - foreach($this->parameters as $param) { - - $str.=';' . $param->serialize(); - - } - } - $src = array( - '\\', - "\n", - ); - $out = array( - '\\\\', - '\n', - ); - $str.=':' . str_replace($src, $out, $this->value); - - $out = ''; - while(strlen($str)>0) { - if (strlen($str)>75) { - $out.= substr($str,0,75) . "\r\n"; - $str = ' ' . substr($str,75); - } else { - $out.=$str . "\r\n"; - $str=''; - break; - } - } - - return $out; - - } - - /** - * Adds a new componenten or element - * - * You can call this method with the following syntaxes: - * - * add(Sabre_VObject_Parameter $element) - * add(string $name, $value) - * - * The first version adds an Parameter - * The second adds a property as a string. - * - * @param mixed $item - * @param mixed $itemValue - * @return void - */ - public function add($item, $itemValue = null) { - - if ($item instanceof Sabre_VObject_Parameter) { - if (!is_null($itemValue)) { - throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); - } - $item->parent = $this; - $this->parameters[] = $item; - } elseif(is_string($item)) { - - if (!is_scalar($itemValue)) { - throw new InvalidArgumentException('The second argument must be scalar'); - } - $parameter = new Sabre_VObject_Parameter($item,$itemValue); - $parameter->parent = $this; - $this->parameters[] = $parameter; - - } else { - - throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); - - } - - } - - - /* ArrayAccess interface {{{ */ - - /** - * Checks if an array element exists - * - * @param mixed $name - * @return bool - */ - public function offsetExists($name) { - - if (is_int($name)) return parent::offsetExists($name); - - $name = strtoupper($name); - - foreach($this->parameters as $parameter) { - if ($parameter->name == $name) return true; - } - return false; - - } - - /** - * Returns a parameter, or parameter list. - * - * @param string $name - * @return Sabre_VObject_Element - */ - public function offsetGet($name) { - - if (is_int($name)) return parent::offsetGet($name); - $name = strtoupper($name); - - $result = array(); - foreach($this->parameters as $parameter) { - if ($parameter->name == $name) - $result[] = $parameter; - } - - if (count($result)===0) { - return null; - } elseif (count($result)===1) { - return $result[0]; - } else { - $result[0]->setIterator(new Sabre_VObject_ElementList($result)); - return $result[0]; - } - - } - - /** - * Creates a new parameter - * - * @param string $name - * @param mixed $value - * @return void - */ - public function offsetSet($name, $value) { - - if (is_int($name)) return parent::offsetSet($name, $value); - - if (is_scalar($value)) { - if (!is_string($name)) - throw new InvalidArgumentException('A parameter name must be specified. This means you cannot use the $array[]="string" to add parameters.'); - - $this->offsetUnset($name); - $parameter = new Sabre_VObject_Parameter($name, $value); - $parameter->parent = $this; - $this->parameters[] = $parameter; - - } elseif ($value instanceof Sabre_VObject_Parameter) { - if (!is_null($name)) - throw new InvalidArgumentException('Don\'t specify a parameter name if you\'re passing a Sabre_VObject_Parameter. Add using $array[]=$parameterObject.'); - - $value->parent = $this; - $this->parameters[] = $value; - } else { - throw new InvalidArgumentException('You can only add parameters to the property object'); - } - - } - - /** - * Removes one or more parameters with the specified name - * - * @param string $name - * @return void - */ - public function offsetUnset($name) { - - if (is_int($name)) return parent::offsetUnset($name, $value); - $name = strtoupper($name); - - $result = array(); - foreach($this->parameters as $key=>$parameter) { - if ($parameter->name == $name) { - $parameter->parent = null; - unset($this->parameters[$key]); - } - - } - - } - - /* }}} */ - - /** - * Called when this object is being cast to a string - * - * @return string - */ - public function __toString() { - - return $this->value; - - } - - -} diff --git a/3rdparty/Sabre/VObject/Reader.php b/3rdparty/Sabre/VObject/Reader.php deleted file mode 100644 index 7d1c282838..0000000000 --- a/3rdparty/Sabre/VObject/Reader.php +++ /dev/null @@ -1,191 +0,0 @@ - 'Sabre_VObject_Element_DateTime', - 'DTEND' => 'Sabre_VObject_Element_DateTime', - 'COMPLETED' => 'Sabre_VObject_Element_DateTime', - 'DUE' => 'Sabre_VObject_Element_DateTime', - 'EXDATE' => 'Sabre_VObject_Element_MultiDateTime', - ); - - /** - * Parses the file and returns the top component - * - * @param string $data - * @return Sabre_VObject_Element - */ - static function read($data) { - - // Normalizing newlines - $data = str_replace(array("\r","\n\n"), array("\n","\n"), $data); - - $lines = explode("\n", $data); - - // Unfolding lines - $lines2 = array(); - foreach($lines as $line) { - - // Skipping empty lines - if (!$line) continue; - - if ($line[0]===" " || $line[0]==="\t") { - $lines2[count($lines2)-1].=substr($line,1); - } else { - $lines2[] = $line; - } - - } - - unset($lines); - - reset($lines2); - - return self::readLine($lines2); - - } - - /** - * Reads and parses a single line. - * - * This method receives the full array of lines. The array pointer is used - * to traverse. - * - * @param array $lines - * @return Sabre_VObject_Element - */ - static private function readLine(&$lines) { - - $line = current($lines); - $lineNr = key($lines); - next($lines); - - // Components - if (stripos($line,"BEGIN:")===0) { - - // This is a component - $obj = new Sabre_VObject_Component(strtoupper(substr($line,6))); - - $nextLine = current($lines); - - while(stripos($nextLine,"END:")!==0) { - - $obj->add(self::readLine($lines)); - $nextLine = current($lines); - - if ($nextLine===false) - throw new Sabre_VObject_ParseException('Invalid VObject. Document ended prematurely.'); - - } - - // Checking component name of the 'END:' line. - if (substr($nextLine,4)!==$obj->name) { - throw new Sabre_VObject_ParseException('Invalid VObject, expected: "END:' . $obj->name . '" got: "' . $nextLine . '"'); - } - next($lines); - - return $obj; - - } - - // Properties - //$result = preg_match('/(?P[A-Z0-9-]+)(?:;(?P^(?([^:^\"]|\"([^\"]*)\")*))?"; - $regex = "/^(?P$token)$parameters:(?P.*)$/i"; - - $result = preg_match($regex,$line,$matches); - - if (!$result) { - throw new Sabre_VObject_ParseException('Invalid VObject, line ' . ($lineNr+1) . ' did not follow the icalendar/vcard format'); - } - - $propertyName = strtoupper($matches['name']); - $propertyValue = stripcslashes($matches['value']); - - if (isset(self::$elementMap[$propertyName])) { - $className = self::$elementMap[$propertyName]; - } else { - $className = 'Sabre_VObject_Property'; - } - - $obj = new $className($propertyName, $propertyValue); - - if ($matches['parameters']) { - - foreach(self::readParameters($matches['parameters']) as $param) { - $obj->add($param); - } - } - - return $obj; - - - } - - /** - * Reads a parameter list from a property - * - * This method returns an array of Sabre_VObject_Parameter - * - * @param string $parameters - * @return array - */ - static private function readParameters($parameters) { - - $token = '[A-Z0-9-]+'; - - $paramValue = '(?P[^\"^;]*|"[^"]*")'; - - $regex = "/(?<=^|;)(?P$token)(=$paramValue(?=$|;))?/i"; - preg_match_all($regex, $parameters, $matches, PREG_SET_ORDER); - - $params = array(); - foreach($matches as $match) { - - $value = isset($match['paramValue'])?$match['paramValue']:null; - - if (isset($value[0])) { - // Stripping quotes, if needed - if ($value[0] === '"') $value = substr($value,1,strlen($value)-2); - } else { - $value = ''; - } - - $params[] = new Sabre_VObject_Parameter($match['paramName'], stripcslashes($value)); - - } - - return $params; - - } - - -} diff --git a/3rdparty/Sabre/VObject/Version.php b/3rdparty/Sabre/VObject/Version.php deleted file mode 100644 index 937c367e22..0000000000 --- a/3rdparty/Sabre/VObject/Version.php +++ /dev/null @@ -1,24 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: System.php,v 1.36 2004/06/15 16:33:46 pajoye Exp $ -// - -require_once( 'PEAR.php'); -require_once( 'Console/Getopt.php'); - -$GLOBALS['_System_temp_files'] = array(); - -/** -* System offers cross plattform compatible system functions -* -* Static functions for different operations. Should work under -* Unix and Windows. The names and usage has been taken from its respectively -* GNU commands. The functions will return (bool) false on error and will -* trigger the error with the PHP trigger_error() function (you can silence -* the error by prefixing a '@' sign after the function call). -* -* Documentation on this class you can find in: -* http://pear.php.net/manual/ -* -* Example usage: -* if (!@System::rm('-r file1 dir1')) { -* print "could not delete file1 or dir1"; -* } -* -* In case you need to to pass file names with spaces, -* pass the params as an array: -* -* System::rm(array('-r', $file1, $dir1)); -* -* @package System -* @author Tomas V.V.Cox -* @version $Revision: 1.36 $ -* @access public -* @see http://pear.php.net/manual/ -*/ -class System -{ - /** - * returns the commandline arguments of a function - * - * @param string $argv the commandline - * @param string $short_options the allowed option short-tags - * @param string $long_options the allowed option long-tags - * @return array the given options and there values - * @access private - */ - function _parseArgs($argv, $short_options, $long_options = null) - { - if (!is_array($argv) && $argv !== null) { - $argv = preg_split('/\s+/', $argv); - } - return Console_Getopt::getopt2($argv, $short_options); - } - - /** - * Output errors with PHP trigger_error(). You can silence the errors - * with prefixing a "@" sign to the function call: @System::mkdir(..); - * - * @param mixed $error a PEAR error or a string with the error message - * @return bool false - * @access private - */ - function raiseError($error) - { - if (PEAR::isError($error)) { - $error = $error->getMessage(); - } - trigger_error($error, E_USER_WARNING); - return false; - } - - /** - * Creates a nested array representing the structure of a directory - * - * System::_dirToStruct('dir1', 0) => - * Array - * ( - * [dirs] => Array - * ( - * [0] => dir1 - * ) - * - * [files] => Array - * ( - * [0] => dir1/file2 - * [1] => dir1/file3 - * ) - * ) - * @param string $sPath Name of the directory - * @param integer $maxinst max. deep of the lookup - * @param integer $aktinst starting deep of the lookup - * @return array the structure of the dir - * @access private - */ - - function _dirToStruct($sPath, $maxinst, $aktinst = 0) - { - $struct = array('dirs' => array(), 'files' => array()); - if (($dir = @opendir($sPath)) === false) { - System::raiseError("Could not open dir $sPath"); - return $struct; // XXX could not open error - } - $struct['dirs'][] = $sPath; // XXX don't add if '.' or '..' ? - $list = array(); - while ($file = readdir($dir)) { - if ($file != '.' && $file != '..') { - $list[] = $file; - } - } - closedir($dir); - sort($list); - if ($aktinst < $maxinst || $maxinst == 0) { - foreach($list as $val) { - $path = $sPath . DIRECTORY_SEPARATOR . $val; - if (is_dir($path)) { - $tmp = System::_dirToStruct($path, $maxinst, $aktinst+1); - $struct = array_merge_recursive($tmp, $struct); - } else { - $struct['files'][] = $path; - } - } - } - return $struct; - } - - /** - * Creates a nested array representing the structure of a directory and files - * - * @param array $files Array listing files and dirs - * @return array - * @see System::_dirToStruct() - */ - function _multipleToStruct($files) - { - $struct = array('dirs' => array(), 'files' => array()); - settype($files, 'array'); - foreach ($files as $file) { - if (is_dir($file)) { - $tmp = System::_dirToStruct($file, 0); - $struct = array_merge_recursive($tmp, $struct); - } else { - $struct['files'][] = $file; - } - } - return $struct; - } - - /** - * The rm command for removing files. - * Supports multiple files and dirs and also recursive deletes - * - * @param string $args the arguments for rm - * @return mixed PEAR_Error or true for success - * @access public - */ - function rm($args) - { - $opts = System::_parseArgs($args, 'rf'); // "f" do nothing but like it :-) - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - foreach($opts[0] as $opt) { - if ($opt[0] == 'r') { - $do_recursive = true; - } - } - $ret = true; - if (isset($do_recursive)) { - $struct = System::_multipleToStruct($opts[1]); - foreach($struct['files'] as $file) { - if (!@unlink($file)) { - $ret = false; - } - } - foreach($struct['dirs'] as $dir) { - if (!@rmdir($dir)) { - $ret = false; - } - } - } else { - foreach ($opts[1] as $file) { - $delete = (is_dir($file)) ? 'rmdir' : 'unlink'; - if (!@$delete($file)) { - $ret = false; - } - } - } - return $ret; - } - - /** - * Make directories. Note that we use call_user_func('mkdir') to avoid - * a problem with ZE2 calling System::mkDir instead of the native PHP func. - * - * @param string $args the name of the director(y|ies) to create - * @return bool True for success - * @access public - */ - function mkDir($args) - { - $opts = System::_parseArgs($args, 'pm:'); - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - $mode = 0777; // default mode - foreach($opts[0] as $opt) { - if ($opt[0] == 'p') { - $create_parents = true; - } elseif($opt[0] == 'm') { - // if the mode is clearly an octal number (starts with 0) - // convert it to decimal - if (strlen($opt[1]) && $opt[1]{0} == '0') { - $opt[1] = octdec($opt[1]); - } else { - // convert to int - $opt[1] += 0; - } - $mode = $opt[1]; - } - } - $ret = true; - if (isset($create_parents)) { - foreach($opts[1] as $dir) { - $dirstack = array(); - while (!@is_dir($dir) && $dir != DIRECTORY_SEPARATOR) { - array_unshift($dirstack, $dir); - $dir = dirname($dir); - } - while ($newdir = array_shift($dirstack)) { - if (!call_user_func('mkdir', $newdir, $mode)) { - $ret = false; - } - } - } - } else { - foreach($opts[1] as $dir) { - if (!@is_dir($dir) && !call_user_func('mkdir', $dir, $mode)) { - $ret = false; - } - } - } - return $ret; - } - - /** - * Concatenate files - * - * Usage: - * 1) $var = System::cat('sample.txt test.txt'); - * 2) System::cat('sample.txt test.txt > final.txt'); - * 3) System::cat('sample.txt test.txt >> final.txt'); - * - * Note: as the class use fopen, urls should work also (test that) - * - * @param string $args the arguments - * @return boolean true on success - * @access public - */ - function &cat($args) - { - $ret = null; - $files = array(); - if (!is_array($args)) { - $args = preg_split('/\s+/', $args); - } - for($i=0; $i < count($args); $i++) { - if ($args[$i] == '>') { - $mode = 'wb'; - $outputfile = $args[$i+1]; - break; - } elseif ($args[$i] == '>>') { - $mode = 'ab+'; - $outputfile = $args[$i+1]; - break; - } else { - $files[] = $args[$i]; - } - } - if (isset($mode)) { - if (!$outputfd = fopen($outputfile, $mode)) { - $err = System::raiseError("Could not open $outputfile"); - return $err; - } - $ret = true; - } - foreach ($files as $file) { - if (!$fd = fopen($file, 'r')) { - System::raiseError("Could not open $file"); - continue; - } - while ($cont = fread($fd, 2048)) { - if (isset($outputfd)) { - fwrite($outputfd, $cont); - } else { - $ret .= $cont; - } - } - fclose($fd); - } - if (@is_resource($outputfd)) { - fclose($outputfd); - } - return $ret; - } - - /** - * Creates temporary files or directories. This function will remove - * the created files when the scripts finish its execution. - * - * Usage: - * 1) $tempfile = System::mktemp("prefix"); - * 2) $tempdir = System::mktemp("-d prefix"); - * 3) $tempfile = System::mktemp(); - * 4) $tempfile = System::mktemp("-t /var/tmp prefix"); - * - * prefix -> The string that will be prepended to the temp name - * (defaults to "tmp"). - * -d -> A temporary dir will be created instead of a file. - * -t -> The target dir where the temporary (file|dir) will be created. If - * this param is missing by default the env vars TMP on Windows or - * TMPDIR in Unix will be used. If these vars are also missing - * c:\windows\temp or /tmp will be used. - * - * @param string $args The arguments - * @return mixed the full path of the created (file|dir) or false - * @see System::tmpdir() - * @access public - */ - function mktemp($args = null) - { - static $first_time = true; - $opts = System::_parseArgs($args, 't:d'); - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - foreach($opts[0] as $opt) { - if($opt[0] == 'd') { - $tmp_is_dir = true; - } elseif($opt[0] == 't') { - $tmpdir = $opt[1]; - } - } - $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp'; - if (!isset($tmpdir)) { - $tmpdir = System::tmpdir(); - } - if (!System::mkDir("-p $tmpdir")) { - return false; - } - $tmp = tempnam($tmpdir, $prefix); - if (isset($tmp_is_dir)) { - unlink($tmp); // be careful possible race condition here - if (!call_user_func('mkdir', $tmp, 0700)) { - return System::raiseError("Unable to create temporary directory $tmpdir"); - } - } - $GLOBALS['_System_temp_files'][] = $tmp; - if ($first_time) { - PEAR::registerShutdownFunc(array('System', '_removeTmpFiles')); - $first_time = false; - } - return $tmp; - } - - /** - * Remove temporary files created my mkTemp. This function is executed - * at script shutdown time - * - * @access private - */ - function _removeTmpFiles() - { - if (count($GLOBALS['_System_temp_files'])) { - $delete = $GLOBALS['_System_temp_files']; - array_unshift($delete, '-r'); - System::rm($delete); - } - } - - /** - * Get the path of the temporal directory set in the system - * by looking in its environments variables. - * Note: php.ini-recommended removes the "E" from the variables_order setting, - * making unavaible the $_ENV array, that s why we do tests with _ENV - * - * @return string The temporal directory on the system - */ - function tmpdir() - { - if (OS_WINDOWS) { - if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) { - return $var; - } - if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) { - return $var; - } - if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) { - return $var; - } - return getenv('SystemRoot') . '\temp'; - } - if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) { - return $var; - } - return '/tmp'; - } - - /** - * The "which" command (show the full path of a command) - * - * @param string $program The command to search for - * @return mixed A string with the full path or false if not found - * @author Stig Bakken - */ - function which($program, $fallback = false) - { - // is_executable() is not available on windows - if (OS_WINDOWS) { - $pear_is_executable = 'is_file'; - } else { - $pear_is_executable = 'is_executable'; - } - - // full path given - if (basename($program) != $program) { - return (@$pear_is_executable($program)) ? $program : $fallback; - } - - // XXX FIXME honor safe mode - $path_delim = OS_WINDOWS ? ';' : ':'; - $exe_suffixes = OS_WINDOWS ? array('.exe','.bat','.cmd','.com') : array(''); - $path_elements = explode($path_delim, getenv('PATH')); - foreach ($exe_suffixes as $suff) { - foreach ($path_elements as $dir) { - $file = $dir . DIRECTORY_SEPARATOR . $program . $suff; - if (@is_file($file) && @$pear_is_executable($file)) { - return $file; - } - } - } - return $fallback; - } - - /** - * The "find" command - * - * Usage: - * - * System::find($dir); - * System::find("$dir -type d"); - * System::find("$dir -type f"); - * System::find("$dir -name *.php"); - * System::find("$dir -name *.php -name *.htm*"); - * System::find("$dir -maxdepth 1"); - * - * Params implmented: - * $dir -> Start the search at this directory - * -type d -> return only directories - * -type f -> return only files - * -maxdepth -> max depth of recursion - * -name -> search pattern (bash style). Multiple -name param allowed - * - * @param mixed Either array or string with the command line - * @return array Array of found files - * - */ - function find($args) - { - if (!is_array($args)) { - $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY); - } - $dir = array_shift($args); - $patterns = array(); - $depth = 0; - $do_files = $do_dirs = true; - for ($i = 0; $i < count($args); $i++) { - switch ($args[$i]) { - case '-type': - if (in_array($args[$i+1], array('d', 'f'))) { - if ($args[$i+1] == 'd') { - $do_files = false; - } else { - $do_dirs = false; - } - } - $i++; - break; - case '-name': - $patterns[] = "(" . preg_replace(array('/\./', '/\*/'), - array('\.', '.*'), - $args[$i+1]) - . ")"; - $i++; - break; - case '-maxdepth': - $depth = $args[$i+1]; - break; - } - } - $path = System::_dirToStruct($dir, $depth); - if ($do_files && $do_dirs) { - $files = array_merge($path['files'], $path['dirs']); - } elseif ($do_dirs) { - $files = $path['dirs']; - } else { - $files = $path['files']; - } - if (count($patterns)) { - $patterns = implode('|', $patterns); - $ret = array(); - for ($i = 0; $i < count($files); $i++) { - if (preg_match("#^$patterns\$#", $files[$i])) { - $ret[] = $files[$i]; - } - } - return $ret; - } - return $files; - } -} -?> diff --git a/3rdparty/XML/Parser.php b/3rdparty/XML/Parser.php deleted file mode 100644 index 38b4f8fe8a..0000000000 --- a/3rdparty/XML/Parser.php +++ /dev/null @@ -1,667 +0,0 @@ - | -// | Tomas V.V.Cox | -// | Stephan Schmidt | -// +----------------------------------------------------------------------+ -// -// $Id: Parser.php,v 1.25 2005/03/25 17:13:10 schst Exp $ - -/** - * XML Parser class. - * - * This is an XML parser based on PHP's "xml" extension, - * based on the bundled expat library. - * - * @category XML - * @package XML_Parser - * @author Stig Bakken - * @author Tomas V.V.Cox - * @author Stephan Schmidt - */ - -/** - * uses PEAR's error handling - */ -require_once('PEAR.php'); - -/** - * resource could not be created - */ -define('XML_PARSER_ERROR_NO_RESOURCE', 200); - -/** - * unsupported mode - */ -define('XML_PARSER_ERROR_UNSUPPORTED_MODE', 201); - -/** - * invalid encoding was given - */ -define('XML_PARSER_ERROR_INVALID_ENCODING', 202); - -/** - * specified file could not be read - */ -define('XML_PARSER_ERROR_FILE_NOT_READABLE', 203); - -/** - * invalid input - */ -define('XML_PARSER_ERROR_INVALID_INPUT', 204); - -/** - * remote file cannot be retrieved in safe mode - */ -define('XML_PARSER_ERROR_REMOTE', 205); - -/** - * XML Parser class. - * - * This is an XML parser based on PHP's "xml" extension, - * based on the bundled expat library. - * - * Notes: - * - It requires PHP 4.0.4pl1 or greater - * - From revision 1.17, the function names used by the 'func' mode - * are in the format "xmltag_$elem", for example: use "xmltag_name" - * to handle the tags of your xml file. - * - * @category XML - * @package XML_Parser - * @author Stig Bakken - * @author Tomas V.V.Cox - * @author Stephan Schmidt - * @todo create XML_Parser_Namespace to parse documents with namespaces - * @todo create XML_Parser_Pull - * @todo Tests that need to be made: - * - mixing character encodings - * - a test using all expat handlers - * - options (folding, output charset) - * - different parsing modes - */ -class XML_Parser extends PEAR -{ - // {{{ properties - - /** - * XML parser handle - * - * @var resource - * @see xml_parser_create() - */ - var $parser; - - /** - * File handle if parsing from a file - * - * @var resource - */ - var $fp; - - /** - * Whether to do case folding - * - * If set to true, all tag and attribute names will - * be converted to UPPER CASE. - * - * @var boolean - */ - var $folding = true; - - /** - * Mode of operation, one of "event" or "func" - * - * @var string - */ - var $mode; - - /** - * Mapping from expat handler function to class method. - * - * @var array - */ - var $handler = array( - 'character_data_handler' => 'cdataHandler', - 'default_handler' => 'defaultHandler', - 'processing_instruction_handler' => 'piHandler', - 'unparsed_entity_decl_handler' => 'unparsedHandler', - 'notation_decl_handler' => 'notationHandler', - 'external_entity_ref_handler' => 'entityrefHandler' - ); - - /** - * source encoding - * - * @var string - */ - var $srcenc; - - /** - * target encoding - * - * @var string - */ - var $tgtenc; - - /** - * handler object - * - * @var object - */ - var $_handlerObj; - - // }}} - - /** - * PHP5 constructor - * - * @param string $srcenc source charset encoding, use NULL (default) to use - * whatever the document specifies - * @param string $mode how this parser object should work, "event" for - * startelement/endelement-type events, "func" - * to have it call functions named after elements - * @param string $tgenc a valid target encoding - */ - function __construct($srcenc = null, $mode = 'event', $tgtenc = null) - { - $this->PEAR('XML_Parser_Error'); - - $this->mode = $mode; - $this->srcenc = $srcenc; - $this->tgtenc = $tgtenc; - } - // }}} - - /** - * Sets the mode of the parser. - * - * Possible modes are: - * - func - * - event - * - * You can set the mode using the second parameter - * in the constructor. - * - * This method is only needed, when switching to a new - * mode at a later point. - * - * @access public - * @param string mode, either 'func' or 'event' - * @return boolean|object true on success, PEAR_Error otherwise - */ - function setMode($mode) - { - if ($mode != 'func' && $mode != 'event') { - $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE); - } - - $this->mode = $mode; - return true; - } - - /** - * Sets the object, that will handle the XML events - * - * This allows you to create a handler object independent of the - * parser object that you are using and easily switch the underlying - * parser. - * - * If no object will be set, XML_Parser assumes that you - * extend this class and handle the events in $this. - * - * @access public - * @param object object to handle the events - * @return boolean will always return true - * @since v1.2.0beta3 - */ - function setHandlerObj(&$obj) - { - $this->_handlerObj = &$obj; - return true; - } - - /** - * Init the element handlers - * - * @access private - */ - function _initHandlers() - { - if (!is_resource($this->parser)) { - return false; - } - - if (!is_object($this->_handlerObj)) { - $this->_handlerObj = &$this; - } - switch ($this->mode) { - - case 'func': - xml_set_object($this->parser, $this->_handlerObj); - xml_set_element_handler($this->parser, array(&$this, 'funcStartHandler'), array(&$this, 'funcEndHandler')); - break; - - case 'event': - xml_set_object($this->parser, $this->_handlerObj); - xml_set_element_handler($this->parser, 'startHandler', 'endHandler'); - break; - default: - return $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE); - break; - } - - - /** - * set additional handlers for character data, entities, etc. - */ - foreach ($this->handler as $xml_func => $method) { - if (method_exists($this->_handlerObj, $method)) { - $xml_func = 'xml_set_' . $xml_func; - $xml_func($this->parser, $method); - } - } - } - - // {{{ _create() - - /** - * create the XML parser resource - * - * Has been moved from the constructor to avoid - * problems with object references. - * - * Furthermore it allows us returning an error - * if something fails. - * - * @access private - * @return boolean|object true on success, PEAR_Error otherwise - * - * @see xml_parser_create - */ - function _create() - { - if ($this->srcenc === null) { - $xp = @xml_parser_create(); - } else { - $xp = @xml_parser_create($this->srcenc); - } - if (is_resource($xp)) { - if ($this->tgtenc !== null) { - if (!@xml_parser_set_option($xp, XML_OPTION_TARGET_ENCODING, - $this->tgtenc)) { - return $this->raiseError('invalid target encoding', XML_PARSER_ERROR_INVALID_ENCODING); - } - } - $this->parser = $xp; - $result = $this->_initHandlers($this->mode); - if ($this->isError($result)) { - return $result; - } - xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, $this->folding); - - return true; - } - return $this->raiseError('Unable to create XML parser resource.', XML_PARSER_ERROR_NO_RESOURCE); - } - - // }}} - // {{{ reset() - - /** - * Reset the parser. - * - * This allows you to use one parser instance - * to parse multiple XML documents. - * - * @access public - * @return boolean|object true on success, PEAR_Error otherwise - */ - function reset() - { - $result = $this->_create(); - if ($this->isError( $result )) { - return $result; - } - return true; - } - - // }}} - // {{{ setInputFile() - - /** - * Sets the input xml file to be parsed - * - * @param string Filename (full path) - * @return resource fopen handle of the given file - * @throws XML_Parser_Error - * @see setInput(), setInputString(), parse() - * @access public - */ - function setInputFile($file) - { - /** - * check, if file is a remote file - */ - if (preg_match('[^(http|ftp)://]', substr($file, 0, 10))) { - if (!ini_get('allow_url_fopen')) { - return $this->raiseError('Remote files cannot be parsed, as safe mode is enabled.', XML_PARSER_ERROR_REMOTE); - } - } - $fp = fopen($file, 'rb'); - if (is_resource($fp)) { - $this->fp = $fp; - return $fp; - } - return $this->raiseError('File could not be opened.', XML_PARSER_ERROR_FILE_NOT_READABLE); - } - - // }}} - // {{{ setInputString() - - /** - * XML_Parser::setInputString() - * - * Sets the xml input from a string - * - * @param string $data a string containing the XML document - * @return null - **/ - function setInputString($data) - { - $this->fp = $data; - return null; - } - - // }}} - // {{{ setInput() - - /** - * Sets the file handle to use with parse(). - * - * You should use setInputFile() or setInputString() if you - * pass a string - * - * @param mixed $fp Can be either a resource returned from fopen(), - * a URL, a local filename or a string. - * @access public - * @see parse() - * @uses setInputString(), setInputFile() - */ - function setInput($fp) - { - if (is_resource($fp)) { - $this->fp = $fp; - return true; - } - // see if it's an absolute URL (has a scheme at the beginning) - elseif (eregi('^[a-z]+://', substr($fp, 0, 10))) { - return $this->setInputFile($fp); - } - // see if it's a local file - elseif (file_exists($fp)) { - return $this->setInputFile($fp); - } - // it must be a string - else { - $this->fp = $fp; - return true; - } - - return $this->raiseError('Illegal input format', XML_PARSER_ERROR_INVALID_INPUT); - } - - // }}} - // {{{ parse() - - /** - * Central parsing function. - * - * @return true|object PEAR error returns true on success, or a PEAR_Error otherwise - * @access public - */ - function parse() - { - /** - * reset the parser - */ - $result = $this->reset(); - if ($this->isError($result)) { - return $result; - } - // if $this->fp was fopened previously - if (is_resource($this->fp)) { - - while ($data = fread($this->fp, 4096)) { - if (!$this->_parseString($data, feof($this->fp))) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - } - // otherwise, $this->fp must be a string - } else { - if (!$this->_parseString($this->fp, true)) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - } - $this->free(); - - return true; - } - - /** - * XML_Parser::_parseString() - * - * @param string $data - * @param boolean $eof - * @return bool - * @access private - * @see parseString() - **/ - function _parseString($data, $eof = false) - { - return xml_parse($this->parser, $data, $eof); - } - - // }}} - // {{{ parseString() - - /** - * XML_Parser::parseString() - * - * Parses a string. - * - * @param string $data XML data - * @param boolean $eof If set and TRUE, data is the last piece of data sent in this parser - * @throws XML_Parser_Error - * @return Pear Error|true true on success or a PEAR Error - * @see _parseString() - */ - function parseString($data, $eof = false) - { - if (!isset($this->parser) || !is_resource($this->parser)) { - $this->reset(); - } - - if (!$this->_parseString($data, $eof)) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - - if ($eof === true) { - $this->free(); - } - return true; - } - - /** - * XML_Parser::free() - * - * Free the internal resources associated with the parser - * - * @return null - **/ - function free() - { - if (isset($this->parser) && is_resource($this->parser)) { - xml_parser_free($this->parser); - unset( $this->parser ); - } - if (isset($this->fp) && is_resource($this->fp)) { - fclose($this->fp); - } - unset($this->fp); - return null; - } - - /** - * XML_Parser::raiseError() - * - * Throws a XML_Parser_Error - * - * @param string $msg the error message - * @param integer $ecode the error message code - * @return XML_Parser_Error - **/ - function raiseError($msg = null, $ecode = 0,$mode = null, - $options = null, - $userinfo = null, - $error_class = null, - $skipmsg = false) - { - $msg = !is_null($msg) ? $msg : $this->parser; - $err = new XML_Parser_Error($msg, $ecode); - return parent::raiseError($err); - } - - // }}} - // {{{ funcStartHandler() - - function funcStartHandler($xp, $elem, $attribs) - { - $func = 'xmltag_' . $elem; - if (strchr($func, '.')) { - $func = str_replace('.', '_', $func); - } - if (method_exists($this->_handlerObj, $func)) { - call_user_func(array(&$this->_handlerObj, $func), $xp, $elem, $attribs); - } elseif (method_exists($this->_handlerObj, 'xmltag')) { - call_user_func(array(&$this->_handlerObj, 'xmltag'), $xp, $elem, $attribs); - } - } - - // }}} - // {{{ funcEndHandler() - - function funcEndHandler($xp, $elem) - { - $func = 'xmltag_' . $elem . '_'; - if (strchr($func, '.')) { - $func = str_replace('.', '_', $func); - } - if (method_exists($this->_handlerObj, $func)) { - call_user_func(array(&$this->_handlerObj, $func), $xp, $elem); - } elseif (method_exists($this->_handlerObj, 'xmltag_')) { - call_user_func(array(&$this->_handlerObj, 'xmltag_'), $xp, $elem); - } - } - - // }}} - // {{{ startHandler() - - /** - * - * @abstract - */ - function startHandler($xp, $elem, $attribs) - { - return NULL; - } - - // }}} - // {{{ endHandler() - - /** - * - * @abstract - */ - function endHandler($xp, $elem) - { - return NULL; - } - - - // }}}me -} - -/** - * error class, replaces PEAR_Error - * - * An instance of this class will be returned - * if an error occurs inside XML_Parser. - * - * There are three advantages over using the standard PEAR_Error: - * - All messages will be prefixed - * - check for XML_Parser error, using is_a( $error, 'XML_Parser_Error' ) - * - messages can be generated from the xml_parser resource - * - * @package XML_Parser - * @access public - * @see PEAR_Error - */ -class XML_Parser_Error extends PEAR_Error -{ - // {{{ properties - - /** - * prefix for all messages - * - * @var string - */ - var $error_message_prefix = 'XML_Parser: '; - - // }}} - // {{{ constructor() - /** - * construct a new error instance - * - * You may either pass a message or an xml_parser resource as first - * parameter. If a resource has been passed, the last error that - * happened will be retrieved and returned. - * - * @access public - * @param string|resource message or parser resource - * @param integer error code - * @param integer error handling - * @param integer error level - */ - function XML_Parser_Error($msgorparser = 'unknown error', $code = 0, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE) - { - if (is_resource($msgorparser)) { - $code = xml_get_error_code($msgorparser); - $msgorparser = sprintf('%s at XML input line %d', - xml_error_string($code), - xml_get_current_line_number($msgorparser)); - } - $this->PEAR_Error($msgorparser, $code, $mode, $level); - } - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/XML/RPC.php b/3rdparty/XML/RPC.php deleted file mode 100644 index 096b22a0ab..0000000000 --- a/3rdparty/XML/RPC.php +++ /dev/null @@ -1,1951 +0,0 @@ - - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version CVS: $Id: RPC.php,v 1.83 2005/08/14 20:25:35 danielc Exp $ - * @link http://pear.php.net/package/XML_RPC - */ - - -if (!function_exists('xml_parser_create')) { - PEAR::loadExtension('xml'); -} - -/**#@+ - * Error constants - */ -/** - * Parameter values don't match parameter types - */ -define('XML_RPC_ERROR_INVALID_TYPE', 101); -/** - * Parameter declared to be numeric but the values are not - */ -define('XML_RPC_ERROR_NON_NUMERIC_FOUND', 102); -/** - * Communication error - */ -define('XML_RPC_ERROR_CONNECTION_FAILED', 103); -/** - * The array or struct has already been started - */ -define('XML_RPC_ERROR_ALREADY_INITIALIZED', 104); -/** - * Incorrect parameters submitted - */ -define('XML_RPC_ERROR_INCORRECT_PARAMS', 105); -/** - * Programming error by developer - */ -define('XML_RPC_ERROR_PROGRAMMING', 106); -/**#@-*/ - - -/** - * Data types - * @global string $GLOBALS['XML_RPC_I4'] - */ -$GLOBALS['XML_RPC_I4'] = 'i4'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Int'] - */ -$GLOBALS['XML_RPC_Int'] = 'int'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Boolean'] - */ -$GLOBALS['XML_RPC_Boolean'] = 'boolean'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Double'] - */ -$GLOBALS['XML_RPC_Double'] = 'double'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_String'] - */ -$GLOBALS['XML_RPC_String'] = 'string'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_DateTime'] - */ -$GLOBALS['XML_RPC_DateTime'] = 'dateTime.iso8601'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Base64'] - */ -$GLOBALS['XML_RPC_Base64'] = 'base64'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Array'] - */ -$GLOBALS['XML_RPC_Array'] = 'array'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Struct'] - */ -$GLOBALS['XML_RPC_Struct'] = 'struct'; - - -/** - * Data type meta-types - * @global array $GLOBALS['XML_RPC_Types'] - */ -$GLOBALS['XML_RPC_Types'] = array( - $GLOBALS['XML_RPC_I4'] => 1, - $GLOBALS['XML_RPC_Int'] => 1, - $GLOBALS['XML_RPC_Boolean'] => 1, - $GLOBALS['XML_RPC_String'] => 1, - $GLOBALS['XML_RPC_Double'] => 1, - $GLOBALS['XML_RPC_DateTime'] => 1, - $GLOBALS['XML_RPC_Base64'] => 1, - $GLOBALS['XML_RPC_Array'] => 2, - $GLOBALS['XML_RPC_Struct'] => 3, -); - - -/** - * Error message numbers - * @global array $GLOBALS['XML_RPC_err'] - */ -$GLOBALS['XML_RPC_err'] = array( - 'unknown_method' => 1, - 'invalid_return' => 2, - 'incorrect_params' => 3, - 'introspect_unknown' => 4, - 'http_error' => 5, - 'not_response_object' => 6, - 'invalid_request' => 7, -); - -/** - * Error message strings - * @global array $GLOBALS['XML_RPC_str'] - */ -$GLOBALS['XML_RPC_str'] = array( - 'unknown_method' => 'Unknown method', - 'invalid_return' => 'Invalid return payload: enable debugging to examine incoming payload', - 'incorrect_params' => 'Incorrect parameters passed to method', - 'introspect_unknown' => 'Can\'t introspect: method unknown', - 'http_error' => 'Didn\'t receive 200 OK from remote server.', - 'not_response_object' => 'The requested method didn\'t return an XML_RPC_Response object.', - 'invalid_request' => 'Invalid request payload', -); - - -/** - * Default XML encoding (ISO-8859-1, UTF-8 or US-ASCII) - * @global string $GLOBALS['XML_RPC_defencoding'] - */ -$GLOBALS['XML_RPC_defencoding'] = 'UTF-8'; - -/** - * User error codes start at 800 - * @global int $GLOBALS['XML_RPC_erruser'] - */ -$GLOBALS['XML_RPC_erruser'] = 800; - -/** - * XML parse error codes start at 100 - * @global int $GLOBALS['XML_RPC_errxml'] - */ -$GLOBALS['XML_RPC_errxml'] = 100; - - -/** - * Compose backslashes for escaping regexp - * @global string $GLOBALS['XML_RPC_backslash'] - */ -$GLOBALS['XML_RPC_backslash'] = chr(92) . chr(92); - - -/** - * Valid parents of XML elements - * @global array $GLOBALS['XML_RPC_valid_parents'] - */ -$GLOBALS['XML_RPC_valid_parents'] = array( - 'BOOLEAN' => array('VALUE'), - 'I4' => array('VALUE'), - 'INT' => array('VALUE'), - 'STRING' => array('VALUE'), - 'DOUBLE' => array('VALUE'), - 'DATETIME.ISO8601' => array('VALUE'), - 'BASE64' => array('VALUE'), - 'ARRAY' => array('VALUE'), - 'STRUCT' => array('VALUE'), - 'PARAM' => array('PARAMS'), - 'METHODNAME' => array('METHODCALL'), - 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), - 'MEMBER' => array('STRUCT'), - 'NAME' => array('MEMBER'), - 'DATA' => array('ARRAY'), - 'FAULT' => array('METHODRESPONSE'), - 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), -); - - -/** - * Stores state during parsing - * - * quick explanation of components: - * + ac = accumulates values - * + qt = decides if quotes are needed for evaluation - * + cm = denotes struct or array (comma needed) - * + isf = indicates a fault - * + lv = indicates "looking for a value": implements the logic - * to allow values with no types to be strings - * + params = stores parameters in method calls - * + method = stores method name - * - * @global array $GLOBALS['XML_RPC_xh'] - */ -$GLOBALS['XML_RPC_xh'] = array(); - - -/** - * Start element handler for the XML parser - * - * @return void - */ -function XML_RPC_se($parser_resource, $name, $attrs) -{ - global $XML_RPC_xh, $XML_RPC_DateTime, $XML_RPC_String, $XML_RPC_valid_parents; - $parser = (int) $parser_resource; - - // if invalid xmlrpc already detected, skip all processing - if ($XML_RPC_xh[$parser]['isf'] >= 2) { - return; - } - - // check for correct element nesting - // top level element can only be of 2 types - if (count($XML_RPC_xh[$parser]['stack']) == 0) { - if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') { - $XML_RPC_xh[$parser]['isf'] = 2; - $XML_RPC_xh[$parser]['isf_reason'] = 'missing top level xmlrpc element'; - return; - } - } else { - // not top level element: see if parent is OK - if (!in_array($XML_RPC_xh[$parser]['stack'][0], $XML_RPC_valid_parents[$name])) { - $name = preg_replace('[^a-zA-Z0-9._-]', '', $name); - $XML_RPC_xh[$parser]['isf'] = 2; - $XML_RPC_xh[$parser]['isf_reason'] = "xmlrpc element $name cannot be child of {$XML_RPC_xh[$parser]['stack'][0]}"; - return; - } - } - - switch ($name) { - case 'STRUCT': - $XML_RPC_xh[$parser]['cm']++; - - // turn quoting off - $XML_RPC_xh[$parser]['qt'] = 0; - - $cur_val = array(); - $cur_val['value'] = array(); - $cur_val['members'] = 1; - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - break; - - case 'ARRAY': - $XML_RPC_xh[$parser]['cm']++; - - // turn quoting off - $XML_RPC_xh[$parser]['qt'] = 0; - - $cur_val = array(); - $cur_val['value'] = array(); - $cur_val['members'] = 0; - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - break; - - case 'NAME': - $XML_RPC_xh[$parser]['ac'] = ''; - break; - - case 'FAULT': - $XML_RPC_xh[$parser]['isf'] = 1; - break; - - case 'PARAM': - $XML_RPC_xh[$parser]['valuestack'] = array(); - break; - - case 'VALUE': - $XML_RPC_xh[$parser]['lv'] = 1; - $XML_RPC_xh[$parser]['vt'] = $XML_RPC_String; - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - // look for a value: if this is still 1 by the - // time we reach the first data segment then the type is string - // by implication and we need to add in a quote - break; - - case 'I4': - case 'INT': - case 'STRING': - case 'BOOLEAN': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - $XML_RPC_xh[$parser]['ac'] = ''; // reset the accumulator - - if ($name == 'DATETIME.ISO8601' || $name == 'STRING') { - $XML_RPC_xh[$parser]['qt'] = 1; - - if ($name == 'DATETIME.ISO8601') { - $XML_RPC_xh[$parser]['vt'] = $XML_RPC_DateTime; - } - - } elseif ($name == 'BASE64') { - $XML_RPC_xh[$parser]['qt'] = 2; - } else { - // No quoting is required here -- but - // at the end of the element we must check - // for data format errors. - $XML_RPC_xh[$parser]['qt'] = 0; - } - break; - - case 'MEMBER': - $XML_RPC_xh[$parser]['ac'] = ''; - break; - - case 'DATA': - case 'METHODCALL': - case 'METHODNAME': - case 'METHODRESPONSE': - case 'PARAMS': - // valid elements that add little to processing - break; - } - - - // Save current element to stack - array_unshift($XML_RPC_xh[$parser]['stack'], $name); - - if ($name != 'VALUE') { - $XML_RPC_xh[$parser]['lv'] = 0; - } -} - -/** - * End element handler for the XML parser - * - * @return void - */ -function XML_RPC_ee($parser_resource, $name) -{ - global $XML_RPC_xh, $XML_RPC_Types, $XML_RPC_String; - $parser = (int) $parser_resource; - - if ($XML_RPC_xh[$parser]['isf'] >= 2) { - return; - } - - // push this element from stack - // NB: if XML validates, correct opening/closing is guaranteed and - // we do not have to check for $name == $curr_elem. - // we also checked for proper nesting at start of elements... - $curr_elem = array_shift($XML_RPC_xh[$parser]['stack']); - - switch ($name) { - case 'STRUCT': - case 'ARRAY': - $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']); - $XML_RPC_xh[$parser]['value'] = $cur_val['value']; - $XML_RPC_xh[$parser]['vt'] = strtolower($name); - $XML_RPC_xh[$parser]['cm']--; - break; - - case 'NAME': - $XML_RPC_xh[$parser]['valuestack'][0]['name'] = $XML_RPC_xh[$parser]['ac']; - break; - - case 'BOOLEAN': - // special case here: we translate boolean 1 or 0 into PHP - // constants true or false - if ($XML_RPC_xh[$parser]['ac'] == '1') { - $XML_RPC_xh[$parser]['ac'] = 'true'; - } else { - $XML_RPC_xh[$parser]['ac'] = 'false'; - } - - $XML_RPC_xh[$parser]['vt'] = strtolower($name); - // Drop through intentionally. - - case 'I4': - case 'INT': - case 'STRING': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - if ($XML_RPC_xh[$parser]['qt'] == 1) { - // we use double quotes rather than single so backslashification works OK - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } elseif ($XML_RPC_xh[$parser]['qt'] == 2) { - $XML_RPC_xh[$parser]['value'] = base64_decode($XML_RPC_xh[$parser]['ac']); - } elseif ($name == 'BOOLEAN') { - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } else { - // we have an I4, INT or a DOUBLE - // we must check that only 0123456789-. are characters here - if (!ereg("^[+-]?[0123456789 \t\.]+$", $XML_RPC_xh[$parser]['ac'])) { - XML_RPC_Base::raiseError('Non-numeric value received in INT or DOUBLE', - XML_RPC_ERROR_NON_NUMERIC_FOUND); - $XML_RPC_xh[$parser]['value'] = XML_RPC_ERROR_NON_NUMERIC_FOUND; - } else { - // it's ok, add it on - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } - } - - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - $XML_RPC_xh[$parser]['lv'] = 3; // indicate we've found a value - break; - - case 'VALUE': - // deal with a string value - if (strlen($XML_RPC_xh[$parser]['ac']) > 0 && - $XML_RPC_xh[$parser]['vt'] == $XML_RPC_String) { - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } - - $temp = new XML_RPC_Value($XML_RPC_xh[$parser]['value'], $XML_RPC_xh[$parser]['vt']); - - $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']); - if (is_array($cur_val)) { - if ($cur_val['members']==0) { - $cur_val['value'][] = $temp; - } else { - $XML_RPC_xh[$parser]['value'] = $temp; - } - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - } else { - $XML_RPC_xh[$parser]['value'] = $temp; - } - break; - - case 'MEMBER': - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - - $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']); - if (is_array($cur_val)) { - if ($cur_val['members']==1) { - $cur_val['value'][$cur_val['name']] = $XML_RPC_xh[$parser]['value']; - } - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - } - break; - - case 'DATA': - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - break; - - case 'PARAM': - $XML_RPC_xh[$parser]['params'][] = $XML_RPC_xh[$parser]['value']; - break; - - case 'METHODNAME': - case 'RPCMETHODNAME': - $XML_RPC_xh[$parser]['method'] = ereg_replace("^[\n\r\t ]+", '', - $XML_RPC_xh[$parser]['ac']); - break; - } - - // if it's a valid type name, set the type - if (isset($XML_RPC_Types[strtolower($name)])) { - $XML_RPC_xh[$parser]['vt'] = strtolower($name); - } -} - -/** - * Character data handler for the XML parser - * - * @return void - */ -function XML_RPC_cd($parser_resource, $data) -{ - global $XML_RPC_xh, $XML_RPC_backslash; - $parser = (int) $parser_resource; - - if ($XML_RPC_xh[$parser]['lv'] != 3) { - // "lookforvalue==3" means that we've found an entire value - // and should discard any further character data - - if ($XML_RPC_xh[$parser]['lv'] == 1) { - // if we've found text and we're just in a then - // turn quoting on, as this will be a string - $XML_RPC_xh[$parser]['qt'] = 1; - // and say we've found a value - $XML_RPC_xh[$parser]['lv'] = 2; - } - - // replace characters that eval would - // do special things with - if (!isset($XML_RPC_xh[$parser]['ac'])) { - $XML_RPC_xh[$parser]['ac'] = ''; - } - $XML_RPC_xh[$parser]['ac'] .= $data; - } -} - -/** - * The common methods and properties for all of the XML_RPC classes - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Base { - - /** - * PEAR Error handling - * - * @return object PEAR_Error object - */ - function raiseError($msg, $code) - { - include_once 'PEAR.php'; - if (is_object(@$this)) { - return PEAR::raiseError(get_class($this) . ': ' . $msg, $code); - } else { - return PEAR::raiseError('XML_RPC: ' . $msg, $code); - } - } - - /** - * Tell whether something is a PEAR_Error object - * - * @param mixed $value the item to check - * - * @return bool whether $value is a PEAR_Error object or not - * - * @access public - */ - function isError($value) - { - return is_a($value, 'PEAR_Error'); - } -} - -/** - * The methods and properties for submitting XML RPC requests - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Client extends XML_RPC_Base { - - /** - * The path and name of the RPC server script you want the request to go to - * @var string - */ - var $path = ''; - - /** - * The name of the remote server to connect to - * @var string - */ - var $server = ''; - - /** - * The protocol to use in contacting the remote server - * @var string - */ - var $protocol = 'http://'; - - /** - * The port for connecting to the remote server - * - * The default is 80 for http:// connections - * and 443 for https:// and ssl:// connections. - * - * @var integer - */ - var $port = 80; - - /** - * A user name for accessing the RPC server - * @var string - * @see XML_RPC_Client::setCredentials() - */ - var $username = ''; - - /** - * A password for accessing the RPC server - * @var string - * @see XML_RPC_Client::setCredentials() - */ - var $password = ''; - - /** - * The name of the proxy server to use, if any - * @var string - */ - var $proxy = ''; - - /** - * The protocol to use in contacting the proxy server, if any - * @var string - */ - var $proxy_protocol = 'http://'; - - /** - * The port for connecting to the proxy server - * - * The default is 8080 for http:// connections - * and 443 for https:// and ssl:// connections. - * - * @var integer - */ - var $proxy_port = 8080; - - /** - * A user name for accessing the proxy server - * @var string - */ - var $proxy_user = ''; - - /** - * A password for accessing the proxy server - * @var string - */ - var $proxy_pass = ''; - - /** - * The error number, if any - * @var integer - */ - var $errno = 0; - - /** - * The error message, if any - * @var string - */ - var $errstr = ''; - - /** - * The current debug mode (1 = on, 0 = off) - * @var integer - */ - var $debug = 0; - - /** - * The HTTP headers for the current request. - * @var string - */ - var $headers = ''; - - - /** - * Sets the object's properties - * - * @param string $path the path and name of the RPC server script - * you want the request to go to - * @param string $server the URL of the remote server to connect to. - * If this parameter doesn't specify a - * protocol and $port is 443, ssl:// is - * assumed. - * @param integer $port a port for connecting to the remote server. - * Defaults to 80 for http:// connections and - * 443 for https:// and ssl:// connections. - * @param string $proxy the URL of the proxy server to use, if any. - * If this parameter doesn't specify a - * protocol and $port is 443, ssl:// is - * assumed. - * @param integer $proxy_port a port for connecting to the remote server. - * Defaults to 8080 for http:// connections and - * 443 for https:// and ssl:// connections. - * @param string $proxy_user a user name for accessing the proxy server - * @param string $proxy_pass a password for accessing the proxy server - * - * @return void - */ - function XML_RPC_Client($path, $server, $port = 0, - $proxy = '', $proxy_port = 0, - $proxy_user = '', $proxy_pass = '') - { - $this->path = $path; - $this->proxy_user = $proxy_user; - $this->proxy_pass = $proxy_pass; - - preg_match('@^(http://|https://|ssl://)?(.*)$@', $server, $match); - if ($match[1] == '') { - if ($port == 443) { - $this->server = $match[2]; - $this->protocol = 'ssl://'; - $this->port = 443; - } else { - $this->server = $match[2]; - if ($port) { - $this->port = $port; - } - } - } elseif ($match[1] == 'http://') { - $this->server = $match[2]; - if ($port) { - $this->port = $port; - } - } else { - $this->server = $match[2]; - $this->protocol = 'ssl://'; - if ($port) { - $this->port = $port; - } else { - $this->port = 443; - } - } - - if ($proxy) { - preg_match('@^(http://|https://|ssl://)?(.*)$@', $proxy, $match); - if ($match[1] == '') { - if ($proxy_port == 443) { - $this->proxy = $match[2]; - $this->proxy_protocol = 'ssl://'; - $this->proxy_port = 443; - } else { - $this->proxy = $match[2]; - if ($proxy_port) { - $this->proxy_port = $proxy_port; - } - } - } elseif ($match[1] == 'http://') { - $this->proxy = $match[2]; - if ($proxy_port) { - $this->proxy_port = $proxy_port; - } - } else { - $this->proxy = $match[2]; - $this->proxy_protocol = 'ssl://'; - if ($proxy_port) { - $this->proxy_port = $proxy_port; - } else { - $this->proxy_port = 443; - } - } - } - } - - /** - * Change the current debug mode - * - * @param int $in where 1 = on, 0 = off - * - * @return void - */ - function setDebug($in) - { - if ($in) { - $this->debug = 1; - } else { - $this->debug = 0; - } - } - - /** - * Set username and password properties for connecting to the RPC server - * - * @param string $u the user name - * @param string $p the password - * - * @return void - * - * @see XML_RPC_Client::$username, XML_RPC_Client::$password - */ - function setCredentials($u, $p) - { - $this->username = $u; - $this->password = $p; - } - - /** - * Transmit the RPC request via HTTP 1.0 protocol - * - * @param object $msg the XML_RPC_Message object - * @param int $timeout how many seconds to wait for the request - * - * @return object an XML_RPC_Response object. 0 is returned if any - * problems happen. - * - * @see XML_RPC_Message, XML_RPC_Client::XML_RPC_Client(), - * XML_RPC_Client::setCredentials() - */ - function send($msg, $timeout = 0) - { - if (strtolower(get_class($msg)) != 'xml_rpc_message') { - $this->errstr = 'send()\'s $msg parameter must be an' - . ' XML_RPC_Message object.'; - $this->raiseError($this->errstr, XML_RPC_ERROR_PROGRAMMING); - return 0; - } - $msg->debug = $this->debug; - return $this->sendPayloadHTTP10($msg, $this->server, $this->port, - $timeout, $this->username, - $this->password); - } - - /** - * Transmit the RPC request via HTTP 1.0 protocol - * - * Requests should be sent using XML_RPC_Client send() rather than - * calling this method directly. - * - * @param object $msg the XML_RPC_Message object - * @param string $server the server to send the request to - * @param int $port the server port send the request to - * @param int $timeout how many seconds to wait for the request - * before giving up - * @param string $username a user name for accessing the RPC server - * @param string $password a password for accessing the RPC server - * - * @return object an XML_RPC_Response object. 0 is returned if any - * problems happen. - * - * @access protected - * @see XML_RPC_Client::send() - */ - function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, - $username = '', $password = '') - { - /* - * If we're using a proxy open a socket to the proxy server - * instead to the xml-rpc server - */ - if ($this->proxy) { - if ($this->proxy_protocol == 'http://') { - $protocol = ''; - } else { - $protocol = $this->proxy_protocol; - } - if ($timeout > 0) { - $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port, - $this->errno, $this->errstr, $timeout); - } else { - $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port, - $this->errno, $this->errstr); - } - } else { - if ($this->protocol == 'http://') { - $protocol = ''; - } else { - $protocol = $this->protocol; - } - if ($timeout > 0) { - $fp = @fsockopen($protocol . $server, $port, - $this->errno, $this->errstr, $timeout); - } else { - $fp = @fsockopen($protocol . $server, $port, - $this->errno, $this->errstr); - } - } - - /* - * Just raising the error without returning it is strange, - * but keep it here for backwards compatibility. - */ - if (!$fp && $this->proxy) { - $this->raiseError('Connection to proxy server ' - . $this->proxy . ':' . $this->proxy_port - . ' failed. ' . $this->errstr, - XML_RPC_ERROR_CONNECTION_FAILED); - return 0; - } elseif (!$fp) { - $this->raiseError('Connection to RPC server ' - . $server . ':' . $port - . ' failed. ' . $this->errstr, - XML_RPC_ERROR_CONNECTION_FAILED); - return 0; - } - - if ($timeout) { - /* - * Using socket_set_timeout() because stream_set_timeout() - * was introduced in 4.3.0, but we need to support 4.2.0. - */ - socket_set_timeout($fp, $timeout); - } - - // Pre-emptive BC hacks for fools calling sendPayloadHTTP10() directly - if ($username != $this->username) { - $this->setCredentials($username, $password); - } - - // Only create the payload if it was not created previously - if (empty($msg->payload)) { - $msg->createPayload(); - } - $this->createHeaders($msg); - - $op = $this->headers . "\r\n\r\n"; - $op .= $msg->payload; - - if (!fputs($fp, $op, strlen($op))) { - $this->errstr = 'Write error'; - return 0; - } - $resp = $msg->parseResponseFile($fp); - - $meta = socket_get_status($fp); - if ($meta['timed_out']) { - fclose($fp); - $this->errstr = 'RPC server did not send response before timeout.'; - $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED); - return 0; - } - - fclose($fp); - return $resp; - } - - /** - * Determines the HTTP headers and puts it in the $headers property - * - * @param object $msg the XML_RPC_Message object - * - * @return boolean TRUE if okay, FALSE if the message payload isn't set. - * - * @access protected - */ - function createHeaders($msg) - { - if (empty($msg->payload)) { - return false; - } - if ($this->proxy) { - $this->headers = 'POST ' . $this->protocol . $this->server; - if ($this->proxy_port) { - $this->headers .= ':' . $this->port; - } - } else { - $this->headers = 'POST '; - } - $this->headers .= $this->path. " HTTP/1.0\r\n"; - - $this->headers .= "User-Agent: PEAR XML_RPC\r\n"; - $this->headers .= 'Host: ' . $this->server . "\r\n"; - - if ($this->proxy && $this->proxy_user) { - $this->headers .= 'Proxy-Authorization: Basic ' - . base64_encode("$this->proxy_user:$this->proxy_pass") - . "\r\n"; - } - - // thanks to Grant Rauscher for this - if ($this->username) { - $this->headers .= 'Authorization: Basic ' - . base64_encode("$this->username:$this->password") - . "\r\n"; - } - - $this->headers .= "Content-Type: text/xml\r\n"; - $this->headers .= 'Content-Length: ' . strlen($msg->payload); - return true; - } -} - -/** - * The methods and properties for interpreting responses to XML RPC requests - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Response extends XML_RPC_Base -{ - var $xv; - var $fn; - var $fs; - var $hdrs; - - /** - * @return void - */ - function XML_RPC_Response($val, $fcode = 0, $fstr = '') - { - if ($fcode != 0) { - $this->fn = $fcode; - $this->fs = htmlspecialchars($fstr); - } else { - $this->xv = $val; - } - } - - /** - * @return int the error code - */ - function faultCode() - { - if (isset($this->fn)) { - return $this->fn; - } else { - return 0; - } - } - - /** - * @return string the error string - */ - function faultString() - { - return $this->fs; - } - - /** - * @return mixed the value - */ - function value() - { - return $this->xv; - } - - /** - * @return string the error message in XML format - */ - function serialize() - { - $rs = "\n"; - if ($this->fn) { - $rs .= " - - - - faultCode - " . $this->fn . " - - - faultString - " . $this->fs . " - - - -"; - } else { - $rs .= "\n\n" . $this->xv->serialize() . - "\n"; - } - $rs .= "\n"; - return $rs; - } -} - -/** - * The methods and properties for composing XML RPC messages - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Message extends XML_RPC_Base -{ - /** - * The current debug mode (1 = on, 0 = off) - * @var integer - */ - var $debug = 0; - - /** - * The encoding to be used for outgoing messages - * - * Defaults to the value of $GLOBALS['XML_RPC_defencoding'] - * - * @var string - * @see XML_RPC_Message::setSendEncoding(), - * $GLOBALS['XML_RPC_defencoding'], XML_RPC_Message::xml_header() - */ - var $send_encoding = ''; - - /** - * The method presently being evaluated - * @var string - */ - var $methodname = ''; - - /** - * @var array - */ - var $params = array(); - - /** - * The XML message being generated - * @var string - */ - var $payload = ''; - - /** - * @return void - */ - function XML_RPC_Message($meth, $pars = 0) - { - $this->methodname = $meth; - if (is_array($pars) && sizeof($pars) > 0) { - for ($i = 0; $i < sizeof($pars); $i++) { - $this->addParam($pars[$i]); - } - } - } - - /** - * Produces the XML declaration including the encoding attribute - * - * The encoding is determined by this class' $send_encoding - * property. If the $send_encoding property is not set, use - * $GLOBALS['XML_RPC_defencoding']. - * - * @return string the XML declaration and element - * - * @see XML_RPC_Message::setSendEncoding(), - * XML_RPC_Message::$send_encoding, $GLOBALS['XML_RPC_defencoding'] - */ - function xml_header() - { - global $XML_RPC_defencoding; - if (!$this->send_encoding) { - $this->send_encoding = $XML_RPC_defencoding; - } - return 'send_encoding . '"?>' - . "\n\n"; - } - - /** - * @return string the closing tag - */ - function xml_footer() - { - return "\n"; - } - - /** - * @return void - * - * @uses XML_RPC_Message::xml_header(), XML_RPC_Message::xml_footer() - */ - function createPayload() - { - $this->payload = $this->xml_header(); - $this->payload .= '' . $this->methodname . "\n"; - $this->payload .= "\n"; - for ($i = 0; $i < sizeof($this->params); $i++) { - $p = $this->params[$i]; - $this->payload .= "\n" . $p->serialize() . "\n"; - } - $this->payload .= "\n"; - $this->payload .= $this->xml_footer(); - $this->payload = ereg_replace("[\r\n]+", "\r\n", $this->payload); - } - - /** - * @return string the name of the method - */ - function method($meth = '') - { - if ($meth != '') { - $this->methodname = $meth; - } - return $this->methodname; - } - - /** - * @return string the payload - */ - function serialize() - { - $this->createPayload(); - return $this->payload; - } - - /** - * @return void - */ - function addParam($par) - { - $this->params[] = $par; - } - - /** - * Obtains an XML_RPC_Value object for the given parameter - * - * @param int $i the index number of the parameter to obtain - * - * @return object the XML_RPC_Value object. - * If the parameter doesn't exist, an XML_RPC_Response object. - * - * @since Returns XML_RPC_Response object on error since Release 1.3.0 - */ - function getParam($i) - { - global $XML_RPC_err, $XML_RPC_str; - - if (isset($this->params[$i])) { - return $this->params[$i]; - } else { - $this->raiseError('The submitted request did not contain this parameter', - XML_RPC_ERROR_INCORRECT_PARAMS); - return new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'], - $XML_RPC_str['incorrect_params']); - } - } - - /** - * @return int the number of parameters - */ - function getNumParams() - { - return sizeof($this->params); - } - - /** - * Sets the XML declaration's encoding attribute - * - * @param string $type the encoding type (ISO-8859-1, UTF-8 or US-ASCII) - * - * @return void - * - * @see XML_RPC_Message::$send_encoding, XML_RPC_Message::xml_header() - * @since Method available since Release 1.2.0 - */ - function setSendEncoding($type) - { - $this->send_encoding = $type; - } - - /** - * Determine the XML's encoding via the encoding attribute - * in the XML declaration - * - * If the encoding parameter is not set or is not ISO-8859-1, UTF-8 - * or US-ASCII, $XML_RPC_defencoding will be returned. - * - * @param string $data the XML that will be parsed - * - * @return string the encoding to be used - * - * @link http://php.net/xml_parser_create - * @since Method available since Release 1.2.0 - */ - function getEncoding($data) - { - global $XML_RPC_defencoding; - - if (preg_match('/<\?xml[^>]*\s*encoding\s*=\s*[\'"]([^"\']*)[\'"]/i', - $data, $match)) - { - $match[1] = trim(strtoupper($match[1])); - switch ($match[1]) { - case 'ISO-8859-1': - case 'UTF-8': - case 'US-ASCII': - return $match[1]; - break; - - default: - return $XML_RPC_defencoding; - } - } else { - return $XML_RPC_defencoding; - } - } - - /** - * @return object a new XML_RPC_Response object - */ - function parseResponseFile($fp) - { - $ipd = ''; - while ($data = @fread($fp, 8192)) { - $ipd .= $data; - } - return $this->parseResponse($ipd); - } - - /** - * @return object a new XML_RPC_Response object - */ - function parseResponse($data = '') - { - global $XML_RPC_xh, $XML_RPC_err, $XML_RPC_str, $XML_RPC_defencoding; - - $encoding = $this->getEncoding($data); - $parser_resource = xml_parser_create($encoding); - $parser = (int) $parser_resource; - - $XML_RPC_xh = array(); - $XML_RPC_xh[$parser] = array(); - - $XML_RPC_xh[$parser]['cm'] = 0; - $XML_RPC_xh[$parser]['isf'] = 0; - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = ''; - $XML_RPC_xh[$parser]['stack'] = array(); - $XML_RPC_xh[$parser]['valuestack'] = array(); - - xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true); - xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee'); - xml_set_character_data_handler($parser_resource, 'XML_RPC_cd'); - - $hdrfnd = 0; - if ($this->debug) { - print "\n
---GOT---\n";
-            print isset($_SERVER['SERVER_PROTOCOL']) ? htmlspecialchars($data) : $data;
-            print "\n---END---
\n"; - } - - // See if response is a 200 or a 100 then a 200, else raise error. - // But only do this if we're using the HTTP protocol. - if (ereg('^HTTP', $data) && - !ereg('^HTTP/[0-9\.]+ 200 ', $data) && - !preg_match('@^HTTP/[0-9\.]+ 10[0-9]([A-Za-z ]+)?[\r\n]+HTTP/[0-9\.]+ 200@', $data)) - { - $errstr = substr($data, 0, strpos($data, "\n") - 1); - if(defined("DEBUG") && DEBUG) {error_log('HTTP error, got response: ' . $errstr);} - $r = new XML_RPC_Response(0, $XML_RPC_err['http_error'], - $XML_RPC_str['http_error'] . ' (' . - $errstr . ')'); - xml_parser_free($parser_resource); - return $r; - } - - // gotta get rid of headers here - if (!$hdrfnd && ($brpos = strpos($data,"\r\n\r\n"))) { - $XML_RPC_xh[$parser]['ha'] = substr($data, 0, $brpos); - $data = substr($data, $brpos + 4); - $hdrfnd = 1; - } - - /* - * be tolerant of junk after methodResponse - * (e.g. javascript automatically inserted by free hosts) - * thanks to Luca Mariano - */ - $data = substr($data, 0, strpos($data, "") + 17); - - if (!xml_parse($parser_resource, $data, sizeof($data))) { - // thanks to Peter Kocks - if (xml_get_current_line_number($parser_resource) == 1) { - $errstr = 'XML error at line 1, check URL'; - } else { - $errstr = sprintf('XML error: %s at line %d', - xml_error_string(xml_get_error_code($parser_resource)), - xml_get_current_line_number($parser_resource)); - } - if(defined("DEBUG") && DEBUG) {error_log($errstr);} - $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'], - $XML_RPC_str['invalid_return']); - xml_parser_free($parser_resource); - return $r; - } - - xml_parser_free($parser_resource); - - if ($this->debug) { - print "\n
---PARSED---\n";
-            var_dump($XML_RPC_xh[$parser]['value']);
-            print "---END---
\n"; - } - - if ($XML_RPC_xh[$parser]['isf'] > 1) { - $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'], - $XML_RPC_str['invalid_return'].' '.$XML_RPC_xh[$parser]['isf_reason']); - } elseif (!is_object($XML_RPC_xh[$parser]['value'])) { - // then something odd has happened - // and it's time to generate a client side error - // indicating something odd went on - $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'], - $XML_RPC_str['invalid_return']); - } else { - $v = $XML_RPC_xh[$parser]['value']; - $allOK=1; - if ($XML_RPC_xh[$parser]['isf']) { - $f = $v->structmem('faultCode'); - $fs = $v->structmem('faultString'); - $r = new XML_RPC_Response($v, $f->scalarval(), - $fs->scalarval()); - } else { - $r = new XML_RPC_Response($v); - } - } - $r->hdrs = split("\r?\n", $XML_RPC_xh[$parser]['ha'][1]); - return $r; - } -} - -/** - * The methods and properties that represent data in XML RPC format - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Value extends XML_RPC_Base -{ - var $me = array(); - var $mytype = 0; - - /** - * @return void - */ - function XML_RPC_Value($val = -1, $type = '') - { - global $XML_RPC_Types; - $this->me = array(); - $this->mytype = 0; - if ($val != -1 || $type != '') { - if ($type == '') { - $type = 'string'; - } - if (!array_key_exists($type, $XML_RPC_Types)) { - // XXX - // need some way to report this error - } elseif ($XML_RPC_Types[$type] == 1) { - $this->addScalar($val, $type); - } elseif ($XML_RPC_Types[$type] == 2) { - $this->addArray($val); - } elseif ($XML_RPC_Types[$type] == 3) { - $this->addStruct($val); - } - } - } - - /** - * @return int returns 1 if successful or 0 if there are problems - */ - function addScalar($val, $type = 'string') - { - global $XML_RPC_Types, $XML_RPC_Boolean; - - if ($this->mytype == 1) { - $this->raiseError('Scalar can have only one value', - XML_RPC_ERROR_INVALID_TYPE); - return 0; - } - $typeof = $XML_RPC_Types[$type]; - if ($typeof != 1) { - $this->raiseError("Not a scalar type (${typeof})", - XML_RPC_ERROR_INVALID_TYPE); - return 0; - } - - if ($type == $XML_RPC_Boolean) { - if (strcasecmp($val, 'true') == 0 - || $val == 1 - || ($val == true && strcasecmp($val, 'false'))) - { - $val = 1; - } else { - $val = 0; - } - } - - if ($this->mytype == 2) { - // we're adding to an array here - $ar = $this->me['array']; - $ar[] = new XML_RPC_Value($val, $type); - $this->me['array'] = $ar; - } else { - // a scalar, so set the value and remember we're scalar - $this->me[$type] = $val; - $this->mytype = $typeof; - } - return 1; - } - - /** - * @return int returns 1 if successful or 0 if there are problems - */ - function addArray($vals) - { - global $XML_RPC_Types; - if ($this->mytype != 0) { - $this->raiseError( - 'Already initialized as a [' . $this->kindOf() . ']', - XML_RPC_ERROR_ALREADY_INITIALIZED); - return 0; - } - $this->mytype = $XML_RPC_Types['array']; - $this->me['array'] = $vals; - return 1; - } - - /** - * @return int returns 1 if successful or 0 if there are problems - */ - function addStruct($vals) - { - global $XML_RPC_Types; - if ($this->mytype != 0) { - $this->raiseError( - 'Already initialized as a [' . $this->kindOf() . ']', - XML_RPC_ERROR_ALREADY_INITIALIZED); - return 0; - } - $this->mytype = $XML_RPC_Types['struct']; - $this->me['struct'] = $vals; - return 1; - } - - /** - * @return void - */ - function dump($ar) - { - reset($ar); - foreach ($ar as $key => $val) { - echo "$key => $val
"; - if ($key == 'array') { - foreach ($val as $key2 => $val2) { - echo "-- $key2 => $val2
"; - } - } - } - } - - /** - * @return string the data type of the current value - */ - function kindOf() - { - switch ($this->mytype) { - case 3: - return 'struct'; - - case 2: - return 'array'; - - case 1: - return 'scalar'; - - default: - return 'undef'; - } - } - - /** - * @return string the data in XML format - */ - function serializedata($typ, $val) - { - $rs = ''; - global $XML_RPC_Types, $XML_RPC_Base64, $XML_RPC_String, $XML_RPC_Boolean; - if (!array_key_exists($typ, $XML_RPC_Types)) { - // XXX - // need some way to report this error - return; - } - switch ($XML_RPC_Types[$typ]) { - case 3: - // struct - $rs .= "\n"; - reset($val); - foreach ($val as $key2 => $val2) { - $rs .= "${key2}\n"; - $rs .= $this->serializeval($val2); - $rs .= "\n"; - } - $rs .= ''; - break; - - case 2: - // array - $rs .= "\n\n"; - for ($i = 0; $i < sizeof($val); $i++) { - $rs .= $this->serializeval($val[$i]); - } - $rs .= "\n"; - break; - - case 1: - switch ($typ) { - case $XML_RPC_Base64: - $rs .= "<${typ}>" . base64_encode($val) . ""; - break; - case $XML_RPC_Boolean: - $rs .= "<${typ}>" . ($val ? '1' : '0') . ""; - break; - case $XML_RPC_String: - $rs .= "<${typ}>" . htmlspecialchars($val). ""; - break; - default: - $rs .= "<${typ}>${val}"; - } - } - return $rs; - } - - /** - * @return string the data in XML format - */ - function serialize() - { - return $this->serializeval($this); - } - - /** - * @return string the data in XML format - */ - function serializeval($o) - { - if (!is_object($o) || empty($o->me) || !is_array($o->me)) { - return ''; - } - $ar = $o->me; - reset($ar); - list($typ, $val) = each($ar); - return '' . $this->serializedata($typ, $val) . "\n"; - } - - /** - * @return mixed the contents of the element requested - */ - function structmem($m) - { - return $this->me['struct'][$m]; - } - - /** - * @return void - */ - function structreset() - { - reset($this->me['struct']); - } - - /** - * @return the key/value pair of the struct's current element - */ - function structeach() - { - return each($this->me['struct']); - } - - /** - * @return mixed the current value - */ - function getval() - { - // UNSTABLE - global $XML_RPC_BOOLEAN, $XML_RPC_Base64; - - reset($this->me); - $b = current($this->me); - - // contributed by I Sofer, 2001-03-24 - // add support for nested arrays to scalarval - // i've created a new method here, so as to - // preserve back compatibility - - if (is_array($b)) { - foreach ($b as $id => $cont) { - $b[$id] = $cont->scalarval(); - } - } - - // add support for structures directly encoding php objects - if (is_object($b)) { - $t = get_object_vars($b); - foreach ($t as $id => $cont) { - $t[$id] = $cont->scalarval(); - } - foreach ($t as $id => $cont) { - $b->$id = $cont; - } - } - - // end contrib - return $b; - } - - /** - * @return mixed - */ - function scalarval() - { - global $XML_RPC_Boolean, $XML_RPC_Base64; - reset($this->me); - return current($this->me); - } - - /** - * @return string - */ - function scalartyp() - { - global $XML_RPC_I4, $XML_RPC_Int; - reset($this->me); - $a = key($this->me); - if ($a == $XML_RPC_I4) { - $a = $XML_RPC_Int; - } - return $a; - } - - /** - * @return mixed the struct's current element - */ - function arraymem($m) - { - return $this->me['array'][$m]; - } - - /** - * @return int the number of elements in the array - */ - function arraysize() - { - reset($this->me); - list($a, $b) = each($this->me); - return sizeof($b); - } - - /** - * Determines if the item submitted is an XML_RPC_Value object - * - * @param mixed $val the variable to be evaluated - * - * @return bool TRUE if the item is an XML_RPC_Value object - * - * @static - * @since Method available since Release 1.3.0 - */ - function isValue($val) - { - return (strtolower(get_class($val)) == 'xml_rpc_value'); - } -} - -/** - * Return an ISO8601 encoded string - * - * While timezones ought to be supported, the XML-RPC spec says: - * - * "Don't assume a timezone. It should be specified by the server in its - * documentation what assumptions it makes about timezones." - * - * This routine always assumes localtime unless $utc is set to 1, in which - * case UTC is assumed and an adjustment for locale is made when encoding. - * - * @return string the formatted date - */ -function XML_RPC_iso8601_encode($timet, $utc = 0) -{ - if (!$utc) { - $t = strftime('%Y%m%dT%H:%M:%S', $timet); - } else { - if (function_exists('gmstrftime')) { - // gmstrftime doesn't exist in some versions - // of PHP - $t = gmstrftime('%Y%m%dT%H:%M:%S', $timet); - } else { - $t = strftime('%Y%m%dT%H:%M:%S', $timet - date('Z')); - } - } - return $t; -} - -/** - * Convert a datetime string into a Unix timestamp - * - * While timezones ought to be supported, the XML-RPC spec says: - * - * "Don't assume a timezone. It should be specified by the server in its - * documentation what assumptions it makes about timezones." - * - * This routine always assumes localtime unless $utc is set to 1, in which - * case UTC is assumed and an adjustment for locale is made when encoding. - * - * @return int the unix timestamp of the date submitted - */ -function XML_RPC_iso8601_decode($idate, $utc = 0) -{ - $t = 0; - if (ereg('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})', $idate, $regs)) { - if ($utc) { - $t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); - } else { - $t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); - } - } - return $t; -} - -/** - * Converts an XML_RPC_Value object into native PHP types - * - * @param object $XML_RPC_val the XML_RPC_Value object to decode - * - * @return mixed the PHP values - */ -function XML_RPC_decode($XML_RPC_val) -{ - $kind = $XML_RPC_val->kindOf(); - - if ($kind == 'scalar') { - return $XML_RPC_val->scalarval(); - - } elseif ($kind == 'array') { - $size = $XML_RPC_val->arraysize(); - $arr = array(); - for ($i = 0; $i < $size; $i++) { - $arr[] = XML_RPC_decode($XML_RPC_val->arraymem($i)); - } - return $arr; - - } elseif ($kind == 'struct') { - $XML_RPC_val->structreset(); - $arr = array(); - while (list($key, $value) = $XML_RPC_val->structeach()) { - $arr[$key] = XML_RPC_decode($value); - } - return $arr; - } -} - -/** - * Converts native PHP types into an XML_RPC_Value object - * - * @param mixed $php_val the PHP value or variable you want encoded - * - * @return object the XML_RPC_Value object - */ -function XML_RPC_encode($php_val) -{ - global $XML_RPC_Boolean, $XML_RPC_Int, $XML_RPC_Double, $XML_RPC_String, - $XML_RPC_Array, $XML_RPC_Struct; - - $type = gettype($php_val); - $XML_RPC_val = new XML_RPC_Value; - - switch ($type) { - case 'array': - if (empty($php_val)) { - $XML_RPC_val->addArray($php_val); - break; - } - $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1)); - if (empty($tmp)) { - $arr = array(); - foreach ($php_val as $k => $v) { - $arr[$k] = XML_RPC_encode($v); - } - $XML_RPC_val->addArray($arr); - break; - } - // fall though if it's not an enumerated array - - case 'object': - $arr = array(); - foreach ($php_val as $k => $v) { - $arr[$k] = XML_RPC_encode($v); - } - $XML_RPC_val->addStruct($arr); - break; - - case 'integer': - $XML_RPC_val->addScalar($php_val, $XML_RPC_Int); - break; - - case 'double': - $XML_RPC_val->addScalar($php_val, $XML_RPC_Double); - break; - - case 'string': - case 'NULL': - $XML_RPC_val->addScalar($php_val, $XML_RPC_String); - break; - - case 'boolean': - // Add support for encoding/decoding of booleans, since they - // are supported in PHP - // by - $XML_RPC_val->addScalar($php_val, $XML_RPC_Boolean); - break; - - case 'unknown type': - default: - $XML_RPC_val = false; - } - return $XML_RPC_val; -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ - -?> diff --git a/3rdparty/XML/RPC/Server.php b/3rdparty/XML/RPC/Server.php deleted file mode 100644 index 5c5c04b1f7..0000000000 --- a/3rdparty/XML/RPC/Server.php +++ /dev/null @@ -1,624 +0,0 @@ - - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version CVS: $Id: Server.php,v 1.29 2005/08/14 20:25:35 danielc Exp $ - * @link http://pear.php.net/package/XML_RPC - */ - - -/** - * Pull in the XML_RPC class - */ -require_once 'XML/RPC.php'; - - -/** - * signature for system.listMethods: return = array, - * parameters = a string or nothing - * @global array $GLOBALS['XML_RPC_Server_listMethods_sig'] - */ -$GLOBALS['XML_RPC_Server_listMethods_sig'] = array( - array($GLOBALS['XML_RPC_Array'], - $GLOBALS['XML_RPC_String'] - ), - array($GLOBALS['XML_RPC_Array']) -); - -/** - * docstring for system.listMethods - * @global string $GLOBALS['XML_RPC_Server_listMethods_doc'] - */ -$GLOBALS['XML_RPC_Server_listMethods_doc'] = 'This method lists all the' - . ' methods that the XML-RPC server knows how to dispatch'; - -/** - * signature for system.methodSignature: return = array, - * parameters = string - * @global array $GLOBALS['XML_RPC_Server_methodSignature_sig'] - */ -$GLOBALS['XML_RPC_Server_methodSignature_sig'] = array( - array($GLOBALS['XML_RPC_Array'], - $GLOBALS['XML_RPC_String'] - ) -); - -/** - * docstring for system.methodSignature - * @global string $GLOBALS['XML_RPC_Server_methodSignature_doc'] - */ -$GLOBALS['XML_RPC_Server_methodSignature_doc'] = 'Returns an array of known' - . ' signatures (an array of arrays) for the method name passed. If' - . ' no signatures are known, returns a none-array (test for type !=' - . ' array to detect missing signature)'; - -/** - * signature for system.methodHelp: return = string, - * parameters = string - * @global array $GLOBALS['XML_RPC_Server_methodHelp_sig'] - */ -$GLOBALS['XML_RPC_Server_methodHelp_sig'] = array( - array($GLOBALS['XML_RPC_String'], - $GLOBALS['XML_RPC_String'] - ) -); - -/** - * docstring for methodHelp - * @global string $GLOBALS['XML_RPC_Server_methodHelp_doc'] - */ -$GLOBALS['XML_RPC_Server_methodHelp_doc'] = 'Returns help text if defined' - . ' for the method passed, otherwise returns an empty string'; - -/** - * dispatch map for the automatically declared XML-RPC methods. - * @global array $GLOBALS['XML_RPC_Server_dmap'] - */ -$GLOBALS['XML_RPC_Server_dmap'] = array( - 'system.listMethods' => array( - 'function' => 'XML_RPC_Server_listMethods', - 'signature' => $GLOBALS['XML_RPC_Server_listMethods_sig'], - 'docstring' => $GLOBALS['XML_RPC_Server_listMethods_doc'] - ), - 'system.methodHelp' => array( - 'function' => 'XML_RPC_Server_methodHelp', - 'signature' => $GLOBALS['XML_RPC_Server_methodHelp_sig'], - 'docstring' => $GLOBALS['XML_RPC_Server_methodHelp_doc'] - ), - 'system.methodSignature' => array( - 'function' => 'XML_RPC_Server_methodSignature', - 'signature' => $GLOBALS['XML_RPC_Server_methodSignature_sig'], - 'docstring' => $GLOBALS['XML_RPC_Server_methodSignature_doc'] - ) -); - -/** - * @global string $GLOBALS['XML_RPC_Server_debuginfo'] - */ -$GLOBALS['XML_RPC_Server_debuginfo'] = ''; - - -/** - * Lists all the methods that the XML-RPC server knows how to dispatch - * - * @return object a new XML_RPC_Response object - */ -function XML_RPC_Server_listMethods($server, $m) -{ - global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap; - - $v = new XML_RPC_Value(); - $outAr = array(); - foreach ($server->dmap as $key => $val) { - $outAr[] = new XML_RPC_Value($key, 'string'); - } - foreach ($XML_RPC_Server_dmap as $key => $val) { - $outAr[] = new XML_RPC_Value($key, 'string'); - } - $v->addArray($outAr); - return new XML_RPC_Response($v); -} - -/** - * Returns an array of known signatures (an array of arrays) - * for the given method - * - * If no signatures are known, returns a none-array - * (test for type != array to detect missing signature) - * - * @return object a new XML_RPC_Response object - */ -function XML_RPC_Server_methodSignature($server, $m) -{ - global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap; - - $methName = $m->getParam(0); - $methName = $methName->scalarval(); - if (strpos($methName, 'system.') === 0) { - $dmap = $XML_RPC_Server_dmap; - $sysCall = 1; - } else { - $dmap = $server->dmap; - $sysCall = 0; - } - // print "\n"; - if (isset($dmap[$methName])) { - if ($dmap[$methName]['signature']) { - $sigs = array(); - $thesigs = $dmap[$methName]['signature']; - for ($i = 0; $i < sizeof($thesigs); $i++) { - $cursig = array(); - $inSig = $thesigs[$i]; - for ($j = 0; $j < sizeof($inSig); $j++) { - $cursig[] = new XML_RPC_Value($inSig[$j], 'string'); - } - $sigs[] = new XML_RPC_Value($cursig, 'array'); - } - $r = new XML_RPC_Response(new XML_RPC_Value($sigs, 'array')); - } else { - $r = new XML_RPC_Response(new XML_RPC_Value('undef', 'string')); - } - } else { - $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'], - $XML_RPC_str['introspect_unknown']); - } - return $r; -} - -/** - * Returns help text if defined for the method passed, otherwise returns - * an empty string - * - * @return object a new XML_RPC_Response object - */ -function XML_RPC_Server_methodHelp($server, $m) -{ - global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap; - - $methName = $m->getParam(0); - $methName = $methName->scalarval(); - if (strpos($methName, 'system.') === 0) { - $dmap = $XML_RPC_Server_dmap; - $sysCall = 1; - } else { - $dmap = $server->dmap; - $sysCall = 0; - } - - if (isset($dmap[$methName])) { - if ($dmap[$methName]['docstring']) { - $r = new XML_RPC_Response(new XML_RPC_Value($dmap[$methName]['docstring']), - 'string'); - } else { - $r = new XML_RPC_Response(new XML_RPC_Value('', 'string')); - } - } else { - $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'], - $XML_RPC_str['introspect_unknown']); - } - return $r; -} - -/** - * @return void - */ -function XML_RPC_Server_debugmsg($m) -{ - global $XML_RPC_Server_debuginfo; - $XML_RPC_Server_debuginfo = $XML_RPC_Server_debuginfo . $m . "\n"; -} - - -/** - * A server for receiving and replying to XML RPC requests - * - * - * $server = new XML_RPC_Server( - * array( - * 'isan8' => - * array( - * 'function' => 'is_8', - * 'signature' => - * array( - * array('boolean', 'int'), - * array('boolean', 'int', 'boolean'), - * array('boolean', 'string'), - * array('boolean', 'string', 'boolean'), - * ), - * 'docstring' => 'Is the value an 8?' - * ), - * ), - * 1, - * 0 - * ); - * - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill - * @author Stig Bakken - * @author Martin Jansen - * @author Daniel Convissor - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Server -{ - /** - * The dispatch map, listing the methods this server provides. - * @var array - */ - var $dmap = array(); - - /** - * The present response's encoding - * @var string - * @see XML_RPC_Message::getEncoding() - */ - var $encoding = ''; - - /** - * Debug mode (0 = off, 1 = on) - * @var integer - */ - var $debug = 0; - - /** - * The response's HTTP headers - * @var string - */ - var $server_headers = ''; - - /** - * The response's XML payload - * @var string - */ - var $server_payload = ''; - - - /** - * Constructor for the XML_RPC_Server class - * - * @param array $dispMap the dispatch map. An associative array - * explaining each function. The keys of the main - * array are the procedure names used by the - * clients. The value is another associative array - * that contains up to three elements: - * + The 'function' element's value is the name - * of the function or method that gets called. - * To define a class' method: 'class::method'. - * + The 'signature' element (optional) is an - * array describing the return values and - * parameters - * + The 'docstring' element (optional) is a - * string describing what the method does - * @param int $serviceNow should the HTTP response be sent now? - * (1 = yes, 0 = no) - * @param int $debug should debug output be displayed? - * (1 = yes, 0 = no) - * - * @return void - */ - function XML_RPC_Server($dispMap, $serviceNow = 1, $debug = 0) - { - global $HTTP_RAW_POST_DATA; - - if ($debug) { - $this->debug = 1; - } else { - $this->debug = 0; - } - - $this->dmap = $dispMap; - - if ($serviceNow) { - $this->service(); - } else { - $this->createServerPayload(); - $this->createServerHeaders(); - } - } - - /** - * @return string the debug information if debug debug mode is on - */ - function serializeDebug() - { - global $XML_RPC_Server_debuginfo, $HTTP_RAW_POST_DATA; - - if ($this->debug) { - XML_RPC_Server_debugmsg('vvv POST DATA RECEIVED BY SERVER vvv' . "\n" - . $HTTP_RAW_POST_DATA - . "\n" . '^^^ END POST DATA ^^^'); - } - - if ($XML_RPC_Server_debuginfo != '') { - return "\n"; - } else { - return ''; - } - } - - /** - * Sends the response - * - * The encoding and content-type are determined by - * XML_RPC_Message::getEncoding() - * - * @return void - * - * @uses XML_RPC_Server::createServerPayload(), - * XML_RPC_Server::createServerHeaders() - */ - function service() - { - if (!$this->server_payload) { - $this->createServerPayload(); - } - if (!$this->server_headers) { - $this->createServerHeaders(); - } - header($this->server_headers); - print $this->server_payload; - } - - /** - * Generates the payload and puts it in the $server_payload property - * - * @return void - * - * @uses XML_RPC_Server::parseRequest(), XML_RPC_Server::$encoding, - * XML_RPC_Response::serialize(), XML_RPC_Server::serializeDebug() - */ - function createServerPayload() - { - $r = $this->parseRequest(); - $this->server_payload = 'encoding . '"?>' . "\n" - . $this->serializeDebug() - . $r->serialize(); - } - - /** - * Determines the HTTP headers and puts them in the $server_headers - * property - * - * @return boolean TRUE if okay, FALSE if $server_payload isn't set. - * - * @uses XML_RPC_Server::createServerPayload(), - * XML_RPC_Server::$server_headers - */ - function createServerHeaders() - { - if (!$this->server_payload) { - return false; - } - $this->server_headers = 'Content-Length: ' - . strlen($this->server_payload) . "\r\n" - . 'Content-Type: text/xml;' - . ' charset=' . $this->encoding; - return true; - } - - /** - * @return array - */ - function verifySignature($in, $sig) - { - for ($i = 0; $i < sizeof($sig); $i++) { - // check each possible signature in turn - $cursig = $sig[$i]; - if (sizeof($cursig) == $in->getNumParams() + 1) { - $itsOK = 1; - for ($n = 0; $n < $in->getNumParams(); $n++) { - $p = $in->getParam($n); - // print "\n"; - if ($p->kindOf() == 'scalar') { - $pt = $p->scalartyp(); - } else { - $pt = $p->kindOf(); - } - // $n+1 as first type of sig is return type - if ($pt != $cursig[$n+1]) { - $itsOK = 0; - $pno = $n+1; - $wanted = $cursig[$n+1]; - $got = $pt; - break; - } - } - if ($itsOK) { - return array(1); - } - } - } - if (isset($wanted)) { - return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); - } else { - $allowed = array(); - foreach ($sig as $val) { - end($val); - $allowed[] = key($val); - } - $allowed = array_unique($allowed); - $last = count($allowed) - 1; - if ($last > 0) { - $allowed[$last] = 'or ' . $allowed[$last]; - } - return array(0, - 'Signature permits ' . implode(', ', $allowed) - . ' parameters but the request had ' - . $in->getNumParams()); - } - } - - /** - * @return object a new XML_RPC_Response object - * - * @uses XML_RPC_Message::getEncoding(), XML_RPC_Server::$encoding - */ - function parseRequest($data = '') - { - global $XML_RPC_xh, $HTTP_RAW_POST_DATA, - $XML_RPC_err, $XML_RPC_str, $XML_RPC_errxml, - $XML_RPC_defencoding, $XML_RPC_Server_dmap; - - if ($data == '') { - $data = $HTTP_RAW_POST_DATA; - } - - $this->encoding = XML_RPC_Message::getEncoding($data); - $parser_resource = xml_parser_create($this->encoding); - $parser = (int) $parser_resource; - - $XML_RPC_xh[$parser] = array(); - $XML_RPC_xh[$parser]['cm'] = 0; - $XML_RPC_xh[$parser]['isf'] = 0; - $XML_RPC_xh[$parser]['params'] = array(); - $XML_RPC_xh[$parser]['method'] = ''; - $XML_RPC_xh[$parser]['stack'] = array(); - $XML_RPC_xh[$parser]['valuestack'] = array(); - - $plist = ''; - - // decompose incoming XML into request structure - - xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true); - xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee'); - xml_set_character_data_handler($parser_resource, 'XML_RPC_cd'); - if (!xml_parse($parser_resource, $data, 1)) { - // return XML error as a faultCode - $r = new XML_RPC_Response(0, - $XML_RPC_errxml+xml_get_error_code($parser_resource), - sprintf('XML error: %s at line %d', - xml_error_string(xml_get_error_code($parser_resource)), - xml_get_current_line_number($parser_resource))); - xml_parser_free($parser_resource); - } elseif ($XML_RPC_xh[$parser]['isf']>1) { - $r = new XML_RPC_Response(0, - $XML_RPC_err['invalid_request'], - $XML_RPC_str['invalid_request'] - . ': ' - . $XML_RPC_xh[$parser]['isf_reason']); - xml_parser_free($parser_resource); - } else { - xml_parser_free($parser_resource); - $m = new XML_RPC_Message($XML_RPC_xh[$parser]['method']); - // now add parameters in - for ($i = 0; $i < sizeof($XML_RPC_xh[$parser]['params']); $i++) { - // print '\n"; - $plist .= "$i - " . var_export($XML_RPC_xh[$parser]['params'][$i], true) . " \n"; - $m->addParam($XML_RPC_xh[$parser]['params'][$i]); - } - XML_RPC_Server_debugmsg($plist); - - // now to deal with the method - $methName = $XML_RPC_xh[$parser]['method']; - if (strpos($methName, 'system.') === 0) { - $dmap = $XML_RPC_Server_dmap; - $sysCall = 1; - } else { - $dmap = $this->dmap; - $sysCall = 0; - } - - if (isset($dmap[$methName]['function']) - && is_string($dmap[$methName]['function']) - && strpos($dmap[$methName]['function'], '::') !== false) - { - $dmap[$methName]['function'] = - explode('::', $dmap[$methName]['function']); - } - - if (isset($dmap[$methName]['function']) - && is_callable($dmap[$methName]['function'])) - { - // dispatch if exists - if (isset($dmap[$methName]['signature'])) { - $sr = $this->verifySignature($m, - $dmap[$methName]['signature'] ); - } - if (!isset($dmap[$methName]['signature']) || $sr[0]) { - // if no signature or correct signature - if ($sysCall) { - $r = call_user_func($dmap[$methName]['function'], $this, $m); - } else { - $r = call_user_func($dmap[$methName]['function'], $m); - } - if (!is_a($r, 'XML_RPC_Response')) { - $r = new XML_RPC_Response(0, $XML_RPC_err['not_response_object'], - $XML_RPC_str['not_response_object']); - } - } else { - $r = new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'], - $XML_RPC_str['incorrect_params'] - . ': ' . $sr[1]); - } - } else { - // else prepare error response - $r = new XML_RPC_Response(0, $XML_RPC_err['unknown_method'], - $XML_RPC_str['unknown_method']); - } - } - return $r; - } - - /** - * Echos back the input packet as a string value - * - * @return void - * - * Useful for debugging. - */ - function echoInput() - { - global $HTTP_RAW_POST_DATA; - - $r = new XML_RPC_Response(0); - $r->xv = new XML_RPC_Value("'Aha said I: '" . $HTTP_RAW_POST_DATA, 'string'); - print $r->serialize(); - } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ - -?> diff --git a/3rdparty/css/chosen-sprite.png b/3rdparty/css/chosen-sprite.png deleted file mode 100644 index f20db4439ea5c1038126bf326c8fd048b03a8226..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 742 zcmeAS@N?(olHy`uVBq!ia0vp^HbAV#!3-qV=X2}@QlA5SLR>pKI{yFvKXc~Hw6wJT z{{AOVo_zoQeZqtZ&!0cvw{PF?-@ki%d;k6WS6EoMdiClhOP1WeeS7cTz4PYH`}FD4 zt5>h?-n~0()~rX59=&++V%xTD`T6-@zI<7}eEIzO^LOst`S@T)vFse zZ0PFhnmc#y*RNl9?AVc)msea|{PX9}Ns}gR+O%o+?%jtD9eVii;l+y=r%jvo;K760 zvu76+6kNZ4ed^SyPoF-WIC0|Z*ROy4_>r5N`~Lm=&!0c{_4O@WxbWAnUpYBBmoHy_ z_Uzfgg9n!`T{?O4j}$9Asc%4D@ty45_&F_R{g9Lk0qD52mW_e8hCD#Hn3?L-tbj`>OxT zJ7v;md~}?7W?s>W`VVqX@=db;D+pYCKd;4N)z`osoP6iyoB9teW8`B#?2;Ii#BfGM zL+6u_bqvF)z6Qwy7F^e#>{}{m61e02bdHnN$L$~3eq~pF@_OO1hcV%@q4${;^UfV+ znXY)w;%ghbu4vj9l}FCEd^hZyc+KPP6}AS4MsdBpQGw+X69gF?tV83O8O(MiJx^-A zboXW1bFqq*pAC;_YOi~??#RV$D!*(*_VfK;FjaJ|%YuJ~uPm<26>Fce&`YSSyXC`g zaTdR+Ec5IClowvmjG1!3;Krqz>yXh1n|0hl70CPiOba zI=4&!39B1KMO0(W{Q8mw4?6Xika+f}m9PcE^BN~5f?74wTX`RZT~qGJrJCTOg7I2C z3rkUs#R|t@D9pHaz7t$Ovb0>g+88czlYyWWPyf*? zPM(_kC~*Rm^Ht8{{hM~LNVDGHqHL=vWon_U?K%A;xBszG$o^PAJG-&IKBL+xXKc~0 z?{|f0H*3|ubo%Enae+Je(Xz@Kz;7C$bo2B_`{1#9-h<&!#KD#eo3Tn4b)?r9jN^|w zRV?cbIB3?isoi7b)1r^~^BzUWeR|sUcAWC>oJ6~Rr%x&L9gUlx#9ga(mg~FB%c+)Q7OxC z+;*3C+t`}|h;PdF65X+2o(spbj5J`0A)-$WIc08BzDXU$%G4K5qy0!N zPDq(gClb!2r_6XL>2X6e%tWyvPP`Z554;F%QsPSpsMeO8AghJd7mC~uR?HzCvG(Lk zi>1p-AMyBlUou)aduyb`j&d$m3f9Bh`tvTKK&KNgcXx+e)pJhbc&mY`N2O#X-S;bB zmf|-?oLCK4A#YL#D6|p_-$cqWSv-_gHc&UvoKY@hdcZ1pdyZIy7(ZCM{mG;FLbb1K z4Y&Vw-nHcC3o}sWWSOFly~9K08xHFfVWp0M@jt2mctfS?3w(@vOmWObhh>|yC|ywb zK1+PxoV8;$p=bgp)3e@?b@Y12y1+WaI`g413EEP|{mZHDD!WdaenbqF{$2>-T*wd=#{QtxuTwc?phJ?L{f=fG5W=> zE`u(jNW3tt7*Xg7m;T~!co{)p*rDE`1^c3%Rb{r;)XhX{b+5*Yli88HB=k*yP$yf} z(CoXn9E~ZLjEzx}#YNeoFacEo{TiL41Y2pswG{W$3{OqsE%t)sBmc-HnuDjSPZ{zB z)$93eOdN}ol9LQdluNWrly;ki%l8V<`OONAhUWnkvOTI#Or9tqVzIZ-Te`Eliv=VF zbQ+RkC*|D5j(H5(jq=FvE(QB3nJuqSnd+_uOWw^}XAk^%F5#EXX9XupWCjE^WUK`9 zWZ1hBT|(}z5{x`O^MABqrX4b{Jc~q&qhy8`Q;3erKbSsDQQf`DjTwUZ za*Q*^&jMjdkErV^@7RxTj`wTu`*0~qNFFvzQNn1%=>Phw2aVWEv86O@#=f*)*KyJ| z55i!WYIsIq4RdGUX{S9}H+@_QL64|^9dr~P6`>Y5z@03`ozBp`*xS6W>UrXBy5ci- zf=;hVZ{I7Nuhq)H9HiSIXn_n$((v$P)jOq1m8FYh7>MfL4cVrdh}`>^;l1^|jCS zC{%!YjEBIF2#^ghzHxr)^N#s@jI`Li&EM+TJ=y52dRbc8*ub*DjkYpoyWU?P%b0On zDcCryJw?b1|DRJMgch3?Q62tdPeQ^%^h2d%+`#cb7=T{`W4qCZ>l7s5+j9iG+QQH6KfF8FG zN;01f?G4uS&wmujIQV?MN8L`n@(Gg{s;1AyXt3E_>L6Mz;qE<8vPOIBS?EiGQi*So z7!K!2t&%{wTj@fQ+E^%cVQzR89ZzfZ?kk8J2C0~B| zb?@Y_!aPs%5c_;%5C&GC`(5H&lTAS%c1T@Acr1;a?K6P++F(Cng!k zB;h)-Q_pslD0=>Dxk4WxxyXgd^*&^Dud=wwd#`Wfh?j8>$;Ia0M*Eho5RU)%mJz|o z;~E!M-b~I%)JNYm<{=4(Lyvv=| z-Fp@D-R<2ETl%~N_+A~qJl|_WE+82Xa+fK!*55I`XTP@lS9PL0Qg9xBFFyYICVtA% zg_Qu;Jow*avQpO3fFPg85QGYXpnun3--e(!yb!cw4nblm5Jd0#$*fBeg7Bdi>Tred z@bK&F>(ta#TU*=M*x2>;bsP@&@#Dv>t*w@pmhprGLM=g;-^^_Q2Ig@uJxRaKLd zla-Z~k&%&TH2UP^Zc zp6=%6Ha$I^n3%Y+u@M&+x4XN0dV1>Y?0j%=aCCGO6BCo2oqcw8=H%owK0dy=x!Km% zmY0_oA0J;-R5Uj?x3;#{*Vp&=@85-mg}uGK=;&w<4-YV`wzjs8j*hObE*uWm)6;wT z@}<7MzJY;(p`oFXk&&^nv5AR^sj2C!SFg;>%*@TrEi5c7EiJ9AtgNlAZES1+CFeoS}I5;>YBqTI6G%PF(c!`LJ0K}rAqQJ?41u!oV z1k?Z&02&xGAt3?40l1QrlT%VsfJEQ|aLdTZ0Gxp%U?D3j3sB0*$;r*l1^NJ={QP_% z2zUXMii?YZ*3#0_va+)B^74v`3ZM!20!C_TYQBE`T3cHSwAR(t0cAjFLqh{F)zs7k z8UT5G|NgzTwH06o?m9X;Iy*bNy1Kf%yL)iSy9yArl)&L9wgI;jjyqzDv8-a6|DdEb4ucxO}_gKbxMo`wwPB~2%IKpWcEuBvkj zuDfz;vj~;@=f;uP3-ZFbmkUdkpF=Fz#Mxas_La@9vmR=4MAD00wLgVqkQ-7vh~pmLQ0;6EC?TrrH?mB^G&+t$mRxrTy|;osEc! zTI&;~xjpoj1Vw*I5m}7)iTam3CyJDli9j7;zgLpAl&P8hUx(Xc$SA0}imEG(HP|EH zUbmC}(wD@oAJo5pt`lMQWyx!X+M?ukdXvZR+)AgMLD+tD0L&siyq9K}>_HtJ&LA@& zxi@ox-!1p8s=OzcEtyky4WTuqW0e}V@FIgsZe6~m^{I-j-3j6?{FvmI4?#{2y*W~x kidOrojp+E9y!>Z;D448bs%_%b1&D-H6g1__<;(;B4?`9=;Q#;t diff --git a/3rdparty/css/chosen/chosen.css b/3rdparty/css/chosen/chosen.css deleted file mode 100644 index b9c6d88028..0000000000 --- a/3rdparty/css/chosen/chosen.css +++ /dev/null @@ -1,368 +0,0 @@ -/* @group Base */ -.chzn-container { - font-size: 13px; - position: relative; - display: inline-block; - zoom: 1; - *display: inline; -} -.chzn-container .chzn-drop { - background: #fff; - border: 1px solid #aaa; - border-top: 0; - position: absolute; - top: 29px; - left: 0; - -webkit-box-shadow: 0 4px 5px rgba(0,0,0,.15); - -moz-box-shadow : 0 4px 5px rgba(0,0,0,.15); - -o-box-shadow : 0 4px 5px rgba(0,0,0,.15); - box-shadow : 0 4px 5px rgba(0,0,0,.15); - z-index: 999; -} -/* @end */ - -/* @group Single Chosen */ -.chzn-container-single .chzn-single { - background-color: #fff; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.5, white)); - background-image: -webkit-linear-gradient(center bottom, #eeeeee 0%, white 50%); - background-image: -moz-linear-gradient(center bottom, #eeeeee 0%, white 50%); - background-image: -o-linear-gradient(top, #eeeeee 0%,#ffffff 50%); - background-image: -ms-linear-gradient(top, #eeeeee 0%,#ffffff 50%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#ffffff',GradientType=0 ); - background-image: linear-gradient(top, #eeeeee 0%,#ffffff 50%); - -webkit-border-radius: 4px; - -moz-border-radius : 4px; - border-radius : 4px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - border: 1px solid #aaa; - display: block; - overflow: hidden; - white-space: nowrap; - position: relative; - height: 26px; - line-height: 26px; - padding: 0 0 0 8px; - color: #444; - text-decoration: none; -} -.chzn-container-single .chzn-single span { - margin-right: 26px; - display: block; - overflow: hidden; - white-space: nowrap; - -o-text-overflow: ellipsis; - -ms-text-overflow: ellipsis; - text-overflow: ellipsis; -} -.chzn-container-single .chzn-single abbr { - display: block; - position: absolute; - right: 26px; - top: 8px; - width: 12px; - height: 13px; - font-size: 1px; - background: url(chosen-sprite.png) right top no-repeat; -} -.chzn-container-single .chzn-single abbr:hover { - background-position: right -11px; -} -.chzn-container-single .chzn-single div { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius : 0 4px 4px 0; - border-radius : 0 4px 4px 0; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - background: #ccc; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #ccc), color-stop(0.6, #eee)); - background-image: -webkit-linear-gradient(center bottom, #ccc 0%, #eee 60%); - background-image: -moz-linear-gradient(center bottom, #ccc 0%, #eee 60%); - background-image: -o-linear-gradient(bottom, #ccc 0%, #eee 60%); - background-image: -ms-linear-gradient(top, #cccccc 0%,#eeeeee 60%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cccccc', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #cccccc 0%,#eeeeee 60%); - border-left: 1px solid #aaa; - position: absolute; - right: 0; - top: 0; - display: block; - height: 100%; - width: 18px; -} -.chzn-container-single .chzn-single div b { - background: url('chosen-sprite.png') no-repeat 0 1px; - display: block; - width: 100%; - height: 100%; -} -.chzn-container-single .chzn-search { - padding: 3px 4px; - position: relative; - margin: 0; - white-space: nowrap; -} -.chzn-container-single .chzn-search input { - background: #fff url('chosen-sprite.png') no-repeat 100% -22px; - background: url('chosen-sprite.png') no-repeat 100% -22px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background: url('chosen-sprite.png') no-repeat 100% -22px, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, linear-gradient(top, #ffffff 85%,#eeeeee 99%); - margin: 1px 0; - padding: 4px 20px 4px 5px; - outline: 0; - border: 1px solid #aaa; - font-family: sans-serif; - font-size: 1em; -} -.chzn-container-single .chzn-drop { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius : 0 0 4px 4px; - border-radius : 0 0 4px 4px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; -} -/* @end */ - -.chzn-container-single-nosearch .chzn-search input { - position: absolute; - left: -9000px; -} - -/* @group Multi Chosen */ -.chzn-container-multi .chzn-choices { - background-color: #fff; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background-image: -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background-image: -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background-image: -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #ffffff 85%,#eeeeee 99%); - border: 1px solid #aaa; - margin: 0; - padding: 0; - cursor: text; - overflow: hidden; - height: auto !important; - height: 1%; - position: relative; -} -.chzn-container-multi .chzn-choices li { - float: left; - list-style: none; -} -.chzn-container-multi .chzn-choices .search-field { - white-space: nowrap; - margin: 0; - padding: 0; -} -.chzn-container-multi .chzn-choices .search-field input { - color: #666; - background: transparent !important; - border: 0 !important; - padding: 5px; - margin: 1px 0; - outline: 0; - -webkit-box-shadow: none; - -moz-box-shadow : none; - -o-box-shadow : none; - box-shadow : none; -} -.chzn-container-multi .chzn-choices .search-field .default { - color: #999; -} -.chzn-container-multi .chzn-choices .search-choice { - -webkit-border-radius: 3px; - -moz-border-radius : 3px; - border-radius : 3px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - background-color: #e4e4e4; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #e4e4e4), color-stop(0.7, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -moz-linear-gradient(center bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -o-linear-gradient(bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -ms-linear-gradient(top, #e4e4e4 0%,#eeeeee 70%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e4e4e4', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #e4e4e4 0%,#eeeeee 70%); - color: #333; - border: 1px solid #b4b4b4; - line-height: 13px; - padding: 3px 19px 3px 6px; - margin: 3px 0 3px 5px; - position: relative; -} -.chzn-container-multi .chzn-choices .search-choice span { - cursor: default; -} -.chzn-container-multi .chzn-choices .search-choice-focus { - background: #d4d4d4; -} -.chzn-container-multi .chzn-choices .search-choice .search-choice-close { - display: block; - position: absolute; - right: 3px; - top: 4px; - width: 12px; - height: 13px; - font-size: 1px; - background: url(chosen-sprite.png) right top no-repeat; -} -.chzn-container-multi .chzn-choices .search-choice .search-choice-close:hover { - background-position: right -11px; -} -.chzn-container-multi .chzn-choices .search-choice-focus .search-choice-close { - background-position: right -11px; -} -/* @end */ - -/* @group Results */ -.chzn-container .chzn-results { - margin: 0 4px 4px 0; - max-height: 190px; - padding: 0 0 0 4px; - position: relative; - overflow-x: hidden; - overflow-y: auto; -} -.chzn-container-multi .chzn-results { - margin: -1px 0 0; - padding: 0; -} -.chzn-container .chzn-results li { - display: none; - line-height: 80%; - padding: 7px 7px 8px; - margin: 0; - list-style: none; -} -.chzn-container .chzn-results .active-result { - cursor: pointer; - display: list-item; -} -.chzn-container .chzn-results .highlighted { - background: #3875d7; - color: #fff; -} -.chzn-container .chzn-results li em { - background: #feffde; - font-style: normal; -} -.chzn-container .chzn-results .highlighted em { - background: transparent; -} -.chzn-container .chzn-results .no-results { - background: #f4f4f4; - display: list-item; -} -.chzn-container .chzn-results .group-result { - cursor: default; - color: #999; - font-weight: bold; -} -.chzn-container .chzn-results .group-option { - padding-left: 20px; -} -.chzn-container-multi .chzn-drop .result-selected { - display: none; -} -/* @end */ - -/* @group Active */ -.chzn-container-active .chzn-single { - -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3); - -moz-box-shadow : 0 0 5px rgba(0,0,0,.3); - -o-box-shadow : 0 0 5px rgba(0,0,0,.3); - box-shadow : 0 0 5px rgba(0,0,0,.3); - border: 1px solid #5897fb; -} -.chzn-container-active .chzn-single-with-drop { - border: 1px solid #aaa; - -webkit-box-shadow: 0 1px 0 #fff inset; - -moz-box-shadow : 0 1px 0 #fff inset; - -o-box-shadow : 0 1px 0 #fff inset; - box-shadow : 0 1px 0 #fff inset; - background-color: #eee; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, white), color-stop(0.5, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, white 0%, #eeeeee 50%); - background-image: -moz-linear-gradient(center bottom, white 0%, #eeeeee 50%); - background-image: -o-linear-gradient(bottom, white 0%, #eeeeee 50%); - background-image: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 50%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #ffffff 0%,#eeeeee 50%); - -webkit-border-bottom-left-radius : 0; - -webkit-border-bottom-right-radius: 0; - -moz-border-radius-bottomleft : 0; - -moz-border-radius-bottomright: 0; - border-bottom-left-radius : 0; - border-bottom-right-radius: 0; -} -.chzn-container-active .chzn-single-with-drop div { - background: transparent; - border-left: none; -} -.chzn-container-active .chzn-single-with-drop div b { - background-position: -18px 1px; -} -.chzn-container-active .chzn-choices { - -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3); - -moz-box-shadow : 0 0 5px rgba(0,0,0,.3); - -o-box-shadow : 0 0 5px rgba(0,0,0,.3); - box-shadow : 0 0 5px rgba(0,0,0,.3); - border: 1px solid #5897fb; -} -.chzn-container-active .chzn-choices .search-field input { - color: #111 !important; -} -/* @end */ - -/* @group Disabled Support */ -.chzn-disabled { - cursor: default; - opacity:0.5 !important; -} -.chzn-disabled .chzn-single { - cursor: default; -} -.chzn-disabled .chzn-choices .search-choice .search-choice-close { - cursor: default; -} - -/* @group Right to Left */ -.chzn-rtl { direction:rtl;text-align: right; } -.chzn-rtl .chzn-single { padding-left: 0; padding-right: 8px; } -.chzn-rtl .chzn-single span { margin-left: 26px; margin-right: 0; } -.chzn-rtl .chzn-single div { - left: 0; right: auto; - border-left: none; border-right: 1px solid #aaaaaa; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius : 4px 0 0 4px; - border-radius : 4px 0 0 4px; -} -.chzn-rtl .chzn-choices li { float: right; } -.chzn-rtl .chzn-choices .search-choice { padding: 3px 6px 3px 19px; margin: 3px 5px 3px 0; } -.chzn-rtl .chzn-choices .search-choice .search-choice-close { left: 5px; right: auto; background-position: right top;} -.chzn-rtl.chzn-container-single .chzn-results { margin-left: 4px; margin-right: 0; padding-left: 0; padding-right: 4px; } -.chzn-rtl .chzn-results .group-option { padding-left: 0; padding-right: 20px; } -.chzn-rtl.chzn-container-active .chzn-single-with-drop div { border-right: none; } -.chzn-rtl .chzn-search input { - background: url('chosen-sprite.png') no-repeat -38px -22px, #ffffff; - background: url('chosen-sprite.png') no-repeat -38px -22px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background: url('chosen-sprite.png') no-repeat -38px -22px, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, linear-gradient(top, #ffffff 85%,#eeeeee 99%); - padding: 4px 5px 4px 20px; -} -/* @end */ \ No newline at end of file diff --git a/3rdparty/fullcalendar/GPL-LICENSE.txt b/3rdparty/fullcalendar/GPL-LICENSE.txt deleted file mode 100644 index 11dddd00ef..0000000000 --- a/3rdparty/fullcalendar/GPL-LICENSE.txt +++ /dev/null @@ -1,278 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, 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. - - 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 Lesser 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. diff --git a/3rdparty/fullcalendar/MIT-LICENSE.txt b/3rdparty/fullcalendar/MIT-LICENSE.txt deleted file mode 100644 index 46d4754496..0000000000 --- a/3rdparty/fullcalendar/MIT-LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 Adam Shaw - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/3rdparty/fullcalendar/changelog.txt b/3rdparty/fullcalendar/changelog.txt deleted file mode 100644 index 50d0880fd7..0000000000 --- a/3rdparty/fullcalendar/changelog.txt +++ /dev/null @@ -1,313 +0,0 @@ - -version 1.5.2 (8/21/11) - - correctly process UTC "Z" ISO8601 date strings (issue 750) - -version 1.5.1 (4/9/11) - - more flexible ISO8601 date parsing (issue 814) - - more flexible parsing of UNIX timestamps (issue 826) - - FullCalendar now buildable from source on a Mac (issue 795) - - FullCalendar QA'd in FF4 (issue 883) - - upgraded to jQuery 1.5.2 (which supports IE9) and jQuery UI 1.8.11 - -version 1.5 (3/19/11) - - slicker default styling for buttons - - reworked a lot of the calendar's HTML and accompanying CSS - (solves issues 327 and 395) - - more printer-friendly (fullcalendar-print.css) - - fullcalendar now inherits styles from jquery-ui themes differently. - styles for buttons are distinct from styles for calendar cells. - (solves issue 299) - - can now color events through FullCalendar options and Event-Object properties (issue 117) - THIS IS NOW THE PREFERRED METHOD OF COLORING EVENTS (as opposed to using className and CSS) - - FullCalendar options: - - eventColor (changes both background and border) - - eventBackgroundColor - - eventBorderColor - - eventTextColor - - Event-Object options: - - color (changes both background and border) - - backgroundColor - - borderColor - - textColor - - can now specify an event source as an *object* with a `url` property (json feed) or - an `events` property (function or array) with additional properties that will - be applied to the entire event source: - - color (changes both background and border) - - backgroudColor - - borderColor - - textColor - - className - - editable - - allDayDefault - - ignoreTimezone - - startParam (for a feed) - - endParam (for a feed) - - ANY OF THE JQUERY $.ajax OPTIONS - allows for easily changing from GET to POST and sending additional parameters (issue 386) - allows for easily attaching ajax handlers such as `error` (issue 754) - allows for turning caching on (issue 355) - - Google Calendar feeds are now specified differently: - - specify a simple string of your feed's URL - - specify an *object* with a `url` property of your feed's URL. - you can include any of the new Event-Source options in this object. - - the old `$.fullCalendar.gcalFeed` method still works - - no more IE7 SSL popup (issue 504) - - remove `cacheParam` - use json event source `cache` option instead - - latest jquery/jquery-ui - -version 1.4.11 (2/22/11) - - fixed rerenderEvents bug (issue 790) - - fixed bug with faulty dragging of events from all-day slot in agenda views - - bundled with jquery 1.5 and jquery-ui 1.8.9 - -version 1.4.10 (1/2/11) - - fixed bug with resizing event to different week in 5-day month view (issue 740) - - fixed bug with events not sticking after a removeEvents call (issue 757) - - fixed bug with underlying parseTime method, and other uses of parseInt (issue 688) - -version 1.4.9 (11/16/10) - - new algorithm for vertically stacking events (issue 111) - - resizing an event to a different week (issue 306) - - bug: some events not rendered with consecutive calls to addEventSource (issue 679) - -version 1.4.8 (10/16/10) - - ignoreTimezone option (set to `false` to process UTC offsets in ISO8601 dates) - - bugfixes - - event refetching not being called under certain conditions (issues 417, 554) - - event refetching being called multiple times under certain conditions (issues 586, 616) - - selection cannot be triggered by right mouse button (issue 558) - - agenda view left axis sized incorrectly (issue 465) - - IE js error when calendar is too narrow (issue 517) - - agenda view looks strange when no scrollbars (issue 235) - - improved parsing of ISO8601 dates with UTC offsets - - $.fullCalendar.version - - an internal refactor of the code, for easier future development and modularity - -version 1.4.7 (7/5/10) - - "dropping" external objects onto the calendar - - droppable (boolean, to turn on/off) - - dropAccept (to filter which events the calendar will accept) - - drop (trigger) - - selectable options can now be specified with a View Option Hash - - bugfixes - - dragged & reverted events having wrong time text (issue 406) - - bug rendering events that have an endtime with seconds, but no hours/minutes (issue 477) - - gotoDate date overflow bug (issue 429) - - wrong date reported when clicking on edge of last column in agenda views (412) - - support newlines in event titles - - select/unselect callbacks now passes native js event - -version 1.4.6 (5/31/10) - - "selecting" days or timeslots - - options: selectable, selectHelper, unselectAuto, unselectCancel - - callbacks: select, unselect - - methods: select, unselect - - when dragging an event, the highlighting reflects the duration of the event - - code compressing by Google Closure Compiler - - bundled with jQuery 1.4.2 and jQuery UI 1.8.1 - -version 1.4.5 (2/21/10) - - lazyFetching option, which can force the calendar to fetch events on every view/date change - - scroll state of agenda views are preserved when switching back to view - - bugfixes - - calling methods on an uninitialized fullcalendar throws error - - IE6/7 bug where an entire view becomes invisible (issue 320) - - error when rendering a hidden calendar (in jquery ui tabs for example) in IE (issue 340) - - interconnected bugs related to calendar resizing and scrollbars - - when switching views or clicking prev/next, calendar would "blink" (issue 333) - - liquid-width calendar's events shifted (depending on initial height of browser) (issue 341) - - more robust underlying algorithm for calendar resizing - -version 1.4.4 (2/3/10) - - optimized event rendering in all views (events render in 1/10 the time) - - gotoDate() does not force the calendar to unnecessarily rerender - - render() method now correctly readjusts height - -version 1.4.3 (12/22/09) - - added destroy method - - Google Calendar event pages respect currentTimezone - - caching now handled by jQuery's ajax - - protection from setting aspectRatio to zero - - bugfixes - - parseISO8601 and DST caused certain events to display day before - - button positioning problem in IE6 - - ajax event source removed after recently being added, events still displayed - - event not displayed when end is an empty string - - dynamically setting calendar height when no events have been fetched, throws error - -version 1.4.2 (12/02/09) - - eventAfterRender trigger - - getDate & getView methods - - height & contentHeight options (explicitly sets the pixel height) - - minTime & maxTime options (restricts shown hours in agenda view) - - getters [for all options] and setters [for height, contentHeight, and aspectRatio ONLY! stay tuned..] - - render method now readjusts calendar's size - - bugfixes - - lightbox scripts that use iframes (like fancybox) - - day-of-week classNames were off when firstDay=1 - - guaranteed space on right side of agenda events (even when stacked) - - accepts ISO8601 dates with a space (instead of 'T') - -version 1.4.1 (10/31/09) - - can exclude weekends with new 'weekends' option - - gcal feed 'currentTimezone' option - - bugfixes - - year/month/date option sometimes wouldn't set correctly (depending on current date) - - daylight savings issue caused agenda views to start at 1am (for BST users) - - cleanup of gcal.js code - -version 1.4 (10/19/09) - - agendaWeek and agendaDay views - - added some options for agenda views: - - allDaySlot - - allDayText - - firstHour - - slotMinutes - - defaultEventMinutes - - axisFormat - - modified some existing options/triggers to work with agenda views: - - dragOpacity and timeFormat can now accept a "View Hash" (a new concept) - - dayClick now has an allDay parameter - - eventDrop now has an an allDay parameter - (this will affect those who use revertFunc, adjust parameter list) - - added 'prevYear' and 'nextYear' for buttons in header - - minor change for theme users, ui-state-hover not applied to active/inactive buttons - - added event-color-changing example in docs - - better defaults for right-to-left themed button icons - -version 1.3.2 (10/13/09) - - Bugfixes (please upgrade from 1.3.1!) - - squashed potential infinite loop when addMonths and addDays - is called with an invalid date - - $.fullCalendar.parseDate() now correctly parses IETF format - - when switching views, the 'today' button sticks inactive, fixed - - gotoDate now can accept a single Date argument - - documentation for changes in 1.3.1 and 1.3.2 now on website - -version 1.3.1 (9/30/09) - - Important Bugfixes (please upgrade from 1.3!) - - When current date was late in the month, for long months, and prev/next buttons - were clicked in month-view, some months would be skipped/repeated - - In certain time zones, daylight savings time would cause certain days - to be misnumbered in month-view - - Subtle change in way week interval is chosen when switching from month to basicWeek/basicDay view - - Added 'allDayDefault' option - - Added 'changeView' and 'render' methods - -version 1.3 (9/21/09) - - different 'views': month/basicWeek/basicDay - - more flexible 'header' system for buttons - - themable by jQuery UI themes - - resizable events (require jQuery UI resizable plugin) - - rescoped & rewritten CSS, enhanced default look - - cleaner css & rendering techniques for right-to-left - - reworked options & API to support multiple views / be consistent with jQuery UI - - refactoring of entire codebase - - broken into different JS & CSS files, assembled w/ build scripts - - new test suite for new features, uses firebug-lite - - refactored docs - - Options - + date - + defaultView - + aspectRatio - + disableResizing - + monthNames (use instead of $.fullCalendar.monthNames) - + monthNamesShort (use instead of $.fullCalendar.monthAbbrevs) - + dayNames (use instead of $.fullCalendar.dayNames) - + dayNamesShort (use instead of $.fullCalendar.dayAbbrevs) - + theme - + buttonText - + buttonIcons - x draggable -> editable/disableDragging - x fixedWeeks -> weekMode - x abbrevDayHeadings -> columnFormat - x buttons/title -> header - x eventDragOpacity -> dragOpacity - x eventRevertDuration -> dragRevertDuration - x weekStart -> firstDay - x rightToLeft -> isRTL - x showTime (use 'allDay' CalEvent property instead) - - Triggered Actions - + eventResizeStart - + eventResizeStop - + eventResize - x monthDisplay -> viewDisplay - x resize -> windowResize - 'eventDrop' params changed, can revert if ajax cuts out - - CalEvent Properties - x showTime -> allDay - x draggable -> editable - 'end' is now INCLUSIVE when allDay=true - 'url' now produces a real tag, more native clicking/tab behavior - - Methods: - + renderEvent - x prevMonth -> prev - x nextMonth -> next - x prevYear/nextYear -> moveDate - x refresh -> rerenderEvents/refetchEvents - x removeEvent -> removeEvents - x getEventsByID -> clientEvents - - Utilities: - 'formatDate' format string completely changed (inspired by jQuery UI datepicker + datejs) - 'formatDates' added to support date-ranges - - Google Calendar Options: - x draggable -> editable - - Bugfixes - - gcal extension fetched 25 results max, now fetches all - -version 1.2.1 (6/29/09) - - bugfixes - - allows and corrects invalid end dates for events - - doesn't throw an error in IE while rendering when display:none - - fixed 'loading' callback when used w/ multiple addEventSource calls - - gcal className can now be an array - -version 1.2 (5/31/09) - - expanded API - - 'className' CalEvent attribute - - 'source' CalEvent attribute - - dynamically get/add/remove/update events of current month - - locale improvements: change month/day name text - - better date formatting ($.fullCalendar.formatDate) - - multiple 'event sources' allowed - - dynamically add/remove event sources - - options for prevYear and nextYear buttons - - docs have been reworked (include addition of Google Calendar docs) - - changed behavior of parseDate for number strings - (now interpets as unix timestamp, not MS times) - - bugfixes - - rightToLeft month start bug - - off-by-one errors with month formatting commands - - events from previous months sticking when clicking prev/next quickly - - Google Calendar API changed to work w/ multiple event sources - - can also provide 'className' and 'draggable' options - - date utilties moved from $ to $.fullCalendar - - more documentation in source code - - minified version of fullcalendar.js - - test suit (available from svn) - - top buttons now use ' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('b'))); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('B'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('b')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('BBB')), - 'SimpleForm'); - } - - function testCanFindFormById() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormById(54)); - $this->assertIsA($page->getFormById(55), 'SimpleForm'); - } - - function testFormCanBeSubmitted() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $form = $page->getFormBySubmit(new SimpleByLabel('Submit')); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('s' => 'Submit'))); - } - - function testUnparsedTagDoesNotCrash() { - $raw = '
'; - $this->whenVisiting('http://host', $raw); - } - - function testReadingTextField() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testEntitiesAreDecodedInDefaultTextFieldValue() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testReadingTextFieldIsCaseInsensitive() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testSettingTextField() { - $raw = '
' . - '' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - $this->assertTrue($page->setField(new SimpleById(3), 'bbb')); - $this->assertEqual($page->getField(new SimpleBYId(3)), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('z'), 'zzz')); - $this->assertNull($page->getField(new SimpleByName('z'))); - } - - function testSettingTextFieldByEnclosingLabel() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testLabelsWithoutForDoNotAttachToInputsWithNoId() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), 'one'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), 'two'); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text A'), '1')); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text B'), '2')); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), '1'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), '2'); - } - - function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByName('b')), 'B'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - } - - function testSettingTextFieldByExternalLabel() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testReadingTextArea() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testEntitiesAreDecodedInTextareaValue() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testNewlinesPreservedInTextArea() { - $raw = "
"; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), "hello\r\nworld"); - } - - function testWhitespacePreservedInTextArea() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), ' '); - } - - function testComplexWhitespaceInTextArea() { - $raw = "\n" . - " \n" . - " \n" . - "
\n". - " \n" . - "
\n" . - " \n" . - ""; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('c')), " "); - } - - function testSettingTextArea() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'AAA')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'AAA'); - } - - function testDontIncludeTextAreaContentInLabel() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Text area C')), 'mouse'); - } - - function testSettingSelectionField() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('a'), 'ccc')); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testSelectionOptionsAreNormalised() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'Big bold'); - $this->assertTrue($page->setField(new SimpleByName('a'), 'small italic')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'small italic'); - } - - function testCanParseBlankOptions() { - $raw = '
- -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), '')); - } - - function testTwoSelectionFieldsAreIndependent() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testEmptyOptionDoesNotScrewUpTwoSelectionFields() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testSettingSelectionFieldByEnclosingLabel() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'B')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'B'); - } - - function testTwoSelectionFieldsWithLabelsAreIndependent() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled D'), 'd2')); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled H'), 'h1')); - $this->assertEqual($page->getField(new SimpleByLabel('Labelled D')), 'd2'); - } - - function testSettingRadioButtonByEnclosingLabel() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('A')), 'a'); - $this->assertTrue($page->setField(new SimpleBylabel('B'), 'b')); - $this->assertEqual($page->getField(new SimpleByLabel('B')), 'b'); - } - - function testCanParseInputsWithAllKindsOfAttributeQuoting() { - $raw = '
' . - '' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('first')), 'one'); - $this->assertEqual($page->getField(new SimpleByName('second')), false); - $this->assertEqual($page->getField(new SimpleByName('third')), 'three'); - } - - function urlToString($url) { - return $url->asString(); - } - - function assertSameFrameset($actual, $expected) { - $this->assertIdentical(array_map(array($this, 'urlToString'), $actual), - array_map(array($this, 'urlToString'), $expected)); - } -} - -class TestOfParsingUsingPhpParser extends TestOfParsing { - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimplePhpPageBuilder(); - return $builder->parse($response); - } - - function testNastyTitle() { - $page = $this->whenVisiting('http://host', - ' <b>Me&Me '); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testLabelShouldStopAtClosingLabelTag() { - $raw = '
stuff
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('startend')), 'stuff'); - } -} - -class TestOfParsingUsingTidyParser extends TestOfParsing { - - function skip() { - $this->skipUnless(extension_loaded('tidy'), 'Install \'tidy\' php extension to enable html tidy based parser'); - } - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimpleTidyPageBuilder(); - return $builder->parse($response); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/php_parser_test.php b/3rdparty/simpletest/test/php_parser_test.php deleted file mode 100755 index d95c7d06a6..0000000000 --- a/3rdparty/simpletest/test/php_parser_test.php +++ /dev/null @@ -1,489 +0,0 @@ -assertFalse($regex->match("Hello", $match)); - $this->assertEqual($match, ""); - } - - function testNoSubject() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("", $match)); - $this->assertEqual($match, ""); - } - - function testMatchAll() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("Hello", $match)); - $this->assertEqual($match, "Hello"); - } - - function testCaseSensitive() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "abc"); - } - - function testCaseInsensitive() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - } - - function testMatchMultiple() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $regex->addPattern("ABC"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - $this->assertFalse($regex->match("Hello", $match)); - } - - function testPatternLabels() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc", "letter"); - $regex->addPattern("123", "number"); - $this->assertIdentical($regex->match("abcdef", $match), "letter"); - $this->assertEqual($match, "abc"); - $this->assertIdentical($regex->match("0123456789", $match), "number"); - $this->assertEqual($match, "123"); - } -} - -class TestOfStateStack extends UnitTestCase { - - function testStartState() { - $stack = new SimpleStateStack("one"); - $this->assertEqual($stack->getCurrent(), "one"); - } - - function testExhaustion() { - $stack = new SimpleStateStack("one"); - $this->assertFalse($stack->leave()); - } - - function testStateMoves() { - $stack = new SimpleStateStack("one"); - $stack->enter("two"); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("three"); - $this->assertEqual($stack->getCurrent(), "three"); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("third"); - $this->assertEqual($stack->getCurrent(), "third"); - $this->assertTrue($stack->leave()); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "one"); - } -} - -class TestParser { - - function accept() { - } - - function a() { - } - - function b() { - } -} -Mock::generate('TestParser'); - -class TestOfLexer extends UnitTestCase { - - function testEmptyPage() { - $handler = new MockTestParser(); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("")); - } - - function testSinglePattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(1, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(2, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(3, "accept", array("yyy", LEXER_UNMATCHED)); - $handler->expectAt(4, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(5, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(7, "accept", array("z", LEXER_UNMATCHED)); - $handler->expectCallCount("accept", 8); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); - } - - function testMultiplePattern() { - $handler = new MockTestParser(); - $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); - for ($i = 0; $i < count($target); $i++) { - $handler->expectAt($i, "accept", array($target[$i], '*')); - } - $handler->expectCallCount("accept", count($target)); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $lexer->addPattern("b+"); - $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); - } -} - -class TestOfLexerModes extends UnitTestCase { - - function testIsolatedPattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("bxb", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "a", array("aaaa", LEXER_MATCHED)); - $handler->expectAt(7, "a", array("x", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 8); - $handler->setReturnValue("a", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); - } - - function testModeChange() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(0, "b", array(":", LEXER_ENTER)); - $handler->expectAt(1, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(2, "b", array("b", LEXER_MATCHED)); - $handler->expectAt(3, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(6, "b", array("bbb", LEXER_MATCHED)); - $handler->expectAt(7, "b", array("a", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 5); - $handler->expectCallCount("b", 8); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern(":", "a", "b"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); - } - - function testNesting() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("(", LEXER_ENTER)); - $handler->expectAt(1, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(2, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(3, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(4, "b", array(")", LEXER_EXIT)); - $handler->expectAt(4, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 6); - $handler->expectCallCount("b", 5); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern("(", "a", "b"); - $lexer->addPattern("b+", "b"); - $lexer->addExitPattern(")", "b"); - $this->assertTrue($lexer->parse("aabaab(bbabb)aab")); - } - - function testSingular() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(2, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(3, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("b", LEXER_SPECIAL)); - $handler->expectAt(1, "b", array("bbb", LEXER_SPECIAL)); - $handler->expectCallCount("a", 4); - $handler->expectCallCount("b", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addSpecialPattern("b+", "a", "b"); - $this->assertTrue($lexer->parse("aabaaxxbbbxx")); - } - - function testUnwindTooFar() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array(")", LEXER_EXIT)); - $handler->expectCallCount("a", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addExitPattern(")", "a"); - $this->assertFalse($lexer->parse("aa)aa")); - } -} - -class TestOfLexerHandlers extends UnitTestCase { - - function testModeMapping() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("(", LEXER_ENTER)); - $handler->expectAt(2, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "a", array(")", LEXER_EXIT)); - $handler->expectAt(6, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 7); - $lexer = new SimpleLexer($handler, "mode_a"); - $lexer->addPattern("a+", "mode_a"); - $lexer->addEntryPattern("(", "mode_a", "mode_b"); - $lexer->addPattern("b+", "mode_b"); - $lexer->addExitPattern(")", "mode_b"); - $lexer->mapHandler("mode_a", "a"); - $lexer->mapHandler("mode_b", "a"); - $this->assertTrue($lexer->parse("aa(bbabb)b")); - } -} - -class TestOfSimpleHtmlLexer extends UnitTestCase { - - function &createParser() { - $parser = new MockSimpleHtmlSaxParser(); - $parser->setReturnValue('acceptStartToken', true); - $parser->setReturnValue('acceptEndToken', true); - $parser->setReturnValue('acceptAttributeToken', true); - $parser->setReturnValue('acceptEntityToken', true); - $parser->setReturnValue('acceptTextToken', true); - $parser->setReturnValue('ignore', true); - return $parser; - } - - function testNoContent() { - $parser = $this->createParser(); - $parser->expectNever('acceptStartToken'); - $parser->expectNever('acceptEndToken'); - $parser->expectNever('acceptAttributeToken'); - $parser->expectNever('acceptEntityToken'); - $parser->expectNever('acceptTextToken'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testUninteresting() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testSkipCss() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipJavaScript() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipHtmlComments() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testTagWithNoAttributes() { - $parser = $this->createParser(); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 2); - $parser->expectOnce('acceptTextToken', array('Hello', '*')); - $parser->expectOnce('acceptEndToken', array('', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('Hello')); - } - - function testTagWithAttributes() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('label', '*')); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('href', '*')); - $parser->expectAt(2, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 3); - $parser->expectAt(0, 'acceptAttributeToken', array('= "', '*')); - $parser->expectAt(1, 'acceptAttributeToken', array('here.html', '*')); - $parser->expectAt(2, 'acceptAttributeToken', array('"', '*')); - $parser->expectCallCount('acceptAttributeToken', 3); - $parser->expectOnce('acceptEndToken', array('
', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('label')); - } -} - -class TestOfHtmlSaxParser extends UnitTestCase { - - function createListener() { - $listener = new MockSimplePhpPageBuilder(); - $listener->setReturnValue('startElement', true); - $listener->setReturnValue('addContent', true); - $listener->setReturnValue('endElement', true); - return $listener; - } - - function testFramesetTag() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('frameset', array())); - $listener->expectOnce('addContent', array('Frames')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('Frames')); - } - - function testTagWithUnquotedAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('name' => 'a.b.c', 'value' => 'd'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagInsideContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectAt(0, 'addContent', array('')); - $listener->expectAt(1, 'addContent', array('')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagWithInternalContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testLinkAddress() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testEncodedAttribute() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here&there.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testTagWithId() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('id' => '0'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testTagWithEmptyAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('option', array('value' => '', 'selected' => ''))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('option')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testComplexTagWithLotsOfCaseVariations() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('a', array('href' => 'here.html', 'style' => "'cool'"))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testXhtmlSelfClosingTag() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('type' => 'submit', 'name' => 'N', 'value' => 'V'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testNestedFrameInFrameset() { - $listener = $this->createListener(); - $listener->expectAt(0, 'startElement', array('frameset', array())); - $listener->expectAt(1, 'startElement', array('frame', array('src' => 'frame.html'))); - $listener->expectCallCount('startElement', 2); - $listener->expectOnce('addContent', array('Hello')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse( - 'Hello')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/recorder_test.php b/3rdparty/simpletest/test/recorder_test.php deleted file mode 100755 index fdae4c1ccc..0000000000 --- a/3rdparty/simpletest/test/recorder_test.php +++ /dev/null @@ -1,23 +0,0 @@ -addFile(dirname(__FILE__) . '/support/recorder_sample.php'); - $recorder = new Recorder(new SimpleReporter()); - $test->run($recorder); - $this->assertEqual(count($recorder->results), 2); - $this->assertIsA($recorder->results[0], 'SimpleResultOfPass'); - $this->assertEqual('testTrueIsTrue', array_pop($recorder->results[0]->breadcrumb)); - $this->assertPattern('/ at \[.*\Wrecorder_sample\.php line 7\]/', $recorder->results[0]->message); - $this->assertIsA($recorder->results[1], 'SimpleResultOfFail'); - $this->assertEqual('testFalseIsTrue', array_pop($recorder->results[1]->breadcrumb)); - $this->assertPattern("/Expected false, got \[Boolean: true\] at \[.*\Wrecorder_sample\.php line 11\]/", - $recorder->results[1]->message); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/reflection_php5_test.php b/3rdparty/simpletest/test/reflection_php5_test.php deleted file mode 100755 index d9f46e6db7..0000000000 --- a/3rdparty/simpletest/test/reflection_php5_test.php +++ /dev/null @@ -1,263 +0,0 @@ -assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertFalse($reflection->isAbstract()); - $this->assertFalse($reflection->isInterface()); - } - - function testClassNonExistence() { - $reflection = new SimpleReflection('UnknownThing'); - $this->assertFalse($reflection->classOrInterfaceExists()); - $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testDetectionOfAbstractClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertTrue($reflection->isAbstract()); - } - - function testDetectionOfFinalMethods() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertFalse($reflection->hasFinal()); - $reflection = new SimpleReflection('AnyOldLeafClassWithAFinal'); - $this->assertTrue($reflection->hasFinal()); - } - - function testFindingParentClass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual($reflection->getParent(), 'AnyOldImplementation'); - } - - function testInterfaceExistence() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertTrue($reflection->isInterface()); - } - - function testMethodsListFromClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testMethodsListFromInterface() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesASWell() { - $reflection = new SimpleReflection('AnyDescendentInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testCanSeparateInterfaceMethodsFromOthers() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesInAbstractClass() { - $reflection = new SimpleReflection('AnyAbstractImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testInterfaceHasOnlyItselfToImplement() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForClass() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForSubclass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testNoParameterCreationWhenNoInterface() { - $reflection = new SimpleReflection('AnyOldArgumentClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod($argument)', strtolower($function)); - } else { - $this->assertEqual('function aMethod($argument)', $function); - } - } - - function testParameterCreationWithoutTypeHinting() { - $reflection = new SimpleReflection('AnyOldArgumentImplementation'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testParameterCreationForTypeHinting() { - $reflection = new SimpleReflection('AnyOldTypeHintedClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testIssetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__isset'); - $this->assertEqual('function __isset($key)', $function); - } - - function testUnsetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__unset'); - $this->assertEqual('function __unset($key)', $function); - } - - function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() { - $reflection = new SimpleReflection('AnyDescendentImplementation'); - $interfaces = $reflection->getInterfaces(); - $this->assertEqual(1, count($interfaces)); - $this->assertEqual('AnyDescendentInterface', array_shift($interfaces)); - } - - function testCreatingSignatureForAbstractMethod() { - $reflection = new SimpleReflection('AnotherOldAbstractClass'); - $this->assertEqual($reflection->getSignature('aMethod'), 'function aMethod(AnyOldInterface $argument)'); - } - - function testCanProperlyGenerateStaticMethodSignatures() { - $reflection = new SimpleReflection('AnyOldClassWithStaticMethods'); - $this->assertEqual('static function aStatic()', $reflection->getSignature('aStatic')); - $this->assertEqual( - 'static function aStaticWithParameters($arg1, $arg2)', - $reflection->getSignature('aStaticWithParameters') - ); - } -} - -class TestOfReflectionWithTypeHints extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1.0', '<'), 'Reflection with type hints only tested for PHP 5.1.0 and above'); - } - - function testParameterCreationForTypeHintingWithArray() { - eval('interface AnyOldArrayTypeHintedInterface { - function amethod(array $argument); - } - class AnyOldArrayTypeHintedClass implements AnyOldArrayTypeHintedInterface { - function amethod(array $argument) {} - }'); - $reflection = new SimpleReflection('AnyOldArrayTypeHintedClass'); - $function = $reflection->getSignature('amethod'); - $this->assertEqual('function amethod(array $argument)', $function); - } -} - -class TestOfAbstractsWithAbstractMethods extends UnitTestCase { - function testCanProperlyGenerateAbstractMethods() { - $reflection = new SimpleReflection('AnyOldAbstractClassWithAbstractMethods'); - $this->assertEqual( - 'function anAbstract()', - $reflection->getSignature('anAbstract') - ); - $this->assertEqual( - 'function anAbstractWithParameter($foo)', - $reflection->getSignature('anAbstractWithParameter') - ); - $this->assertEqual( - 'function anAbstractWithMultipleParameters($foo, $bar)', - $reflection->getSignature('anAbstractWithMultipleParameters') - ); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/remote_test.php b/3rdparty/simpletest/test/remote_test.php deleted file mode 100755 index 5f3f96a4de..0000000000 --- a/3rdparty/simpletest/test/remote_test.php +++ /dev/null @@ -1,19 +0,0 @@ -add(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes')); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); diff --git a/3rdparty/simpletest/test/shell_test.php b/3rdparty/simpletest/test/shell_test.php deleted file mode 100755 index d1d769a679..0000000000 --- a/3rdparty/simpletest/test/shell_test.php +++ /dev/null @@ -1,38 +0,0 @@ -assertIdentical($shell->execute('echo Hello'), 0); - $this->assertPattern('/Hello/', $shell->getOutput()); - } - - function testBadCommand() { - $shell = new SimpleShell(); - $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0); - } -} - -class TestOfShellTesterAndShell extends ShellTestCase { - - function testEcho() { - $this->assertTrue($this->execute('echo Hello')); - $this->assertExitCode(0); - $this->assertoutput('Hello'); - } - - function testFileExistence() { - $this->assertFileExists(dirname(__FILE__) . '/all_tests.php'); - $this->assertFileNotExists('wibble'); - } - - function testFilePatterns() { - $this->assertFilePattern('/all[_ ]tests/i', dirname(__FILE__) . '/all_tests.php'); - $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/shell_tester_test.php b/3rdparty/simpletest/test/shell_tester_test.php deleted file mode 100755 index b12c602a39..0000000000 --- a/3rdparty/simpletest/test/shell_tester_test.php +++ /dev/null @@ -1,42 +0,0 @@ -mock_shell; - } - - function testGenericEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } - - function testExitCode() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->expectOnce('execute', array('ls')); - $this->assertTrue($this->execute('ls')); - $this->assertExitCode(0); - } - - function testOutput() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutput("Line 1\nLine 2\n"); - } - - function testOutputPatterns() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutputPattern('/line/i'); - $this->assertNoOutputPattern('/line 2/'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/simpletest_test.php b/3rdparty/simpletest/test/simpletest_test.php deleted file mode 100755 index daa65c6f47..0000000000 --- a/3rdparty/simpletest/test/simpletest_test.php +++ /dev/null @@ -1,58 +0,0 @@ -fail('Should be ignored'); - } -} - -class ShouldNeverBeRunEither extends ShouldNeverBeRun { } - -class TestOfStackTrace extends UnitTestCase { - - function testCanFindAssertInTrace() { - $trace = new SimpleStackTrace(array('assert')); - $this->assertEqual( - $trace->traceMethod(array(array( - 'file' => '/my_test.php', - 'line' => 24, - 'function' => 'assertSomething'))), - ' at [/my_test.php line 24]'); - } -} - -class DummyResource { } - -class TestOfContext extends UnitTestCase { - - function testCurrentContextIsUnique() { - $this->assertSame( - SimpleTest::getContext(), - SimpleTest::getContext()); - } - - function testContextHoldsCurrentTestCase() { - $context = SimpleTest::getContext(); - $this->assertSame($this, $context->getTest()); - } - - function testResourceIsSingleInstanceWithContext() { - $context = new SimpleTestContext(); - $this->assertSame( - $context->get('DummyResource'), - $context->get('DummyResource')); - } - - function testClearingContextResetsResources() { - $context = new SimpleTestContext(); - $resource = $context->get('DummyResource'); - $context->clear(); - $this->assertClone($resource, $context->get('DummyResource')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/site/file.html b/3rdparty/simpletest/test/site/file.html deleted file mode 100755 index cc41aee1b8..0000000000 --- a/3rdparty/simpletest/test/site/file.html +++ /dev/null @@ -1,6 +0,0 @@ - - Link to SimpleTest - - Link to SimpleTest - - \ No newline at end of file diff --git a/3rdparty/simpletest/test/socket_test.php b/3rdparty/simpletest/test/socket_test.php deleted file mode 100755 index 729adda496..0000000000 --- a/3rdparty/simpletest/test/socket_test.php +++ /dev/null @@ -1,25 +0,0 @@ -assertFalse($error->isError()); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $this->assertEqual($error->getError(), 'Ouch'); - } - - function testClearingError() { - $error = new SimpleStickyError(); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $error->clearError(); - $this->assertFalse($error->isError()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/collector/collectable.1 b/3rdparty/simpletest/test/support/collector/collectable.1 deleted file mode 100755 index e69de29bb2..0000000000 diff --git a/3rdparty/simpletest/test/support/collector/collectable.2 b/3rdparty/simpletest/test/support/collector/collectable.2 deleted file mode 100755 index e69de29bb2..0000000000 diff --git a/3rdparty/simpletest/test/support/empty_test_file.php b/3rdparty/simpletest/test/support/empty_test_file.php deleted file mode 100755 index 31e3f7bed6..0000000000 --- a/3rdparty/simpletest/test/support/empty_test_file.php +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/failing_test.php b/3rdparty/simpletest/test/support/failing_test.php deleted file mode 100755 index 30f0d7507d..0000000000 --- a/3rdparty/simpletest/test/support/failing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -assertEqual(1,2); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/latin1_sample b/3rdparty/simpletest/test/support/latin1_sample deleted file mode 100755 index 1903525776..0000000000 --- a/3rdparty/simpletest/test/support/latin1_sample +++ /dev/null @@ -1 +0,0 @@ -@櫻 \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/passing_test.php b/3rdparty/simpletest/test/support/passing_test.php deleted file mode 100755 index b786321635..0000000000 --- a/3rdparty/simpletest/test/support/passing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -assertEqual(2,2); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/recorder_sample.php b/3rdparty/simpletest/test/support/recorder_sample.php deleted file mode 100755 index 4f157f6b60..0000000000 --- a/3rdparty/simpletest/test/support/recorder_sample.php +++ /dev/null @@ -1,14 +0,0 @@ -assertTrue(true); - } - - function testFalseIsTrue() { - $this->assertFalse(true); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/spl_examples.php b/3rdparty/simpletest/test/support/spl_examples.php deleted file mode 100755 index 45add356c4..0000000000 --- a/3rdparty/simpletest/test/support/spl_examples.php +++ /dev/null @@ -1,15 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/supplementary_upload_sample.txt b/3rdparty/simpletest/test/support/supplementary_upload_sample.txt deleted file mode 100755 index d8aa9e8101..0000000000 --- a/3rdparty/simpletest/test/support/supplementary_upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Some more text content \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/test1.php b/3rdparty/simpletest/test/support/test1.php deleted file mode 100755 index b414586d64..0000000000 --- a/3rdparty/simpletest/test/support/test1.php +++ /dev/null @@ -1,7 +0,0 @@ -assertEqual(3,1+2, "pass1"); - } -} -?> diff --git a/3rdparty/simpletest/test/support/upload_sample.txt b/3rdparty/simpletest/test/support/upload_sample.txt deleted file mode 100755 index ec98d7c5e3..0000000000 --- a/3rdparty/simpletest/test/support/upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Sample for testing file upload \ No newline at end of file diff --git a/3rdparty/simpletest/test/tag_test.php b/3rdparty/simpletest/test/tag_test.php deleted file mode 100755 index 5e8a377f08..0000000000 --- a/3rdparty/simpletest/test/tag_test.php +++ /dev/null @@ -1,554 +0,0 @@ - '1', 'b' => '')); - $this->assertEqual($tag->getTagName(), 'title'); - $this->assertIdentical($tag->getAttribute('a'), '1'); - $this->assertIdentical($tag->getAttribute('b'), ''); - $this->assertIdentical($tag->getAttribute('c'), false); - $this->assertIdentical($tag->getContent(), ''); - } - - function testTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testMessyTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testTagWithNoEnd() { - $tag = new SimpleTextTag(array()); - $this->assertFalse($tag->expectEndTag()); - } - - function testAnchorHref() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/')); - $this->assertEqual($tag->getHref(), 'http://here/'); - - $tag = new SimpleAnchorTag(array('href' => '')); - $this->assertIdentical($tag->getAttribute('href'), ''); - $this->assertIdentical($tag->getHref(), ''); - - $tag = new SimpleAnchorTag(array()); - $this->assertIdentical($tag->getAttribute('href'), false); - $this->assertIdentical($tag->getHref(), ''); - } - - function testIsIdMatchesIdAttribute() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7)); - $this->assertIdentical($tag->getAttribute('id'), '7'); - $this->assertTrue($tag->isId(7)); - } -} - -class TestOfWidget extends UnitTestCase { - - function testTextEmptyDefault() { - $tag = new SimpleTextTag(array('type' => 'text')); - $this->assertIdentical($tag->getDefault(), ''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSettingOfExternalLabel() { - $tag = new SimpleTextTag(array('type' => 'text')); - $tag->setLabel('it'); - $this->assertTrue($tag->isLabel('it')); - } - - function testTextDefault() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $this->assertEqual($tag->getDefault(), 'aaa'); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSettingTextValue() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $tag->setValue('bbb'); - $this->assertEqual($tag->getValue(), 'bbb'); - $tag->resetValue(); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testFailToSetHiddenValue() { - $tag = new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden')); - $this->assertFalse($tag->setValue('bbb')); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSubmitDefaults() { - $tag = new SimpleSubmitTag(array('type' => 'submit')); - $this->assertIdentical($tag->getName(), false); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertFalse($tag->setValue('Cannot set this')); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertEqual($tag->getLabel(), 'Submit'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectNever('add'); - $tag->write($encoding); - } - - function testPopulatedSubmit() { - $tag = new SimpleSubmitTag( - array('type' => 'submit', 'name' => 's', 'value' => 'Ok!')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'Ok!'); - $this->assertEqual($tag->getLabel(), 'Ok!'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'Ok!')); - $tag->write($encoding); - } - - function testImageSubmit() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getLabel(), 'Label'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectAt(0, 'add', array('s.x', 20)); - $encoding->expectAt(1, 'add', array('s.y', 30)); - $tag->write($encoding, 20, 30); - } - - function testImageSubmitTitlePreferredOverAltForLabel() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title')); - $this->assertEqual($tag->getLabel(), 'Title'); - } - - function testButton() { - $tag = new SimpleButtonTag( - array('type' => 'submit', 'name' => 's', 'value' => 'do')); - $tag->addContent('I am a button'); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'do'); - $this->assertEqual($tag->getLabel(), 'I am a button'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'do')); - $tag->write($encoding); - } -} - -class TestOfTextArea extends UnitTestCase { - - function testDefault() { - $tag = new SimpleTextAreaTag(array('name' => 'a')); - $tag->addContent('Some text'); - $this->assertEqual($tag->getName(), 'a'); - $this->assertEqual($tag->getDefault(), 'Some text'); - } - - function testWrapping() { - $tag = new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical')); - $tag->addContent("Lot's of text that should be wrapped"); - $this->assertEqual( - $tag->getDefault(), - "Lot's of\r\ntext that\r\nshould be\r\nwrapped"); - $tag->setValue("New long text\r\nwith two lines"); - $this->assertEqual( - $tag->getValue(), - "New long\r\ntext\r\nwith two\r\nlines"); - } - - function testWrappingRemovesLeadingcariageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical')); - $tag->addContent("\rStuff"); - $this->assertEqual($tag->getDefault(), 'Stuff'); - $tag->setValue("\nNew stuff\n"); - $this->assertEqual($tag->getValue(), "New stuff\r\n"); - } - - function testBreaksAreNewlineAndCarriageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '10')); - $tag->addContent("Some\nText\rwith\r\nbreaks"); - $this->assertEqual($tag->getValue(), "Some\r\nText\r\nwith\r\nbreaks"); - } -} - -class TestOfCheckbox extends UnitTestCase { - - function testCanSetCheckboxToNamedValueWithBooleanTrue() { - $tag = new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A')); - $this->assertEqual($tag->getValue(), false); - $tag->setValue(true); - $this->assertIdentical($tag->getValue(), 'A'); - } -} - -class TestOfSelection extends UnitTestCase { - - function testEmpty() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSingle() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array()); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleMappedDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '', 'value' => 'aaa')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testStartsWithDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testSettingOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSettingMappedOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => 'aaa')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => 'bbb', 'selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'aaa'); - $tag->setValue('ccc'); - $this->assertEqual($tag->getValue(), 'ccc'); - } - - function testSelectionDespiteSpuriousWhitespace() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent(' AAA '); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent(' BBB '); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent(' CCC '); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), ' BBB '); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), ' AAA '); - } - - function testFailToSetIllegalOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertFalse($tag->setValue('Not present')); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testNastyOptionValuesThatLookLikeFalse() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => '1')); - $a->addContent('One'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => '0')); - $b->addContent('Zero'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), '1'); - $tag->setValue('Zero'); - $this->assertIdentical($tag->getValue(), '0'); - } - - function testBlankOption() { - $tag = new SimpleSelectionTag(array('name' => 'A')); - $a = new SimpleOptionTag(array()); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('b'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), ''); - $tag->setValue('b'); - $this->assertIdentical($tag->getValue(), 'b'); - $tag->setValue(''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testMultipleDefaultWithNoSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array()); - $this->assertIdentical($tag->getValue(), array()); - } - - function testMultipleDefaultWithSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array('AAA', 'BBB')); - $this->assertIdentical($tag->getValue(), array('AAA', 'BBB')); - } - - function testSettingMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('selected' => '', 'value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertIdentical($tag->getDefault(), array('AAA', 'ccc')); - $this->assertTrue($tag->setValue(array('BBB', 'ccc'))); - $this->assertIdentical($tag->getValue(), array('BBB', 'ccc')); - $this->assertTrue($tag->setValue(array())); - $this->assertIdentical($tag->getValue(), array()); - } - - function testFailToSetIllegalOptionsInMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertFalse($tag->setValue(array('CCC'))); - $this->assertTrue($tag->setValue(array('AAA', 'BBB'))); - $this->assertFalse($tag->setValue(array('AAA', 'CCC'))); - } -} - -class TestOfRadioGroup extends UnitTestCase { - - function testEmptyGroup() { - $group = new SimpleRadioGroup(); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - $this->assertFalse($group->setValue('a')); - } - - function testReadingSingleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'A'); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testReadingMultipleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testFailToSetUnlistedValue() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag(array('value' => 'z'))); - $this->assertFalse($group->setValue('a')); - $this->assertIdentical($group->getValue(), false); - } - - function testSettingNewValueClearsTheOldOne() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testIsIdMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'id' => 'i1'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'id' => 'i2'))); - $this->assertFalse($group->isId('i0')); - $this->assertTrue($group->isId('i1')); - $this->assertTrue($group->isId('i2')); - } - - function testIsLabelMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $button1 = new SimpleRadioButtonTag(array('value' => 'A')); - $button1->setLabel('one'); - $group->addWidget($button1); - $button2 = new SimpleRadioButtonTag(array('value' => 'B')); - $button2->setLabel('two'); - $group->addWidget($button2); - $this->assertFalse($group->isLabel('three')); - $this->assertTrue($group->isLabel('one')); - $this->assertTrue($group->isLabel('two')); - } -} - -class TestOfTagGroup extends UnitTestCase { - - function testReadingMultipleCheckboxGroup() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testReadingMultipleUncheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - } - - function testReadingMultipleCheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'A', 'checked' => ''))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), array('A', 'B')); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingSingleValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - $this->assertTrue($group->setValue('B')); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testSettingMultipleValues() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(array('A', 'B'))); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingNoValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(false)); - $this->assertIdentical($group->getValue(), false); - } - - function testIsIdMatchesAnyIdInSet() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B'))); - $this->assertFalse($group->isId(0)); - $this->assertTrue($group->isId(1)); - $this->assertTrue($group->isId(2)); - } -} - -class TestOfUploadWidget extends UnitTestCase { - - function testValueIsFilePath() { - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt'); - } - - function testSubmitsFileContents() { - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('attach', array( - 'a', - 'Sample for testing file upload', - 'upload_sample.txt')); - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $upload->write($encoding); - } -} - -class TestOfLabelTag extends UnitTestCase { - - function testLabelShouldHaveAnEndTag() { - $label = new SimpleLabelTag(array()); - $this->assertTrue($label->expectEndTag()); - } - - function testContentIsTextOnly() { - $label = new SimpleLabelTag(array()); - $label->addContent('Here are words'); - $this->assertEqual($label->getText(), 'Here are words'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/test_with_parse_error.php b/3rdparty/simpletest/test/test_with_parse_error.php deleted file mode 100755 index 41a5832a5c..0000000000 --- a/3rdparty/simpletest/test/test_with_parse_error.php +++ /dev/null @@ -1,8 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/simpletest/test/unit_tester_test.php b/3rdparty/simpletest/test/unit_tester_test.php deleted file mode 100755 index ce9850f09a..0000000000 --- a/3rdparty/simpletest/test/unit_tester_test.php +++ /dev/null @@ -1,61 +0,0 @@ -assertTrue($this->assertTrue(true)); - } - - function testAssertFalseReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertFalse(false)); - } - - function testAssertEqualReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertEqual(5, 5)); - } - - function testAssertIdenticalReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertIdentical(5, 5)); - } - - function testCoreAssertionsDoNotThrowErrors() { - $this->assertIsA($this, 'UnitTestCase'); - $this->assertNotA($this, 'WebTestCase'); - } - - function testReferenceAssertionOnObjects() { - $a = new ReferenceForTesting(); - $b = $a; - $this->assertSame($a, $b); - } - - function testReferenceAssertionOnScalars() { - $a = 25; - $b = &$a; - $this->assertReference($a, $b); - } - - function testCloneOnObjects() { - $a = new ReferenceForTesting(); - $b = new ReferenceForTesting(); - $this->assertClone($a, $b); - } - - function TODO_testCloneOnScalars() { - $a = 25; - $b = 25; - $this->assertClone($a, $b); - } - - function testCopyOnScalars() { - $a = 25; - $b = 25; - $this->assertCopy($a, $b); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/unit_tests.php b/3rdparty/simpletest/test/unit_tests.php deleted file mode 100755 index 9e621293f9..0000000000 --- a/3rdparty/simpletest/test/unit_tests.php +++ /dev/null @@ -1,49 +0,0 @@ -TestSuite('Unit tests'); - $path = dirname(__FILE__); - $this->addFile($path . '/errors_test.php'); - $this->addFile($path . '/exceptions_test.php'); - $this->addFile($path . '/arguments_test.php'); - $this->addFile($path . '/autorun_test.php'); - $this->addFile($path . '/compatibility_test.php'); - $this->addFile($path . '/simpletest_test.php'); - $this->addFile($path . '/dumper_test.php'); - $this->addFile($path . '/expectation_test.php'); - $this->addFile($path . '/unit_tester_test.php'); - $this->addFile($path . '/reflection_php5_test.php'); - $this->addFile($path . '/mock_objects_test.php'); - $this->addFile($path . '/interfaces_test.php'); - $this->addFile($path . '/collector_test.php'); - $this->addFile($path . '/recorder_test.php'); - $this->addFile($path . '/adapter_test.php'); - $this->addFile($path . '/socket_test.php'); - $this->addFile($path . '/encoding_test.php'); - $this->addFile($path . '/url_test.php'); - $this->addFile($path . '/cookies_test.php'); - $this->addFile($path . '/http_test.php'); - $this->addFile($path . '/authentication_test.php'); - $this->addFile($path . '/user_agent_test.php'); - $this->addFile($path . '/php_parser_test.php'); - $this->addFile($path . '/parsing_test.php'); - $this->addFile($path . '/tag_test.php'); - $this->addFile($path . '/form_test.php'); - $this->addFile($path . '/page_test.php'); - $this->addFile($path . '/frames_test.php'); - $this->addFile($path . '/browser_test.php'); - $this->addFile($path . '/web_tester_test.php'); - $this->addFile($path . '/shell_tester_test.php'); - $this->addFile($path . '/xml_test.php'); - $this->addFile($path . '/../extensions/testdox/test.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/url_test.php b/3rdparty/simpletest/test/url_test.php deleted file mode 100755 index 80119afbdd..0000000000 --- a/3rdparty/simpletest/test/url_test.php +++ /dev/null @@ -1,515 +0,0 @@ -assertEqual($url->getScheme(), ''); - $this->assertEqual($url->getHost(), ''); - $this->assertEqual($url->getScheme('http'), 'http'); - $this->assertEqual($url->getHost('localhost'), 'localhost'); - $this->assertEqual($url->getPath(), ''); - } - - function testBasicParsing() { - $url = new SimpleUrl('https://www.lastcraft.com/test/'); - $this->assertEqual($url->getScheme(), 'https'); - $this->assertEqual($url->getHost(), 'www.lastcraft.com'); - $this->assertEqual($url->getPath(), '/test/'); - } - - function testRelativeUrls() { - $url = new SimpleUrl('../somewhere.php'); - $this->assertEqual($url->getScheme(), false); - $this->assertEqual($url->getHost(), false); - $this->assertEqual($url->getPath(), '../somewhere.php'); - } - - function testParseBareParameter() { - $url = new SimpleUrl('?a'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseEmptyParameter() { - $url = new SimpleUrl('?a='); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a='); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseParameterPair() { - $url = new SimpleUrl('?a=A'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&x=X'); - } - - function testParseMultipleParameters() { - $url = new SimpleUrl('?a=A&b=B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X'); - } - - function testParsingParameterMixture() { - $url = new SimpleUrl('?a=A&b=&c'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X'); - } - - function testAddParametersFromScratch() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('b', 'B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('a', 'aaa'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa'); - } - - function testClearingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $url->clearRequest(); - $this->assertIdentical($url->getEncodedRequest(), ''); - } - - function testEncodingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', '?!"\'#~@[]{}:;<>,./|$%^&*()_+-='); - $this->assertIdentical( - $request = $url->getEncodedRequest(), - '?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - } - - function testDecodingParameters() { - $url = new SimpleUrl('?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - $this->assertEqual( - $url->getEncodedRequest(), - '?a=' . urlencode('?!"\'#~@[]{}:;<>,./|$%^&*()_+-=')); - } - - function testUrlInQueryDoesNotConfuseParsing() { - $url = new SimpleUrl('wibble/login.php?url=http://www.google.com/moo/'); - $this->assertFalse($url->getScheme()); - $this->assertFalse($url->getHost()); - $this->assertEqual($url->getPath(), 'wibble/login.php'); - $this->assertEqual($url->getEncodedRequest(), '?url=http://www.google.com/moo/'); - } - - function testSettingCordinates() { - $url = new SimpleUrl(''); - $url->setCoordinates('32', '45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), ''); - } - - function testParseCordinates() { - $url = new SimpleUrl('?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - } - - function testClearingCordinates() { - $url = new SimpleUrl('?32,45'); - $url->setCoordinates(); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - } - - function testParsingParameterCordinateMixture() { - $url = new SimpleUrl('?a=A&b=&c?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - } - - function testParsingParameterWithBadCordinates() { - $url = new SimpleUrl('?a=A&b=&c?32'); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32'); - } - - function testPageSplitting() { - $url = new SimpleUrl('./here/../there/somewhere.php'); - $this->assertEqual($url->getPath(), './here/../there/somewhere.php'); - $this->assertEqual($url->getPage(), 'somewhere.php'); - $this->assertEqual($url->getBasePath(), './here/../there/'); - } - - function testAbsolutePathPageSplitting() { - $url = new SimpleUrl("http://host.com/here/there/somewhere.php"); - $this->assertEqual($url->getPath(), "/here/there/somewhere.php"); - $this->assertEqual($url->getPage(), "somewhere.php"); - $this->assertEqual($url->getBasePath(), "/here/there/"); - } - - function testSplittingUrlWithNoPageGivesEmptyPage() { - $url = new SimpleUrl('/here/there/'); - $this->assertEqual($url->getPath(), '/here/there/'); - $this->assertEqual($url->getPage(), ''); - $this->assertEqual($url->getBasePath(), '/here/there/'); - } - - function testPathNormalisation() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1535407 - function testPathNormalisationWithSinglePeriod() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/./../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1852413 - function testHostnameExtractedFromUContainingAtSign() { - $url = new SimpleUrl("http://localhost/name@example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name@example.com"); - } - - function testHostnameInLocalhost() { - $url = new SimpleUrl("http://localhost/name/example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name/example.com"); - } - - function testUsernameAndPasswordAreUrlDecoded() { - $url = new SimpleUrl('http://' . urlencode('test@test') . - ':' . urlencode('$!�@*&%') . '@www.lastcraft.com'); - $this->assertEqual($url->getUsername(), 'test@test'); - $this->assertEqual($url->getPassword(), '$!�@*&%'); - } - - function testBlitz() { - $this->assertUrl( - "https://username:password@www.somewhere.com:243/this/that/here.php?a=1&b=2#anchor", - array("https", "username", "password", "www.somewhere.com", 243, "/this/that/here.php", "com", "?a=1&b=2", "anchor"), - array("a" => "1", "b" => "2")); - $this->assertUrl( - "username:password@www.somewhere.com/this/that/here.php?a=1", - array(false, "username", "password", "www.somewhere.com", false, "/this/that/here.php", "com", "?a=1", false), - array("a" => "1")); - $this->assertUrl( - "username:password@somewhere.com:243?1,2", - array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false), - array(), - array(1, 2)); - $this->assertUrl( - "https://www.somewhere.com", - array("https", false, false, "www.somewhere.com", false, "/", "com", "", false)); - $this->assertUrl( - "username@www.somewhere.com:243#anchor", - array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor")); - $this->assertUrl( - "/this/that/here.php?a=1&b=2?3,4", - array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2"), - array(3, 4)); - $this->assertUrl( - "username@/here.php?a=1&b=2", - array(false, "username", false, false, false, "/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2")); - } - - function testAmbiguousHosts() { - $this->assertUrl( - "tigger", - array(false, false, false, false, false, "tigger", false, "", false)); - $this->assertUrl( - "/tigger", - array(false, false, false, false, false, "/tigger", false, "", false)); - $this->assertUrl( - "//tigger", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "//tigger/", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "tigger.com", - array(false, false, false, "tigger.com", false, "/", "com", "", false)); - $this->assertUrl( - "me.net/tigger", - array(false, false, false, "me.net", false, "/tigger", "net", "", false)); - } - - function testAsString() { - $this->assertPreserved('https://www.here.com'); - $this->assertPreserved('http://me:secret@www.here.com'); - $this->assertPreserved('http://here/there'); - $this->assertPreserved('http://here/there?a=A&b=B'); - $this->assertPreserved('http://here/there?a=1&a=2'); - $this->assertPreserved('http://here/there?a=1&a=2?9,8'); - $this->assertPreserved('http://host?a=1&a=2'); - $this->assertPreserved('http://host#stuff'); - $this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6'); - $this->assertPreserved('http://www.here.com/?a=A__b=B'); - $this->assertPreserved('http://www.example.com:8080/'); - } - - function testUrlWithTwoSlashesInPath() { - $url = new SimpleUrl('/article/categoryedit/insert//'); - $this->assertEqual($url->getPath(), '/article/categoryedit/insert//'); - } - - function testUrlWithRequestKeyEncoded() { - $url = new SimpleUrl('/?foo%5B1%5D=bar'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar&a%5B1%5D=b%5B%5D'); - - $url = new SimpleUrl('/'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?a%5B1%5D=b%5B%5D'); - } - - function testUrlWithRequestKeyEncodedAndParamNamLookingLikePair() { - $url = new SimpleUrl('/'); - $url->addRequestParameter('foo[]=bar', ''); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - $url = new SimpleUrl('/?foo%5B%5D%3Dbar='); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - } - - function assertUrl($raw, $parts, $params = false, $coords = false) { - if (! is_array($params)) { - $params = array(); - } - $url = new SimpleUrl($raw); - $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s"); - $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s"); - $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s"); - $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s"); - $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s"); - $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s"); - $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s"); - $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s"); - $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s"); - if ($coords) { - $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s"); - $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s"); - } - } - - function assertPreserved($string) { - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - } -} - -class TestOfAbsoluteUrls extends UnitTestCase { - - function testDirectoriesAfterFilename() { - $string = '../../index.php/foo/bar'; - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - - $absolute = $url->makeAbsolute('http://www.domain.com/some/path/'); - $this->assertEqual($absolute->asString(), 'http://www.domain.com/index.php/foo/bar'); - } - - function testMakingAbsolute() { - $url = new SimpleUrl('../there/somewhere.php'); - $this->assertEqual($url->getPath(), '../there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com:1234/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPort(), 1234); - $this->assertEqual($absolute->getPath(), '/I/am/there/somewhere.php'); - } - - function testMakingAnEmptyUrlAbsolute() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/page.html'); - } - - function testMakingAnEmptyUrlAbsoluteWithMissingPageName() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - } - - function testMakingAShortQueryUrlAbsolute() { - $url = new SimpleUrl('?a#b'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a'); - $this->assertEqual($absolute->getFragment(), 'b'); - } - - function testMakingADirectoryUrlAbsolute() { - $url = new SimpleUrl('hello/'); - $this->assertEqual($url->getPath(), 'hello/'); - $this->assertEqual($url->getBasePath(), 'hello/'); - $this->assertEqual($url->getPage(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/I/am/here/hello/'); - } - - function testMakingARootUrlAbsolute() { - $url = new SimpleUrl('/'); - $this->assertEqual($url->getPath(), '/'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/'); - } - - function testMakingARootPageUrlAbsolute() { - $url = new SimpleUrl('/here.html'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/here.html'); - } - - function testCarryAuthenticationFromRootPage() { - $url = new SimpleUrl('here.html'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/'); - $this->assertEqual($absolute->getPath(), '/here.html'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingCoordinateUrlAbsolute() { - $url = new SimpleUrl('?1,2'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getX(), 1); - $this->assertEqual($absolute->getY(), 2); - } - - function testMakingAbsoluteAppendedPath() { - $url = new SimpleUrl('./there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteBadlyFormedAppendedPath() { - $url = new SimpleUrl('there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteHasNoEffectWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://test:secret@www.lastcraft.com:321/stuff/?a=1#f'); - $absolute = $url->makeAbsolute('http://host.com/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getPort(), 321); - $this->assertEqual($absolute->getPath(), '/stuff/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a=1'); - $this->assertEqual($absolute->getFragment(), 'f'); - } - - function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://www.lastcraft.com'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/here/'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() { - $url = new SimpleUrl('http://www.lastcraft.com'); - $absolute = $url->makeAbsolute('https://host.com:81/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertIdentical($absolute->getPort(), false); - $this->assertEqual($absolute->getPath(), '/'); - } -} - -class TestOfFrameUrl extends UnitTestCase { - - function testTargetAttachment() { - $url = new SimpleUrl('http://www.site.com/home.html'); - $this->assertIdentical($url->getTarget(), false); - $url->setTarget('A frame'); - $this->assertIdentical($url->getTarget(), 'A frame'); - } -} - -/** - * @note Based off of http://www.mozilla.org/quality/networking/testing/filetests.html - */ -class TestOfFileUrl extends UnitTestCase { - - function testMinimalUrl() { - $url = new SimpleUrl('file:///'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/'); - } - - function testUnixUrl() { - $url = new SimpleUrl('file:///fileInRoot'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/fileInRoot'); - } - - function testDOSVolumeUrl() { - $url = new SimpleUrl('file:///C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSVolumePromotion() { - $url = new SimpleUrl('file://C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSBackslashes() { - $url = new SimpleUrl('file:///C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSDirnameAfterFile() { - $url = new SimpleUrl('file://C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/user_agent_test.php b/3rdparty/simpletest/test/user_agent_test.php deleted file mode 100755 index 030abeb257..0000000000 --- a/3rdparty/simpletest/test/user_agent_test.php +++ /dev/null @@ -1,348 +0,0 @@ -headers = new MockSimpleHttpHeaders(); - $this->response = new MockSimpleHttpResponse(); - $this->response->setReturnValue('isError', false); - $this->response->returns('getHeaders', new MockSimpleHttpHeaders()); - $this->request = new MockSimpleHttpRequest(); - $this->request->returns('fetch', $this->response); - } - - function testGetRequestWithoutIncidentGivesNoErrors() { - $url = new SimpleUrl('http://test:secret@this.com/page.html'); - $url->addRequestParameters(array('a' => 'A', 'b' => 'B')); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $this->request); - $agent->__construct(); - - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A', 'b' => 'B'))); - $this->assertFalse($response->isError()); - } -} - -class TestOfAdditionalHeaders extends UnitTestCase { - - function testAdditionalHeaderAddedToRequest() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('User-Agent: SimpleTest')); - - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $agent->addHeader('User-Agent: SimpleTest'); - $response = $agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding()); - } -} - -class TestOfBrowserCookies extends UnitTestCase { - - private function createStandardResponse() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnValue("getContent", "stuff"); - $response->setReturnReference("getHeaders", new MockSimpleHttpHeaders()); - return $response; - } - - private function createCookieSite($header_lines) { - $headers = new SimpleHttpHeaders($header_lines); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnReference("getHeaders", $headers); - $response->setReturnValue("getContent", "stuff"); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference("fetch", $response); - return $request; - } - - private function createMockedRequestUserAgent(&$request) { - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - return $agent; - } - - function testCookieJarIsSentToRequest() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectOnce('readCookiesFromJar', array($jar, '*')); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testNoCookieJarIsSentToRequestWhenCookiesAreDisabled() { - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectNever('readCookiesFromJar'); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testReadingNewCookie() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testIgnoringNewCookieWhenCookiesDisabled() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical($agent->getCookieValue("this.com", "this/path/", "a"), false); - } - - function testOverwriteCookieThatAlreadyExists() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testClearCookieBySettingExpiry() { - $request = $this->createCookieSite('Set-cookie: a=b'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "b"); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testAgeingAndClearing() { - $request = $this->createCookieSite('Set-cookie: a=A; expires=Wed, 25-Dec-02 04:24:21 GMT; path=/this/path'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "A"); - $agent->ageCookies(2); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testReadingIncomingAndSettingNewCookies() { - $request = $this->createCookieSite('Set-cookie: a=AAA'); - $agent = $this->createMockedRequestUserAgent($request); - - $this->assertNull($agent->getBaseCookieValue("a", false)); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->setCookie("b", "BBB", "this.com", "this/path/"); - $this->assertEqual( - $agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')), - "AAA"); - $this->assertEqual( - $agent->getBaseCookieValue("b", new SimpleUrl('http://this.com/this/path/page.html')), - "BBB"); - } -} - -class TestOfHttpRedirects extends UnitTestCase { - - function createRedirect($content, $redirect) { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('isRedirect', (boolean)$redirect); - $headers->setReturnValue('getLocation', $redirect); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnReference('getHeaders', $headers); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testDisabledRedirects() { - $agent = new MockRequestUserAgent(); - $agent->returns( - 'createHttpRequest', - $this->createRedirect('stuff', 'there.html')); - $agent->expectOnce('createHttpRequest'); - $agent->__construct(); - $agent->setMaximumRedirects(0); - $response = $agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'stuff'); - } - - function testSingleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testDoubleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 3); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'third'); - } - - function testSuccessAfterRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', false)); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testRedirectChangesPostToGet() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->expectAt(0, 'createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding'))); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectAt(1, 'createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding'))); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding()); - } -} - -class TestOfBadHosts extends UnitTestCase { - - private function createSimulatedBadHost() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('isError', true); - $response->setReturnValue('getError', 'Bad socket'); - $response->setReturnValue('getContent', false); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testUntestedHost() { - $request = $this->createSimulatedBadHost(); - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://this.host/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - } -} - -class TestOfAuthorisation extends UnitTestCase { - - function testAuthenticateHeaderAdded() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('Authorization: Basic ' . base64_encode('test:secret'))); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.host'), - new SimpleGetEncoding()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/visual_test.php b/3rdparty/simpletest/test/visual_test.php deleted file mode 100755 index 6b9d085d67..0000000000 --- a/3rdparty/simpletest/test/visual_test.php +++ /dev/null @@ -1,495 +0,0 @@ -a = $a; - } -} - -class PassingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->pass('Pass'); - } - - function testTrue() { - $this->assertTrue(true); - } - - function testFalse() { - $this->assertFalse(false); - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 25, 'My assert message : %s'); - } - - function testNull() { - $this->assertNull(null, "%s -> Pass"); - $this->assertNotNull(false, "%s -> Pass"); - } - - function testType() { - $this->assertIsA("hello", "string", "%s -> Pass"); - $this->assertIsA($this, "PassingUnitTestCaseOutput", "%s -> Pass"); - $this->assertIsA($this, "UnitTestCase", "%s -> Pass"); - } - - function testTypeEquality() { - $this->assertEqual("0", 0, "%s -> Pass"); - } - - function testNullEquality() { - $this->assertNotEqual(null, 1, "%s -> Pass"); - $this->assertNotEqual(1, null, "%s -> Pass"); - } - - function testIntegerEquality() { - $this->assertNotEqual(1, 2, "%s -> Pass"); - } - - function testStringEquality() { - $this->assertEqual("a", "a", "%s -> Pass"); - $this->assertNotEqual("aa", "ab", "%s -> Pass"); - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass"); - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass"); - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertIdentical($a, $b, "%s -> Pass"); - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertNotIdentical($a, $b, "%s -> Pass"); - } - - function testNullIdentity() { - $this->assertNotIdentical(null, 1, "%s -> Pass"); - $this->assertNotIdentical(1, null, "%s -> Pass"); - } - - function testHashIdentity() { - } - - function testObjectEquality() { - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass"); - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Pass"); - } - - function testObjectIndentity() { - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Pass"); - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass"); - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertReference($a, $b, "%s -> Pass"); - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $b, "%s -> Pass"); - } - - function testPatterns() { - $this->assertPattern('/hello/i', "Hello there", "%s -> Pass"); - $this->assertNoPattern('/hello/', "Hello there", "%s -> Pass"); - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text, $text); - } -} - -class FailingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->fail('Fail'); // Fail. - } - - function testTrue() { - $this->assertTrue(false); // Fail. - } - - function testFalse() { - $this->assertFalse(true); // Fail. - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 24, 'My assert message : %s'); // Fail. - } - - function testNull() { - $this->assertNull(false, "%s -> Fail"); // Fail. - $this->assertNotNull(null, "%s -> Fail"); // Fail. - } - - function testType() { - $this->assertIsA(14, "string", "%s -> Fail"); // Fail. - $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail. - $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail. - } - - function testTypeEquality() { - $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail. - } - - function testNullEquality() { - $this->assertEqual(null, 1, "%s -> Fail"); // Fail. - $this->assertEqual(1, null, "%s -> Fail"); // Fail. - } - - function testIntegerEquality() { - $this->assertEqual(1, 2, "%s -> Fail"); // Fail. - } - - function testStringEquality() { - $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail. - $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail. - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Fail"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail. - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail. - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testNullIdentity() { - $this->assertIdentical(null, 1, "%s -> Fail"); // Fail. - $this->assertIdentical(1, null, "%s -> Fail"); // Fail. - } - - function testHashIdentity() { - $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail. - } - - function testObjectEquality() { - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail. - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail. - } - - function testObjectIndentity() { - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Fail"); // Fail. - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail. - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertClone($a, $b, "%s -> Fail"); // Fail. - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $c, "%s -> Fail"); // Fail. - } - - function testPatterns() { - $this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail. - $this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail. - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text . $text, $text . "a" . $text); // Fail. - } -} - -class Dummy { - function Dummy() { - } - - function a() { - } -} -Mock::generate('Dummy'); - -class TestOfMockObjectsOutput extends UnitTestCase { - - function testCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectCallCount('a', 1, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testMinimumCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectMinimumCallCount('a', 2, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testEmptyMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array()); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testEmptyMatchingWithCustomMessage() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(), 'My expectation message: %s'); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testNullMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(null)); - $dummy->a(null); - $dummy->a(); // Fail. - } - - function testBooleanMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(true, false)); - $dummy->a(true, false); - $dummy->a(true, true); // Fail. - } - - function testIntegerMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(32, 33)); - $dummy->a(32, 33); - $dummy->a(32, 34); // Fail. - } - - function testFloatMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(3.2, 3.3)); - $dummy->a(3.2, 3.3); - $dummy->a(3.2, 3.4); // Fail. - } - - function testStringMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('32', '33')); - $dummy->a('32', '33'); - $dummy->a('32', '34'); // Fail. - } - - function testEmptyMatchingWithCustomExpectationMessage() { - $dummy = &new MockDummy(); - $dummy->expect( - 'a', - array(new EqualExpectation('A', 'My part expectation message: %s')), - 'My expectation message: %s'); - $dummy->a('A'); - $dummy->a('B'); // Fail. - } - - function testArrayMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(array(32), array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } - - function testObjectMatching() { - $a = new Dummy(); - $a->a = 'a'; - $b = new Dummy(); - $b->b = 'b'; - $dummy = &new MockDummy(); - $dummy->expect('a', array($a, $b)); - $dummy->a($a, $b); - $dummy->a($a, $a); // Fail. - } - - function testBigList() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(false, 0, 1, 1.0)); - $dummy->a(false, 0, 1, 1.0); - $dummy->a(true, false, 2, 2.0); // Fail. - } -} - -class TestOfPastBugs extends UnitTestCase { - - function testMixedTypes() { - $this->assertEqual(array(), null, "%s -> Pass"); - $this->assertIdentical(array(), null, "%s -> Fail"); // Fail. - } - - function testMockWildcards() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('*', array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } -} - -class TestOfVisualShell extends ShellTestCase { - - function testDump() { - $this->execute('ls'); - $this->dumpOutput(); - $this->execute('dir'); - $this->dumpOutput(); - } - - function testDumpOfList() { - $this->execute('ls'); - $this->dump($this->getOutputAsList()); - } -} - -class PassesAsWellReporter extends HtmlReporter { - - protected function getCss() { - return parent::getCss() . ' .pass { color: darkgreen; }'; - } - - function paintPass($message) { - parent::paintPass($message); - print "Pass: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities($message) . "
\n"; - } - - function paintSignal($type, &$payload) { - print "$type: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities(serialize($payload)) . "
\n"; - } -} - -class TestOfSkippingNoMatterWhat extends UnitTestCase { - function skip() { - $this->skipIf(true, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingOrElse extends UnitTestCase { - function skip() { - $this->skipUnless(false, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingTwiceOver extends UnitTestCase { - function skip() { - $this->skipIf(true, 'First reason -> %s'); - $this->skipIf(true, 'Second reason -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestThatShouldNotBeSkipped extends UnitTestCase { - function skip() { - $this->skipIf(false); - $this->skipUnless(true); - } - - function testFail() { - $this->fail('We should see this message'); - } - - function testPass() { - $this->pass('We should see this message'); - } -} - -$test = &new TestSuite('Visual test with 46 passes, 47 fails and 0 exceptions'); -$test->add(new PassingUnitTestCaseOutput()); -$test->add(new FailingUnitTestCaseOutput()); -$test->add(new TestOfMockObjectsOutput()); -$test->add(new TestOfPastBugs()); -$test->add(new TestOfVisualShell()); -$test->add(new TestOfSkippingNoMatterWhat()); -$test->add(new TestOfSkippingOrElse()); -$test->add(new TestOfSkippingTwiceOver()); -$test->add(new TestThatShouldNotBeSkipped()); - -if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) { - $reporter = new XmlReporter(); -} elseif (TextReporter::inCli()) { - $reporter = new TextReporter(); -} else { - $reporter = new PassesAsWellReporter(); -} -if (isset($_GET['dry']) || in_array('dry', (isset($argv) ? $argv : array()))) { - $reporter->makeDry(); -} -exit ($test->run($reporter) ? 0 : 1); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/web_tester_test.php b/3rdparty/simpletest/test/web_tester_test.php deleted file mode 100755 index 8c3bf1adf6..0000000000 --- a/3rdparty/simpletest/test/web_tester_test.php +++ /dev/null @@ -1,155 +0,0 @@ -assertTrue($expectation->test('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertFalse($expectation->test('A')); - } - - function testMatchesInteger() { - $expectation = new FieldExpectation('1'); - $this->assertTrue($expectation->test('1')); - $this->assertTrue($expectation->test(1)); - $this->assertTrue($expectation->test(array('1'))); - $this->assertTrue($expectation->test(array(1))); - } - - function testNonStringFailsExpectation() { - $expectation = new FieldExpectation('a'); - $this->assertFalse($expectation->test(null)); - } - - function testUnsetFieldCanBeTestedFor() { - $expectation = new FieldExpectation(false); - $this->assertTrue($expectation->test(false)); - } - - function testMultipleValuesCanBeInAnyOrder() { - $expectation = new FieldExpectation(array('a', 'b')); - $this->assertTrue($expectation->test(array('a', 'b'))); - $this->assertTrue($expectation->test(array('b', 'a'))); - $this->assertFalse($expectation->test(array('a', 'a'))); - $this->assertFalse($expectation->test('a')); - } - - function testSingleItemCanBeArrayOrString() { - $expectation = new FieldExpectation(array('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertTrue($expectation->test('a')); - } -} - -class TestOfHeaderExpectations extends UnitTestCase { - - function testExpectingOnlyTheHeaderName() { - $expectation = new HttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('a: B'), true); - $this->assertIdentical($expectation->test(' a : A '), true); - } - - function testHeaderValueAsWell() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), false); - } - - function testHeaderValueWithColons() { - $expectation = new HttpHeaderExpectation('a', 'A:B:C'); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('a: A:B'), false); - $this->assertIdentical($expectation->test('a: A:B:C'), true); - $this->assertIdentical($expectation->test('a: A:B:C:D'), false); - } - - function testMultilineSearch() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false); - $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true); - } - - function testMultilineSearchWithPadding() { - $expectation = new HttpHeaderExpectation('a', ' A '); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true); - } - - function testPatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/')); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), true); - } - - function testCaseInsensitivePatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i')); - $this->assertIdentical($expectation->test('a: a'), true); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : BAB '), true); - $this->assertIdentical($expectation->test(' a : bab '), true); - } - - function testUnwantedHeader() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('stuff'), true); - $this->assertIdentical($expectation->test('b: B'), true); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('A: A'), false); - } - - function testMultilineUnwantedSearch() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false); - } - - function testLocationHeaderSplitsCorrectly() { - $expectation = new HttpHeaderExpectation('Location', 'http://here/'); - $this->assertIdentical($expectation->test('Location: http://here/'), true); - } -} - -class TestOfTextExpectations extends UnitTestCase { - - function testMatchingSubString() { - $expectation = new TextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), false); - $this->assertIdentical($expectation->test('Wanted'), false); - $this->assertIdentical($expectation->test('wanted'), true); - $this->assertIdentical($expectation->test('the wanted text is here'), true); - } - - function testNotMatchingSubString() { - $expectation = new NoTextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('Wanted'), true); - $this->assertIdentical($expectation->test('wanted'), false); - $this->assertIdentical($expectation->test('the wanted text is here'), false); - } -} - -class TestOfGenericAssertionsInWebTester extends WebTestCase { - function testEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/xml_test.php b/3rdparty/simpletest/test/xml_test.php deleted file mode 100755 index f99e0dcd98..0000000000 --- a/3rdparty/simpletest/test/xml_test.php +++ /dev/null @@ -1,187 +0,0 @@ - 2)); - $this->assertEqual($nesting->getSize(), 2); - } -} - -class TestOfXmlStructureParsing extends UnitTestCase { - function testValidXml() { - $listener = new MockSimpleScorer(); - $listener->expectNever('paintGroupStart'); - $listener->expectNever('paintGroupEnd'); - $listener->expectNever('paintCaseStart'); - $listener->expectNever('paintCaseEnd'); - $parser = new SimpleTestXmlParser($listener); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - } - - function testEmptyGroup() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintGroupStart', array('a_group', 7)); - $listener->expectOnce('paintGroupEnd', array('a_group')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyCase() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_case\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyMethod() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $listener->expectOnce('paintMethodStart', array('a_method')); - $listener->expectOnce('paintMethodEnd', array('a_method')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_method\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testNestedGroup() { - $listener = new MockSimpleScorer(); - $listener->expectAt(0, 'paintGroupStart', array('a_group', 7)); - $listener->expectAt(1, 'paintGroupStart', array('b_group', 3)); - $listener->expectCallCount('paintGroupStart', 2); - $listener->expectAt(0, 'paintGroupEnd', array('b_group')); - $listener->expectAt(1, 'paintGroupEnd', array('a_group')); - $listener->expectCallCount('paintGroupEnd', 2); - - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("b_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } -} - -class AnyOldSignal { - public $stuff = true; -} - -class TestOfXmlResultsParsing extends UnitTestCase { - - function sendValidStart(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $parser->parse("\n"); - $parser->parse("a_method\n"); - } - - function sendValidEnd(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testPass() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintPass', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFail() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFail', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testException() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintError', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSkip() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSkip', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSignal() { - $signal = new AnyOldSignal(); - $signal->stuff = "Hello"; - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSignal', array('a_signal', $signal)); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse( - "\n")); - $this->sendValidEnd($parser); - } - - function testMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintMessage', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFormattedMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("\n")); - $this->sendValidEnd($parser); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test_case.php b/3rdparty/simpletest/test_case.php deleted file mode 100644 index ba023c3b2e..0000000000 --- a/3rdparty/simpletest/test_case.php +++ /dev/null @@ -1,658 +0,0 @@ -label = $label; - } - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->label ? $this->label : get_class($this); - } - - /** - * This is a placeholder for skipping tests. In this - * method you place skipIf() and skipUnless() calls to - * set the skipping state. - * @access public - */ - function skip() { - } - - /** - * Will issue a message to the reporter and tell the test - * case to skip if the incoming flag is true. - * @param string $should_skip Condition causing the tests to be skipped. - * @param string $message Text of skip condition. - * @access public - */ - function skipIf($should_skip, $message = '%s') { - if ($should_skip && ! $this->should_skip) { - $this->should_skip = true; - $message = sprintf($message, 'Skipping [' . get_class($this) . ']'); - $this->reporter->paintSkip($message . $this->getAssertionLine()); - } - } - - /** - * Accessor for the private variable $_shoud_skip - * @access public - */ - function shouldSkip() { - return $this->should_skip; - } - - /** - * Will issue a message to the reporter and tell the test - * case to skip if the incoming flag is false. - * @param string $shouldnt_skip Condition causing the tests to be run. - * @param string $message Text of skip condition. - * @access public - */ - function skipUnless($shouldnt_skip, $message = false) { - $this->skipIf(! $shouldnt_skip, $message); - } - - /** - * Used to invoke the single tests. - * @return SimpleInvoker Individual test runner. - * @access public - */ - function createInvoker() { - return new SimpleErrorTrappingInvoker( - new SimpleExceptionTrappingInvoker(new SimpleInvoker($this))); - } - - /** - * Uses reflection to run every method within itself - * starting with the string "test" unless a method - * is specified. - * @param SimpleReporter $reporter Current test reporter. - * @return boolean True if all tests passed. - * @access public - */ - function run($reporter) { - $context = SimpleTest::getContext(); - $context->setTest($this); - $context->setReporter($reporter); - $this->reporter = $reporter; - $started = false; - foreach ($this->getTests() as $method) { - if ($reporter->shouldInvoke($this->getLabel(), $method)) { - $this->skip(); - if ($this->should_skip) { - break; - } - if (! $started) { - $reporter->paintCaseStart($this->getLabel()); - $started = true; - } - $invoker = $this->reporter->createInvoker($this->createInvoker()); - $invoker->before($method); - $invoker->invoke($method); - $invoker->after($method); - } - } - if ($started) { - $reporter->paintCaseEnd($this->getLabel()); - } - unset($this->reporter); - $context->setTest(null); - return $reporter->getStatus(); - } - - /** - * Gets a list of test names. Normally that will - * be all internal methods that start with the - * name "test". This method should be overridden - * if you want a different rule. - * @return array List of test names. - * @access public - */ - function getTests() { - $methods = array(); - foreach (get_class_methods(get_class($this)) as $method) { - if ($this->isTest($method)) { - $methods[] = $method; - } - } - return $methods; - } - - /** - * Tests to see if the method is a test that should - * be run. Currently any method that starts with 'test' - * is a candidate unless it is the constructor. - * @param string $method Method name to try. - * @return boolean True if test method. - * @access protected - */ - protected function isTest($method) { - if (strtolower(substr($method, 0, 4)) == 'test') { - return ! SimpleTestCompatibility::isA($this, strtolower($method)); - } - return false; - } - - /** - * Announces the start of the test. - * @param string $method Test method just started. - * @access public - */ - function before($method) { - $this->reporter->paintMethodStart($method); - $this->observers = array(); - } - - /** - * Sets up unit test wide variables at the start - * of each test method. To be overridden in - * actual user test cases. - * @access public - */ - function setUp() { - } - - /** - * Clears the data set in the setUp() method call. - * To be overridden by the user in actual user test cases. - * @access public - */ - function tearDown() { - } - - /** - * Announces the end of the test. Includes private clean up. - * @param string $method Test method just finished. - * @access public - */ - function after($method) { - for ($i = 0; $i < count($this->observers); $i++) { - $this->observers[$i]->atTestEnd($method, $this); - } - $this->reporter->paintMethodEnd($method); - } - - /** - * Sets up an observer for the test end. - * @param object $observer Must have atTestEnd() - * method. - * @access public - */ - function tell($observer) { - $this->observers[] = &$observer; - } - - /** - * @deprecated - */ - function pass($message = "Pass") { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintPass( - $message . $this->getAssertionLine()); - return true; - } - - /** - * Sends a fail event with a message. - * @param string $message Message to send. - * @access public - */ - function fail($message = "Fail") { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintFail( - $message . $this->getAssertionLine()); - return false; - } - - /** - * Formats a PHP error and dispatches it to the - * reporter. - * @param integer $severity PHP error code. - * @param string $message Text of error. - * @param string $file File error occoured in. - * @param integer $line Line number of error. - * @access public - */ - function error($severity, $message, $file, $line) { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintError( - "Unexpected PHP error [$message] severity [$severity] in [$file line $line]"); - } - - /** - * Formats an exception and dispatches it to the - * reporter. - * @param Exception $exception Object thrown. - * @access public - */ - function exception($exception) { - $this->reporter->paintException($exception); - } - - /** - * For user defined expansion of the available messages. - * @param string $type Tag for sorting the signals. - * @param mixed $payload Extra user specific information. - */ - function signal($type, $payload) { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintSignal($type, $payload); - } - - /** - * Runs an expectation directly, for extending the - * tests with new expectation classes. - * @param SimpleExpectation $expectation Expectation subclass. - * @param mixed $compare Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assert($expectation, $compare, $message = '%s') { - if ($expectation->test($compare)) { - return $this->pass(sprintf( - $message, - $expectation->overlayMessage($compare, $this->reporter->getDumper()))); - } else { - return $this->fail(sprintf( - $message, - $expectation->overlayMessage($compare, $this->reporter->getDumper()))); - } - } - - /** - * Uses a stack trace to find the line of an assertion. - * @return string Line number of first assert* - * method embedded in format string. - * @access public - */ - function getAssertionLine() { - $trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip')); - return $trace->traceMethod(); - } - - /** - * Sends a formatted dump of a variable to the - * test suite for those emergency debugging - * situations. - * @param mixed $variable Variable to display. - * @param string $message Message to display. - * @return mixed The original variable. - * @access public - */ - function dump($variable, $message = false) { - $dumper = $this->reporter->getDumper(); - $formatted = $dumper->dump($variable); - if ($message) { - $formatted = $message . "\n" . $formatted; - } - $this->reporter->paintFormattedMessage($formatted); - return $variable; - } - - /** - * Accessor for the number of subtests including myelf. - * @return integer Number of test cases. - * @access public - */ - function getSize() { - return 1; - } -} - -/** - * Helps to extract test cases automatically from a file. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleFileLoader { - - /** - * Builds a test suite from a library of test cases. - * The new suite is composed into this one. - * @param string $test_file File name of library with - * test case classes. - * @return TestSuite The new test suite. - * @access public - */ - function load($test_file) { - $existing_classes = get_declared_classes(); - $existing_globals = get_defined_vars(); - include_once($test_file); - $new_globals = get_defined_vars(); - $this->makeFileVariablesGlobal($existing_globals, $new_globals); - $new_classes = array_diff(get_declared_classes(), $existing_classes); - if (empty($new_classes)) { - $new_classes = $this->scrapeClassesFromFile($test_file); - } - $classes = $this->selectRunnableTests($new_classes); - return $this->createSuiteFromClasses($test_file, $classes); - } - - /** - * Imports new variables into the global namespace. - * @param hash $existing Variables before the file was loaded. - * @param hash $new Variables after the file was loaded. - * @access private - */ - protected function makeFileVariablesGlobal($existing, $new) { - $globals = array_diff(array_keys($new), array_keys($existing)); - foreach ($globals as $global) { - $GLOBALS[$global] = $new[$global]; - } - } - - /** - * Lookup classnames from file contents, in case the - * file may have been included before. - * Note: This is probably too clever by half. Figuring this - * out after a failed test case is going to be tricky for us, - * never mind the user. A test case should not be included - * twice anyway. - * @param string $test_file File name with classes. - * @access private - */ - protected function scrapeClassesFromFile($test_file) { - preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi', - file_get_contents($test_file), - $matches ); - return $matches[1]; - } - - /** - * Calculates the incoming test cases. Skips abstract - * and ignored classes. - * @param array $candidates Candidate classes. - * @return array New classes which are test - * cases that shouldn't be ignored. - * @access public - */ - function selectRunnableTests($candidates) { - $classes = array(); - foreach ($candidates as $class) { - if (TestSuite::getBaseTestCase($class)) { - $reflection = new SimpleReflection($class); - if ($reflection->isAbstract()) { - SimpleTest::ignore($class); - } else { - $classes[] = $class; - } - } - } - return $classes; - } - - /** - * Builds a test suite from a class list. - * @param string $title Title of new group. - * @param array $classes Test classes. - * @return TestSuite Group loaded with the new - * test cases. - * @access public - */ - function createSuiteFromClasses($title, $classes) { - if (count($classes) == 0) { - $suite = new BadTestSuite($title, "No runnable test cases in [$title]"); - return $suite; - } - SimpleTest::ignoreParentsIfIgnored($classes); - $suite = new TestSuite($title); - foreach ($classes as $class) { - if (! SimpleTest::isIgnored($class)) { - $suite->add($class); - } - } - return $suite; - } -} - -/** - * This is a composite test class for combining - * test cases and other RunnableTest classes into - * a group test. - * @package SimpleTest - * @subpackage UnitTester - */ -class TestSuite { - private $label; - private $test_cases; - - /** - * Sets the name of the test suite. - * @param string $label Name sent at the start and end - * of the test. - * @access public - */ - function TestSuite($label = false) { - $this->label = $label; - $this->test_cases = array(); - } - - /** - * Accessor for the test name for subclasses. If the suite - * wraps a single test case the label defaults to the name of that test. - * @return string Name of the test. - * @access public - */ - function getLabel() { - if (! $this->label) { - return ($this->getSize() == 1) ? - get_class($this->test_cases[0]) : get_class($this); - } else { - return $this->label; - } - } - - /** - * Adds a test into the suite by instance or class. The class will - * be instantiated if it's a test suite. - * @param SimpleTestCase $test_case Suite or individual test - * case implementing the - * runnable test interface. - * @access public - */ - function add($test_case) { - if (! is_string($test_case)) { - $this->test_cases[] = $test_case; - } elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') { - $this->test_cases[] = new $test_case(); - } else { - $this->test_cases[] = $test_case; - } - } - - /** - * Builds a test suite from a library of test cases. - * The new suite is composed into this one. - * @param string $test_file File name of library with - * test case classes. - * @access public - */ - function addFile($test_file) { - $extractor = new SimpleFileLoader(); - $this->add($extractor->load($test_file)); - } - - /** - * Delegates to a visiting collector to add test - * files. - * @param string $path Path to scan from. - * @param SimpleCollector $collector Directory scanner. - * @access public - */ - function collect($path, $collector) { - $collector->collect($this, $path); - } - - /** - * Invokes run() on all of the held test cases, instantiating - * them if necessary. - * @param SimpleReporter $reporter Current test reporter. - * @access public - */ - function run($reporter) { - $reporter->paintGroupStart($this->getLabel(), $this->getSize()); - for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) { - if (is_string($this->test_cases[$i])) { - $class = $this->test_cases[$i]; - $test = new $class(); - $test->run($reporter); - unset($test); - } else { - $this->test_cases[$i]->run($reporter); - } - } - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - /** - * Number of contained test cases. - * @return integer Total count of cases in the group. - * @access public - */ - function getSize() { - $count = 0; - foreach ($this->test_cases as $case) { - if (is_string($case)) { - if (! SimpleTest::isIgnored($case)) { - $count++; - } - } else { - $count += $case->getSize(); - } - } - return $count; - } - - /** - * Test to see if a class is derived from the - * SimpleTestCase class. - * @param string $class Class name. - * @access public - */ - static function getBaseTestCase($class) { - while ($class = get_parent_class($class)) { - $class = strtolower($class); - if ($class == 'simpletestcase' || $class == 'testsuite') { - return $class; - } - } - return false; - } -} - -/** - * This is a failing group test for when a test suite hasn't - * loaded properly. - * @package SimpleTest - * @subpackage UnitTester - */ -class BadTestSuite { - private $label; - private $error; - - /** - * Sets the name of the test suite and error message. - * @param string $label Name sent at the start and end - * of the test. - * @access public - */ - function BadTestSuite($label, $error) { - $this->label = $label; - $this->error = $error; - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->label; - } - - /** - * Sends a single error to the reporter. - * @param SimpleReporter $reporter Current test reporter. - * @access public - */ - function run($reporter) { - $reporter->paintGroupStart($this->getLabel(), $this->getSize()); - $reporter->paintFail('Bad TestSuite [' . $this->getLabel() . - '] with error [' . $this->error . ']'); - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - /** - * Number of contained test cases. Always zero. - * @return integer Total count of cases in the group. - * @access public - */ - function getSize() { - return 0; - } -} -?> diff --git a/3rdparty/simpletest/tidy_parser.php b/3rdparty/simpletest/tidy_parser.php deleted file mode 100755 index 3d8b4b2ac7..0000000000 --- a/3rdparty/simpletest/tidy_parser.php +++ /dev/null @@ -1,382 +0,0 @@ -free(); - } - - /** - * Frees up any references so as to allow the PHP garbage - * collection from unset() to work. - */ - private function free() { - unset($this->page); - $this->forms = array(); - $this->labels = array(); - } - - /** - * This builder is only available if the 'tidy' extension is loaded. - * @return boolean True if available. - */ - function can() { - return extension_loaded('tidy'); - } - - /** - * Reads the raw content the page using HTML Tidy. - * @param $response SimpleHttpResponse Fetched response. - * @return SimplePage Newly parsed page. - */ - function parse($response) { - $this->page = new SimplePage($response); - $tidied = tidy_parse_string($input = $this->insertGuards($response->getContent()), - array('output-xml' => false, 'wrap' => '0', 'indent' => 'no'), - 'latin1'); - $this->walkTree($tidied->html()); - $this->attachLabels($this->widgets_by_id, $this->labels); - $this->page->setForms($this->forms); - $page = $this->page; - $this->free(); - return $page; - } - - /** - * Stops HTMLTidy stripping content that we wish to preserve. - * @param string The raw html. - * @return string The html with guard tags inserted. - */ - private function insertGuards($html) { - return $this->insertEmptyTagGuards($this->insertTextareaSimpleWhitespaceGuards($html)); - } - - /** - * Removes the extra content added during the parse stage - * in order to preserve content we don't want stripped - * out by HTMLTidy. - * @param string The raw html. - * @return string The html with guard tags removed. - */ - private function stripGuards($html) { - return $this->stripTextareaWhitespaceGuards($this->stripEmptyTagGuards($html)); - } - - /** - * HTML tidy strips out empty tags such as