diff --git a/.gitignore b/.gitignore index 0e3231b04b..eb2474a3f7 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ !/lib/plugins/popularity !/lib/plugins/revert !/lib/plugins/safefnrecode +!/lib/plugins/testing !/lib/plugins/usermanager !/lib/plugins/action.php !/lib/plugins/admin.php diff --git a/_test/README b/_test/README index 099290a0db..a4206f4893 100644 --- a/_test/README +++ b/_test/README @@ -1,84 +1,82 @@ --------------------------------------------------------------------------------- - Dokuwiki Unit Test Suite --------------------------------------------------------------------------------- -$Date: 2004/02/14 02:14:50 $ - -Credits: to the WACT team - http://www.phpwact.org, from whom the basis of -this test suite was stolen - --------------------------------------------------------------------------------- -INSTALLING & SETUP - -1. Grab a copy of the SimpleTest unit testing framework an extract somewhere - - http://www.lastcraft.com/simple_test.php - or - http://sourceforge.net/projects/simpletest - -2. Edit ./tests.ini - - - TEST_ENABLED - set to "1" to allow the test suite to be used - by vistors to your site. Generally best to leave as 0 for - a productive site - running tests alot will hammer the server - Note: you will still be able to run the tests from the command - line even when this is set to 0 - - - WEB_TEST_URL - this is for running "web tests" where SimpleTest - acts as a web browser and executes HTTP requests against pages. - Should point at your Dokuwiki URL e.g. - - http://localhost/dokuwiki - - - PROXY - if you're behind a proxy, specify it here - Note: username / password are optional e.g. - - http://proxyuser:proxypwd@proxy.yourdomain.com:8080 - - - REMOTE_TEST_URL - it's possible to run the full test suite - remotely (over HTTP) with some XML goodness. This should - point at the URL of the test suite you want to test - See the following URL for more info; - http://www.sitepoint.com/blogs/2004/06/15/simple-test-remote-testing/ - - - Simple Test - Update the library_path to point at the directory where you installed - Simple Test - --------------------------------------------------------------------------------- -RUNNING THE TESTS - -You can run the tests in three ways. From the command line: - - $ ./runtests.php -h - -Using a web browser; - - http://localhost/dokuwiki/_test/index.php - -As remote tests run on a remote serveri (specified in tests.ini with REMOTE_TEST_URL) and driven locally from the command line using; - - $ ./remotetests.php -h - - --------------------------------------------------------------------------------- -ADDING TESTS - -The test cases are kept in the './cases' directory in a directory structure -mirroring that of the Dokuwiki's - -Files with the extension .group.php are group tests (collections of -one or more seperate unit test files) - there should be one group -test per file in Dokuwiki's real directory. - -Individual tests files have the extension .test.php - -To add tests, create a .test.php file in the correct directory under ./cases -Probably best to use one of the existing scripts as a basis - -The test will not be executable via one of the test runners (see above). - -To add it to a group of tests, modify the corresponding .group.php file. - -One exception to the naming convention - files named .webtest.php and -.webgroup.php are run using SimpleTest's browser simulator. - +====== DokuWiki Test Suite ====== + +This is the test suit to automatically test various parts of DokuWiki. + +===== Requirements ===== + + * PHPUnit 3.6.10+ http://www.phpunit.de/ + * PHP 5.3+ http://www.php.net + +===== PHPUnit Installation ====== + +via PEAR: + + pear config-set auto_discover 1 + pear upgrade + pear install pear.phpunit.de/PHPUnit + +on Windows: + + FIXME + + +===== Running all Tests ===== + +Just change to the ''_test'' directory and run phpunit: + + cd _testing/ + phpunit + +PHPUnit will fail on some systems with a //headers already sent// error. +This is a known problem with PHPUnit, the error can be avoided by passing the +'--stderr' flag to phpunit: + + phpunit --stderr + +On windows you may have to enable OpenSSL support for https tests. +Some of them point to httpclient_http.tests.php on the failure. +To enable HTTPS support copy the ''libeay32.dll'' and ''ssleay32.dll'' to your ''windows\system32'' folder +and add the following line to your php.ini in the extension section: + +extension=php_openssl.dll + + +===== Running selected Tests ===== + +You can run a single test file by providing it as an argument to phpunit: + + phpunit --stderr tests/inc/common_cleanText.test.php + +You can also use groups to exclude certain test from running. For example use +the following command to avoid long running test or tests accessing the +Internet. + + phpunit --stderr --exclude-group slow,internet + +===== Create new Tests ===== + +To create a test for DokuWiki, create a *.test.php file within the tests/ +folder. Please respect the folder structure and naming convention. Inside the +file, implement a class, extending 'DokuWikiTest'. Every method, starting +with 'test' will be called as a test (e.g. 'testIfThisIsValid'); + + +===== TODO for the test framework ===== + + * test cross platform compatibility: especially test windows + * update http://www.dokuwiki.org/devel:unittesting + * optional: add helper methods to TestRequest for easy form submission + * createForm(), ... + * check PHP Unit test_helpers https://github.com/sebastianbergmann/php-test-helpers + + +===== Migration Protocol ===== + +The following tests were not migrated: + + * inc/indexer_idx_indexlengths (fs dependencies) + * inc/mail_send (integration test) + * inc/parser/parser_formatting + * inc/parser/xhtml_htmlphp (runkit) + * inc/parser/xhtml_links + diff --git a/_test/bootstrap.php b/_test/bootstrap.php new file mode 100644 index 0000000000..6c3d6aaa88 --- /dev/null +++ b/_test/bootstrap.php @@ -0,0 +1,107 @@ + '?id=', + 'REQUEST_METHOD' => 'GET', + 'CONTENT_TYPE' => '', + 'CONTENT_LENGTH' => '', + 'SCRIPT_NAME' => '/doku.php', + 'REQUEST_URI' => '/doku.php?id=', + 'DOCUMENT_URI' => '/doku.php', + 'DOCUMENT_ROOT' => DOKU_INC, + 'SERVER_PROTOCOL' => 'HTTP/1.1', + 'SERVER_SOFTWARE' => 'nginx/0.7.67', + 'REMOTE_ADDR' => '87.142.120.6', + 'REMOTE_PORT' => '21418', + 'SERVER_ADDR' => '46.38.241.24', + 'SERVER_PORT' => '443', + 'SERVER_NAME' => 'wiki.example.com', + 'REDIRECT_STATUS' => '200', + 'SCRIPT_FILENAME' => DOKU_INC.'doku.php', + 'HTTP_HOST' => 'wiki.example.com', + 'HTTP_USER_AGENT' => 'Mozilla/5.0 (X11; OpenBSD amd64; rv:11.0) Gecko/20100101 Firefox/11.0', + 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5', + 'HTTP_ACCEPT_ENCODING' => 'gzip, deflate', + 'HTTP_CONNECTION' => 'keep-alive', + 'HTTP_CACHE_CONTROL' => 'max-age=0', + 'PHP_SELF' => '/doku.php', + 'REQUEST_TIME' => time(), +); + +// create temp directories +mkdir(TMP_DIR); + +// cleanup dir after exit +if (getenv('PRESERVE_TMP') != 'true') { + register_shutdown_function(function() { + TestUtils::rdelete(TMP_DIR); + }); +} else { + echo ">>>> Preserving temporary directory: ".TMP_DIR."\n"; +} + +// populate default dirs +TestUtils::rcopy(TMP_DIR, DOKU_INC.'/conf'); +TestUtils::rcopy(TMP_DIR, dirname(__FILE__).'/conf'); +TestUtils::rcopy(TMP_DIR, dirname(__FILE__).'/data'); + +// disable all non-default plugins by default +$dh = dir(DOKU_INC.'lib/plugins/'); +while (false !== ($entry = $dh->read())) { + if ($entry == '.' || $entry == '..') { + continue; + } + + if (!is_dir(DOKU_INC.'lib/plugins/'.$entry)) { + continue; + } + + if (!in_array($entry, $default_plugins)) { + // disable this plugin + TestUtils::fappend(DOKU_CONF.'plugins.local.php', "\$plugins['$entry'] = 0;\n"); + } +} +$dh->close(); + +// load dw +require_once(DOKU_INC.'inc/init.php'); + diff --git a/_test/cases/inc/DifferenceEngine.test.php b/_test/cases/inc/DifferenceEngine.test.php deleted file mode 100644 index aa1756114b..0000000000 --- a/_test/cases/inc/DifferenceEngine.test.php +++ /dev/null @@ -1,31 +0,0 @@ -assertEqual($idf->format($df), '@@ ' . $lang['line'] . - ' -1 +1 @@ ' . $lang['deleted'] . - ' ' . $lang['created'] . - ' - -example example2 -'); - $this->assertEqual($tdf->format($df), - '' . $lang['line'] . ' 1: -' . $lang['line'] . ' 1: - --example+example example2 -'); - } -} -//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/auth_aclcheck.test.php b/_test/cases/inc/auth_aclcheck.test.php deleted file mode 100644 index ff092c2de4..0000000000 --- a/_test/cases/inc/auth_aclcheck.test.php +++ /dev/null @@ -1,231 +0,0 @@ -assertEqual(auth_aclcheck('page', '',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); - - // user with no matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); - - // user with matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_UPLOAD); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); - - // super user - $this->assertEqual(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); - } - - function test_restricted_ropage(){ - global $conf; - global $AUTH_ACL; - $conf['superuser'] = 'john'; - $conf['useacl'] = 1; - - $AUTH_ACL = array( - '* @ALL 0', - '* @user 8', - 'namespace:page @user 1', - ); - - // anonymous user - $this->assertEqual(auth_aclcheck('page', '',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); - - // user with no matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); - - // user with matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_READ); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); - - // super user - $this->assertEqual(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); - } - - function test_aclexample(){ - global $conf; - global $AUTH_ACL; - $conf['superuser'] = 'john'; - $conf['useacl'] = 1; - - $AUTH_ACL = array( - '* @ALL 4', - '* bigboss 16', - 'start @ALL 1', - 'marketing:* @marketing 8', - 'devel:* @ALL 0', - 'devel:* @devel 8', - 'devel:* bigboss 16', - 'devel:funstuff bigboss 0', - 'devel:* @marketing 1', - 'devel:marketing @marketing 2', - ); - - - $this->assertEqual(auth_aclcheck('page', '' ,array()) , AUTH_CREATE); - $this->assertEqual(auth_aclcheck('page', 'bigboss' ,array('foo')) , AUTH_DELETE); - $this->assertEqual(auth_aclcheck('page', 'jill' ,array('marketing')) , AUTH_CREATE); - $this->assertEqual(auth_aclcheck('page', 'jane' ,array('devel')) , AUTH_CREATE); - - $this->assertEqual(auth_aclcheck('start', '' ,array()) , AUTH_READ); - $this->assertEqual(auth_aclcheck('start', 'bigboss' ,array('foo')) , AUTH_READ); - $this->assertEqual(auth_aclcheck('start', 'jill' ,array('marketing')) , AUTH_READ); - $this->assertEqual(auth_aclcheck('start', 'jane' ,array('devel')) , AUTH_READ); - - $this->assertEqual(auth_aclcheck('marketing:page', '' ,array()) , AUTH_CREATE); - $this->assertEqual(auth_aclcheck('marketing:page', 'bigboss' ,array('foo')) , AUTH_DELETE); - $this->assertEqual(auth_aclcheck('marketing:page', 'jill' ,array('marketing')) , AUTH_UPLOAD); - $this->assertEqual(auth_aclcheck('marketing:page', 'jane' ,array('devel')) , AUTH_CREATE); - - - $this->assertEqual(auth_aclcheck('devel:page', '' ,array()) , AUTH_NONE); - $this->assertEqual(auth_aclcheck('devel:page', 'bigboss' ,array('foo')) , AUTH_DELETE); - $this->assertEqual(auth_aclcheck('devel:page', 'jill' ,array('marketing')) , AUTH_READ); - $this->assertEqual(auth_aclcheck('devel:page', 'jane' ,array('devel')) , AUTH_UPLOAD); - - $this->assertEqual(auth_aclcheck('devel:funstuff', '' ,array()) , AUTH_NONE); - $this->assertEqual(auth_aclcheck('devel:funstuff', 'bigboss' ,array('foo')) , AUTH_NONE); - $this->assertEqual(auth_aclcheck('devel:funstuff', 'jill' ,array('marketing')) , AUTH_READ); - $this->assertEqual(auth_aclcheck('devel:funstuff', 'jane' ,array('devel')) , AUTH_UPLOAD); - - $this->assertEqual(auth_aclcheck('devel:marketing', '' ,array()) , AUTH_NONE); - $this->assertEqual(auth_aclcheck('devel:marketing', 'bigboss' ,array('foo')) , AUTH_DELETE); - $this->assertEqual(auth_aclcheck('devel:marketing', 'jill' ,array('marketing')) , AUTH_EDIT); - $this->assertEqual(auth_aclcheck('devel:marketing', 'jane' ,array('devel')) , AUTH_UPLOAD); - - } - - function test_multiadmin_restricted(){ - global $conf; - global $AUTH_ACL; - $conf['superuser'] = 'john,@admin,doe,@roots'; - $conf['useacl'] = 1; - - $AUTH_ACL = array( - '* @ALL 0', - '* @user 8', - ); - - // anonymous user - $this->assertEqual(auth_aclcheck('page', '',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); - - // user with no matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); - - // user with matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_UPLOAD); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); - - // super user john - $this->assertEqual(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); - - // super user doe - $this->assertEqual(auth_aclcheck('page', 'doe',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','doe',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'doe',array('foo')), AUTH_ADMIN); - - // user with matching admin group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','admin')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','admin')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','admin')), AUTH_ADMIN); - - // user with matching another admin group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','roots')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','roots')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','roots')), AUTH_ADMIN); - } - - function test_multiadmin_restricted_ropage(){ - global $conf; - global $AUTH_ACL; - $conf['superuser'] = 'john,@admin,doe,@roots'; - $conf['useacl'] = 1; - - $AUTH_ACL = array( - '* @ALL 0', - '* @user 8', - 'namespace:page @user 1', - ); - - // anonymous user - $this->assertEqual(auth_aclcheck('page', '',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','',array()), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); - - // user with no matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); - - // user with matching group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_READ); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); - - // super user john - $this->assertEqual(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); - - // super user doe - $this->assertEqual(auth_aclcheck('page', 'doe',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','doe',array('foo')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'doe',array('foo')), AUTH_ADMIN); - - // user with matching admin group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','admin')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','admin')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','admin')), AUTH_ADMIN); - - // user with matching another admin group - $this->assertEqual(auth_aclcheck('page', 'jill',array('foo','roots')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:page','jill',array('foo','roots')), AUTH_ADMIN); - $this->assertEqual(auth_aclcheck('namespace:*', 'jill',array('foo','roots')), AUTH_ADMIN); - } - -} - -//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/auth_admincheck.test.php b/_test/cases/inc/auth_admincheck.test.php deleted file mode 100644 index 2a420ffd45..0000000000 --- a/_test/cases/inc/auth_admincheck.test.php +++ /dev/null @@ -1,132 +0,0 @@ -oldauth = $auth; - parent::setup(); - } - - function setSensitive() { - global $auth; - $auth = new auth_basic; - } - - function setInSensitive() { - global $auth; - $auth = new auth_admin_test_AuthInSensitive; - } - - function teardown() { - global $auth; - global $conf; - global $AUTH_ACL; - unset($conf); - unset($AUTH_ACL); - $auth = $this->oldauth; - parent::teardown(); - } - - function test_ismanager_insensitive(){ - $this->setInSensitive(); - global $conf; - $conf['superuser'] = 'john,@admin,@Mötly Görls, Dörte'; - $conf['manager'] = 'john,@managers,doe, @Mötly Böys, Dänny'; - - // anonymous user - $this->assertEqual(auth_ismanager('jill', null,false), false); - - // admin or manager users - $this->assertEqual(auth_ismanager('john', null,false), true); - $this->assertEqual(auth_ismanager('doe', null,false), true); - - $this->assertEqual(auth_ismanager('dörte', null,false), true); - $this->assertEqual(auth_ismanager('dänny', null,false), true); - - // admin or manager groups - $this->assertEqual(auth_ismanager('jill', array('admin'),false), true); - $this->assertEqual(auth_ismanager('jill', array('managers'),false), true); - - $this->assertEqual(auth_ismanager('jill', array('mötly görls'),false), true); - $this->assertEqual(auth_ismanager('jill', array('mötly böys'),false), true); - } - - function test_isadmin_insensitive(){ - $this->setInSensitive(); - global $conf; - $conf['superuser'] = 'john,@admin,doe,@roots'; - - // anonymous user - $this->assertEqual(auth_ismanager('jill', null,true), false); - - // admin user - $this->assertEqual(auth_ismanager('john', null,true), true); - $this->assertEqual(auth_ismanager('doe', null,true), true); - - // admin groups - $this->assertEqual(auth_ismanager('jill', array('admin'),true), true); - $this->assertEqual(auth_ismanager('jill', array('roots'),true), true); - $this->assertEqual(auth_ismanager('john', array('admin'),true), true); - $this->assertEqual(auth_ismanager('doe', array('admin'),true), true); - } - - function test_ismanager_sensitive(){ - $this->setSensitive(); - global $conf; - $conf['superuser'] = 'john,@admin,@Mötly Görls, Dörte'; - $conf['manager'] = 'john,@managers,doe, @Mötly Böys, Dänny'; - - // anonymous user - $this->assertEqual(auth_ismanager('jill', null,false), false); - - // admin or manager users - $this->assertEqual(auth_ismanager('john', null,false), true); - $this->assertEqual(auth_ismanager('doe', null,false), true); - - $this->assertEqual(auth_ismanager('dörte', null,false), false); - $this->assertEqual(auth_ismanager('dänny', null,false), false); - - // admin or manager groups - $this->assertEqual(auth_ismanager('jill', array('admin'),false), true); - $this->assertEqual(auth_ismanager('jill', array('managers'),false), true); - - $this->assertEqual(auth_ismanager('jill', array('mötly görls'),false), false); - $this->assertEqual(auth_ismanager('jill', array('mötly böys'),false), false); - } - - function test_isadmin_sensitive(){ - $this->setSensitive(); - global $conf; - $conf['superuser'] = 'john,@admin,doe,@roots'; - - // anonymous user - $this->assertEqual(auth_ismanager('jill', null,true), false); - - // admin user - $this->assertEqual(auth_ismanager('john', null,true), true); - $this->assertEqual(auth_ismanager('Doe', null,true), false); - - // admin groups - $this->assertEqual(auth_ismanager('jill', array('admin'),true), true); - $this->assertEqual(auth_ismanager('jill', array('roots'),true), true); - $this->assertEqual(auth_ismanager('john', array('admin'),true), true); - $this->assertEqual(auth_ismanager('doe', array('admin'),true), true); - $this->assertEqual(auth_ismanager('Doe', array('admin'),true), true); - } - -} - -//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/common_cleanText.test.php b/_test/cases/inc/common_cleanText.test.php deleted file mode 100644 index 936ed1d769..0000000000 --- a/_test/cases/inc/common_cleanText.test.php +++ /dev/null @@ -1,34 +0,0 @@ -assertEqual($unix,cleanText($unix)); - } - - function test_win(){ - $unix = 'one - two - - three'; - $win = 'one - two - - three'; - - $this->assertEqual(bin2hex($unix),'6f6e650a2020202020202020202020202020202074776f0a0a202020202020202020202020202020207468726565'); - $this->assertEqual(bin2hex($win),'6f6e650d0a2020202020202020202020202020202074776f0d0a0d0a202020202020202020202020202020207468726565'); - $this->assertNotEqual($unix,$win); - $this->assertEqual($unix,cleanText($win)); - } -} - -//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/html_hilight.test.php b/_test/cases/inc/html_hilight.test.php deleted file mode 100644 index cc5579c710..0000000000 --- a/_test/cases/inc/html_hilight.test.php +++ /dev/null @@ -1,104 +0,0 @@ -assertPattern( - '/Foo bar<\/span> Foo/', - html_hilight($html,'bar') - ); - } - - function testHighlightTwoWords() { - $html = 'Foo bar Foo php Foo'; - $this->assertPattern( - '/Foo bar<\/span> Foo php<\/span> Foo/', - html_hilight($html,array('bar','php')) - ); - } - - function testHighlightTwoWordsHtml() { - $html = 'Foo bar Foo php Foo'; - $this->assertPattern( - '/Foo bar<\/span><\/b> Foo<\/i> php<\/span> Foo/', - html_hilight($html,array('bar','php')) - ); - } - - function testNoHighlight() { - $html = 'Foo bar Foo'; - $this->assertPattern( - '/Foo bar Foo/', - html_hilight($html,'php') - ); - } - - function testHighlightPHP() { - $html = 'Foo $_GET[\'bar\'] Foo'; - $this->assertEqual( - 'Foo $_GET[\'bar\'] Foo', - html_hilight($html,'$_GET[\'bar\']') - ); - } - - function testMatchAttribute() { - $html = 'Foo bar Foo'; - $this->assertPattern( - '/Foo bar<\/b> Foo/', - html_hilight($html,'class="x"') - ); - } - - function testMatchAttributeWord() { - $html = 'Foo bar Foo'; - $this->assertEqual( - 'Foo bar Foo', - html_hilight($html,'class="x">bar') - ); - } - - function testRegexInjection() { - $html = 'Foo bar Foo'; - $this->assertPattern( - '/Foo bar Foo/', - html_hilight($html,'*') - ); - } - - function testRegexInjectionSlash() { - $html = 'Foo bar Foo'; - $this->assertPattern( - '/Foo bar Foo/', - html_hilight($html,'x/') - ); - } - -} - diff --git a/_test/cases/inc/indexer_idx_indexlengths.test.php b/_test/cases/inc/indexer_idx_indexlengths.test.php deleted file mode 100644 index a0f7c9224f..0000000000 --- a/_test/cases/inc/indexer_idx_indexlengths.test.php +++ /dev/null @@ -1,60 +0,0 @@ -assertIdentical($result, $ref); - } - - /** - * Test the function with an array of values - */ - function test_moreWords() { - global $conf; - $filter = array( 4 => array('test'), 8 => array('dokuwiki'), 7 => array('powered')); - // more words should return the indexes - $ref = array(4, 7, 8); - sort($ref); - $result = idx_indexLengths(&$filter); - sort($result); - $this->assertIdentical($result, $ref); - } - - /** - * Test a minimal value in case of wildcard search - */ - function test_minValue() { - global $conf; - $filter = 5; - // construction of the list of the index to compare - $dir = @opendir($conf['indexdir']); - $ref = array(); - while (($f = readdir($dir)) !== false) { - if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){ - $i = substr($f,1,-4); - if (is_numeric($i) && $i >= $filter) - $ref[] = (int)$i; - } - } - closedir($dir); - sort($ref); - $result = idx_indexLengths(&$filter); - sort($result); - $this->assertIdentical($result, $ref); - } -} - - -//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/mail_send.php b/_test/cases/inc/mail_send.php deleted file mode 100644 index e41c501fe0..0000000000 --- a/_test/cases/inc/mail_send.php +++ /dev/null @@ -1,49 +0,0 @@ -', - 'dokuwiki1@spam.la, dokuwiki2@spam.la', - 'Test User 1 , Test User 2 ' - ); - - - $run = 0; - foreach($addr as $ad){ - $run++; - $data = array( - 'to' => $ad, - 'subject' => 'mailtest 1-'.$run, - 'body' => "Mailtest run 1-$run using to: $ad from:", - ); - $this->assertTrue((bool) _mail_send_action($data)); - - $data = array( - 'to' => $ad, - 'from' => 'dokuwiki1@spam.la', - 'subject' => 'mailtest 2-'.$run, - 'body' => "Mailtest run 2-$run using to: $ad from: dokuwiki1@spam.la", - ); - $this->assertTrue((bool) _mail_send_action($data)); - - $data = array( - 'to' => $ad, - 'from' => '"Foo Bar" ', - 'subject' => 'mailtest 3-'.$run, - 'body' => "Mailtest run 3-$run using to: $ad from: \"Foo Bar\" ", - ); - $this->assertTrue((bool) _mail_send_action($data)); - } - } - -} -//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/parser/lexer.group.php b/_test/cases/inc/parser/lexer.group.php deleted file mode 100644 index 6e9ef0742d..0000000000 --- a/_test/cases/inc/parser/lexer.group.php +++ /dev/null @@ -1,21 +0,0 @@ -GroupTest('LexerGroupTest'); - $this->addTestFile(dirname(__FILE__).'/lexer.test.php'); - } - -} - -?> diff --git a/_test/cases/inc/parser/lexer.test.php b/_test/cases/inc/parser/lexer.test.php deleted file mode 100644 index e802277f1e..0000000000 --- a/_test/cases/inc/parser/lexer.test.php +++ /dev/null @@ -1,625 +0,0 @@ -UnitTestCase(); - } - function testNoPatterns() { - $regex = new Doku_LexerParallelRegex(false); - $this->assertFalse($regex->match("Hello", $match)); - $this->assertEqual($match, ""); - } - function testNoSubject() { - $regex = new Doku_LexerParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("", $match)); - $this->assertEqual($match, ""); - } - function testMatchAll() { - $regex = new Doku_LexerParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("Hello", $match)); - $this->assertEqual($match, "Hello"); - } - function testCaseSensitive() { - $regex = new Doku_LexerParallelRegex(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 Doku_LexerParallelRegex(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 Doku_LexerParallelRegex(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 Doku_LexerParallelRegex(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"); - } - function testMatchMultipleWithLookaheadNot() { - $regex = new Doku_LexerParallelRegex(true); - $regex->addPattern("abc"); - $regex->addPattern("ABC"); - $regex->addPattern("a(?!\n).{1}"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - $this->assertTrue($regex->match("a\nab", $match)); - $this->assertEqual($match, "ab"); - $this->assertFalse($regex->match("Hello", $match)); - } - function testMatchSetOptionCaseless() { - $regex = new Doku_LexerParallelRegex(true); - $regex->addPattern("a(?i)b(?i)c"); - $this->assertTrue($regex->match("aBc", $match)); - $this->assertEqual($match, "aBc"); - } - function testMatchSetOptionUngreedy() { - $regex = new Doku_LexerParallelRegex(true); - $regex->addPattern("(?U)\w+"); - $this->assertTrue($regex->match("aaaaaa", $match)); - $this->assertEqual($match, "a"); - } - function testMatchLookaheadEqual() { - $regex = new Doku_LexerParallelRegex(true); - $regex->addPattern("\w(?=c)"); - $this->assertTrue($regex->match("xbyczd", $match)); - $this->assertEqual($match, "y"); - } - function testMatchLookaheadNot() { - $regex = new Doku_LexerParallelRegex(true); - $regex->addPattern("\w(?!b|c)"); - $this->assertTrue($regex->match("xbyczd", $match)); - $this->assertEqual($match, "b"); - } - function testMatchLookbehindEqual() { - $regex = new Doku_LexerParallelRegex(true); - $regex->addPattern("(?<=c)\w"); - $this->assertTrue($regex->match("xbyczd", $match)); - $this->assertEqual($match, "z"); - } - function testMatchLookbehindNot() { - $regex = new Doku_LexerParallelRegex(true); - $regex->addPattern("(?assertTrue($regex->match("xbyczd", $match)); - $this->assertEqual($match, "c"); - } -} - - -class TestOfLexerStateStack extends UnitTestCase { - function TestOfLexerStateStack() { - $this->UnitTestCase(); - } - function testStartState() { - $stack = new Doku_LexerStateStack("one"); - $this->assertEqual($stack->getCurrent(), "one"); - } - function testExhaustion() { - $stack = new Doku_LexerStateStack("one"); - $this->assertFalse($stack->leave()); - } - function testStateMoves() { - $stack = new Doku_LexerStateStack("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 TestParser() { - } - function accept() { - } - function a() { - } - function b() { - } -} -Mock::generate('TestParser'); - -class TestOfLexer extends UnitTestCase { - function TestOfLexer() { - $this->UnitTestCase(); - } - function testNoPatterns() { - $handler = new MockTestParser($this); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $lexer = new Doku_Lexer($handler); - $this->assertFalse($lexer->parse("abcdef")); - } - function testEmptyPage() { - $handler = new MockTestParser($this); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $lexer = new Doku_Lexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("")); - } - function testSinglePattern() { - $handler = new MockTestParser($this); - $handler->expectArgumentsAt(0, "accept", array("aaa", DOKU_LEXER_MATCHED, 0)); - $handler->expectArgumentsAt(1, "accept", array("x", DOKU_LEXER_UNMATCHED, 3)); - $handler->expectArgumentsAt(2, "accept", array("a", DOKU_LEXER_MATCHED, 4)); - $handler->expectArgumentsAt(3, "accept", array("yyy", DOKU_LEXER_UNMATCHED, 5)); - $handler->expectArgumentsAt(4, "accept", array("a", DOKU_LEXER_MATCHED, 8)); - $handler->expectArgumentsAt(5, "accept", array("x", DOKU_LEXER_UNMATCHED, 9)); - $handler->expectArgumentsAt(6, "accept", array("aaa", DOKU_LEXER_MATCHED, 10)); - $handler->expectArgumentsAt(7, "accept", array("z", DOKU_LEXER_UNMATCHED, 13)); - $handler->expectCallCount("accept", 8); - $handler->setReturnValue("accept", true); - $lexer = new Doku_Lexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); - $handler->tally(); - } - function testMultiplePattern() { - $handler = new MockTestParser($this); - $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); - $positions = array(0,1,2,3,5,6,7,8,14,15); - for ($i = 0; $i < count($target); $i++) { - $handler->expectArgumentsAt($i, "accept", array($target[$i], '*', $positions[$i])); - } - $handler->expectCallCount("accept", count($target)); - $handler->setReturnValue("accept", true); - $lexer = new Doku_Lexer($handler); - $lexer->addPattern("a+"); - $lexer->addPattern("b+"); - $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); - $handler->tally(); - } -} - -class TestOfLexerModes extends UnitTestCase { - function TestOfLexerModes() { - $this->UnitTestCase(); - } - function testIsolatedPattern() { - $handler = new MockTestParser($this); - $handler->expectArgumentsAt(0, "a", array("a", DOKU_LEXER_MATCHED,0)); - $handler->expectArgumentsAt(1, "a", array("b", DOKU_LEXER_UNMATCHED,1)); - $handler->expectArgumentsAt(2, "a", array("aa", DOKU_LEXER_MATCHED,2)); - $handler->expectArgumentsAt(3, "a", array("bxb", DOKU_LEXER_UNMATCHED,4)); - $handler->expectArgumentsAt(4, "a", array("aaa", DOKU_LEXER_MATCHED,7)); - $handler->expectArgumentsAt(5, "a", array("x", DOKU_LEXER_UNMATCHED,10)); - $handler->expectArgumentsAt(6, "a", array("aaaa", DOKU_LEXER_MATCHED,11)); - $handler->expectArgumentsAt(7, "a", array("x", DOKU_LEXER_UNMATCHED,15)); - $handler->expectCallCount("a", 8); - $handler->setReturnValue("a", true); - $lexer = new Doku_Lexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); - $handler->tally(); - } - function testModeChange() { - $handler = new MockTestParser($this); - $handler->expectArgumentsAt(0, "a", array("a", DOKU_LEXER_MATCHED,0)); - $handler->expectArgumentsAt(1, "a", array("b", DOKU_LEXER_UNMATCHED,1)); - $handler->expectArgumentsAt(2, "a", array("aa", DOKU_LEXER_MATCHED,2)); - $handler->expectArgumentsAt(3, "a", array("b", DOKU_LEXER_UNMATCHED,4)); - $handler->expectArgumentsAt(4, "a", array("aaa", DOKU_LEXER_MATCHED,5)); - $handler->expectArgumentsAt(0, "b", array(":", DOKU_LEXER_ENTER,8)); - $handler->expectArgumentsAt(1, "b", array("a", DOKU_LEXER_UNMATCHED,9)); - $handler->expectArgumentsAt(2, "b", array("b", DOKU_LEXER_MATCHED, 10)); - $handler->expectArgumentsAt(3, "b", array("a", DOKU_LEXER_UNMATCHED,11)); - $handler->expectArgumentsAt(4, "b", array("bb", DOKU_LEXER_MATCHED,12)); - $handler->expectArgumentsAt(5, "b", array("a", DOKU_LEXER_UNMATCHED,14)); - $handler->expectArgumentsAt(6, "b", array("bbb", DOKU_LEXER_MATCHED,15)); - $handler->expectArgumentsAt(7, "b", array("a", DOKU_LEXER_UNMATCHED,18)); - $handler->expectCallCount("a", 5); - $handler->expectCallCount("b", 8); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $lexer = new Doku_Lexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern(":", "a", "b"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); - $handler->tally(); - } - function testNesting() { - $handler = new MockTestParser($this); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectArgumentsAt(0, "a", array("aa", DOKU_LEXER_MATCHED,0)); - $handler->expectArgumentsAt(1, "a", array("b", DOKU_LEXER_UNMATCHED,2)); - $handler->expectArgumentsAt(2, "a", array("aa", DOKU_LEXER_MATCHED,3)); - $handler->expectArgumentsAt(3, "a", array("b", DOKU_LEXER_UNMATCHED,5)); - $handler->expectArgumentsAt(0, "b", array("(", DOKU_LEXER_ENTER,6)); - $handler->expectArgumentsAt(1, "b", array("bb", DOKU_LEXER_MATCHED,7)); - $handler->expectArgumentsAt(2, "b", array("a", DOKU_LEXER_UNMATCHED,9)); - $handler->expectArgumentsAt(3, "b", array("bb", DOKU_LEXER_MATCHED,10)); - $handler->expectArgumentsAt(4, "b", array(")", DOKU_LEXER_EXIT,12)); - $handler->expectArgumentsAt(4, "a", array("aa", DOKU_LEXER_MATCHED,13)); - $handler->expectArgumentsAt(5, "a", array("b", DOKU_LEXER_UNMATCHED,15)); - $handler->expectCallCount("a", 6); - $handler->expectCallCount("b", 5); - $lexer = new Doku_Lexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern("(", "a", "b"); - $lexer->addPattern("b+", "b"); - $lexer->addExitPattern(")", "b"); - $this->assertTrue($lexer->parse("aabaab(bbabb)aab")); - $handler->tally(); - } - function testSingular() { - $handler = new MockTestParser($this); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectArgumentsAt(0, "a", array("aa", DOKU_LEXER_MATCHED,0)); - $handler->expectArgumentsAt(1, "a", array("aa", DOKU_LEXER_MATCHED,3)); - $handler->expectArgumentsAt(2, "a", array("xx", DOKU_LEXER_UNMATCHED,5)); - $handler->expectArgumentsAt(3, "a", array("xx", DOKU_LEXER_UNMATCHED,10)); - $handler->expectArgumentsAt(0, "b", array("b", DOKU_LEXER_SPECIAL,2)); - $handler->expectArgumentsAt(1, "b", array("bbb", DOKU_LEXER_SPECIAL,7)); - $handler->expectCallCount("a", 4); - $handler->expectCallCount("b", 2); - $lexer = new Doku_Lexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addSpecialPattern("b+", "a", "b"); - $this->assertTrue($lexer->parse("aabaaxxbbbxx")); - $handler->tally(); - } - function testUnwindTooFar() { - $handler = new MockTestParser($this); - $handler->setReturnValue("a", true); - $handler->expectArgumentsAt(0, "a", array("aa", DOKU_LEXER_MATCHED,0)); - $handler->expectArgumentsAt(1, "a", array(")", DOKU_LEXER_EXIT,2)); - $handler->expectCallCount("a", 2); - $lexer = new Doku_Lexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addExitPattern(")", "a"); - $this->assertFalse($lexer->parse("aa)aa")); - $handler->tally(); - } -} - -class TestOfLexerHandlers extends UnitTestCase { - function TestOfLexerHandlers() { - $this->UnitTestCase(); - } - function testModeMapping() { - $handler = new MockTestParser($this); - $handler->setReturnValue("a", true); - $handler->expectArgumentsAt(0, "a", array("aa", DOKU_LEXER_MATCHED,0)); - $handler->expectArgumentsAt(1, "a", array("(", DOKU_LEXER_ENTER,2)); - $handler->expectArgumentsAt(2, "a", array("bb", DOKU_LEXER_MATCHED,3)); - $handler->expectArgumentsAt(3, "a", array("a", DOKU_LEXER_UNMATCHED,5)); - $handler->expectArgumentsAt(4, "a", array("bb", DOKU_LEXER_MATCHED,6)); - $handler->expectArgumentsAt(5, "a", array(")", DOKU_LEXER_EXIT,8)); - $handler->expectArgumentsAt(6, "a", array("b", DOKU_LEXER_UNMATCHED,9)); - $handler->expectCallCount("a", 7); - $lexer = new Doku_Lexer($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")); - $handler->tally(); - } -} - -class TestParserByteIndex { - - function TestParserByteIndex() {} - - function ignore() {} - - function caught() {} -} - -Mock::generate('TestParserByteIndex'); - -class TestOfLexerByteIndices extends UnitTestCase { - - function TestOfLexerByteIndices() { - $this->UnitTestCase(); - } - - function testIndex() { - $doc = "aaabcdeee"; - - $handler = new MockTestParserByteIndex($this); - $handler->setReturnValue("ignore", true); - $handler->setReturnValue("caught", true); - - $handler->expectArgumentsAt( - 0, - "caught", - array("", DOKU_LEXER_ENTER, strpos($doc,'')) - ); - $handler->expectArgumentsAt( - 1, - "caught", - array("b", DOKU_LEXER_SPECIAL, strpos($doc,'b')) - ); - $handler->expectArgumentsAt( - 2, - "caught", - array("c", DOKU_LEXER_MATCHED, strpos($doc,'c')) - ); - $handler->expectArgumentsAt( - 3, - "caught", - array("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d')) - ); - $handler->expectArgumentsAt( - 4, - "caught", - array("", DOKU_LEXER_EXIT, strpos($doc,'')) - ); - $handler->expectCallCount("caught", 5); - - $lexer = new Doku_Lexer($handler, "ignore"); - $lexer->addEntryPattern("", "ignore", "caught"); - $lexer->addExitPattern("", "caught"); - $lexer->addSpecialPattern('b','caught','special'); - $lexer->mapHandler('special','caught'); - $lexer->addPattern('c','caught'); - - $this->assertTrue($lexer->parse($doc)); - $handler->tally(); - } - - function testIndexLookaheadEqual() { - $doc = "aaabcdeee"; - - $handler = new MockTestParserByteIndex($this); - $handler->setReturnValue("ignore", true); - $handler->setReturnValue("caught", true); - - $handler->expectArgumentsAt( - 0, - "caught", - array("", DOKU_LEXER_ENTER, strpos($doc,'')) - ); - $handler->expectArgumentsAt( - 1, - "caught", - array("b", DOKU_LEXER_SPECIAL, strpos($doc,'b')) - ); - $handler->expectArgumentsAt( - 2, - "caught", - array("c", DOKU_LEXER_MATCHED, strpos($doc,'c')) - ); - $handler->expectArgumentsAt( - 3, - "caught", - array("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d')) - ); - $handler->expectArgumentsAt( - 4, - "caught", - array("", DOKU_LEXER_EXIT, strpos($doc,'')) - ); - $handler->expectCallCount("caught", 5); - - $lexer = new Doku_Lexer($handler, "ignore"); - $lexer->addEntryPattern('(?=.*)', "ignore", "caught"); - $lexer->addExitPattern("", "caught"); - $lexer->addSpecialPattern('b','caught','special'); - $lexer->mapHandler('special','caught'); - $lexer->addPattern('c','caught'); - - $this->assertTrue($lexer->parse($doc)); - $handler->tally(); - } - - function testIndexLookaheadNotEqual() { - $doc = "aaabcdeee"; - - $handler = new MockTestParserByteIndex($this); - $handler->setReturnValue("ignore", true); - $handler->setReturnValue("caught", true); - - $handler->expectArgumentsAt( - 0, - "caught", - array("", DOKU_LEXER_ENTER, strpos($doc,'')) - ); - $handler->expectArgumentsAt( - 1, - "caught", - array("b", DOKU_LEXER_SPECIAL, strpos($doc,'b')) - ); - $handler->expectArgumentsAt( - 2, - "caught", - array("c", DOKU_LEXER_MATCHED, strpos($doc,'c')) - ); - $handler->expectArgumentsAt( - 3, - "caught", - array("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d')) - ); - $handler->expectArgumentsAt( - 4, - "caught", - array("", DOKU_LEXER_EXIT, strpos($doc,'')) - ); - $handler->expectCallCount("caught", 5); - - $lexer = new Doku_Lexer($handler, "ignore"); - $lexer->addEntryPattern('(?!foo)', "ignore", "caught"); - $lexer->addExitPattern("", "caught"); - $lexer->addSpecialPattern('b','caught','special'); - $lexer->mapHandler('special','caught'); - $lexer->addPattern('c','caught'); - - $this->assertTrue($lexer->parse($doc)); - $handler->tally(); - } - - function testIndexLookbehindEqual() { - $doc = "aaabcdeee"; - - $handler = new MockTestParserByteIndex($this); - $handler->setReturnValue("ignore", true); - $handler->setReturnValue("caught", true); - - $handler->expectArgumentsAt( - 0, - "caught", - array("", DOKU_LEXER_ENTER, strpos($doc,'')) - ); - $handler->expectArgumentsAt( - 1, - "caught", - array("b", DOKU_LEXER_SPECIAL, strpos($doc,'b')) - ); - $handler->expectArgumentsAt( - 2, - "caught", - array("c", DOKU_LEXER_MATCHED, strpos($doc,'c')) - ); - $handler->expectArgumentsAt( - 3, - "caught", - array("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d')) - ); - $handler->expectArgumentsAt( - 4, - "caught", - array("", DOKU_LEXER_EXIT, strpos($doc,'')) - ); - $handler->expectCallCount("caught", 5); - - $lexer = new Doku_Lexer($handler, "ignore"); - $lexer->addEntryPattern('', "ignore", "caught"); - $lexer->addExitPattern("(?<=d)", "caught"); - $lexer->addSpecialPattern('b','caught','special'); - $lexer->mapHandler('special','caught'); - $lexer->addPattern('c','caught'); - - $this->assertTrue($lexer->parse($doc)); - $handler->tally(); - } - - function testIndexLookbehindNotEqual() { - $doc = "aaabcdeee"; - - $handler = new MockTestParserByteIndex($this); - $handler->setReturnValue("ignore", true); - $handler->setReturnValue("caught", true); - - $handler->expectArgumentsAt( - 0, - "caught", - array("", DOKU_LEXER_ENTER, strpos($doc,'')) - ); - $handler->expectArgumentsAt( - 1, - "caught", - array("b", DOKU_LEXER_SPECIAL, strpos($doc,'b')) - ); - $handler->expectArgumentsAt( - 2, - "caught", - array("c", DOKU_LEXER_MATCHED, strpos($doc,'c')) - ); - $handler->expectArgumentsAt( - 3, - "caught", - array("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d')) - ); - $handler->expectArgumentsAt( - 4, - "caught", - array("", DOKU_LEXER_EXIT, strpos($doc,'')) - ); - $handler->expectCallCount("caught", 5); - - $lexer = new Doku_Lexer($handler, "ignore"); - $lexer->addEntryPattern('', "ignore", "caught"); - $lexer->addExitPattern("(?", "caught"); - $lexer->addSpecialPattern('b','caught','special'); - $lexer->mapHandler('special','caught'); - $lexer->addPattern('c','caught'); - - $this->assertTrue($lexer->parse($doc)); - $handler->tally(); - } - - /** - * This test is primarily to ensure the correct match is chosen - * when there are non-captured elements in the pattern. - */ - function testIndexSelectCorrectMatch() { - $doc = "ALL FOOLS ARE FOO"; - $pattern = '\bFOO\b'; - - $handler = new MockTestParserByteIndex($this); - $handler->setReturnValue("ignore", true); - $handler->setReturnValue("caught", true); - - $matches = array(); - preg_match('/'.$pattern.'/',$doc,$matches,PREG_OFFSET_CAPTURE); - - $handler->expectArgumentsAt( - 0, - "caught", - array("FOO", DOKU_LEXER_SPECIAL, $matches[0][1]) - ); - $handler->expectCallCount("caught", 1); - - $lexer = new Doku_Lexer($handler, "ignore"); - $lexer->addSpecialPattern($pattern,'ignore','caught'); - - $this->assertTrue($lexer->parse($doc)); - $handler->tally(); - } - -} - -?> diff --git a/_test/cases/inc/parser/parser.group.php b/_test/cases/inc/parser/parser.group.php deleted file mode 100644 index ed7fce76ee..0000000000 --- a/_test/cases/inc/parser/parser.group.php +++ /dev/null @@ -1,34 +0,0 @@ -GroupTest('ParserGroupTest'); - $this->addTestFile($dir . 'parser_eol.test.php'); - $this->addTestFile($dir . 'parser_footnote.test.php'); - $this->addTestFile($dir .'parser_formatting.test.php'); - $this->addTestFile($dir .'parser_headers.test.php'); - $this->addTestFile($dir .'parser_i18n.test.php'); - $this->addTestFile($dir .'parser_links.test.php'); - $this->addTestFile($dir .'parser_lists.test.php'); - $this->addTestFile($dir .'parser_preformatted.test.php'); - $this->addTestFile($dir .'parser_quote.test.php'); - $this->addTestFile($dir .'parser_replacements.test.php'); - $this->addTestFile($dir .'parser_table.test.php'); -# $this->addTestFile($dir .'parser_tocsections.test.php'); - $this->addTestFile($dir .'parser_unformatted.test.php'); - } - -} - -?> diff --git a/_test/cases/inc/parser/parser_formatting.test.php b/_test/cases/inc/parser/parser_formatting.test.php deleted file mode 100644 index 69c57dfb59..0000000000 --- a/_test/cases/inc/parser/parser_formatting.test.php +++ /dev/null @@ -1,434 +0,0 @@ -UnitTestCase('TestOfDoku_Parser_Formatting'); - } - - function testStrong() { - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); - $this->P->parse('abc **bar** def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('strong_open',array()), - array('cdata',array('bar')), - array('strong_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotStrong() { - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); - $this->P->parse('abc **bar def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc **bar def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testEm() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc //bar// def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('emphasis_open',array()), - array('cdata',array('bar')), - array('emphasis_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testEmColon() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc //Тест: // def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('emphasis_open',array()), - array('cdata',array('Тест: ')), - array('emphasis_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testEmSingleChar() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc //b// def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('emphasis_open',array()), - array('cdata',array('b')), - array('emphasis_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testEmWithUnknownSchema() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc //foo:// bar// def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('emphasis_open',array()), - array('cdata',array('foo:')), - array('emphasis_close',array()), - array('cdata',array(' bar// def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testEmWithKnownSchema() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); - $this->P->parse('abc //foo http://www.google.com bar// def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('emphasis_open',array()), - array('cdata',array('foo ')), - array('externallink',array('http://www.google.com', NULL)), - array('cdata',array(' bar')), - array('emphasis_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotEm() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc //bar def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc //bar def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotEmSchemaAtOpen() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc foo://bar// def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc foo:')), - array('emphasis_open',array()), - array('cdata',array('bar')), - array('emphasis_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotEmSchemaAtClose() { - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc //http:// def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc //http:// def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testEmWithMultiOccurence() { - // Case from #763 - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('//text:// Blablabla Blablabla - -//text:// another Blablabla Blablabla'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n")), - array('emphasis_open',array()), - array('cdata',array('text:')), - array('emphasis_close',array()), - array('cdata',array(" Blablabla Blablabla\n\n")), - array('emphasis_open',array()), - array('cdata',array('text:')), - array('emphasis_close',array()), - array('cdata',array(" another Blablabla Blablabla")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testEmWithUnicode() { - // Case from #1468 - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('//Тест://'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n")), - array('emphasis_open',array()), - array('cdata',array('Тест:')), - array('emphasis_close',array()), - array('cdata', array('')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNoEmWithInvalidURL() { - // Case from #1629 - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('http:///certsrv/certcarc.asp'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array('http:///certsrv/certcarc.asp')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNoEmWithUnknownURL() { - // Case from #1640 - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('svn://example.com/foo/bar'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array('svn://example.com/foo/bar')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testUnderline() { - $this->P->addMode('underline',new Doku_Parser_Mode_Formatting('underline')); - $this->P->parse('abc __bar__ def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('underline_open',array()), - array('cdata',array('bar')), - array('underline_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotUnderline() { - $this->P->addMode('underline',new Doku_Parser_Mode_Formatting('underline')); - $this->P->parse('abc __bar def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc __bar def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testMonospace() { - $this->P->addMode('monospace',new Doku_Parser_Mode_Formatting('monospace')); - $this->P->parse("abc ''bar'' def"); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('monospace_open',array()), - array('cdata',array('bar')), - array('monospace_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotMonospace() { - $this->P->addMode('monospace',new Doku_Parser_Mode_Formatting('monospace')); - $this->P->parse("abc ''bar def"); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc ''bar def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testSubscript() { - $this->P->addMode('subscript',new Doku_Parser_Mode_Formatting('subscript')); - $this->P->parse('abc bar def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('subscript_open',array()), - array('cdata',array('bar')), - array('subscript_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotSubscript() { - $this->P->addMode('subscript',new Doku_Parser_Mode_Formatting('subscript')); - $this->P->parse('abc bar def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc bar def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testSuperscript() { - $this->P->addMode('superscript',new Doku_Parser_Mode_Formatting('superscript')); - $this->P->parse("abc bar def"); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('superscript_open',array()), - array('cdata',array('bar')), - array('superscript_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotSuperscript() { - $this->P->addMode('superscript',new Doku_Parser_Mode_Formatting('superscript')); - $this->P->parse("abc bar def"); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc bar def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testDeleted() { - $this->P->addMode('deleted',new Doku_Parser_Mode_Formatting('deleted')); - $this->P->parse('abc bar def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('deleted_open',array()), - array('cdata',array('bar')), - array('deleted_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNotDeleted() { - $this->P->addMode('deleted',new Doku_Parser_Mode_Formatting('deleted')); - $this->P->parse('abc bar def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\nabc bar def")), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testNestedFormatting() { - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); - $this->P->addMode('emphasis',new Doku_Parser_Mode_Formatting('emphasis')); - $this->P->parse('abc **a//b//c** def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('strong_open',array()), - array('cdata',array('a')), - array('emphasis_open',array()), - array('cdata',array('b')), - array('emphasis_close',array()), - array('cdata',array('c')), - array('strong_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } - - function testIllegalNestedFormatting() { - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); - $this->P->parse('abc **a**b**c** def'); - $calls = array ( - array('document_start',array()), - array('p_open',array()), - array('cdata',array("\n".'abc ')), - array('strong_open',array()), - array('cdata',array('a')), - array('strong_close',array()), - array('cdata',array('b')), - array('strong_open',array()), - array('cdata',array('c')), - array('strong_close',array()), - array('cdata',array(' def')), - array('p_close',array()), - array('document_end',array()), - ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); - } -} - diff --git a/_test/cases/inc/parser/xhtml_htmlphp.test.php b/_test/cases/inc/parser/xhtml_htmlphp.test.php deleted file mode 100644 index 65d64e579d..0000000000 --- a/_test/cases/inc/parser/xhtml_htmlphp.test.php +++ /dev/null @@ -1,203 +0,0 @@ -purge = isset($_REQUEST['purge']) ? $_REQUEST['purge'] : null; - $_REQUEST['purge'] = 1; - - if (!isset($conf['cachedir'])) { - $conf['cachedir'] = ''; - $this->cachedir = false; - } else { - $this->cachedir = true; - } - - if (function_exists('io_makefiledir')) { - runkit_function_rename('io_makefiledir', 'io_makefiledir_real'); - } - runkit_function_rename('xhtml_htmlphp_test_io_makefiledir','io_makefiledir'); - - if (function_exists('io_savefile')) { - runkit_function_rename('io_savefile', 'io_savefile_real'); - } - runkit_function_rename('xhtml_htmlphp_test_io_savefile','io_savefile'); - - runkit_method_rename('GeSHi','parse_code','parse_code_real'); - runkit_method_add('GeSHi','parse_code','', '{ return hsc($this->source); }'); - - parent::setup(); - } - - function teardown() { - global $conf; - - // restore purge - if (is_null($this->purge)) unset($_REQUEST['purge']); - else $_REQUEST['purge'] = $this->purge; - - // restore $conf['cachedir'] if necessary - if (!$this->cachedir) unset($conf['cachedir']); - - // restore io_functions - runkit_function_rename('io_makefiledir','xhtml_htmlphp_test_io_makefiledir'); - if (function_exists('io_makefiledir_real')) { - runkit_function_rename('io_makefiledir_real', 'io_makefiledir'); - } - - runkit_function_rename('io_savefile','xhtml_htmlphp_test_io_savefile'); - if (function_exists('io_savefile_real')) { - runkit_function_rename('io_savefile_real', 'io_savefile'); - } - - // restore GeSHi::parse_code - runkit_method_remove('GeSHi','parse_code'); - runkit_method_rename('GeSHi','parse_code_real','parse_code'); - - parent::setup(); - } - - function _run_parser($modes,$data) { - - foreach ($modes as $mode => $name) { - $class = 'Doku_Parser_Mode_'.$name; - $this->P->addMode($mode,new $class()); - } - - $R = new Doku_Renderer_tester(); - $this->P->parse($data); - foreach ( $this->H->calls as $instruction ) { - // Execute the callback against the Renderer - call_user_func_array(array(&$R, $instruction[0]),$instruction[1]); - } - - return str_replace("\n",'',$R->doc); - } - - function test_html_off(){ - $test = array('bold','

<b>bold</b>

'); - - global $conf; - $conf['htmlok'] = 0; - - $result = $this->_run_parser(array('html'=>'html'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - - function test_html_on(){ - $test = array('bold','

bold

'); - - global $conf; - $conf['htmlok'] = 1; - - $result = $this->_run_parser(array('html'=>'html'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - - function test_htmlblock_off(){ - $test = array('bold','
<b>bold</b>
'); - - global $conf; - $conf['htmlok'] = 0; - - $result = $this->_run_parser(array('html'=>'html'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - - function test_htmlblock_on(){ - $test = array('bold','bold'); - - global $conf; - $conf['htmlok'] = 1; - - $result = $this->_run_parser(array('html'=>'html'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - - function test_php_off(){ - $test = array('echo(1+1);','

echo(1+1);

'); - - global $conf; - $conf['phpok'] = 0; - - $result = $this->_run_parser(array('php'=>'php'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - - function test_php_on(){ - $test = array('echo(1+1);','

2

'); - - global $conf; - $conf['phpok'] = 1; - - $result = $this->_run_parser(array('php'=>'php'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - - function test_phpblock_off(){ - $test = array('echo(1+1);','
echo(1+1);
'); - - global $conf; - $conf['phpok'] = 0; - - $result = $this->_run_parser(array('php'=>'php'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - - function test_phpblock_on(){ - $test = array('echo(1+1);',"2"); - - global $conf; - $conf['phpok'] = 1; - - $result = $this->_run_parser(array('php'=>'php'),$test[0]); - - $this->assertEqual($result,$test[1]); - } - -} diff --git a/_test/cases/inc/parser/xhtml_links.test.php b/_test/cases/inc/parser/xhtml_links.test.php deleted file mode 100644 index a9a6dfdbc1..0000000000 --- a/_test/cases/inc/parser/xhtml_links.test.php +++ /dev/null @@ -1,239 +0,0 @@ -emaillink('foo@example.com',''); - - $expect = '<script>alert('"alert"');</script>'; - - $this->assertEqual($p->doc,$expect); - } - - function test_emaillink_with_media(){ - global $conf; - $conf['mailguard'] = 'visible'; - $conf['userewrite'] = 2; - - $image = array( - 'type'=>'internalmedia', - 'src'=>'img.gif', - 'title'=>'Some Image', - 'align'=>NULL, - 'width'=>10, - 'height'=>20, - 'cache'=>'nocache', - 'linking'=>'details', - ); - - $p = new Doku_Renderer_xhtml(); - $p->emaillink('foo@example.com',$image); - - $expect = 'Some Image'; - - $this->assertEqual($p->doc,$expect); - } - - /** - * Produced by syntax like [[ ]] - */ - function test_empty_internallink(){ - $page = 'my:space'; - - global $ID; - $ID = $page; - - global $conf; - $conf['start'] = 'start'; - - global $conf; - $conf['basedir'] = '/'; - $conf['useheading'] = 0; - $conf['userewrite'] = 0; - $conf['useslash'] = 0; - $conf['canonical'] = 0; - - $p = new Doku_Renderer_xhtml(); - $p->internallink(''); - - - if (page_exists($page)) { - $class = 'wikilink1'; - $rel = ''; - } - else { - $class = 'wikilink2'; - $rel = ' rel="nofollow"'; - } - - $parts = split(':', $page); - $caption = $parts[count($parts)-1]; - - $expect = ''.$caption.''; - - $this->assertEqual($p->doc, $expect); - } - - /** - * Produced by syntax like [[ |my caption]] - */ - function test_empty_internallink_with_caption(){ - $page = 'my:space'; - $caption = 'my caption'; - - global $ID; - $ID = $page; - - global $conf; - $conf['basedir'] = '/'; - $conf['useheading'] = 0; - $conf['userewrite'] = 0; - $conf['useslash'] = 0; - $conf['canonical'] = 0; - - $p = new Doku_Renderer_xhtml(); - $p->internallink('', $caption); - - if (page_exists($page)) { - $class = 'wikilink1'; - $rel = ''; - } - else { - $class = 'wikilink2'; - $rel = ' rel="nofollow"'; - } - - $expect = ''.$caption.''; - - $this->assertEqual($p->doc, $expect); - } - - /** - * Produced by syntax like [[?do=index]] - */ - function test_empty_internallink_index(){ - $page = 'my:space'; - - global $ID; - $ID = $page; - - global $conf; - $conf['start'] = 'start'; - - global $conf; - $conf['basedir'] = '/'; - $conf['useheading'] = 0; - $conf['userewrite'] = 0; - $conf['useslash'] = 0; - $conf['canonical'] = 0; - - $p = new Doku_Renderer_xhtml(); - $p->internallink('?do=index'); - - if (page_exists($page)) { - $class = 'wikilink1'; - $rel = ''; - } - else { - $class = 'wikilink2'; - $rel = ' rel="nofollow"'; - } - - $parts = split(':', $page); - $caption = $parts[count($parts)-1]; - - $expect = ''.$caption.''; - - $this->assertEqual($p->doc, $expect); - } - - /** - * Produced by syntax like [[?do=index|my caption]] - */ - function test_empty_internallink_index_with_caption(){ - $page = 'my:space'; - $caption = 'my caption'; - - global $ID; - $ID = $page; - - global $conf; - $conf['basedir'] = '/'; - $conf['useheading'] = 0; - $conf['userewrite'] = 0; - $conf['useslash'] = 0; - $conf['canonical'] = 0; - - $p = new Doku_Renderer_xhtml(); - $p->internallink('?do=index', $caption); - - if (page_exists($page)) { - $class = 'wikilink1'; - $rel = ''; - } - else { - $class = 'wikilink2'; - $rel = ' rel="nofollow"'; - } - - $expect = ''.$caption.''; - - $this->assertEqual($p->doc, $expect); - } - - /** - * Produced by syntax like [[#test]] - */ - function test_empty_locallink(){ - $page = 'my:spacex'; - global $ID; - $ID = $page; - - global $conf; - $conf['basedir'] = '/'; - $conf['useheading'] = 0; - $conf['userewrite'] = 0; - $conf['useslash'] = 0; - $conf['canonical'] = 0; - - $p = new Doku_Renderer_xhtml(); - $p->locallink('test'); - - $expect = 'test'; - - $this->assertEqual($p->doc, $expect); - } - - /** - * Produced by syntax like [[#test|my caption]] - */ - function test_empty_locallink_with_caption(){ - $page = 'my:spacex'; - $caption = 'my caption'; - - global $ID; - $ID = $page; - - global $conf; - $conf['basedir'] = '/'; - $conf['useheading'] = 0; - $conf['userewrite'] = 0; - $conf['useslash'] = 0; - $conf['canonical'] = 0; - - $p = new Doku_Renderer_xhtml(); - $p->locallink('test', $caption); - - $expect = ''.$caption.''; - - $this->assertEqual($p->doc, $expect); - } -} diff --git a/_test/conf/acl.auth.php b/_test/conf/acl.auth.php new file mode 100644 index 0000000000..14344d7785 --- /dev/null +++ b/_test/conf/acl.auth.php @@ -0,0 +1,21 @@ +# acl.auth.php +# +# Don't modify the lines above +# +# Access Control Lists +# +# Editing this file by hand shouldn't be necessary. Use the ACL +# Manager interface instead. +# +# If your auth backend allows special char like spaces in groups +# or user names you need to urlencode them (only chars <128, leave +# UTF-8 multibyte chars as is) +# +# none 0 +# read 1 +# edit 2 +# create 4 +# upload 8 +# delete 16 + +* @ALL 8 diff --git a/_test/conf/local.php b/_test/conf/local.php new file mode 100644 index 0000000000..ff12993935 --- /dev/null +++ b/_test/conf/local.php @@ -0,0 +1,10 @@ + +# Don't modify the lines above +# +# Userfile +# +# Format: +# +# user:MD5password:Real Name:email:groups,comma,seperated +# +# testuser : testpass +testuser:179ad45c6ce2cb97cf1029e212046e81:Arthur Dent:arthur@example.com: diff --git a/_test/core/DokuWikiTest.php b/_test/core/DokuWikiTest.php new file mode 100644 index 0000000000..e47c063293 --- /dev/null +++ b/_test/core/DokuWikiTest.php @@ -0,0 +1,96 @@ +getList() as $plugin) { + if (!in_array($plugin, $default_plugins)) { + if (!$plugin_controller->disable($plugin)) { + throw new Exception('Could not disable plugin "'.$plugin.'"!'); + } + } + } + + // disable and enable configured plugins + foreach ($this->pluginsDisabled as $plugin) { + if (!$plugin_controller->disable($plugin)) { + throw new Exception('Could not disable plugin "'.$plugin.'"!'); + } + } + foreach ($this->pluginsEnabled as $plugin) { + /* enable() returns false but works... + if (!$plugin_controller->enable($plugin)) { + throw new Exception('Could not enable plugin "'.$plugin.'"!'); + } + */ + $plugin_controller->enable($plugin); + } + + // reset event handler + global $EVENT_HANDLER; + $EVENT_HANDLER = new Doku_Event_Handler(); + + // reload language + $local = $conf['lang']; + trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true); + } +} diff --git a/_test/core/TestRequest.php b/_test/core/TestRequest.php new file mode 100644 index 0000000000..fa3ddec90f --- /dev/null +++ b/_test/core/TestRequest.php @@ -0,0 +1,82 @@ +server[$key]; } + public function getSession($key) { return $this->session[$key]; } + public function getGet($key) { return $this->get[$key]; } + public function getPost($key) { return $this->post[$key]; } + + public function setServer($key, $value) { $this->server[$key] = $value; } + public function setSession($key, $value) { $this->session[$key] = $value; } + public function setGet($key, $value) { $this->get[$key] = $value; } + public function setPost($key, $value) { $this->post[$key] = $value; } + + /** + * Executes the request + * + * @return TestResponse the resulting output of the request + */ + public function execute() { + // save old environment + $server = $_SERVER; + $session = $_SESSION; + $get = $_GET; + $post = $_POST; + $request = $_REQUEST; + + // fake environment + global $default_server_vars; + $_SERVER = array_merge($default_server_vars, $this->server); + $_SESSION = $this->session; + $_GET = $this->get; + $_POST = $this->post; + $_REQUEST = array_merge($_GET, $_POST); + + // reset output buffer + global $output_buffer; + $output_buffer = ''; + + // now execute dokuwiki and grep the output + header_remove(); + ob_start('ob_start_callback'); + include(DOKU_INC.'doku.php'); + ob_end_flush(); + + // create the response object + $response = new TestResponse( + $output_buffer, + headers_list() + ); + + // reset environment + $_SERVER = $server; + $_SESSION = $session; + $_GET = $get; + $_POST = $post; + $_REQUEST = $request; + + return $response; + } +} diff --git a/_test/core/TestResponse.php b/_test/core/TestResponse.php new file mode 100644 index 0000000000..6d20afb283 --- /dev/null +++ b/_test/core/TestResponse.php @@ -0,0 +1,55 @@ +content = $content; + $this->headers = $headers; + } + + /** + * @return string + */ + public function getContent() { + return $this->content; + } + + /** + * @return array + */ + public function getHeaders() { + return $this->headers; + } + + /** + * Query the response for a JQuery compatible CSS selector + * + * @link https://code.google.com/p/phpquery/wiki/Selectors + * @param $selector string + * @return phpQueryObject + */ + public function queryHTML($selector){ + if(is_null($this->pq)) $this->pq = phpQuery::newDocument($this->content); + return $this->pq->find($selector); + } +} diff --git a/_test/core/TestUtils.php b/_test/core/TestUtils.php new file mode 100644 index 0000000000..2750a3edf1 --- /dev/null +++ b/_test/core/TestUtils.php @@ -0,0 +1,70 @@ +read())) { + if ($entry == '.' || $entry == '..') { + continue; + } + TestUtils::rcopy($newdestdir, $source.'/'.$entry); + } + $dh->close(); + } + } + + /** + * helper for recursive rmdir()/unlink() + * + * @static + * @param $target string + */ + public static function rdelete($target) { + if (!is_dir($target)) { + unlink($target); + } else { + $dh = dir($target); + while (false !== ($entry = $dh->read())) { + if ($entry == '.' || $entry == '..') { + continue; + } + TestUtils::rdelete("$target/$entry"); + } + $dh->close(); + rmdir($target); + } + } + + /** + * helper to append text to a file + * + * @static + * @param $file string + * @param $text string + */ + public static function fappend($file, $text) { + $fh = fopen($file, 'a'); + fwrite($fh, $text); + fclose($fh); + } + +} diff --git a/_test/core/phpQuery-onefile.php b/_test/core/phpQuery-onefile.php new file mode 100644 index 0000000000..4c1dfa3da6 --- /dev/null +++ b/_test/core/phpQuery-onefile.php @@ -0,0 +1,5702 @@ + + * @license http://www.opensource.org/licenses/mit-license.php MIT License + * @package phpQuery + */ + +// class names for instanceof +// TODO move them as class constants into phpQuery +define('DOMDOCUMENT', 'DOMDocument'); +define('DOMELEMENT', 'DOMElement'); +define('DOMNODELIST', 'DOMNodeList'); +define('DOMNODE', 'DOMNode'); + +/** + * DOMEvent class. + * + * Based on + * @link http://developer.mozilla.org/En/DOM:event + * @author Tobiasz Cudnik + * @package phpQuery + * @todo implement ArrayAccess ? + */ +class DOMEvent { + /** + * Returns a boolean indicating whether the event bubbles up through the DOM or not. + * + * @var unknown_type + */ + public $bubbles = true; + /** + * Returns a boolean indicating whether the event is cancelable. + * + * @var unknown_type + */ + public $cancelable = true; + /** + * Returns a reference to the currently registered target for the event. + * + * @var unknown_type + */ + public $currentTarget; + /** + * Returns detail about the event, depending on the type of event. + * + * @var unknown_type + * @link http://developer.mozilla.org/en/DOM/event.detail + */ + public $detail; // ??? + /** + * Used to indicate which phase of the event flow is currently being evaluated. + * + * NOT IMPLEMENTED + * + * @var unknown_type + * @link http://developer.mozilla.org/en/DOM/event.eventPhase + */ + public $eventPhase; // ??? + /** + * The explicit original target of the event (Mozilla-specific). + * + * NOT IMPLEMENTED + * + * @var unknown_type + */ + public $explicitOriginalTarget; // moz only + /** + * The original target of the event, before any retargetings (Mozilla-specific). + * + * NOT IMPLEMENTED + * + * @var unknown_type + */ + public $originalTarget; // moz only + /** + * Identifies a secondary target for the event. + * + * @var unknown_type + */ + public $relatedTarget; + /** + * Returns a reference to the target to which the event was originally dispatched. + * + * @var unknown_type + */ + public $target; + /** + * Returns the time that the event was created. + * + * @var unknown_type + */ + public $timeStamp; + /** + * Returns the name of the event (case-insensitive). + */ + public $type; + public $runDefault = true; + public $data = null; + public function __construct($data) { + foreach($data as $k => $v) { + $this->$k = $v; + } + if (! $this->timeStamp) + $this->timeStamp = time(); + } + /** + * Cancels the event (if it is cancelable). + * + */ + public function preventDefault() { + $this->runDefault = false; + } + /** + * Stops the propagation of events further along in the DOM. + * + */ + public function stopPropagation() { + $this->bubbles = false; + } +} + + +/** + * DOMDocumentWrapper class simplifies work with DOMDocument. + * + * Know bug: + * - in XHTML fragments,
changes to
+ * + * @todo check XML catalogs compatibility + * @author Tobiasz Cudnik + * @package phpQuery + */ +class DOMDocumentWrapper { + /** + * @var DOMDocument + */ + public $document; + public $id; + /** + * @todo Rewrite as method and quess if null. + * @var unknown_type + */ + public $contentType = ''; + public $xpath; + public $uuid = 0; + public $data = array(); + public $dataNodes = array(); + public $events = array(); + public $eventsNodes = array(); + public $eventsGlobal = array(); + /** + * @TODO iframes support http://code.google.com/p/phpquery/issues/detail?id=28 + * @var unknown_type + */ + public $frames = array(); + /** + * Document root, by default equals to document itself. + * Used by documentFragments. + * + * @var DOMNode + */ + public $root; + public $isDocumentFragment; + public $isXML = false; + public $isXHTML = false; + public $isHTML = false; + public $charset; + public function __construct($markup = null, $contentType = null, $newDocumentID = null) { + if (isset($markup)) + $this->load($markup, $contentType, $newDocumentID); + $this->id = $newDocumentID + ? $newDocumentID + : md5(microtime()); + } + public function load($markup, $contentType = null, $newDocumentID = null) { +// phpQuery::$documents[$id] = $this; + $this->contentType = strtolower($contentType); + if ($markup instanceof DOMDOCUMENT) { + $this->document = $markup; + $this->root = $this->document; + $this->charset = $this->document->encoding; + // TODO isDocumentFragment + } else { + $loaded = $this->loadMarkup($markup); + } + if ($loaded) { +// $this->document->formatOutput = true; + $this->document->preserveWhiteSpace = true; + $this->xpath = new DOMXPath($this->document); + $this->afterMarkupLoad(); + return true; + // remember last loaded document +// return phpQuery::selectDocument($id); + } + return false; + } + protected function afterMarkupLoad() { + if ($this->isXHTML) { + $this->xpath->registerNamespace("html", "http://www.w3.org/1999/xhtml"); + } + } + protected function loadMarkup($markup) { + $loaded = false; + if ($this->contentType) { + self::debug("Load markup for content type {$this->contentType}"); + // content determined by contentType + list($contentType, $charset) = $this->contentTypeToArray($this->contentType); + switch($contentType) { + case 'text/html': + phpQuery::debug("Loading HTML, content type '{$this->contentType}'"); + $loaded = $this->loadMarkupHTML($markup, $charset); + break; + case 'text/xml': + case 'application/xhtml+xml': + phpQuery::debug("Loading XML, content type '{$this->contentType}'"); + $loaded = $this->loadMarkupXML($markup, $charset); + break; + default: + // for feeds or anything that sometimes doesn't use text/xml + if (strpos('xml', $this->contentType) !== false) { + phpQuery::debug("Loading XML, content type '{$this->contentType}'"); + $loaded = $this->loadMarkupXML($markup, $charset); + } else + phpQuery::debug("Could not determine document type from content type '{$this->contentType}'"); + } + } else { + // content type autodetection + if ($this->isXML($markup)) { + phpQuery::debug("Loading XML, isXML() == true"); + $loaded = $this->loadMarkupXML($markup); + if (! $loaded && $this->isXHTML) { + phpQuery::debug('Loading as XML failed, trying to load as HTML, isXHTML == true'); + $loaded = $this->loadMarkupHTML($markup); + } + } else { + phpQuery::debug("Loading HTML, isXML() == false"); + $loaded = $this->loadMarkupHTML($markup); + } + } + return $loaded; + } + protected function loadMarkupReset() { + $this->isXML = $this->isXHTML = $this->isHTML = false; + } + protected function documentCreate($charset, $version = '1.0') { + if (! $version) + $version = '1.0'; + $this->document = new DOMDocument($version, $charset); + $this->charset = $this->document->encoding; +// $this->document->encoding = $charset; + $this->document->formatOutput = true; + $this->document->preserveWhiteSpace = true; + } + protected function loadMarkupHTML($markup, $requestedCharset = null) { + if (phpQuery::$debug) + phpQuery::debug('Full markup load (HTML): '.substr($markup, 0, 250)); + $this->loadMarkupReset(); + $this->isHTML = true; + if (!isset($this->isDocumentFragment)) + $this->isDocumentFragment = self::isDocumentFragmentHTML($markup); + $charset = null; + $documentCharset = $this->charsetFromHTML($markup); + $addDocumentCharset = false; + if ($documentCharset) { + $charset = $documentCharset; + $markup = $this->charsetFixHTML($markup); + } else if ($requestedCharset) { + $charset = $requestedCharset; + } + if (! $charset) + $charset = phpQuery::$defaultCharset; + // HTTP 1.1 says that the default charset is ISO-8859-1 + // @see http://www.w3.org/International/O-HTTP-charset + if (! $documentCharset) { + $documentCharset = 'ISO-8859-1'; + $addDocumentCharset = true; + } + // Should be careful here, still need 'magic encoding detection' since lots of pages have other 'default encoding' + // Worse, some pages can have mixed encodings... we'll try not to worry about that + $requestedCharset = strtoupper($requestedCharset); + $documentCharset = strtoupper($documentCharset); + phpQuery::debug("DOC: $documentCharset REQ: $requestedCharset"); + if ($requestedCharset && $documentCharset && $requestedCharset !== $documentCharset) { + phpQuery::debug("CHARSET CONVERT"); + // Document Encoding Conversion + // http://code.google.com/p/phpquery/issues/detail?id=86 + if (function_exists('mb_detect_encoding')) { + $possibleCharsets = array($documentCharset, $requestedCharset, 'AUTO'); + $docEncoding = mb_detect_encoding($markup, implode(', ', $possibleCharsets)); + if (! $docEncoding) + $docEncoding = $documentCharset; // ok trust the document + phpQuery::debug("DETECTED '$docEncoding'"); + // Detected does not match what document says... + if ($docEncoding !== $documentCharset) { + // Tricky.. + } + if ($docEncoding !== $requestedCharset) { + phpQuery::debug("CONVERT $docEncoding => $requestedCharset"); + $markup = mb_convert_encoding($markup, $requestedCharset, $docEncoding); + $markup = $this->charsetAppendToHTML($markup, $requestedCharset); + $charset = $requestedCharset; + } + } else { + phpQuery::debug("TODO: charset conversion without mbstring..."); + } + } + $return = false; + if ($this->isDocumentFragment) { + phpQuery::debug("Full markup load (HTML), DocumentFragment detected, using charset '$charset'"); + $return = $this->documentFragmentLoadMarkup($this, $charset, $markup); + } else { + if ($addDocumentCharset) { + phpQuery::debug("Full markup load (HTML), appending charset: '$charset'"); + $markup = $this->charsetAppendToHTML($markup, $charset); + } + phpQuery::debug("Full markup load (HTML), documentCreate('$charset')"); + $this->documentCreate($charset); + $return = phpQuery::$debug === 2 + ? $this->document->loadHTML($markup) + : @$this->document->loadHTML($markup); + if ($return) + $this->root = $this->document; + } + if ($return && ! $this->contentType) + $this->contentType = 'text/html'; + return $return; + } + protected function loadMarkupXML($markup, $requestedCharset = null) { + if (phpQuery::$debug) + phpQuery::debug('Full markup load (XML): '.substr($markup, 0, 250)); + $this->loadMarkupReset(); + $this->isXML = true; + // check agains XHTML in contentType or markup + $isContentTypeXHTML = $this->isXHTML(); + $isMarkupXHTML = $this->isXHTML($markup); + if ($isContentTypeXHTML || $isMarkupXHTML) { + self::debug('Full markup load (XML), XHTML detected'); + $this->isXHTML = true; + } + // determine document fragment + if (! isset($this->isDocumentFragment)) + $this->isDocumentFragment = $this->isXHTML + ? self::isDocumentFragmentXHTML($markup) + : self::isDocumentFragmentXML($markup); + // this charset will be used + $charset = null; + // charset from XML declaration @var string + $documentCharset = $this->charsetFromXML($markup); + if (! $documentCharset) { + if ($this->isXHTML) { + // this is XHTML, try to get charset from content-type meta header + $documentCharset = $this->charsetFromHTML($markup); + if ($documentCharset) { + phpQuery::debug("Full markup load (XML), appending XHTML charset '$documentCharset'"); + $this->charsetAppendToXML($markup, $documentCharset); + $charset = $documentCharset; + } + } + if (! $documentCharset) { + // if still no document charset... + $charset = $requestedCharset; + } + } else if ($requestedCharset) { + $charset = $requestedCharset; + } + if (! $charset) { + $charset = phpQuery::$defaultCharset; + } + if ($requestedCharset && $documentCharset && $requestedCharset != $documentCharset) { + // TODO place for charset conversion +// $charset = $requestedCharset; + } + $return = false; + if ($this->isDocumentFragment) { + phpQuery::debug("Full markup load (XML), DocumentFragment detected, using charset '$charset'"); + $return = $this->documentFragmentLoadMarkup($this, $charset, $markup); + } else { + // FIXME ??? + if ($isContentTypeXHTML && ! $isMarkupXHTML) + if (! $documentCharset) { + phpQuery::debug("Full markup load (XML), appending charset '$charset'"); + $markup = $this->charsetAppendToXML($markup, $charset); + } + // see http://pl2.php.net/manual/en/book.dom.php#78929 + // LIBXML_DTDLOAD (>= PHP 5.1) + // does XML ctalogues works with LIBXML_NONET + // $this->document->resolveExternals = true; + // TODO test LIBXML_COMPACT for performance improvement + // create document + $this->documentCreate($charset); + if (phpversion() < 5.1) { + $this->document->resolveExternals = true; + $return = phpQuery::$debug === 2 + ? $this->document->loadXML($markup) + : @$this->document->loadXML($markup); + } else { + /** @link http://pl2.php.net/manual/en/libxml.constants.php */ + $libxmlStatic = phpQuery::$debug === 2 + ? LIBXML_DTDLOAD|LIBXML_DTDATTR|LIBXML_NONET + : LIBXML_DTDLOAD|LIBXML_DTDATTR|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOERROR; + $return = $this->document->loadXML($markup, $libxmlStatic); +// if (! $return) +// $return = $this->document->loadHTML($markup); + } + if ($return) + $this->root = $this->document; + } + if ($return) { + if (! $this->contentType) { + if ($this->isXHTML) + $this->contentType = 'application/xhtml+xml'; + else + $this->contentType = 'text/xml'; + } + return $return; + } else { + throw new Exception("Error loading XML markup"); + } + } + protected function isXHTML($markup = null) { + if (! isset($markup)) { + return strpos($this->contentType, 'xhtml') !== false; + } + // XXX ok ? + return strpos($markup, "doctype) && is_object($dom->doctype) +// ? $dom->doctype->publicId +// : self::$defaultDoctype; + } + protected function isXML($markup) { +// return strpos($markup, ']+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i', + $markup, $matches + ); + if (! isset($matches[0])) + return array(null, null); + // get attr 'content' + preg_match('@content\\s*=\\s*(["|\'])(.+?)\\1@', $matches[0], $matches); + if (! isset($matches[0])) + return array(null, null); + return $this->contentTypeToArray($matches[2]); + } + protected function charsetFromHTML($markup) { + $contentType = $this->contentTypeFromHTML($markup); + return $contentType[1]; + } + protected function charsetFromXML($markup) { + $matches; + // find declaration + preg_match('@<'.'?xml[^>]+encoding\\s*=\\s*(["|\'])(.*?)\\1@i', + $markup, $matches + ); + return isset($matches[2]) + ? strtolower($matches[2]) + : null; + } + /** + * Repositions meta[type=charset] at the start of head. Bypasses DOMDocument bug. + * + * @link http://code.google.com/p/phpquery/issues/detail?id=80 + * @param $html + */ + protected function charsetFixHTML($markup) { + $matches = array(); + // find meta tag + preg_match('@\s*]+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i', + $markup, $matches, PREG_OFFSET_CAPTURE + ); + if (! isset($matches[0])) + return; + $metaContentType = $matches[0][0]; + $markup = substr($markup, 0, $matches[0][1]) + .substr($markup, $matches[0][1]+strlen($metaContentType)); + $headStart = stripos($markup, ''); + $markup = substr($markup, 0, $headStart+6).$metaContentType + .substr($markup, $headStart+6); + return $markup; + } + protected function charsetAppendToHTML($html, $charset, $xhtml = false) { + // remove existing meta[type=content-type] + $html = preg_replace('@\s*]+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i', '', $html); + $meta = ''; + if (strpos($html, ')@s', + "{$meta}", + $html + ); + } + } else { + return preg_replace( + '@)@s', + ''.$meta, + $html + ); + } + } + protected function charsetAppendToXML($markup, $charset) { + $declaration = '<'.'?xml version="1.0" encoding="'.$charset.'"?'.'>'; + return $declaration.$markup; + } + public static function isDocumentFragmentHTML($markup) { + return stripos($markup, 'documentFragmentCreate($node, $sourceCharset); +// if ($fake === false) +// throw new Exception("Error loading documentFragment markup"); +// else +// $return = array_merge($return, +// $this->import($fake->root->childNodes) +// ); +// } else { +// $return[] = $this->document->importNode($node, true); +// } +// } +// return $return; +// } else { +// // string markup +// $fake = $this->documentFragmentCreate($source, $sourceCharset); +// if ($fake === false) +// throw new Exception("Error loading documentFragment markup"); +// else +// return $this->import($fake->root->childNodes); +// } + if (is_array($source) || $source instanceof DOMNODELIST) { + // dom nodes + self::debug('Importing nodes to document'); + foreach($source as $node) + $return[] = $this->document->importNode($node, true); + } else { + // string markup + $fake = $this->documentFragmentCreate($source, $sourceCharset); + if ($fake === false) + throw new Exception("Error loading documentFragment markup"); + else + return $this->import($fake->root->childNodes); + } + return $return; + } + /** + * Creates new document fragment. + * + * @param $source + * @return DOMDocumentWrapper + */ + protected function documentFragmentCreate($source, $charset = null) { + $fake = new DOMDocumentWrapper(); + $fake->contentType = $this->contentType; + $fake->isXML = $this->isXML; + $fake->isHTML = $this->isHTML; + $fake->isXHTML = $this->isXHTML; + $fake->root = $fake->document; + if (! $charset) + $charset = $this->charset; +// $fake->documentCreate($this->charset); + if ($source instanceof DOMNODE && !($source instanceof DOMNODELIST)) + $source = array($source); + if (is_array($source) || $source instanceof DOMNODELIST) { + // dom nodes + // load fake document + if (! $this->documentFragmentLoadMarkup($fake, $charset)) + return false; + $nodes = $fake->import($source); + foreach($nodes as $node) + $fake->root->appendChild($node); + } else { + // string markup + $this->documentFragmentLoadMarkup($fake, $charset, $source); + } + return $fake; + } + /** + * + * @param $document DOMDocumentWrapper + * @param $markup + * @return $document + */ + private function documentFragmentLoadMarkup($fragment, $charset, $markup = null) { + // TODO error handling + // TODO copy doctype + // tempolary turn off + $fragment->isDocumentFragment = false; + if ($fragment->isXML) { + if ($fragment->isXHTML) { + // add FAKE element to set default namespace + $fragment->loadMarkupXML('' + .'' + .''.$markup.''); + $fragment->root = $fragment->document->firstChild->nextSibling; + } else { + $fragment->loadMarkupXML(''.$markup.''); + $fragment->root = $fragment->document->firstChild; + } + } else { + $markup2 = phpQuery::$defaultDoctype.''; + $noBody = strpos($markup, 'loadMarkupHTML($markup2); + // TODO resolv body tag merging issue + $fragment->root = $noBody + ? $fragment->document->firstChild->nextSibling->firstChild->nextSibling + : $fragment->document->firstChild->nextSibling->firstChild->nextSibling; + } + if (! $fragment->root) + return false; + $fragment->isDocumentFragment = true; + return true; + } + protected function documentFragmentToMarkup($fragment) { + phpQuery::debug('documentFragmentToMarkup'); + $tmp = $fragment->isDocumentFragment; + $fragment->isDocumentFragment = false; + $markup = $fragment->markup(); + if ($fragment->isXML) { + $markup = substr($markup, 0, strrpos($markup, '')); + if ($fragment->isXHTML) { + $markup = substr($markup, strpos($markup, '')+6); + } + } else { + $markup = substr($markup, strpos($markup, '')+6); + $markup = substr($markup, 0, strrpos($markup, '')); + } + $fragment->isDocumentFragment = $tmp; + if (phpQuery::$debug) + phpQuery::debug('documentFragmentToMarkup: '.substr($markup, 0, 150)); + return $markup; + } + /** + * Return document markup, starting with optional $nodes as root. + * + * @param $nodes DOMNode|DOMNodeList + * @return string + */ + public function markup($nodes = null, $innerMarkup = false) { + if (isset($nodes) && count($nodes) == 1 && $nodes[0] instanceof DOMDOCUMENT) + $nodes = null; + if (isset($nodes)) { + $markup = ''; + if (!is_array($nodes) && !($nodes instanceof DOMNODELIST) ) + $nodes = array($nodes); + if ($this->isDocumentFragment && ! $innerMarkup) + foreach($nodes as $i => $node) + if ($node->isSameNode($this->root)) { + // var_dump($node); + $nodes = array_slice($nodes, 0, $i) + + phpQuery::DOMNodeListToArray($node->childNodes) + + array_slice($nodes, $i+1); + } + if ($this->isXML && ! $innerMarkup) { + self::debug("Getting outerXML with charset '{$this->charset}'"); + // we need outerXML, so we can benefit from + // $node param support in saveXML() + foreach($nodes as $node) + $markup .= $this->document->saveXML($node); + } else { + $loop = array(); + if ($innerMarkup) + foreach($nodes as $node) { + if ($node->childNodes) + foreach($node->childNodes as $child) + $loop[] = $child; + else + $loop[] = $node; + } + else + $loop = $nodes; + self::debug("Getting markup, moving selected nodes (".count($loop).") to new DocumentFragment"); + $fake = $this->documentFragmentCreate($loop); + $markup = $this->documentFragmentToMarkup($fake); + } + if ($this->isXHTML) { + self::debug("Fixing XHTML"); + $markup = self::markupFixXHTML($markup); + } + self::debug("Markup: ".substr($markup, 0, 250)); + return $markup; + } else { + if ($this->isDocumentFragment) { + // documentFragment, html only... + self::debug("Getting markup, DocumentFragment detected"); +// return $this->markup( +//// $this->document->getElementsByTagName('body')->item(0) +// $this->document->root, true +// ); + $markup = $this->documentFragmentToMarkup($this); + // no need for markupFixXHTML, as it's done thought markup($nodes) method + return $markup; + } else { + self::debug("Getting markup (".($this->isXML?'XML':'HTML')."), final with charset '{$this->charset}'"); + $markup = $this->isXML + ? $this->document->saveXML() + : $this->document->saveHTML(); + if ($this->isXHTML) { + self::debug("Fixing XHTML"); + $markup = self::markupFixXHTML($markup); + } + self::debug("Markup: ".substr($markup, 0, 250)); + return $markup; + } + } + } + protected static function markupFixXHTML($markup) { + $markup = self::expandEmptyTag('script', $markup); + $markup = self::expandEmptyTag('select', $markup); + $markup = self::expandEmptyTag('textarea', $markup); + return $markup; + } + public static function debug($text) { + phpQuery::debug($text); + } + /** + * expandEmptyTag + * + * @param $tag + * @param $xml + * @return unknown_type + * @author mjaque at ilkebenson dot com + * @link http://php.net/manual/en/domdocument.savehtml.php#81256 + */ + public static function expandEmptyTag($tag, $xml){ + $indice = 0; + while ($indice< strlen($xml)){ + $pos = strpos($xml, "<$tag ", $indice); + if ($pos){ + $posCierre = strpos($xml, ">", $pos); + if ($xml[$posCierre-1] == "/"){ + $xml = substr_replace($xml, ">", $posCierre-1, 2); + } + $indice = $posCierre; + } + else break; + } + return $xml; + } +} + +/** + * Event handling class. + * + * @author Tobiasz Cudnik + * @package phpQuery + * @static + */ +abstract class phpQueryEvents { + /** + * Trigger a type of event on every matched element. + * + * @param DOMNode|phpQueryObject|string $document + * @param unknown_type $type + * @param unknown_type $data + * + * @TODO exclusive events (with !) + * @TODO global events (test) + * @TODO support more than event in $type (space-separated) + */ + public static function trigger($document, $type, $data = array(), $node = null) { + // trigger: function(type, data, elem, donative, extra) { + $documentID = phpQuery::getDocumentID($document); + $namespace = null; + if (strpos($type, '.') !== false) + list($name, $namespace) = explode('.', $type); + else + $name = $type; + if (! $node) { + if (self::issetGlobal($documentID, $type)) { + $pq = phpQuery::getDocument($documentID); + // TODO check add($pq->document) + $pq->find('*')->add($pq->document) + ->trigger($type, $data); + } + } else { + if (isset($data[0]) && $data[0] instanceof DOMEvent) { + $event = $data[0]; + $event->relatedTarget = $event->target; + $event->target = $node; + $data = array_slice($data, 1); + } else { + $event = new DOMEvent(array( + 'type' => $type, + 'target' => $node, + 'timeStamp' => time(), + )); + } + $i = 0; + while($node) { + // TODO whois + phpQuery::debug("Triggering ".($i?"bubbled ":'')."event '{$type}' on " + ."node \n");//.phpQueryObject::whois($node)."\n"); + $event->currentTarget = $node; + $eventNode = self::getNode($documentID, $node); + if (isset($eventNode->eventHandlers)) { + foreach($eventNode->eventHandlers as $eventType => $handlers) { + $eventNamespace = null; + if (strpos($type, '.') !== false) + list($eventName, $eventNamespace) = explode('.', $eventType); + else + $eventName = $eventType; + if ($name != $eventName) + continue; + if ($namespace && $eventNamespace && $namespace != $eventNamespace) + continue; + foreach($handlers as $handler) { + phpQuery::debug("Calling event handler\n"); + $event->data = $handler['data'] + ? $handler['data'] + : null; + $params = array_merge(array($event), $data); + $return = phpQuery::callbackRun($handler['callback'], $params); + if ($return === false) { + $event->bubbles = false; + } + } + } + } + // to bubble or not to bubble... + if (! $event->bubbles) + break; + $node = $node->parentNode; + $i++; + } + } + } + /** + * Binds a handler to one or more events (like click) for each matched element. + * Can also bind custom events. + * + * @param DOMNode|phpQueryObject|string $document + * @param unknown_type $type + * @param unknown_type $data Optional + * @param unknown_type $callback + * + * @TODO support '!' (exclusive) events + * @TODO support more than event in $type (space-separated) + * @TODO support binding to global events + */ + public static function add($document, $node, $type, $data, $callback = null) { + phpQuery::debug("Binding '$type' event"); + $documentID = phpQuery::getDocumentID($document); +// if (is_null($callback) && is_callable($data)) { +// $callback = $data; +// $data = null; +// } + $eventNode = self::getNode($documentID, $node); + if (! $eventNode) + $eventNode = self::setNode($documentID, $node); + if (!isset($eventNode->eventHandlers[$type])) + $eventNode->eventHandlers[$type] = array(); + $eventNode->eventHandlers[$type][] = array( + 'callback' => $callback, + 'data' => $data, + ); + } + /** + * Enter description here... + * + * @param DOMNode|phpQueryObject|string $document + * @param unknown_type $type + * @param unknown_type $callback + * + * @TODO namespace events + * @TODO support more than event in $type (space-separated) + */ + public static function remove($document, $node, $type = null, $callback = null) { + $documentID = phpQuery::getDocumentID($document); + $eventNode = self::getNode($documentID, $node); + if (is_object($eventNode) && isset($eventNode->eventHandlers[$type])) { + if ($callback) { + foreach($eventNode->eventHandlers[$type] as $k => $handler) + if ($handler['callback'] == $callback) + unset($eventNode->eventHandlers[$type][$k]); + } else { + unset($eventNode->eventHandlers[$type]); + } + } + } + protected static function getNode($documentID, $node) { + foreach(phpQuery::$documents[$documentID]->eventsNodes as $eventNode) { + if ($node->isSameNode($eventNode)) + return $eventNode; + } + } + protected static function setNode($documentID, $node) { + phpQuery::$documents[$documentID]->eventsNodes[] = $node; + return phpQuery::$documents[$documentID]->eventsNodes[ + count(phpQuery::$documents[$documentID]->eventsNodes)-1 + ]; + } + protected static function issetGlobal($documentID, $type) { + return isset(phpQuery::$documents[$documentID]) + ? in_array($type, phpQuery::$documents[$documentID]->eventsGlobal) + : false; + } +} + + +interface ICallbackNamed { + function hasName(); + function getName(); +} +/** + * Callback class introduces currying-like pattern. + * + * Example: + * function foo($param1, $param2, $param3) { + * var_dump($param1, $param2, $param3); + * } + * $fooCurried = new Callback('foo', + * 'param1 is now statically set', + * new CallbackParam, new CallbackParam + * ); + * phpQuery::callbackRun($fooCurried, + * array('param2 value', 'param3 value' + * ); + * + * Callback class is supported in all phpQuery methods which accepts callbacks. + * + * @link http://code.google.com/p/phpquery/wiki/Callbacks#Param_Structures + * @author Tobiasz Cudnik + * + * @TODO??? return fake forwarding function created via create_function + * @TODO honor paramStructure + */ +class Callback + implements ICallbackNamed { + public $callback = null; + public $params = null; + protected $name; + public function __construct($callback, $param1 = null, $param2 = null, + $param3 = null) { + $params = func_get_args(); + $params = array_slice($params, 1); + if ($callback instanceof Callback) { + // TODO implement recurention + } else { + $this->callback = $callback; + $this->params = $params; + } + } + public function getName() { + return 'Callback: '.$this->name; + } + public function hasName() { + return isset($this->name) && $this->name; + } + public function setName($name) { + $this->name = $name; + return $this; + } + // TODO test me +// public function addParams() { +// $params = func_get_args(); +// return new Callback($this->callback, $this->params+$params); +// } +} +/** + * Shorthand for new Callback(create_function(...), ...); + * + * @author Tobiasz Cudnik + */ +class CallbackBody extends Callback { + public function __construct($paramList, $code, $param1 = null, $param2 = null, + $param3 = null) { + $params = func_get_args(); + $params = array_slice($params, 2); + $this->callback = create_function($paramList, $code); + $this->params = $params; + } +} +/** + * Callback type which on execution returns reference passed during creation. + * + * @author Tobiasz Cudnik + */ +class CallbackReturnReference extends Callback + implements ICallbackNamed { + protected $reference; + public function __construct(&$reference, $name = null){ + $this->reference =& $reference; + $this->callback = array($this, 'callback'); + } + public function callback() { + return $this->reference; + } + public function getName() { + return 'Callback: '.$this->name; + } + public function hasName() { + return isset($this->name) && $this->name; + } +} +/** + * Callback type which on execution returns value passed during creation. + * + * @author Tobiasz Cudnik + */ +class CallbackReturnValue extends Callback + implements ICallbackNamed { + protected $value; + protected $name; + public function __construct($value, $name = null){ + $this->value =& $value; + $this->name = $name; + $this->callback = array($this, 'callback'); + } + public function callback() { + return $this->value; + } + public function __toString() { + return $this->getName(); + } + public function getName() { + return 'Callback: '.$this->name; + } + public function hasName() { + return isset($this->name) && $this->name; + } +} +/** + * CallbackParameterToReference can be used when we don't really want a callback, + * only parameter passed to it. CallbackParameterToReference takes first + * parameter's value and passes it to reference. + * + * @author Tobiasz Cudnik + */ +class CallbackParameterToReference extends Callback { + /** + * @param $reference + * @TODO implement $paramIndex; + * param index choose which callback param will be passed to reference + */ + public function __construct(&$reference){ + $this->callback =& $reference; + } +} +//class CallbackReference extends Callback { +// /** +// * +// * @param $reference +// * @param $paramIndex +// * @todo implement $paramIndex; param index choose which callback param will be passed to reference +// */ +// public function __construct(&$reference, $name = null){ +// $this->callback =& $reference; +// } +//} +class CallbackParam {} + +/** + * Class representing phpQuery objects. + * + * @author Tobiasz Cudnik + * @package phpQuery + * @method phpQueryObject clone() clone() + * @method phpQueryObject empty() empty() + * @method phpQueryObject next() next($selector = null) + * @method phpQueryObject prev() prev($selector = null) + * @property Int $length + */ +class phpQueryObject + implements Iterator, Countable, ArrayAccess { + public $documentID = null; + /** + * DOMDocument class. + * + * @var DOMDocument + */ + public $document = null; + public $charset = null; + /** + * + * @var DOMDocumentWrapper + */ + public $documentWrapper = null; + /** + * XPath interface. + * + * @var DOMXPath + */ + public $xpath = null; + /** + * Stack of selected elements. + * @TODO refactor to ->nodes + * @var array + */ + public $elements = array(); + /** + * @access private + */ + protected $elementsBackup = array(); + /** + * @access private + */ + protected $previous = null; + /** + * @access private + * @TODO deprecate + */ + protected $root = array(); + /** + * Indicated if doument is just a fragment (no tag). + * + * Every document is realy a full document, so even documentFragments can + * be queried against , but getDocument(id)->htmlOuter() will return + * only contents of . + * + * @var bool + */ + public $documentFragment = true; + /** + * Iterator interface helper + * @access private + */ + protected $elementsInterator = array(); + /** + * Iterator interface helper + * @access private + */ + protected $valid = false; + /** + * Iterator interface helper + * @access private + */ + protected $current = null; + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function __construct($documentID) { +// if ($documentID instanceof self) +// var_dump($documentID->getDocumentID()); + $id = $documentID instanceof self + ? $documentID->getDocumentID() + : $documentID; +// var_dump($id); + if (! isset(phpQuery::$documents[$id] )) { +// var_dump(phpQuery::$documents); + throw new Exception("Document with ID '{$id}' isn't loaded. Use phpQuery::newDocument(\$html) or phpQuery::newDocumentFile(\$file) first."); + } + $this->documentID = $id; + $this->documentWrapper =& phpQuery::$documents[$id]; + $this->document =& $this->documentWrapper->document; + $this->xpath =& $this->documentWrapper->xpath; + $this->charset =& $this->documentWrapper->charset; + $this->documentFragment =& $this->documentWrapper->isDocumentFragment; + // TODO check $this->DOM->documentElement; +// $this->root = $this->document->documentElement; + $this->root =& $this->documentWrapper->root; +// $this->toRoot(); + $this->elements = array($this->root); + } + /** + * + * @access private + * @param $attr + * @return unknown_type + */ + public function __get($attr) { + switch($attr) { + // FIXME doesnt work at all ? + case 'length': + return $this->size(); + break; + default: + return $this->$attr; + } + } + /** + * Saves actual object to $var by reference. + * Useful when need to break chain. + * @param phpQueryObject $var + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function toReference(&$var) { + return $var = $this; + } + public function documentFragment($state = null) { + if ($state) { + phpQuery::$documents[$this->getDocumentID()]['documentFragment'] = $state; + return $this; + } + return $this->documentFragment; + } + /** + * @access private + * @TODO documentWrapper + */ + protected function isRoot( $node) { +// return $node instanceof DOMDOCUMENT || $node->tagName == 'html'; + return $node instanceof DOMDOCUMENT + || ($node instanceof DOMELEMENT && $node->tagName == 'html') + || $this->root->isSameNode($node); + } + /** + * @access private + */ + protected function stackIsRoot() { + return $this->size() == 1 && $this->isRoot($this->elements[0]); + } + /** + * Enter description here... + * NON JQUERY METHOD + * + * Watch out, it doesn't creates new instance, can be reverted with end(). + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function toRoot() { + $this->elements = array($this->root); + return $this; +// return $this->newInstance(array($this->root)); + } + /** + * Saves object's DocumentID to $var by reference. + * + * $myDocumentId; + * phpQuery::newDocument('
') + * ->getDocumentIDRef($myDocumentId) + * ->find('div')->... + * + * + * @param unknown_type $domId + * @see phpQuery::newDocument + * @see phpQuery::newDocumentFile + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function getDocumentIDRef(&$documentID) { + $documentID = $this->getDocumentID(); + return $this; + } + /** + * Returns object with stack set to document root. + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function getDocument() { + return phpQuery::getDocument($this->getDocumentID()); + } + /** + * + * @return DOMDocument + */ + public function getDOMDocument() { + return $this->document; + } + /** + * Get object's Document ID. + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function getDocumentID() { + return $this->documentID; + } + /** + * Unloads whole document from memory. + * CAUTION! None further operations will be possible on this document. + * All objects refering to it will be useless. + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function unloadDocument() { + phpQuery::unloadDocuments($this->getDocumentID()); + } + public function isHTML() { + return $this->documentWrapper->isHTML; + } + public function isXHTML() { + return $this->documentWrapper->isXHTML; + } + public function isXML() { + return $this->documentWrapper->isXML; + } + /** + * Enter description here... + * + * @link http://docs.jquery.com/Ajax/serialize + * @return string + */ + public function serialize() { + return phpQuery::param($this->serializeArray()); + } + /** + * Enter description here... + * + * @link http://docs.jquery.com/Ajax/serializeArray + * @return array + */ + public function serializeArray($submit = null) { + $source = $this->filter('form, input, select, textarea') + ->find('input, select, textarea') + ->andSelf() + ->not('form'); + $return = array(); +// $source->dumpDie(); + foreach($source as $input) { + $input = phpQuery::pq($input); + if ($input->is('[disabled]')) + continue; + if (!$input->is('[name]')) + continue; + if ($input->is('[type=checkbox]') && !$input->is('[checked]')) + continue; + // jquery diff + if ($submit && $input->is('[type=submit]')) { + if ($submit instanceof DOMELEMENT && ! $input->elements[0]->isSameNode($submit)) + continue; + else if (is_string($submit) && $input->attr('name') != $submit) + continue; + } + $return[] = array( + 'name' => $input->attr('name'), + 'value' => $input->val(), + ); + } + return $return; + } + /** + * @access private + */ + protected function debug($in) { + if (! phpQuery::$debug ) + return; + print('
');
+        print_r($in);
+        // file debug
+//      file_put_contents(dirname(__FILE__).'/phpQuery.log', print_r($in, true)."\n", FILE_APPEND);
+        // quite handy debug trace
+//      if ( is_array($in))
+//          print_r(array_slice(debug_backtrace(), 3));
+        print("
\n"); + } + /** + * @access private + */ + protected function isRegexp($pattern) { + return in_array( + $pattern[ mb_strlen($pattern)-1 ], + array('^','*','$') + ); + } + /** + * Determines if $char is really a char. + * + * @param string $char + * @return bool + * @todo rewrite me to charcode range ! ;) + * @access private + */ + protected function isChar($char) { + return extension_loaded('mbstring') && phpQuery::$mbstringSupport + ? mb_eregi('\w', $char) + : preg_match('@\w@', $char); + } + /** + * @access private + */ + protected function parseSelector($query) { + // clean spaces + // TODO include this inside parsing ? + $query = trim( + preg_replace('@\s+@', ' ', + preg_replace('@\s*(>|\\+|~)\s*@', '\\1', $query) + ) + ); + $queries = array(array()); + if (! $query) + return $queries; + $return =& $queries[0]; + $specialChars = array('>',' '); +// $specialCharsMapping = array('/' => '>'); + $specialCharsMapping = array(); + $strlen = mb_strlen($query); + $classChars = array('.', '-'); + $pseudoChars = array('-'); + $tagChars = array('*', '|', '-'); + // split multibyte string + // http://code.google.com/p/phpquery/issues/detail?id=76 + $_query = array(); + for ($i=0; $i<$strlen; $i++) + $_query[] = mb_substr($query, $i, 1); + $query = $_query; + // it works, but i dont like it... + $i = 0; + while( $i < $strlen) { + $c = $query[$i]; + $tmp = ''; + // TAG + if ($this->isChar($c) || in_array($c, $tagChars)) { + while(isset($query[$i]) + && ($this->isChar($query[$i]) || in_array($query[$i], $tagChars))) { + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // IDs + } else if ( $c == '#') { + $i++; + while( isset($query[$i]) && ($this->isChar($query[$i]) || $query[$i] == '-')) { + $tmp .= $query[$i]; + $i++; + } + $return[] = '#'.$tmp; + // SPECIAL CHARS + } else if (in_array($c, $specialChars)) { + $return[] = $c; + $i++; + // MAPPED SPECIAL MULTICHARS +// } else if ( $c.$query[$i+1] == '//') { +// $return[] = ' '; +// $i = $i+2; + // MAPPED SPECIAL CHARS + } else if ( isset($specialCharsMapping[$c])) { + $return[] = $specialCharsMapping[$c]; + $i++; + // COMMA + } else if ( $c == ',') { + $queries[] = array(); + $return =& $queries[ count($queries)-1 ]; + $i++; + while( isset($query[$i]) && $query[$i] == ' ') + $i++; + // CLASSES + } else if ($c == '.') { + while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $classChars))) { + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // ~ General Sibling Selector + } else if ($c == '~') { + $spaceAllowed = true; + $tmp .= $query[$i++]; + while( isset($query[$i]) + && ($this->isChar($query[$i]) + || in_array($query[$i], $classChars) + || $query[$i] == '*' + || ($query[$i] == ' ' && $spaceAllowed) + )) { + if ($query[$i] != ' ') + $spaceAllowed = false; + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // + Adjacent sibling selectors + } else if ($c == '+') { + $spaceAllowed = true; + $tmp .= $query[$i++]; + while( isset($query[$i]) + && ($this->isChar($query[$i]) + || in_array($query[$i], $classChars) + || $query[$i] == '*' + || ($spaceAllowed && $query[$i] == ' ') + )) { + if ($query[$i] != ' ') + $spaceAllowed = false; + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // ATTRS + } else if ($c == '[') { + $stack = 1; + $tmp .= $c; + while( isset($query[++$i])) { + $tmp .= $query[$i]; + if ( $query[$i] == '[') { + $stack++; + } else if ( $query[$i] == ']') { + $stack--; + if (! $stack ) + break; + } + } + $return[] = $tmp; + $i++; + // PSEUDO CLASSES + } else if ($c == ':') { + $stack = 1; + $tmp .= $query[$i++]; + while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $pseudoChars))) { + $tmp .= $query[$i]; + $i++; + } + // with arguments ? + if ( isset($query[$i]) && $query[$i] == '(') { + $tmp .= $query[$i]; + $stack = 1; + while( isset($query[++$i])) { + $tmp .= $query[$i]; + if ( $query[$i] == '(') { + $stack++; + } else if ( $query[$i] == ')') { + $stack--; + if (! $stack ) + break; + } + } + $return[] = $tmp; + $i++; + } else { + $return[] = $tmp; + } + } else { + $i++; + } + } + foreach($queries as $k => $q) { + if (isset($q[0])) { + if (isset($q[0][0]) && $q[0][0] == ':') + array_unshift($queries[$k], '*'); + if ($q[0] != '>') + array_unshift($queries[$k], ' '); + } + } + return $queries; + } + /** + * Return matched DOM nodes. + * + * @param int $index + * @return array|DOMElement Single DOMElement or array of DOMElement. + */ + public function get($index = null, $callback1 = null, $callback2 = null, $callback3 = null) { + $return = isset($index) + ? (isset($this->elements[$index]) ? $this->elements[$index] : null) + : $this->elements; + // pass thou callbacks + $args = func_get_args(); + $args = array_slice($args, 1); + foreach($args as $callback) { + if (is_array($return)) + foreach($return as $k => $v) + $return[$k] = phpQuery::callbackRun($callback, array($v)); + else + $return = phpQuery::callbackRun($callback, array($return)); + } + return $return; + } + /** + * Return matched DOM nodes. + * jQuery difference. + * + * @param int $index + * @return array|string Returns string if $index != null + * @todo implement callbacks + * @todo return only arrays ? + * @todo maybe other name... + */ + public function getString($index = null, $callback1 = null, $callback2 = null, $callback3 = null) { + if ($index) + $return = $this->eq($index)->text(); + else { + $return = array(); + for($i = 0; $i < $this->size(); $i++) { + $return[] = $this->eq($i)->text(); + } + } + // pass thou callbacks + $args = func_get_args(); + $args = array_slice($args, 1); + foreach($args as $callback) { + $return = phpQuery::callbackRun($callback, array($return)); + } + return $return; + } + /** + * Return matched DOM nodes. + * jQuery difference. + * + * @param int $index + * @return array|string Returns string if $index != null + * @todo implement callbacks + * @todo return only arrays ? + * @todo maybe other name... + */ + public function getStrings($index = null, $callback1 = null, $callback2 = null, $callback3 = null) { + if ($index) + $return = $this->eq($index)->text(); + else { + $return = array(); + for($i = 0; $i < $this->size(); $i++) { + $return[] = $this->eq($i)->text(); + } + // pass thou callbacks + $args = func_get_args(); + $args = array_slice($args, 1); + } + foreach($args as $callback) { + if (is_array($return)) + foreach($return as $k => $v) + $return[$k] = phpQuery::callbackRun($callback, array($v)); + else + $return = phpQuery::callbackRun($callback, array($return)); + } + return $return; + } + /** + * Returns new instance of actual class. + * + * @param array $newStack Optional. Will replace old stack with new and move old one to history.c + */ + public function newInstance($newStack = null) { + $class = get_class($this); + // support inheritance by passing old object to overloaded constructor + $new = $class != 'phpQuery' + ? new $class($this, $this->getDocumentID()) + : new phpQueryObject($this->getDocumentID()); + $new->previous = $this; + if (is_null($newStack)) { + $new->elements = $this->elements; + if ($this->elementsBackup) + $this->elements = $this->elementsBackup; + } else if (is_string($newStack)) { + $new->elements = phpQuery::pq($newStack, $this->getDocumentID())->stack(); + } else { + $new->elements = $newStack; + } + return $new; + } + /** + * Enter description here... + * + * In the future, when PHP will support XLS 2.0, then we would do that this way: + * contains(tokenize(@class, '\s'), "something") + * @param unknown_type $class + * @param unknown_type $node + * @return boolean + * @access private + */ + protected function matchClasses($class, $node) { + // multi-class + if ( mb_strpos($class, '.', 1)) { + $classes = explode('.', substr($class, 1)); + $classesCount = count( $classes ); + $nodeClasses = explode(' ', $node->getAttribute('class') ); + $nodeClassesCount = count( $nodeClasses ); + if ( $classesCount > $nodeClassesCount ) + return false; + $diff = count( + array_diff( + $classes, + $nodeClasses + ) + ); + if (! $diff ) + return true; + // single-class + } else { + return in_array( + // strip leading dot from class name + substr($class, 1), + // get classes for element as array + explode(' ', $node->getAttribute('class') ) + ); + } + } + /** + * @access private + */ + protected function runQuery($XQuery, $selector = null, $compare = null) { + if ($compare && ! method_exists($this, $compare)) + return false; + $stack = array(); + if (! $this->elements) + $this->debug('Stack empty, skipping...'); +// var_dump($this->elements[0]->nodeType); + // element, document + foreach($this->stack(array(1, 9, 13)) as $k => $stackNode) { + $detachAfter = false; + // to work on detached nodes we need temporary place them somewhere + // thats because context xpath queries sucks ;] + $testNode = $stackNode; + while ($testNode) { + if (! $testNode->parentNode && ! $this->isRoot($testNode)) { + $this->root->appendChild($testNode); + $detachAfter = $testNode; + break; + } + $testNode = isset($testNode->parentNode) + ? $testNode->parentNode + : null; + } + // XXX tmp ? + $xpath = $this->documentWrapper->isXHTML + ? $this->getNodeXpath($stackNode, 'html') + : $this->getNodeXpath($stackNode); + // FIXME pseudoclasses-only query, support XML + $query = $XQuery == '//' && $xpath == '/html[1]' + ? '//*' + : $xpath.$XQuery; + $this->debug("XPATH: {$query}"); + // run query, get elements + $nodes = $this->xpath->query($query); + $this->debug("QUERY FETCHED"); + if (! $nodes->length ) + $this->debug('Nothing found'); + $debug = array(); + foreach($nodes as $node) { + $matched = false; + if ( $compare) { + phpQuery::$debug ? + $this->debug("Found: ".$this->whois( $node ).", comparing with {$compare}()") + : null; + $phpQueryDebug = phpQuery::$debug; + phpQuery::$debug = false; + // TODO ??? use phpQuery::callbackRun() + if (call_user_func_array(array($this, $compare), array($selector, $node))) + $matched = true; + phpQuery::$debug = $phpQueryDebug; + } else { + $matched = true; + } + if ( $matched) { + if (phpQuery::$debug) + $debug[] = $this->whois( $node ); + $stack[] = $node; + } + } + if (phpQuery::$debug) { + $this->debug("Matched ".count($debug).": ".implode(', ', $debug)); + } + if ($detachAfter) + $this->root->removeChild($detachAfter); + } + $this->elements = $stack; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function find($selectors, $context = null, $noHistory = false) { + if (!$noHistory) + // backup last stack /for end()/ + $this->elementsBackup = $this->elements; + // allow to define context + // TODO combine code below with phpQuery::pq() context guessing code + // as generic function + if ($context) { + if (! is_array($context) && $context instanceof DOMELEMENT) + $this->elements = array($context); + else if (is_array($context)) { + $this->elements = array(); + foreach ($context as $c) + if ($c instanceof DOMELEMENT) + $this->elements[] = $c; + } else if ( $context instanceof self ) + $this->elements = $context->elements; + } + $queries = $this->parseSelector($selectors); + $this->debug(array('FIND', $selectors, $queries)); + $XQuery = ''; + // remember stack state because of multi-queries + $oldStack = $this->elements; + // here we will be keeping found elements + $stack = array(); + foreach($queries as $selector) { + $this->elements = $oldStack; + $delimiterBefore = false; + foreach($selector as $s) { + // TAG + $isTag = extension_loaded('mbstring') && phpQuery::$mbstringSupport + ? mb_ereg_match('^[\w|\||-]+$', $s) || $s == '*' + : preg_match('@^[\w|\||-]+$@', $s) || $s == '*'; + if ($isTag) { + if ($this->isXML()) { + // namespace support + if (mb_strpos($s, '|') !== false) { + $ns = $tag = null; + list($ns, $tag) = explode('|', $s); + $XQuery .= "$ns:$tag"; + } else if ($s == '*') { + $XQuery .= "*"; + } else { + $XQuery .= "*[local-name()='$s']"; + } + } else { + $XQuery .= $s; + } + // ID + } else if ($s[0] == '#') { + if ($delimiterBefore) + $XQuery .= '*'; + $XQuery .= "[@id='".substr($s, 1)."']"; + // ATTRIBUTES + } else if ($s[0] == '[') { + if ($delimiterBefore) + $XQuery .= '*'; + // strip side brackets + $attr = trim($s, ']['); + $execute = false; + // attr with specifed value + if (mb_strpos($s, '=')) { + $value = null; + list($attr, $value) = explode('=', $attr); + $value = trim($value, "'\""); + if ($this->isRegexp($attr)) { + // cut regexp character + $attr = substr($attr, 0, -1); + $execute = true; + $XQuery .= "[@{$attr}]"; + } else { + $XQuery .= "[@{$attr}='{$value}']"; + } + // attr without specified value + } else { + $XQuery .= "[@{$attr}]"; + } + if ($execute) { + $this->runQuery($XQuery, $s, 'is'); + $XQuery = ''; + if (! $this->length()) + break; + } + // CLASSES + } else if ($s[0] == '.') { + // TODO use return $this->find("./self::*[contains(concat(\" \",@class,\" \"), \" $class \")]"); + // thx wizDom ;) + if ($delimiterBefore) + $XQuery .= '*'; + $XQuery .= '[@class]'; + $this->runQuery($XQuery, $s, 'matchClasses'); + $XQuery = ''; + if (! $this->length() ) + break; + // ~ General Sibling Selector + } else if ($s[0] == '~') { + $this->runQuery($XQuery); + $XQuery = ''; + $this->elements = $this + ->siblings( + substr($s, 1) + )->elements; + if (! $this->length() ) + break; + // + Adjacent sibling selectors + } else if ($s[0] == '+') { + // TODO /following-sibling:: + $this->runQuery($XQuery); + $XQuery = ''; + $subSelector = substr($s, 1); + $subElements = $this->elements; + $this->elements = array(); + foreach($subElements as $node) { + // search first DOMElement sibling + $test = $node->nextSibling; + while($test && ! ($test instanceof DOMELEMENT)) + $test = $test->nextSibling; + if ($test && $this->is($subSelector, $test)) + $this->elements[] = $test; + } + if (! $this->length() ) + break; + // PSEUDO CLASSES + } else if ($s[0] == ':') { + // TODO optimization for :first :last + if ($XQuery) { + $this->runQuery($XQuery); + $XQuery = ''; + } + if (! $this->length()) + break; + $this->pseudoClasses($s); + if (! $this->length()) + break; + // DIRECT DESCENDANDS + } else if ($s == '>') { + $XQuery .= '/'; + $delimiterBefore = 2; + // ALL DESCENDANDS + } else if ($s == ' ') { + $XQuery .= '//'; + $delimiterBefore = 2; + // ERRORS + } else { + phpQuery::debug("Unrecognized token '$s'"); + } + $delimiterBefore = $delimiterBefore === 2; + } + // run query if any + if ($XQuery && $XQuery != '//') { + $this->runQuery($XQuery); + $XQuery = ''; + } + foreach($this->elements as $node) + if (! $this->elementsContainsNode($node, $stack)) + $stack[] = $node; + } + $this->elements = $stack; + return $this->newInstance(); + } + /** + * @todo create API for classes with pseudoselectors + * @access private + */ + protected function pseudoClasses($class) { + // TODO clean args parsing ? + $class = ltrim($class, ':'); + $haveArgs = mb_strpos($class, '('); + if ($haveArgs !== false) { + $args = substr($class, $haveArgs+1, -1); + $class = substr($class, 0, $haveArgs); + } + switch($class) { + case 'even': + case 'odd': + $stack = array(); + foreach($this->elements as $i => $node) { + if ($class == 'even' && ($i%2) == 0) + $stack[] = $node; + else if ( $class == 'odd' && $i % 2 ) + $stack[] = $node; + } + $this->elements = $stack; + break; + case 'eq': + $k = intval($args); + $this->elements = isset( $this->elements[$k] ) + ? array( $this->elements[$k] ) + : array(); + break; + case 'gt': + $this->elements = array_slice($this->elements, $args+1); + break; + case 'lt': + $this->elements = array_slice($this->elements, 0, $args+1); + break; + case 'first': + if (isset($this->elements[0])) + $this->elements = array($this->elements[0]); + break; + case 'last': + if ($this->elements) + $this->elements = array($this->elements[count($this->elements)-1]); + break; + /*case 'parent': + $stack = array(); + foreach($this->elements as $node) { + if ( $node->childNodes->length ) + $stack[] = $node; + } + $this->elements = $stack; + break;*/ + case 'contains': + $text = trim($args, "\"'"); + $stack = array(); + foreach($this->elements as $node) { + if (mb_stripos($node->textContent, $text) === false) + continue; + $stack[] = $node; + } + $this->elements = $stack; + break; + case 'not': + $selector = self::unQuote($args); + $this->elements = $this->not($selector)->stack(); + break; + case 'slice': + // TODO jQuery difference ? + $args = explode(',', + str_replace(', ', ',', trim($args, "\"'")) + ); + $start = $args[0]; + $end = isset($args[1]) + ? $args[1] + : null; + if ($end > 0) + $end = $end-$start; + $this->elements = array_slice($this->elements, $start, $end); + break; + case 'has': + $selector = trim($args, "\"'"); + $stack = array(); + foreach($this->stack(1) as $el) { + if ($this->find($selector, $el, true)->length) + $stack[] = $el; + } + $this->elements = $stack; + break; + case 'submit': + case 'reset': + $this->elements = phpQuery::merge( + $this->map(array($this, 'is'), + "input[type=$class]", new CallbackParam() + ), + $this->map(array($this, 'is'), + "button[type=$class]", new CallbackParam() + ) + ); + break; +// $stack = array(); +// foreach($this->elements as $node) +// if ($node->is('input[type=submit]') || $node->is('button[type=submit]')) +// $stack[] = $el; +// $this->elements = $stack; + case 'input': + $this->elements = $this->map( + array($this, 'is'), + 'input', new CallbackParam() + )->elements; + break; + case 'password': + case 'checkbox': + case 'radio': + case 'hidden': + case 'image': + case 'file': + $this->elements = $this->map( + array($this, 'is'), + "input[type=$class]", new CallbackParam() + )->elements; + break; + case 'parent': + $this->elements = $this->map( + create_function('$node', ' + return $node instanceof DOMELEMENT && $node->childNodes->length + ? $node : null;') + )->elements; + break; + case 'empty': + $this->elements = $this->map( + create_function('$node', ' + return $node instanceof DOMELEMENT && $node->childNodes->length + ? null : $node;') + )->elements; + break; + case 'disabled': + case 'selected': + case 'checked': + $this->elements = $this->map( + array($this, 'is'), + "[$class]", new CallbackParam() + )->elements; + break; + case 'enabled': + $this->elements = $this->map( + create_function('$node', ' + return pq($node)->not(":disabled") ? $node : null;') + )->elements; + break; + case 'header': + $this->elements = $this->map( + create_function('$node', + '$isHeader = isset($node->tagName) && in_array($node->tagName, array( + "h1", "h2", "h3", "h4", "h5", "h6", "h7" + )); + return $isHeader + ? $node + : null;') + )->elements; +// $this->elements = $this->map( +// create_function('$node', '$node = pq($node); +// return $node->is("h1") +// || $node->is("h2") +// || $node->is("h3") +// || $node->is("h4") +// || $node->is("h5") +// || $node->is("h6") +// || $node->is("h7") +// ? $node +// : null;') +// )->elements; + break; + case 'only-child': + $this->elements = $this->map( + create_function('$node', + 'return pq($node)->siblings()->size() == 0 ? $node : null;') + )->elements; + break; + case 'first-child': + $this->elements = $this->map( + create_function('$node', 'return pq($node)->prevAll()->size() == 0 ? $node : null;') + )->elements; + break; + case 'last-child': + $this->elements = $this->map( + create_function('$node', 'return pq($node)->nextAll()->size() == 0 ? $node : null;') + )->elements; + break; + case 'nth-child': + $param = trim($args, "\"'"); + if (! $param) + break; + // nth-child(n+b) to nth-child(1n+b) + if ($param{0} == 'n') + $param = '1'.$param; + // :nth-child(index/even/odd/equation) + if ($param == 'even' || $param == 'odd') + $mapped = $this->map( + create_function('$node, $param', + '$index = pq($node)->prevAll()->size()+1; + if ($param == "even" && ($index%2) == 0) + return $node; + else if ($param == "odd" && $index%2 == 1) + return $node; + else + return null;'), + new CallbackParam(), $param + ); + else if (mb_strlen($param) > 1 && $param{1} == 'n') + // an+b + $mapped = $this->map( + create_function('$node, $param', + '$prevs = pq($node)->prevAll()->size(); + $index = 1+$prevs; + $b = mb_strlen($param) > 3 + ? $param{3} + : 0; + $a = $param{0}; + if ($b && $param{2} == "-") + $b = -$b; + if ($a > 0) { + return ($index-$b)%$a == 0 + ? $node + : null; + phpQuery::debug($a."*".floor($index/$a)."+$b-1 == ".($a*floor($index/$a)+$b-1)." ?= $prevs"); + return $a*floor($index/$a)+$b-1 == $prevs + ? $node + : null; + } else if ($a == 0) + return $index == $b + ? $node + : null; + else + // negative value + return $index <= $b + ? $node + : null; +// if (! $b) +// return $index%$a == 0 +// ? $node +// : null; +// else +// return ($index-$b)%$a == 0 +// ? $node +// : null; + '), + new CallbackParam(), $param + ); + else + // index + $mapped = $this->map( + create_function('$node, $index', + '$prevs = pq($node)->prevAll()->size(); + if ($prevs && $prevs == $index-1) + return $node; + else if (! $prevs && $index == 1) + return $node; + else + return null;'), + new CallbackParam(), $param + ); + $this->elements = $mapped->elements; + break; + default: + $this->debug("Unknown pseudoclass '{$class}', skipping..."); + } + } + /** + * @access private + */ + protected function __pseudoClassParam($paramsString) { + // TODO; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function is($selector, $nodes = null) { + phpQuery::debug(array("Is:", $selector)); + if (! $selector) + return false; + $oldStack = $this->elements; + $returnArray = false; + if ($nodes && is_array($nodes)) { + $this->elements = $nodes; + } else if ($nodes) + $this->elements = array($nodes); + $this->filter($selector, true); + $stack = $this->elements; + $this->elements = $oldStack; + if ($nodes) + return $stack ? $stack : null; + return (bool)count($stack); + } + /** + * Enter description here... + * jQuery difference. + * + * Callback: + * - $index int + * - $node DOMNode + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @link http://docs.jquery.com/Traversing/filter + */ + public function filterCallback($callback, $_skipHistory = false) { + if (! $_skipHistory) { + $this->elementsBackup = $this->elements; + $this->debug("Filtering by callback"); + } + $newStack = array(); + foreach($this->elements as $index => $node) { + $result = phpQuery::callbackRun($callback, array($index, $node)); + if (is_null($result) || (! is_null($result) && $result)) + $newStack[] = $node; + } + $this->elements = $newStack; + return $_skipHistory + ? $this + : $this->newInstance(); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @link http://docs.jquery.com/Traversing/filter + */ + public function filter($selectors, $_skipHistory = false) { + if ($selectors instanceof Callback OR $selectors instanceof Closure) + return $this->filterCallback($selectors, $_skipHistory); + if (! $_skipHistory) + $this->elementsBackup = $this->elements; + $notSimpleSelector = array(' ', '>', '~', '+', '/'); + if (! is_array($selectors)) + $selectors = $this->parseSelector($selectors); + if (! $_skipHistory) + $this->debug(array("Filtering:", $selectors)); + $finalStack = array(); + foreach($selectors as $selector) { + $stack = array(); + if (! $selector) + break; + // avoid first space or / + if (in_array($selector[0], $notSimpleSelector)) + $selector = array_slice($selector, 1); + // PER NODE selector chunks + foreach($this->stack() as $node) { + $break = false; + foreach($selector as $s) { + if (!($node instanceof DOMELEMENT)) { + // all besides DOMElement + if ( $s[0] == '[') { + $attr = trim($s, '[]'); + if ( mb_strpos($attr, '=')) { + list( $attr, $val ) = explode('=', $attr); + if ($attr == 'nodeType' && $node->nodeType != $val) + $break = true; + } + } else + $break = true; + } else { + // DOMElement only + // ID + if ( $s[0] == '#') { + if ( $node->getAttribute('id') != substr($s, 1) ) + $break = true; + // CLASSES + } else if ( $s[0] == '.') { + if (! $this->matchClasses( $s, $node ) ) + $break = true; + // ATTRS + } else if ( $s[0] == '[') { + // strip side brackets + $attr = trim($s, '[]'); + if (mb_strpos($attr, '=')) { + list($attr, $val) = explode('=', $attr); + $val = self::unQuote($val); + if ($attr == 'nodeType') { + if ($val != $node->nodeType) + $break = true; + } else if ($this->isRegexp($attr)) { + $val = extension_loaded('mbstring') && phpQuery::$mbstringSupport + ? quotemeta(trim($val, '"\'')) + : preg_quote(trim($val, '"\''), '@'); + // switch last character + switch( substr($attr, -1)) { + // quotemeta used insted of preg_quote + // http://code.google.com/p/phpquery/issues/detail?id=76 + case '^': + $pattern = '^'.$val; + break; + case '*': + $pattern = '.*'.$val.'.*'; + break; + case '$': + $pattern = '.*'.$val.'$'; + break; + } + // cut last character + $attr = substr($attr, 0, -1); + $isMatch = extension_loaded('mbstring') && phpQuery::$mbstringSupport + ? mb_ereg_match($pattern, $node->getAttribute($attr)) + : preg_match("@{$pattern}@", $node->getAttribute($attr)); + if (! $isMatch) + $break = true; + } else if ($node->getAttribute($attr) != $val) + $break = true; + } else if (! $node->hasAttribute($attr)) + $break = true; + // PSEUDO CLASSES + } else if ( $s[0] == ':') { + // skip + // TAG + } else if (trim($s)) { + if ($s != '*') { + // TODO namespaces + if (isset($node->tagName)) { + if ($node->tagName != $s) + $break = true; + } else if ($s == 'html' && ! $this->isRoot($node)) + $break = true; + } + // AVOID NON-SIMPLE SELECTORS + } else if (in_array($s, $notSimpleSelector)) { + $break = true; + $this->debug(array('Skipping non simple selector', $selector)); + } + } + if ($break) + break; + } + // if element passed all chunks of selector - add it to new stack + if (! $break ) + $stack[] = $node; + } + $tmpStack = $this->elements; + $this->elements = $stack; + // PER ALL NODES selector chunks + foreach($selector as $s) + // PSEUDO CLASSES + if ($s[0] == ':') + $this->pseudoClasses($s); + foreach($this->elements as $node) + // XXX it should be merged without duplicates + // but jQuery doesnt do that + $finalStack[] = $node; + $this->elements = $tmpStack; + } + $this->elements = $finalStack; + if ($_skipHistory) { + return $this; + } else { + $this->debug("Stack length after filter(): ".count($finalStack)); + return $this->newInstance(); + } + } + /** + * + * @param $value + * @return unknown_type + * @TODO implement in all methods using passed parameters + */ + protected static function unQuote($value) { + return $value[0] == '\'' || $value[0] == '"' + ? substr($value, 1, -1) + : $value; + } + /** + * Enter description here... + * + * @link http://docs.jquery.com/Ajax/load + * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo Support $selector + */ + public function load($url, $data = null, $callback = null) { + if ($data && ! is_array($data)) { + $callback = $data; + $data = null; + } + if (mb_strpos($url, ' ') !== false) { + $matches = null; + if (extension_loaded('mbstring') && phpQuery::$mbstringSupport) + mb_ereg('^([^ ]+) (.*)$', $url, $matches); + else + preg_match('^([^ ]+) (.*)$', $url, $matches); + $url = $matches[1]; + $selector = $matches[2]; + // FIXME this sucks, pass as callback param + $this->_loadSelector = $selector; + } + $ajax = array( + 'url' => $url, + 'type' => $data ? 'POST' : 'GET', + 'data' => $data, + 'complete' => $callback, + 'success' => array($this, '__loadSuccess') + ); + phpQuery::ajax($ajax); + return $this; + } + /** + * @access private + * @param $html + * @return unknown_type + */ + public function __loadSuccess($html) { + if ($this->_loadSelector) { + $html = phpQuery::newDocument($html)->find($this->_loadSelector); + unset($this->_loadSelector); + } + foreach($this->stack(1) as $node) { + phpQuery::pq($node, $this->getDocumentID()) + ->markup($html); + } + } + /** + * Enter description here... + * + * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo + */ + public function css() { + // TODO + return $this; + } + /** + * @todo + * + */ + public function show(){ + // TODO + return $this; + } + /** + * @todo + * + */ + public function hide(){ + // TODO + return $this; + } + /** + * Trigger a type of event on every matched element. + * + * @param unknown_type $type + * @param unknown_type $data + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @TODO support more than event in $type (space-separated) + */ + public function trigger($type, $data = array()) { + foreach($this->elements as $node) + phpQueryEvents::trigger($this->getDocumentID(), $type, $data, $node); + return $this; + } + /** + * This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions. + * + * @param unknown_type $type + * @param unknown_type $data + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @TODO + */ + public function triggerHandler($type, $data = array()) { + // TODO; + } + /** + * Binds a handler to one or more events (like click) for each matched element. + * Can also bind custom events. + * + * @param unknown_type $type + * @param unknown_type $data Optional + * @param unknown_type $callback + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @TODO support '!' (exclusive) events + * @TODO support more than event in $type (space-separated) + */ + public function bind($type, $data, $callback = null) { + // TODO check if $data is callable, not using is_callable + if (! isset($callback)) { + $callback = $data; + $data = null; + } + foreach($this->elements as $node) + phpQueryEvents::add($this->getDocumentID(), $node, $type, $data, $callback); + return $this; + } + /** + * Enter description here... + * + * @param unknown_type $type + * @param unknown_type $callback + * @return unknown + * @TODO namespace events + * @TODO support more than event in $type (space-separated) + */ + public function unbind($type = null, $callback = null) { + foreach($this->elements as $node) + phpQueryEvents::remove($this->getDocumentID(), $node, $type, $callback); + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function change($callback = null) { + if ($callback) + return $this->bind('change', $callback); + return $this->trigger('change'); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function submit($callback = null) { + if ($callback) + return $this->bind('submit', $callback); + return $this->trigger('submit'); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function click($callback = null) { + if ($callback) + return $this->bind('click', $callback); + return $this->trigger('click'); + } + /** + * Enter description here... + * + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function wrapAllOld($wrapper) { + $wrapper = pq($wrapper)->_clone(); + if (! $wrapper->length() || ! $this->length() ) + return $this; + $wrapper->insertBefore($this->elements[0]); + $deepest = $wrapper->elements[0]; + while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT) + $deepest = $deepest->firstChild; + pq($deepest)->append($this); + return $this; + } + /** + * Enter description here... + * + * TODO testme... + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function wrapAll($wrapper) { + if (! $this->length()) + return $this; + return phpQuery::pq($wrapper, $this->getDocumentID()) + ->clone() + ->insertBefore($this->get(0)) + ->map(array($this, '___wrapAllCallback')) + ->append($this); + } + /** + * + * @param $node + * @return unknown_type + * @access private + */ + public function ___wrapAllCallback($node) { + $deepest = $node; + while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT) + $deepest = $deepest->firstChild; + return $deepest; + } + /** + * Enter description here... + * NON JQUERY METHOD + * + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function wrapAllPHP($codeBefore, $codeAfter) { + return $this + ->slice(0, 1) + ->beforePHP($codeBefore) + ->end() + ->slice(-1) + ->afterPHP($codeAfter) + ->end(); + } + /** + * Enter description here... + * + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function wrap($wrapper) { + foreach($this->stack() as $node) + phpQuery::pq($node, $this->getDocumentID())->wrapAll($wrapper); + return $this; + } + /** + * Enter description here... + * + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function wrapPHP($codeBefore, $codeAfter) { + foreach($this->stack() as $node) + phpQuery::pq($node, $this->getDocumentID())->wrapAllPHP($codeBefore, $codeAfter); + return $this; + } + /** + * Enter description here... + * + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function wrapInner($wrapper) { + foreach($this->stack() as $node) + phpQuery::pq($node, $this->getDocumentID())->contents()->wrapAll($wrapper); + return $this; + } + /** + * Enter description here... + * + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function wrapInnerPHP($codeBefore, $codeAfter) { + foreach($this->stack(1) as $node) + phpQuery::pq($node, $this->getDocumentID())->contents() + ->wrapAllPHP($codeBefore, $codeAfter); + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @testme Support for text nodes + */ + public function contents() { + $stack = array(); + foreach($this->stack(1) as $el) { + // FIXME (fixed) http://code.google.com/p/phpquery/issues/detail?id=56 +// if (! isset($el->childNodes)) +// continue; + foreach($el->childNodes as $node) { + $stack[] = $node; + } + } + return $this->newInstance($stack); + } + /** + * Enter description here... + * + * jQuery difference. + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function contentsUnwrap() { + foreach($this->stack(1) as $node) { + if (! $node->parentNode ) + continue; + $childNodes = array(); + // any modification in DOM tree breaks childNodes iteration, so cache them first + foreach($node->childNodes as $chNode ) + $childNodes[] = $chNode; + foreach($childNodes as $chNode ) +// $node->parentNode->appendChild($chNode); + $node->parentNode->insertBefore($chNode, $node); + $node->parentNode->removeChild($node); + } + return $this; + } + /** + * Enter description here... + * + * jQuery difference. + */ + public function switchWith($markup) { + $markup = pq($markup, $this->getDocumentID()); + $content = null; + foreach($this->stack(1) as $node) { + pq($node) + ->contents()->toReference($content)->end() + ->replaceWith($markup->clone()->append($content)); + } + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function eq($num) { + $oldStack = $this->elements; + $this->elementsBackup = $this->elements; + $this->elements = array(); + if ( isset($oldStack[$num]) ) + $this->elements[] = $oldStack[$num]; + return $this->newInstance(); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function size() { + return count($this->elements); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @deprecated Use length as attribute + */ + public function length() { + return $this->size(); + } + public function count() { + return $this->size(); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo $level + */ + public function end($level = 1) { +// $this->elements = array_pop( $this->history ); +// return $this; +// $this->previous->DOM = $this->DOM; +// $this->previous->XPath = $this->XPath; + return $this->previous + ? $this->previous + : $this; + } + /** + * Enter description here... + * Normal use ->clone() . + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @access private + */ + public function _clone() { + $newStack = array(); + //pr(array('copy... ', $this->whois())); + //$this->dumpHistory('copy'); + $this->elementsBackup = $this->elements; + foreach($this->elements as $node) { + $newStack[] = $node->cloneNode(true); + } + $this->elements = $newStack; + return $this->newInstance(); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function replaceWithPHP($code) { + return $this->replaceWith(phpQuery::php($code)); + } + /** + * Enter description here... + * + * @param String|phpQuery $content + * @link http://docs.jquery.com/Manipulation/replaceWith#content + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function replaceWith($content) { + return $this->after($content)->remove(); + } + /** + * Enter description here... + * + * @param String $selector + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo this works ? + */ + public function replaceAll($selector) { + foreach(phpQuery::pq($selector, $this->getDocumentID()) as $node) + phpQuery::pq($node, $this->getDocumentID()) + ->after($this->_clone()) + ->remove(); + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function remove($selector = null) { + $loop = $selector + ? $this->filter($selector)->elements + : $this->elements; + foreach($loop as $node) { + if (! $node->parentNode ) + continue; + if (isset($node->tagName)) + $this->debug("Removing '{$node->tagName}'"); + $node->parentNode->removeChild($node); + // Mutation event + $event = new DOMEvent(array( + 'target' => $node, + 'type' => 'DOMNodeRemoved' + )); + phpQueryEvents::trigger($this->getDocumentID(), + $event->type, array($event), $node + ); + } + return $this; + } + protected function markupEvents($newMarkup, $oldMarkup, $node) { + if ($node->tagName == 'textarea' && $newMarkup != $oldMarkup) { + $event = new DOMEvent(array( + 'target' => $node, + 'type' => 'change' + )); + phpQueryEvents::trigger($this->getDocumentID(), + $event->type, array($event), $node + ); + } + } + /** + * jQuey difference + * + * @param $markup + * @return unknown_type + * @TODO trigger change event for textarea + */ + public function markup($markup = null, $callback1 = null, $callback2 = null, $callback3 = null) { + $args = func_get_args(); + if ($this->documentWrapper->isXML) + return call_user_func_array(array($this, 'xml'), $args); + else + return call_user_func_array(array($this, 'html'), $args); + } + /** + * jQuey difference + * + * @param $markup + * @return unknown_type + */ + public function markupOuter($callback1 = null, $callback2 = null, $callback3 = null) { + $args = func_get_args(); + if ($this->documentWrapper->isXML) + return call_user_func_array(array($this, 'xmlOuter'), $args); + else + return call_user_func_array(array($this, 'htmlOuter'), $args); + } + /** + * Enter description here... + * + * @param unknown_type $html + * @return string|phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @TODO force html result + */ + public function html($html = null, $callback1 = null, $callback2 = null, $callback3 = null) { + if (isset($html)) { + // INSERT + $nodes = $this->documentWrapper->import($html); + $this->empty(); + foreach($this->stack(1) as $alreadyAdded => $node) { + // for now, limit events for textarea + if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea') + $oldHtml = pq($node, $this->getDocumentID())->markup(); + foreach($nodes as $newNode) { + $node->appendChild($alreadyAdded + ? $newNode->cloneNode(true) + : $newNode + ); + } + // for now, limit events for textarea + if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea') + $this->markupEvents($html, $oldHtml, $node); + } + return $this; + } else { + // FETCH + $return = $this->documentWrapper->markup($this->elements, true); + $args = func_get_args(); + foreach(array_slice($args, 1) as $callback) { + $return = phpQuery::callbackRun($callback, array($return)); + } + return $return; + } + } + /** + * @TODO force xml result + */ + public function xml($xml = null, $callback1 = null, $callback2 = null, $callback3 = null) { + $args = func_get_args(); + return call_user_func_array(array($this, 'html'), $args); + } + /** + * Enter description here... + * @TODO force html result + * + * @return String + */ + public function htmlOuter($callback1 = null, $callback2 = null, $callback3 = null) { + $markup = $this->documentWrapper->markup($this->elements); + // pass thou callbacks + $args = func_get_args(); + foreach($args as $callback) { + $markup = phpQuery::callbackRun($callback, array($markup)); + } + return $markup; + } + /** + * @TODO force xml result + */ + public function xmlOuter($callback1 = null, $callback2 = null, $callback3 = null) { + $args = func_get_args(); + return call_user_func_array(array($this, 'htmlOuter'), $args); + } + public function __toString() { + return $this->markupOuter(); + } + /** + * Just like html(), but returns markup with VALID (dangerous) PHP tags. + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo support returning markup with PHP tags when called without param + */ + public function php($code = null) { + return $this->markupPHP($code); + } + /** + * Enter description here... + * + * @param $code + * @return unknown_type + */ + public function markupPHP($code = null) { + return isset($code) + ? $this->markup(phpQuery::php($code)) + : phpQuery::markupToPHP($this->markup()); + } + /** + * Enter description here... + * + * @param $code + * @return unknown_type + */ + public function markupOuterPHP() { + return phpQuery::markupToPHP($this->markupOuter()); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function children($selector = null) { + $stack = array(); + foreach($this->stack(1) as $node) { +// foreach($node->getElementsByTagName('*') as $newNode) { + foreach($node->childNodes as $newNode) { + if ($newNode->nodeType != 1) + continue; + if ($selector && ! $this->is($selector, $newNode)) + continue; + if ($this->elementsContainsNode($newNode, $stack)) + continue; + $stack[] = $newNode; + } + } + $this->elementsBackup = $this->elements; + $this->elements = $stack; + return $this->newInstance(); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function ancestors($selector = null) { + return $this->children( $selector ); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function append( $content) { + return $this->insert($content, __FUNCTION__); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function appendPHP( $content) { + return $this->insert("", 'append'); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function appendTo( $seletor) { + return $this->insert($seletor, __FUNCTION__); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function prepend( $content) { + return $this->insert($content, __FUNCTION__); + } + /** + * Enter description here... + * + * @todo accept many arguments, which are joined, arrays maybe also + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function prependPHP( $content) { + return $this->insert("", 'prepend'); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function prependTo( $seletor) { + return $this->insert($seletor, __FUNCTION__); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function before($content) { + return $this->insert($content, __FUNCTION__); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function beforePHP( $content) { + return $this->insert("", 'before'); + } + /** + * Enter description here... + * + * @param String|phpQuery + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function insertBefore( $seletor) { + return $this->insert($seletor, __FUNCTION__); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function after( $content) { + return $this->insert($content, __FUNCTION__); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function afterPHP( $content) { + return $this->insert("", 'after'); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function insertAfter( $seletor) { + return $this->insert($seletor, __FUNCTION__); + } + /** + * Internal insert method. Don't use it. + * + * @param unknown_type $target + * @param unknown_type $type + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @access private + */ + public function insert($target, $type) { + $this->debug("Inserting data with '{$type}'"); + $to = false; + switch( $type) { + case 'appendTo': + case 'prependTo': + case 'insertBefore': + case 'insertAfter': + $to = true; + } + switch(gettype($target)) { + case 'string': + $insertFrom = $insertTo = array(); + if ($to) { + // INSERT TO + $insertFrom = $this->elements; + if (phpQuery::isMarkup($target)) { + // $target is new markup, import it + $insertTo = $this->documentWrapper->import($target); + // insert into selected element + } else { + // $tagret is a selector + $thisStack = $this->elements; + $this->toRoot(); + $insertTo = $this->find($target)->elements; + $this->elements = $thisStack; + } + } else { + // INSERT FROM + $insertTo = $this->elements; + $insertFrom = $this->documentWrapper->import($target); + } + break; + case 'object': + $insertFrom = $insertTo = array(); + // phpQuery + if ($target instanceof self) { + if ($to) { + $insertTo = $target->elements; + if ($this->documentFragment && $this->stackIsRoot()) + // get all body children +// $loop = $this->find('body > *')->elements; + // TODO test it, test it hard... +// $loop = $this->newInstance($this->root)->find('> *')->elements; + $loop = $this->root->childNodes; + else + $loop = $this->elements; + // import nodes if needed + $insertFrom = $this->getDocumentID() == $target->getDocumentID() + ? $loop + : $target->documentWrapper->import($loop); + } else { + $insertTo = $this->elements; + if ( $target->documentFragment && $target->stackIsRoot() ) + // get all body children +// $loop = $target->find('body > *')->elements; + $loop = $target->root->childNodes; + else + $loop = $target->elements; + // import nodes if needed + $insertFrom = $this->getDocumentID() == $target->getDocumentID() + ? $loop + : $this->documentWrapper->import($loop); + } + // DOMNODE + } elseif ($target instanceof DOMNODE) { + // import node if needed +// if ( $target->ownerDocument != $this->DOM ) +// $target = $this->DOM->importNode($target, true); + if ( $to) { + $insertTo = array($target); + if ($this->documentFragment && $this->stackIsRoot()) + // get all body children + $loop = $this->root->childNodes; +// $loop = $this->find('body > *')->elements; + else + $loop = $this->elements; + foreach($loop as $fromNode) + // import nodes if needed + $insertFrom[] = ! $fromNode->ownerDocument->isSameNode($target->ownerDocument) + ? $target->ownerDocument->importNode($fromNode, true) + : $fromNode; + } else { + // import node if needed + if (! $target->ownerDocument->isSameNode($this->document)) + $target = $this->document->importNode($target, true); + $insertTo = $this->elements; + $insertFrom[] = $target; + } + } + break; + } + phpQuery::debug("From ".count($insertFrom)."; To ".count($insertTo)." nodes"); + foreach($insertTo as $insertNumber => $toNode) { + // we need static relative elements in some cases + switch( $type) { + case 'prependTo': + case 'prepend': + $firstChild = $toNode->firstChild; + break; + case 'insertAfter': + case 'after': + $nextSibling = $toNode->nextSibling; + break; + } + foreach($insertFrom as $fromNode) { + // clone if inserted already before + $insert = $insertNumber + ? $fromNode->cloneNode(true) + : $fromNode; + switch($type) { + case 'appendTo': + case 'append': +// $toNode->insertBefore( +// $fromNode, +// $toNode->lastChild->nextSibling +// ); + $toNode->appendChild($insert); + $eventTarget = $insert; + break; + case 'prependTo': + case 'prepend': + $toNode->insertBefore( + $insert, + $firstChild + ); + break; + case 'insertBefore': + case 'before': + if (! $toNode->parentNode) + throw new Exception("No parentNode, can't do {$type}()"); + else + $toNode->parentNode->insertBefore( + $insert, + $toNode + ); + break; + case 'insertAfter': + case 'after': + if (! $toNode->parentNode) + throw new Exception("No parentNode, can't do {$type}()"); + else + $toNode->parentNode->insertBefore( + $insert, + $nextSibling + ); + break; + } + // Mutation event + $event = new DOMEvent(array( + 'target' => $insert, + 'type' => 'DOMNodeInserted' + )); + phpQueryEvents::trigger($this->getDocumentID(), + $event->type, array($event), $insert + ); + } + } + return $this; + } + /** + * Enter description here... + * + * @return Int + */ + public function index($subject) { + $index = -1; + $subject = $subject instanceof phpQueryObject + ? $subject->elements[0] + : $subject; + foreach($this->newInstance() as $k => $node) { + if ($node->isSameNode($subject)) + $index = $k; + } + return $index; + } + /** + * Enter description here... + * + * @param unknown_type $start + * @param unknown_type $end + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @testme + */ + public function slice($start, $end = null) { +// $last = count($this->elements)-1; +// $end = $end +// ? min($end, $last) +// : $last; +// if ($start < 0) +// $start = $last+$start; +// if ($start > $last) +// return array(); + if ($end > 0) + $end = $end-$start; + return $this->newInstance( + array_slice($this->elements, $start, $end) + ); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function reverse() { + $this->elementsBackup = $this->elements; + $this->elements = array_reverse($this->elements); + return $this->newInstance(); + } + /** + * Return joined text content. + * @return String + */ + public function text($text = null, $callback1 = null, $callback2 = null, $callback3 = null) { + if (isset($text)) + return $this->html(htmlspecialchars($text)); + $args = func_get_args(); + $args = array_slice($args, 1); + $return = ''; + foreach($this->elements as $node) { + $text = $node->textContent; + if (count($this->elements) > 1 && $text) + $text .= "\n"; + foreach($args as $callback) { + $text = phpQuery::callbackRun($callback, array($text)); + } + $return .= $text; + } + return $return; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function plugin($class, $file = null) { + phpQuery::plugin($class, $file); + return $this; + } + /** + * Deprecated, use $pq->plugin() instead. + * + * @deprecated + * @param $class + * @param $file + * @return unknown_type + */ + public static function extend($class, $file = null) { + return $this->plugin($class, $file); + } + /** + * + * @access private + * @param $method + * @param $args + * @return unknown_type + */ + public function __call($method, $args) { + $aliasMethods = array('clone', 'empty'); + if (isset(phpQuery::$extendMethods[$method])) { + array_unshift($args, $this); + return phpQuery::callbackRun( + phpQuery::$extendMethods[$method], $args + ); + } else if (isset(phpQuery::$pluginsMethods[$method])) { + array_unshift($args, $this); + $class = phpQuery::$pluginsMethods[$method]; + $realClass = "phpQueryObjectPlugin_$class"; + $return = call_user_func_array( + array($realClass, $method), + $args + ); + // XXX deprecate ? + return is_null($return) + ? $this + : $return; + } else if (in_array($method, $aliasMethods)) { + return call_user_func_array(array($this, '_'.$method), $args); + } else + throw new Exception("Method '{$method}' doesnt exist"); + } + /** + * Safe rename of next(). + * + * Use it ONLY when need to call next() on an iterated object (in same time). + * Normaly there is no need to do such thing ;) + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @access private + */ + public function _next($selector = null) { + return $this->newInstance( + $this->getElementSiblings('nextSibling', $selector, true) + ); + } + /** + * Use prev() and next(). + * + * @deprecated + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @access private + */ + public function _prev($selector = null) { + return $this->prev($selector); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function prev($selector = null) { + return $this->newInstance( + $this->getElementSiblings('previousSibling', $selector, true) + ); + } + /** + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo + */ + public function prevAll($selector = null) { + return $this->newInstance( + $this->getElementSiblings('previousSibling', $selector) + ); + } + /** + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo FIXME: returns source elements insted of next siblings + */ + public function nextAll($selector = null) { + return $this->newInstance( + $this->getElementSiblings('nextSibling', $selector) + ); + } + /** + * @access private + */ + protected function getElementSiblings($direction, $selector = null, $limitToOne = false) { + $stack = array(); + $count = 0; + foreach($this->stack() as $node) { + $test = $node; + while( isset($test->{$direction}) && $test->{$direction}) { + $test = $test->{$direction}; + if (! $test instanceof DOMELEMENT) + continue; + $stack[] = $test; + if ($limitToOne) + break; + } + } + if ($selector) { + $stackOld = $this->elements; + $this->elements = $stack; + $stack = $this->filter($selector, true)->stack(); + $this->elements = $stackOld; + } + return $stack; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function siblings($selector = null) { + $stack = array(); + $siblings = array_merge( + $this->getElementSiblings('previousSibling', $selector), + $this->getElementSiblings('nextSibling', $selector) + ); + foreach($siblings as $node) { + if (! $this->elementsContainsNode($node, $stack)) + $stack[] = $node; + } + return $this->newInstance($stack); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function not($selector = null) { + if (is_string($selector)) + phpQuery::debug(array('not', $selector)); + else + phpQuery::debug('not'); + $stack = array(); + if ($selector instanceof self || $selector instanceof DOMNODE) { + foreach($this->stack() as $node) { + if ($selector instanceof self) { + $matchFound = false; + foreach($selector->stack() as $notNode) { + if ($notNode->isSameNode($node)) + $matchFound = true; + } + if (! $matchFound) + $stack[] = $node; + } else if ($selector instanceof DOMNODE) { + if (! $selector->isSameNode($node)) + $stack[] = $node; + } else { + if (! $this->is($selector)) + $stack[] = $node; + } + } + } else { + $orgStack = $this->stack(); + $matched = $this->filter($selector, true)->stack(); +// $matched = array(); +// // simulate OR in filter() instead of AND 5y +// foreach($this->parseSelector($selector) as $s) { +// $matched = array_merge($matched, +// $this->filter(array($s))->stack() +// ); +// } + foreach($orgStack as $node) + if (! $this->elementsContainsNode($node, $matched)) + $stack[] = $node; + } + return $this->newInstance($stack); + } + /** + * Enter description here... + * + * @param string|phpQueryObject + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function add($selector = null) { + if (! $selector) + return $this; + $stack = array(); + $this->elementsBackup = $this->elements; + $found = phpQuery::pq($selector, $this->getDocumentID()); + $this->merge($found->elements); + return $this->newInstance(); + } + /** + * @access private + */ + protected function merge() { + foreach(func_get_args() as $nodes) + foreach($nodes as $newNode ) + if (! $this->elementsContainsNode($newNode) ) + $this->elements[] = $newNode; + } + /** + * @access private + * TODO refactor to stackContainsNode + */ + protected function elementsContainsNode($nodeToCheck, $elementsStack = null) { + $loop = ! is_null($elementsStack) + ? $elementsStack + : $this->elements; + foreach($loop as $node) { + if ( $node->isSameNode( $nodeToCheck ) ) + return true; + } + return false; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function parent($selector = null) { + $stack = array(); + foreach($this->elements as $node ) + if ( $node->parentNode && ! $this->elementsContainsNode($node->parentNode, $stack) ) + $stack[] = $node->parentNode; + $this->elementsBackup = $this->elements; + $this->elements = $stack; + if ( $selector ) + $this->filter($selector, true); + return $this->newInstance(); + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function parents($selector = null) { + $stack = array(); + if (! $this->elements ) + $this->debug('parents() - stack empty'); + foreach($this->elements as $node) { + $test = $node; + while( $test->parentNode) { + $test = $test->parentNode; + if ($this->isRoot($test)) + break; + if (! $this->elementsContainsNode($test, $stack)) { + $stack[] = $test; + continue; + } + } + } + $this->elementsBackup = $this->elements; + $this->elements = $stack; + if ( $selector ) + $this->filter($selector, true); + return $this->newInstance(); + } + /** + * Internal stack iterator. + * + * @access private + */ + public function stack($nodeTypes = null) { + if (!isset($nodeTypes)) + return $this->elements; + if (!is_array($nodeTypes)) + $nodeTypes = array($nodeTypes); + $return = array(); + foreach($this->elements as $node) { + if (in_array($node->nodeType, $nodeTypes)) + $return[] = $node; + } + return $return; + } + // TODO phpdoc; $oldAttr is result of hasAttribute, before any changes + protected function attrEvents($attr, $oldAttr, $oldValue, $node) { + // skip events for XML documents + if (! $this->isXHTML() && ! $this->isHTML()) + return; + $event = null; + // identify + $isInputValue = $node->tagName == 'input' + && ( + in_array($node->getAttribute('type'), + array('text', 'password', 'hidden')) + || !$node->getAttribute('type') + ); + $isRadio = $node->tagName == 'input' + && $node->getAttribute('type') == 'radio'; + $isCheckbox = $node->tagName == 'input' + && $node->getAttribute('type') == 'checkbox'; + $isOption = $node->tagName == 'option'; + if ($isInputValue && $attr == 'value' && $oldValue != $node->getAttribute($attr)) { + $event = new DOMEvent(array( + 'target' => $node, + 'type' => 'change' + )); + } else if (($isRadio || $isCheckbox) && $attr == 'checked' && ( + // check + (! $oldAttr && $node->hasAttribute($attr)) + // un-check + || (! $node->hasAttribute($attr) && $oldAttr) + )) { + $event = new DOMEvent(array( + 'target' => $node, + 'type' => 'change' + )); + } else if ($isOption && $node->parentNode && $attr == 'selected' && ( + // select + (! $oldAttr && $node->hasAttribute($attr)) + // un-select + || (! $node->hasAttribute($attr) && $oldAttr) + )) { + $event = new DOMEvent(array( + 'target' => $node->parentNode, + 'type' => 'change' + )); + } + if ($event) { + phpQueryEvents::trigger($this->getDocumentID(), + $event->type, array($event), $node + ); + } + } + public function attr($attr = null, $value = null) { + foreach($this->stack(1) as $node) { + if (! is_null($value)) { + $loop = $attr == '*' + ? $this->getNodeAttrs($node) + : array($attr); + foreach($loop as $a) { + $oldValue = $node->getAttribute($a); + $oldAttr = $node->hasAttribute($a); + // TODO raises an error when charset other than UTF-8 + // while document's charset is also not UTF-8 + @$node->setAttribute($a, $value); + $this->attrEvents($a, $oldAttr, $oldValue, $node); + } + } else if ($attr == '*') { + // jQuery difference + $return = array(); + foreach($node->attributes as $n => $v) + $return[$n] = $v->value; + return $return; + } else + return $node->hasAttribute($attr) + ? $node->getAttribute($attr) + : null; + } + return is_null($value) + ? '' : $this; + } + /** + * @access private + */ + protected function getNodeAttrs($node) { + $return = array(); + foreach($node->attributes as $n => $o) + $return[] = $n; + return $return; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo check CDATA ??? + */ + public function attrPHP($attr, $code) { + if (! is_null($code)) { + $value = '<'.'?php '.$code.' ?'.'>'; + // TODO tempolary solution + // http://code.google.com/p/phpquery/issues/detail?id=17 +// if (function_exists('mb_detect_encoding') && mb_detect_encoding($value) == 'ASCII') +// $value = mb_convert_encoding($value, 'UTF-8', 'HTML-ENTITIES'); + } + foreach($this->stack(1) as $node) { + if (! is_null($code)) { +// $attrNode = $this->DOM->createAttribute($attr); + $node->setAttribute($attr, $value); +// $attrNode->value = $value; +// $node->appendChild($attrNode); + } else if ( $attr == '*') { + // jQuery diff + $return = array(); + foreach($node->attributes as $n => $v) + $return[$n] = $v->value; + return $return; + } else + return $node->getAttribute($attr); + } + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function removeAttr($attr) { + foreach($this->stack(1) as $node) { + $loop = $attr == '*' + ? $this->getNodeAttrs($node) + : array($attr); + foreach($loop as $a) { + $oldValue = $node->getAttribute($a); + $node->removeAttribute($a); + $this->attrEvents($a, $oldValue, null, $node); + } + } + return $this; + } + /** + * Return form element value. + * + * @return String Fields value. + */ + public function val($val = null) { + if (! isset($val)) { + if ($this->eq(0)->is('select')) { + $selected = $this->eq(0)->find('option[selected=selected]'); + if ($selected->is('[value]')) + return $selected->attr('value'); + else + return $selected->text(); + } else if ($this->eq(0)->is('textarea')) + return $this->eq(0)->markup(); + else + return $this->eq(0)->attr('value'); + } else { + $_val = null; + foreach($this->stack(1) as $node) { + $node = pq($node, $this->getDocumentID()); + if (is_array($val) && in_array($node->attr('type'), array('checkbox', 'radio'))) { + $isChecked = in_array($node->attr('value'), $val) + || in_array($node->attr('name'), $val); + if ($isChecked) + $node->attr('checked', 'checked'); + else + $node->removeAttr('checked'); + } else if ($node->get(0)->tagName == 'select') { + if (! isset($_val)) { + $_val = array(); + if (! is_array($val)) + $_val = array((string)$val); + else + foreach($val as $v) + $_val[] = $v; + } + foreach($node['option']->stack(1) as $option) { + $option = pq($option, $this->getDocumentID()); + $selected = false; + // XXX: workaround for string comparsion, see issue #96 + // http://code.google.com/p/phpquery/issues/detail?id=96 + $selected = is_null($option->attr('value')) + ? in_array($option->markup(), $_val) + : in_array($option->attr('value'), $_val); +// $optionValue = $option->attr('value'); +// $optionText = $option->text(); +// $optionTextLenght = mb_strlen($optionText); +// foreach($_val as $v) +// if ($optionValue == $v) +// $selected = true; +// else if ($optionText == $v && $optionTextLenght == mb_strlen($v)) +// $selected = true; + if ($selected) + $option->attr('selected', 'selected'); + else + $option->removeAttr('selected'); + } + } else if ($node->get(0)->tagName == 'textarea') + $node->markup($val); + else + $node->attr('value', $val); + } + } + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function andSelf() { + if ( $this->previous ) + $this->elements = array_merge($this->elements, $this->previous->elements); + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function addClass( $className) { + if (! $className) + return $this; + foreach($this->stack(1) as $node) { + if (! $this->is(".$className", $node)) + $node->setAttribute( + 'class', + trim($node->getAttribute('class').' '.$className) + ); + } + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function addClassPHP( $className) { + foreach($this->stack(1) as $node) { + $classes = $node->getAttribute('class'); + $newValue = $classes + ? $classes.' <'.'?php '.$className.' ?'.'>' + : '<'.'?php '.$className.' ?'.'>'; + $node->setAttribute('class', $newValue); + } + return $this; + } + /** + * Enter description here... + * + * @param string $className + * @return bool + */ + public function hasClass($className) { + foreach($this->stack(1) as $node) { + if ( $this->is(".$className", $node)) + return true; + } + return false; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function removeClass($className) { + foreach($this->stack(1) as $node) { + $classes = explode( ' ', $node->getAttribute('class')); + if ( in_array($className, $classes)) { + $classes = array_diff($classes, array($className)); + if ( $classes ) + $node->setAttribute('class', implode(' ', $classes)); + else + $node->removeAttribute('class'); + } + } + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function toggleClass($className) { + foreach($this->stack(1) as $node) { + if ( $this->is( $node, '.'.$className )) + $this->removeClass($className); + else + $this->addClass($className); + } + return $this; + } + /** + * Proper name without underscore (just ->empty()) also works. + * + * Removes all child nodes from the set of matched elements. + * + * Example: + * pq("p")._empty() + * + * HTML: + *

Hello, Person and person

+ * + * Result: + * [

] + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @access private + */ + public function _empty() { + foreach($this->stack(1) as $node) { + // thx to 'dave at dgx dot cz' + $node->nodeValue = ''; + } + return $this; + } + /** + * Enter description here... + * + * @param array|string $callback Expects $node as first param, $index as second + * @param array $scope External variables passed to callback. Use compact('varName1', 'varName2'...) and extract($scope) + * @param array $arg1 Will ba passed as third and futher args to callback. + * @param array $arg2 Will ba passed as fourth and futher args to callback, and so on... + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function each($callback, $param1 = null, $param2 = null, $param3 = null) { + $paramStructure = null; + if (func_num_args() > 1) { + $paramStructure = func_get_args(); + $paramStructure = array_slice($paramStructure, 1); + } + foreach($this->elements as $v) + phpQuery::callbackRun($callback, array($v), $paramStructure); + return $this; + } + /** + * Run callback on actual object. + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function callback($callback, $param1 = null, $param2 = null, $param3 = null) { + $params = func_get_args(); + $params[0] = $this; + phpQuery::callbackRun($callback, $params); + return $this; + } + /** + * Enter description here... + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @todo add $scope and $args as in each() ??? + */ + public function map($callback, $param1 = null, $param2 = null, $param3 = null) { +// $stack = array(); +//// foreach($this->newInstance() as $node) { +// foreach($this->newInstance() as $node) { +// $result = call_user_func($callback, $node); +// if ($result) +// $stack[] = $result; +// } + $params = func_get_args(); + array_unshift($params, $this->elements); + return $this->newInstance( + call_user_func_array(array('phpQuery', 'map'), $params) +// phpQuery::map($this->elements, $callback) + ); + } + /** + * Enter description here... + * + * @param $key + * @param $value + */ + public function data($key, $value = null) { + if (! isset($value)) { + // TODO? implement specific jQuery behavior od returning parent values + // is child which we look up doesn't exist + return phpQuery::data($this->get(0), $key, $value, $this->getDocumentID()); + } else { + foreach($this as $node) + phpQuery::data($node, $key, $value, $this->getDocumentID()); + return $this; + } + } + /** + * Enter description here... + * + * @param $key + */ + public function removeData($key) { + foreach($this as $node) + phpQuery::removeData($node, $key, $this->getDocumentID()); + return $this; + } + // INTERFACE IMPLEMENTATIONS + + // ITERATOR INTERFACE + /** + * @access private + */ + public function rewind(){ + $this->debug('iterating foreach'); +// phpQuery::selectDocument($this->getDocumentID()); + $this->elementsBackup = $this->elements; + $this->elementsInterator = $this->elements; + $this->valid = isset( $this->elements[0] ) + ? 1 : 0; +// $this->elements = $this->valid +// ? array($this->elements[0]) +// : array(); + $this->current = 0; + } + /** + * @access private + */ + public function current(){ + return $this->elementsInterator[ $this->current ]; + } + /** + * @access private + */ + public function key(){ + return $this->current; + } + /** + * Double-function method. + * + * First: main iterator interface method. + * Second: Returning next sibling, alias for _next(). + * + * Proper functionality is choosed automagicaly. + * + * @see phpQueryObject::_next() + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public function next($cssSelector = null){ +// if ($cssSelector || $this->valid) +// return $this->_next($cssSelector); + $this->valid = isset( $this->elementsInterator[ $this->current+1 ] ) + ? true + : false; + if (! $this->valid && $this->elementsInterator) { + $this->elementsInterator = null; + } else if ($this->valid) { + $this->current++; + } else { + return $this->_next($cssSelector); + } + } + /** + * @access private + */ + public function valid(){ + return $this->valid; + } + // ITERATOR INTERFACE END + // ARRAYACCESS INTERFACE + /** + * @access private + */ + public function offsetExists($offset) { + return $this->find($offset)->size() > 0; + } + /** + * @access private + */ + public function offsetGet($offset) { + return $this->find($offset); + } + /** + * @access private + */ + public function offsetSet($offset, $value) { +// $this->find($offset)->replaceWith($value); + $this->find($offset)->html($value); + } + /** + * @access private + */ + public function offsetUnset($offset) { + // empty + throw new Exception("Can't do unset, use array interface only for calling queries and replacing HTML."); + } + // ARRAYACCESS INTERFACE END + /** + * Returns node's XPath. + * + * @param unknown_type $oneNode + * @return string + * @TODO use native getNodePath is avaible + * @access private + */ + protected function getNodeXpath($oneNode = null, $namespace = null) { + $return = array(); + $loop = $oneNode + ? array($oneNode) + : $this->elements; +// if ($namespace) +// $namespace .= ':'; + foreach($loop as $node) { + if ($node instanceof DOMDOCUMENT) { + $return[] = ''; + continue; + } + $xpath = array(); + while(! ($node instanceof DOMDOCUMENT)) { + $i = 1; + $sibling = $node; + while($sibling->previousSibling) { + $sibling = $sibling->previousSibling; + $isElement = $sibling instanceof DOMELEMENT; + if ($isElement && $sibling->tagName == $node->tagName) + $i++; + } + $xpath[] = $this->isXML() + ? "*[local-name()='{$node->tagName}'][{$i}]" + : "{$node->tagName}[{$i}]"; + $node = $node->parentNode; + } + $xpath = join('/', array_reverse($xpath)); + $return[] = '/'.$xpath; + } + return $oneNode + ? $return[0] + : $return; + } + // HELPERS + public function whois($oneNode = null) { + $return = array(); + $loop = $oneNode + ? array( $oneNode ) + : $this->elements; + foreach($loop as $node) { + if (isset($node->tagName)) { + $tag = in_array($node->tagName, array('php', 'js')) + ? strtoupper($node->tagName) + : $node->tagName; + $return[] = $tag + .($node->getAttribute('id') + ? '#'.$node->getAttribute('id'):'') + .($node->getAttribute('class') + ? '.'.join('.', split(' ', $node->getAttribute('class'))):'') + .($node->getAttribute('name') + ? '[name="'.$node->getAttribute('name').'"]':'') + .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') === false + ? '[value="'.substr(str_replace("\n", '', $node->getAttribute('value')), 0, 15).'"]':'') + .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') !== false + ? '[value=PHP]':'') + .($node->getAttribute('selected') + ? '[selected]':'') + .($node->getAttribute('checked') + ? '[checked]':'') + ; + } else if ($node instanceof DOMTEXT) { + if (trim($node->textContent)) + $return[] = 'Text:'.substr(str_replace("\n", ' ', $node->textContent), 0, 15); + } else { + + } + } + return $oneNode && isset($return[0]) + ? $return[0] + : $return; + } + /** + * Dump htmlOuter and preserve chain. Usefull for debugging. + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * + */ + public function dump() { + print 'DUMP #'.(phpQuery::$dumpCount++).' '; + $debug = phpQuery::$debug; + phpQuery::$debug = false; +// print __FILE__.':'.__LINE__."\n"; + var_dump($this->htmlOuter()); + return $this; + } + public function dumpWhois() { + print 'DUMP #'.(phpQuery::$dumpCount++).' '; + $debug = phpQuery::$debug; + phpQuery::$debug = false; +// print __FILE__.':'.__LINE__."\n"; + var_dump('whois', $this->whois()); + phpQuery::$debug = $debug; + return $this; + } + public function dumpLength() { + print 'DUMP #'.(phpQuery::$dumpCount++).' '; + $debug = phpQuery::$debug; + phpQuery::$debug = false; +// print __FILE__.':'.__LINE__."\n"; + var_dump('length', $this->length()); + phpQuery::$debug = $debug; + return $this; + } + public function dumpTree($html = true, $title = true) { + $output = $title + ? 'DUMP #'.(phpQuery::$dumpCount++)." \n" : ''; + $debug = phpQuery::$debug; + phpQuery::$debug = false; + foreach($this->stack() as $node) + $output .= $this->__dumpTree($node); + phpQuery::$debug = $debug; + print $html + ? nl2br(str_replace(' ', ' ', $output)) + : $output; + return $this; + } + private function __dumpTree($node, $intend = 0) { + $whois = $this->whois($node); + $return = ''; + if ($whois) + $return .= str_repeat(' - ', $intend).$whois."\n"; + if (isset($node->childNodes)) + foreach($node->childNodes as $chNode) + $return .= $this->__dumpTree($chNode, $intend+1); + return $return; + } + /** + * Dump htmlOuter and stop script execution. Usefull for debugging. + * + */ + public function dumpDie() { + print __FILE__.':'.__LINE__; + var_dump($this->htmlOuter()); + die(); + } +} + + +// -- Multibyte Compatibility functions --------------------------------------- +// http://svn.iphonewebdev.com/lace/lib/mb_compat.php + +/** + * mb_internal_encoding() + * + * Included for mbstring pseudo-compatability. + */ +if (!function_exists('mb_internal_encoding')) +{ + function mb_internal_encoding($enc) {return true; } +} + +/** + * mb_regex_encoding() + * + * Included for mbstring pseudo-compatability. + */ +if (!function_exists('mb_regex_encoding')) +{ + function mb_regex_encoding($enc) {return true; } +} + +/** + * mb_strlen() + * + * Included for mbstring pseudo-compatability. + */ +if (!function_exists('mb_strlen')) +{ + function mb_strlen($str) + { + return strlen($str); + } +} + +/** + * mb_strpos() + * + * Included for mbstring pseudo-compatability. + */ +if (!function_exists('mb_strpos')) +{ + function mb_strpos($haystack, $needle, $offset=0) + { + return strpos($haystack, $needle, $offset); + } +} +/** + * mb_stripos() + * + * Included for mbstring pseudo-compatability. + */ +if (!function_exists('mb_stripos')) +{ + function mb_stripos($haystack, $needle, $offset=0) + { + return stripos($haystack, $needle, $offset); + } +} + +/** + * mb_substr() + * + * Included for mbstring pseudo-compatability. + */ +if (!function_exists('mb_substr')) +{ + function mb_substr($str, $start, $length=0) + { + return substr($str, $start, $length); + } +} + +/** + * mb_substr_count() + * + * Included for mbstring pseudo-compatability. + */ +if (!function_exists('mb_substr_count')) +{ + function mb_substr_count($haystack, $needle) + { + return substr_count($haystack, $needle); + } +} + + +/** + * Static namespace for phpQuery functions. + * + * @author Tobiasz Cudnik + * @package phpQuery + */ +abstract class phpQuery { + /** + * XXX: Workaround for mbstring problems + * + * @var bool + */ + public static $mbstringSupport = true; + public static $debug = false; + public static $documents = array(); + public static $defaultDocumentID = null; +// public static $defaultDoctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"'; + /** + * Applies only to HTML. + * + * @var unknown_type + */ + public static $defaultDoctype = ''; + public static $defaultCharset = 'UTF-8'; + /** + * Static namespace for plugins. + * + * @var object + */ + public static $plugins = array(); + /** + * List of loaded plugins. + * + * @var unknown_type + */ + public static $pluginsLoaded = array(); + public static $pluginsMethods = array(); + public static $pluginsStaticMethods = array(); + public static $extendMethods = array(); + /** + * @TODO implement + */ + public static $extendStaticMethods = array(); + /** + * Hosts allowed for AJAX connections. + * Dot '.' means $_SERVER['HTTP_HOST'] (if any). + * + * @var array + */ + public static $ajaxAllowedHosts = array( + '.' + ); + /** + * AJAX settings. + * + * @var array + * XXX should it be static or not ? + */ + public static $ajaxSettings = array( + 'url' => '',//TODO + 'global' => true, + 'type' => "GET", + 'timeout' => null, + 'contentType' => "application/x-www-form-urlencoded", + 'processData' => true, +// 'async' => true, + 'data' => null, + 'username' => null, + 'password' => null, + 'accepts' => array( + 'xml' => "application/xml, text/xml", + 'html' => "text/html", + 'script' => "text/javascript, application/javascript", + 'json' => "application/json, text/javascript", + 'text' => "text/plain", + '_default' => "*/*" + ) + ); + public static $lastModified = null; + public static $active = 0; + public static $dumpCount = 0; + /** + * Multi-purpose function. + * Use pq() as shortcut. + * + * In below examples, $pq is any result of pq(); function. + * + * 1. Import markup into existing document (without any attaching): + * - Import into selected document: + * pq('
') // DOESNT accept text nodes at beginning of input string ! + * - Import into document with ID from $pq->getDocumentID(): + * pq('
', $pq->getDocumentID()) + * - Import into same document as DOMNode belongs to: + * pq('
', DOMNode) + * - Import into document from phpQuery object: + * pq('
', $pq) + * + * 2. Run query: + * - Run query on last selected document: + * pq('div.myClass') + * - Run query on document with ID from $pq->getDocumentID(): + * pq('div.myClass', $pq->getDocumentID()) + * - Run query on same document as DOMNode belongs to and use node(s)as root for query: + * pq('div.myClass', DOMNode) + * - Run query on document from phpQuery object + * and use object's stack as root node(s) for query: + * pq('div.myClass', $pq) + * + * @param string|DOMNode|DOMNodeList|array $arg1 HTML markup, CSS Selector, DOMNode or array of DOMNodes + * @param string|phpQueryObject|DOMNode $context DOM ID from $pq->getDocumentID(), phpQuery object (determines also query root) or DOMNode (determines also query root) + * + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery|QueryTemplatesPhpQuery|false + * phpQuery object or false in case of error. + */ + public static function pq($arg1, $context = null) { + if ($arg1 instanceof DOMNODE && ! isset($context)) { + foreach(phpQuery::$documents as $documentWrapper) { + $compare = $arg1 instanceof DOMDocument + ? $arg1 : $arg1->ownerDocument; + if ($documentWrapper->document->isSameNode($compare)) + $context = $documentWrapper->id; + } + } + if (! $context) { + $domId = self::$defaultDocumentID; + if (! $domId) + throw new Exception("Can't use last created DOM, because there isn't any. Use phpQuery::newDocument() first."); +// } else if (is_object($context) && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject'))) + } else if (is_object($context) && $context instanceof phpQueryObject) + $domId = $context->getDocumentID(); + else if ($context instanceof DOMDOCUMENT) { + $domId = self::getDocumentID($context); + if (! $domId) { + //throw new Exception('Orphaned DOMDocument'); + $domId = self::newDocument($context)->getDocumentID(); + } + } else if ($context instanceof DOMNODE) { + $domId = self::getDocumentID($context); + if (! $domId) { + throw new Exception('Orphaned DOMNode'); +// $domId = self::newDocument($context->ownerDocument); + } + } else + $domId = $context; + if ($arg1 instanceof phpQueryObject) { +// if (is_object($arg1) && (get_class($arg1) == 'phpQueryObject' || $arg1 instanceof PHPQUERY || is_subclass_of($arg1, 'phpQueryObject'))) { + /** + * Return $arg1 or import $arg1 stack if document differs: + * pq(pq('
')) + */ + if ($arg1->getDocumentID() == $domId) + return $arg1; + $class = get_class($arg1); + // support inheritance by passing old object to overloaded constructor + $phpQuery = $class != 'phpQuery' + ? new $class($arg1, $domId) + : new phpQueryObject($domId); + $phpQuery->elements = array(); + foreach($arg1->elements as $node) + $phpQuery->elements[] = $phpQuery->document->importNode($node, true); + return $phpQuery; + } else if ($arg1 instanceof DOMNODE || (is_array($arg1) && isset($arg1[0]) && $arg1[0] instanceof DOMNODE)) { + /* + * Wrap DOM nodes with phpQuery object, import into document when needed: + * pq(array($domNode1, $domNode2)) + */ + $phpQuery = new phpQueryObject($domId); + if (!($arg1 instanceof DOMNODELIST) && ! is_array($arg1)) + $arg1 = array($arg1); + $phpQuery->elements = array(); + foreach($arg1 as $node) { + $sameDocument = $node->ownerDocument instanceof DOMDOCUMENT + && ! $node->ownerDocument->isSameNode($phpQuery->document); + $phpQuery->elements[] = $sameDocument + ? $phpQuery->document->importNode($node, true) + : $node; + } + return $phpQuery; + } else if (self::isMarkup($arg1)) { + /** + * Import HTML: + * pq('
') + */ + $phpQuery = new phpQueryObject($domId); + return $phpQuery->newInstance( + $phpQuery->documentWrapper->import($arg1) + ); + } else { + /** + * Run CSS query: + * pq('div.myClass') + */ + $phpQuery = new phpQueryObject($domId); +// if ($context && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject'))) + if ($context && $context instanceof phpQueryObject) + $phpQuery->elements = $context->elements; + else if ($context && $context instanceof DOMNODELIST) { + $phpQuery->elements = array(); + foreach($context as $node) + $phpQuery->elements[] = $node; + } else if ($context && $context instanceof DOMNODE) + $phpQuery->elements = array($context); + return $phpQuery->find($arg1); + } + } + /** + * Sets default document to $id. Document has to be loaded prior + * to using this method. + * $id can be retrived via getDocumentID() or getDocumentIDRef(). + * + * @param unknown_type $id + */ + public static function selectDocument($id) { + $id = self::getDocumentID($id); + self::debug("Selecting document '$id' as default one"); + self::$defaultDocumentID = self::getDocumentID($id); + } + /** + * Returns document with id $id or last used as phpQueryObject. + * $id can be retrived via getDocumentID() or getDocumentIDRef(). + * Chainable. + * + * @see phpQuery::selectDocument() + * @param unknown_type $id + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function getDocument($id = null) { + if ($id) + phpQuery::selectDocument($id); + else + $id = phpQuery::$defaultDocumentID; + return new phpQueryObject($id); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocument($markup = null, $contentType = null) { + if (! $markup) + $markup = ''; + $documentID = phpQuery::createDocumentWrapper($markup, $contentType); + return new phpQueryObject($documentID); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentHTML($markup = null, $charset = null) { + $contentType = $charset + ? ";charset=$charset" + : ''; + return self::newDocument($markup, "text/html{$contentType}"); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentXML($markup = null, $charset = null) { + $contentType = $charset + ? ";charset=$charset" + : ''; + return self::newDocument($markup, "text/xml{$contentType}"); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentXHTML($markup = null, $charset = null) { + $contentType = $charset + ? ";charset=$charset" + : ''; + return self::newDocument($markup, "application/xhtml+xml{$contentType}"); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentPHP($markup = null, $contentType = "text/html") { + // TODO pass charset to phpToMarkup if possible (use DOMDocumentWrapper function) + $markup = phpQuery::phpToMarkup($markup, self::$defaultCharset); + return self::newDocument($markup, $contentType); + } + public static function phpToMarkup($php, $charset = 'utf-8') { + $regexes = array( + '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)<'.'?php?(.*?)(?:\\?>)([^\']*)\'@s', + '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)<'.'?php?(.*?)(?:\\?>)([^"]*)"@s', + ); + foreach($regexes as $regex) + while (preg_match($regex, $php, $matches)) { + $php = preg_replace_callback( + $regex, +// create_function('$m, $charset = "'.$charset.'"', +// 'return $m[1].$m[2] +// .htmlspecialchars("<"."?php".$m[4]."?".">", ENT_QUOTES|ENT_NOQUOTES, $charset) +// .$m[5].$m[2];' +// ), + array('phpQuery', '_phpToMarkupCallback'), + $php + ); + } + $regex = '@(^|>[^<]*)+?(<\?php(.*?)(\?>))@s'; +//preg_match_all($regex, $php, $matches); +//var_dump($matches); + $php = preg_replace($regex, '\\1', $php); + return $php; + } + public static function _phpToMarkupCallback($php, $charset = 'utf-8') { + return $m[1].$m[2] + .htmlspecialchars("<"."?php".$m[4]."?".">", ENT_QUOTES|ENT_NOQUOTES, $charset) + .$m[5].$m[2]; + } + public static function _markupToPHPCallback($m) { + return "<"."?php ".htmlspecialchars_decode($m[1])." ?".">"; + } + /** + * Converts document markup containing PHP code generated by phpQuery::php() + * into valid (executable) PHP code syntax. + * + * @param string|phpQueryObject $content + * @return string PHP code. + */ + public static function markupToPHP($content) { + if ($content instanceof phpQueryObject) + $content = $content->markupOuter(); + /* ... to */ + $content = preg_replace_callback( + '@\s*\s*@s', +// create_function('$m', +// 'return "<'.'?php ".htmlspecialchars_decode($m[1])." ?'.'>";' +// ), + array('phpQuery', '_markupToPHPCallback'), + $content + ); + /* extra space added to save highlighters */ + $regexes = array( + '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)(?:<|%3C)\\?(?:php)?(.*?)(?:\\?(?:>|%3E))([^\']*)\'@s', + '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)(?:<|%3C)\\?(?:php)?(.*?)(?:\\?(?:>|%3E))([^"]*)"@s', + ); + foreach($regexes as $regex) + while (preg_match($regex, $content)) + $content = preg_replace_callback( + $regex, + create_function('$m', + 'return $m[1].$m[2].$m[3]."", " ", "\n", " ", "{", "$", "}", \'"\', "[", "]"), + htmlspecialchars_decode($m[4]) + ) + ." ?>".$m[5].$m[2];' + ), + $content + ); + return $content; + } + /** + * Creates new document from file $file. + * Chainable. + * + * @param string $file URLs allowed. See File wrapper page at php.net for more supported sources. + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentFile($file, $contentType = null) { + $documentID = self::createDocumentWrapper( + file_get_contents($file), $contentType + ); + return new phpQueryObject($documentID); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentFileHTML($file, $charset = null) { + $contentType = $charset + ? ";charset=$charset" + : ''; + return self::newDocumentFile($file, "text/html{$contentType}"); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentFileXML($file, $charset = null) { + $contentType = $charset + ? ";charset=$charset" + : ''; + return self::newDocumentFile($file, "text/xml{$contentType}"); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentFileXHTML($file, $charset = null) { + $contentType = $charset + ? ";charset=$charset" + : ''; + return self::newDocumentFile($file, "application/xhtml+xml{$contentType}"); + } + /** + * Creates new document from markup. + * Chainable. + * + * @param unknown_type $markup + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + */ + public static function newDocumentFilePHP($file, $contentType = null) { + return self::newDocumentPHP(file_get_contents($file), $contentType); + } + /** + * Reuses existing DOMDocument object. + * Chainable. + * + * @param $document DOMDocument + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @TODO support DOMDocument + */ + public static function loadDocument($document) { + // TODO + die('TODO loadDocument'); + } + /** + * Enter description here... + * + * @param unknown_type $html + * @param unknown_type $domId + * @return unknown New DOM ID + * @todo support PHP tags in input + * @todo support passing DOMDocument object from self::loadDocument + */ + protected static function createDocumentWrapper($html, $contentType = null, $documentID = null) { + if (function_exists('domxml_open_mem')) + throw new Exception("Old PHP4 DOM XML extension detected. phpQuery won't work until this extension is enabled."); +// $id = $documentID +// ? $documentID +// : md5(microtime()); + $document = null; + if ($html instanceof DOMDOCUMENT) { + if (self::getDocumentID($html)) { + // document already exists in phpQuery::$documents, make a copy + $document = clone $html; + } else { + // new document, add it to phpQuery::$documents + $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID); + } + } else { + $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID); + } +// $wrapper->id = $id; + // bind document + phpQuery::$documents[$wrapper->id] = $wrapper; + // remember last loaded document + phpQuery::selectDocument($wrapper->id); + return $wrapper->id; + } + /** + * Extend class namespace. + * + * @param string|array $target + * @param array $source + * @TODO support string $source + * @return unknown_type + */ + public static function extend($target, $source) { + switch($target) { + case 'phpQueryObject': + $targetRef = &self::$extendMethods; + $targetRef2 = &self::$pluginsMethods; + break; + case 'phpQuery': + $targetRef = &self::$extendStaticMethods; + $targetRef2 = &self::$pluginsStaticMethods; + break; + default: + throw new Exception("Unsupported \$target type"); + } + if (is_string($source)) + $source = array($source => $source); + foreach($source as $method => $callback) { + if (isset($targetRef[$method])) { +// throw new Exception + self::debug("Duplicate method '{$method}', can\'t extend '{$target}'"); + continue; + } + if (isset($targetRef2[$method])) { +// throw new Exception + self::debug("Duplicate method '{$method}' from plugin '{$targetRef2[$method]}'," + ." can\'t extend '{$target}'"); + continue; + } + $targetRef[$method] = $callback; + } + return true; + } + /** + * Extend phpQuery with $class from $file. + * + * @param string $class Extending class name. Real class name can be prepended phpQuery_. + * @param string $file Filename to include. Defaults to "{$class}.php". + */ + public static function plugin($class, $file = null) { + // TODO $class checked agains phpQuery_$class +// if (strpos($class, 'phpQuery') === 0) +// $class = substr($class, 8); + if (in_array($class, self::$pluginsLoaded)) + return true; + if (! $file) + $file = $class.'.php'; + $objectClassExists = class_exists('phpQueryObjectPlugin_'.$class); + $staticClassExists = class_exists('phpQueryPlugin_'.$class); + if (! $objectClassExists && ! $staticClassExists) + require_once($file); + self::$pluginsLoaded[] = $class; + // static methods + if (class_exists('phpQueryPlugin_'.$class)) { + $realClass = 'phpQueryPlugin_'.$class; + $vars = get_class_vars($realClass); + $loop = isset($vars['phpQueryMethods']) + && ! is_null($vars['phpQueryMethods']) + ? $vars['phpQueryMethods'] + : get_class_methods($realClass); + foreach($loop as $method) { + if ($method == '__initialize') + continue; + if (! is_callable(array($realClass, $method))) + continue; + if (isset(self::$pluginsStaticMethods[$method])) { + throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsStaticMethods[$method]."'"); + return; + } + self::$pluginsStaticMethods[$method] = $class; + } + if (method_exists($realClass, '__initialize')) + call_user_func_array(array($realClass, '__initialize'), array()); + } + // object methods + if (class_exists('phpQueryObjectPlugin_'.$class)) { + $realClass = 'phpQueryObjectPlugin_'.$class; + $vars = get_class_vars($realClass); + $loop = isset($vars['phpQueryMethods']) + && ! is_null($vars['phpQueryMethods']) + ? $vars['phpQueryMethods'] + : get_class_methods($realClass); + foreach($loop as $method) { + if (! is_callable(array($realClass, $method))) + continue; + if (isset(self::$pluginsMethods[$method])) { + throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsMethods[$method]."'"); + continue; + } + self::$pluginsMethods[$method] = $class; + } + } + return true; + } + /** + * Unloades all or specified document from memory. + * + * @param mixed $documentID @see phpQuery::getDocumentID() for supported types. + */ + public static function unloadDocuments($id = null) { + if (isset($id)) { + if ($id = self::getDocumentID($id)) + unset(phpQuery::$documents[$id]); + } else { + foreach(phpQuery::$documents as $k => $v) { + unset(phpQuery::$documents[$k]); + } + } + } + /** + * Parses phpQuery object or HTML result against PHP tags and makes them active. + * + * @param phpQuery|string $content + * @deprecated + * @return string + */ + public static function unsafePHPTags($content) { + return self::markupToPHP($content); + } + public static function DOMNodeListToArray($DOMNodeList) { + $array = array(); + if (! $DOMNodeList) + return $array; + foreach($DOMNodeList as $node) + $array[] = $node; + return $array; + } + /** + * Checks if $input is HTML string, which has to start with '<'. + * + * @deprecated + * @param String $input + * @return Bool + * @todo still used ? + */ + public static function isMarkup($input) { + return ! is_array($input) && substr(trim($input), 0, 1) == '<'; + } + public static function debug($text) { + if (self::$debug) + print var_dump($text); + } + /** + * Make an AJAX request. + * + * @param array See $options http://docs.jquery.com/Ajax/jQuery.ajax#toptions + * Additional options are: + * 'document' - document for global events, @see phpQuery::getDocumentID() + * 'referer' - implemented + * 'requested_with' - TODO; not implemented (X-Requested-With) + * @return Zend_Http_Client + * @link http://docs.jquery.com/Ajax/jQuery.ajax + * + * @TODO $options['cache'] + * @TODO $options['processData'] + * @TODO $options['xhr'] + * @TODO $options['data'] as string + * @TODO XHR interface + */ + public static function ajax($options = array(), $xhr = null) { + $options = array_merge( + self::$ajaxSettings, $options + ); + $documentID = isset($options['document']) + ? self::getDocumentID($options['document']) + : null; + if ($xhr) { + // reuse existing XHR object, but clean it up + $client = $xhr; +// $client->setParameterPost(null); +// $client->setParameterGet(null); + $client->setAuth(false); + $client->setHeaders("If-Modified-Since", null); + $client->setHeaders("Referer", null); + $client->resetParameters(); + } else { + // create new XHR object + require_once('Zend/Http/Client.php'); + $client = new Zend_Http_Client(); + $client->setCookieJar(); + } + if (isset($options['timeout'])) + $client->setConfig(array( + 'timeout' => $options['timeout'], + )); +// 'maxredirects' => 0, + foreach(self::$ajaxAllowedHosts as $k => $host) + if ($host == '.' && isset($_SERVER['HTTP_HOST'])) + self::$ajaxAllowedHosts[$k] = $_SERVER['HTTP_HOST']; + $host = parse_url($options['url'], PHP_URL_HOST); + if (! in_array($host, self::$ajaxAllowedHosts)) { + throw new Exception("Request not permitted, host '$host' not present in " + ."phpQuery::\$ajaxAllowedHosts"); + } + // JSONP + $jsre = "/=\\?(&|$)/"; + if (isset($options['dataType']) && $options['dataType'] == 'jsonp') { + $jsonpCallbackParam = $options['jsonp'] + ? $options['jsonp'] : 'callback'; + if (strtolower($options['type']) == 'get') { + if (! preg_match($jsre, $options['url'])) { + $sep = strpos($options['url'], '?') + ? '&' : '?'; + $options['url'] .= "$sep$jsonpCallbackParam=?"; + } + } else if ($options['data']) { + $jsonp = false; + foreach($options['data'] as $n => $v) { + if ($v == '?') + $jsonp = true; + } + if (! $jsonp) { + $options['data'][$jsonpCallbackParam] = '?'; + } + } + $options['dataType'] = 'json'; + } + if (isset($options['dataType']) && $options['dataType'] == 'json') { + $jsonpCallback = 'json_'.md5(microtime()); + $jsonpData = $jsonpUrl = false; + if ($options['data']) { + foreach($options['data'] as $n => $v) { + if ($v == '?') + $jsonpData = $n; + } + } + if (preg_match($jsre, $options['url'])) + $jsonpUrl = true; + if ($jsonpData !== false || $jsonpUrl) { + // remember callback name for httpData() + $options['_jsonp'] = $jsonpCallback; + if ($jsonpData !== false) + $options['data'][$jsonpData] = $jsonpCallback; + if ($jsonpUrl) + $options['url'] = preg_replace($jsre, "=$jsonpCallback\\1", $options['url']); + } + } + $client->setUri($options['url']); + $client->setMethod(strtoupper($options['type'])); + if (isset($options['referer']) && $options['referer']) + $client->setHeaders('Referer', $options['referer']); + $client->setHeaders(array( +// 'content-type' => $options['contentType'], + 'User-Agent' => 'Mozilla/5.0 (X11; U; Linux x86; en-US; rv:1.9.0.5) Gecko' + .'/2008122010 Firefox/3.0.5', + // TODO custom charset + 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', +// 'Connection' => 'keep-alive', +// 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'Accept-Language' => 'en-us,en;q=0.5', + )); + if ($options['username']) + $client->setAuth($options['username'], $options['password']); + if (isset($options['ifModified']) && $options['ifModified']) + $client->setHeaders("If-Modified-Since", + self::$lastModified + ? self::$lastModified + : "Thu, 01 Jan 1970 00:00:00 GMT" + ); + $client->setHeaders("Accept", + isset($options['dataType']) + && isset(self::$ajaxSettings['accepts'][ $options['dataType'] ]) + ? self::$ajaxSettings['accepts'][ $options['dataType'] ].", */*" + : self::$ajaxSettings['accepts']['_default'] + ); + // TODO $options['processData'] + if ($options['data'] instanceof phpQueryObject) { + $serialized = $options['data']->serializeArray($options['data']); + $options['data'] = array(); + foreach($serialized as $r) + $options['data'][ $r['name'] ] = $r['value']; + } + if (strtolower($options['type']) == 'get') { + $client->setParameterGet($options['data']); + } else if (strtolower($options['type']) == 'post') { + $client->setEncType($options['contentType']); + $client->setParameterPost($options['data']); + } + if (self::$active == 0 && $options['global']) + phpQueryEvents::trigger($documentID, 'ajaxStart'); + self::$active++; + // beforeSend callback + if (isset($options['beforeSend']) && $options['beforeSend']) + phpQuery::callbackRun($options['beforeSend'], array($client)); + // ajaxSend event + if ($options['global']) + phpQueryEvents::trigger($documentID, 'ajaxSend', array($client, $options)); + if (phpQuery::$debug) { + self::debug("{$options['type']}: {$options['url']}\n"); + self::debug("Options:
".var_export($options, true)."
\n"); +// if ($client->getCookieJar()) +// self::debug("Cookies:
".var_export($client->getCookieJar()->getMatchingCookies($options['url']), true)."
\n"); + } + // request + $response = $client->request(); + if (phpQuery::$debug) { + self::debug('Status: '.$response->getStatus().' / '.$response->getMessage()); + self::debug($client->getLastRequest()); + self::debug($response->getHeaders()); + } + if ($response->isSuccessful()) { + // XXX tempolary + self::$lastModified = $response->getHeader('Last-Modified'); + $data = self::httpData($response->getBody(), $options['dataType'], $options); + if (isset($options['success']) && $options['success']) + phpQuery::callbackRun($options['success'], array($data, $response->getStatus(), $options)); + if ($options['global']) + phpQueryEvents::trigger($documentID, 'ajaxSuccess', array($client, $options)); + } else { + if (isset($options['error']) && $options['error']) + phpQuery::callbackRun($options['error'], array($client, $response->getStatus(), $response->getMessage())); + if ($options['global']) + phpQueryEvents::trigger($documentID, 'ajaxError', array($client, /*$response->getStatus(),*/$response->getMessage(), $options)); + } + if (isset($options['complete']) && $options['complete']) + phpQuery::callbackRun($options['complete'], array($client, $response->getStatus())); + if ($options['global']) + phpQueryEvents::trigger($documentID, 'ajaxComplete', array($client, $options)); + if ($options['global'] && ! --self::$active) + phpQueryEvents::trigger($documentID, 'ajaxStop'); + return $client; +// if (is_null($domId)) +// $domId = self::$defaultDocumentID ? self::$defaultDocumentID : false; +// return new phpQueryAjaxResponse($response, $domId); + } + protected static function httpData($data, $type, $options) { + if (isset($options['dataFilter']) && $options['dataFilter']) + $data = self::callbackRun($options['dataFilter'], array($data, $type)); + if (is_string($data)) { + if ($type == "json") { + if (isset($options['_jsonp']) && $options['_jsonp']) { + $data = preg_replace('/^\s*\w+\((.*)\)\s*$/s', '$1', $data); + } + $data = self::parseJSON($data); + } + } + return $data; + } + /** + * Enter description here... + * + * @param array|phpQuery $data + * + */ + public static function param($data) { + return http_build_query($data, null, '&'); + } + public static function get($url, $data = null, $callback = null, $type = null) { + if (!is_array($data)) { + $callback = $data; + $data = null; + } + // TODO some array_values on this shit + return phpQuery::ajax(array( + 'type' => 'GET', + 'url' => $url, + 'data' => $data, + 'success' => $callback, + 'dataType' => $type, + )); + } + public static function post($url, $data = null, $callback = null, $type = null) { + if (!is_array($data)) { + $callback = $data; + $data = null; + } + return phpQuery::ajax(array( + 'type' => 'POST', + 'url' => $url, + 'data' => $data, + 'success' => $callback, + 'dataType' => $type, + )); + } + public static function getJSON($url, $data = null, $callback = null) { + if (!is_array($data)) { + $callback = $data; + $data = null; + } + // TODO some array_values on this shit + return phpQuery::ajax(array( + 'type' => 'GET', + 'url' => $url, + 'data' => $data, + 'success' => $callback, + 'dataType' => 'json', + )); + } + public static function ajaxSetup($options) { + self::$ajaxSettings = array_merge( + self::$ajaxSettings, + $options + ); + } + public static function ajaxAllowHost($host1, $host2 = null, $host3 = null) { + $loop = is_array($host1) + ? $host1 + : func_get_args(); + foreach($loop as $host) { + if ($host && ! in_array($host, phpQuery::$ajaxAllowedHosts)) { + phpQuery::$ajaxAllowedHosts[] = $host; + } + } + } + public static function ajaxAllowURL($url1, $url2 = null, $url3 = null) { + $loop = is_array($url1) + ? $url1 + : func_get_args(); + foreach($loop as $url) + phpQuery::ajaxAllowHost(parse_url($url, PHP_URL_HOST)); + } + /** + * Returns JSON representation of $data. + * + * @static + * @param mixed $data + * @return string + */ + public static function toJSON($data) { + if (function_exists('json_encode')) + return json_encode($data); + require_once('Zend/Json/Encoder.php'); + return Zend_Json_Encoder::encode($data); + } + /** + * Parses JSON into proper PHP type. + * + * @static + * @param string $json + * @return mixed + */ + public static function parseJSON($json) { + if (function_exists('json_decode')) { + $return = json_decode(trim($json), true); + // json_decode and UTF8 issues + if (isset($return)) + return $return; + } + require_once('Zend/Json/Decoder.php'); + return Zend_Json_Decoder::decode($json); + } + /** + * Returns source's document ID. + * + * @param $source DOMNode|phpQueryObject + * @return string + */ + public static function getDocumentID($source) { + if ($source instanceof DOMDOCUMENT) { + foreach(phpQuery::$documents as $id => $document) { + if ($source->isSameNode($document->document)) + return $id; + } + } else if ($source instanceof DOMNODE) { + foreach(phpQuery::$documents as $id => $document) { + if ($source->ownerDocument->isSameNode($document->document)) + return $id; + } + } else if ($source instanceof phpQueryObject) + return $source->getDocumentID(); + else if (is_string($source) && isset(phpQuery::$documents[$source])) + return $source; + } + /** + * Get DOMDocument object related to $source. + * Returns null if such document doesn't exist. + * + * @param $source DOMNode|phpQueryObject|string + * @return string + */ + public static function getDOMDocument($source) { + if ($source instanceof DOMDOCUMENT) + return $source; + $source = self::getDocumentID($source); + return $source + ? self::$documents[$id]['document'] + : null; + } + + // UTILITIES + // http://docs.jquery.com/Utilities + + /** + * + * @return unknown_type + * @link http://docs.jquery.com/Utilities/jQuery.makeArray + */ + public static function makeArray($obj) { + $array = array(); + if (is_object($object) && $object instanceof DOMNODELIST) { + foreach($object as $value) + $array[] = $value; + } else if (is_object($object) && ! ($object instanceof Iterator)) { + foreach(get_object_vars($object) as $name => $value) + $array[0][$name] = $value; + } else { + foreach($object as $name => $value) + $array[0][$name] = $value; + } + return $array; + } + public static function inArray($value, $array) { + return in_array($value, $array); + } + /** + * + * @param $object + * @param $callback + * @return unknown_type + * @link http://docs.jquery.com/Utilities/jQuery.each + */ + public static function each($object, $callback, $param1 = null, $param2 = null, $param3 = null) { + $paramStructure = null; + if (func_num_args() > 2) { + $paramStructure = func_get_args(); + $paramStructure = array_slice($paramStructure, 2); + } + if (is_object($object) && ! ($object instanceof Iterator)) { + foreach(get_object_vars($object) as $name => $value) + phpQuery::callbackRun($callback, array($name, $value), $paramStructure); + } else { + foreach($object as $name => $value) + phpQuery::callbackRun($callback, array($name, $value), $paramStructure); + } + } + /** + * + * @link http://docs.jquery.com/Utilities/jQuery.map + */ + public static function map($array, $callback, $param1 = null, $param2 = null, $param3 = null) { + $result = array(); + $paramStructure = null; + if (func_num_args() > 2) { + $paramStructure = func_get_args(); + $paramStructure = array_slice($paramStructure, 2); + } + foreach($array as $v) { + $vv = phpQuery::callbackRun($callback, array($v), $paramStructure); +// $callbackArgs = $args; +// foreach($args as $i => $arg) { +// $callbackArgs[$i] = $arg instanceof CallbackParam +// ? $v +// : $arg; +// } +// $vv = call_user_func_array($callback, $callbackArgs); + if (is_array($vv)) { + foreach($vv as $vvv) + $result[] = $vvv; + } else if ($vv !== null) { + $result[] = $vv; + } + } + return $result; + } + /** + * + * @param $callback Callback + * @param $params + * @param $paramStructure + * @return unknown_type + */ + public static function callbackRun($callback, $params = array(), $paramStructure = null) { + if (! $callback) + return; + if ($callback instanceof CallbackParameterToReference) { + // TODO support ParamStructure to select which $param push to reference + if (isset($params[0])) + $callback->callback = $params[0]; + return true; + } + if ($callback instanceof Callback) { + $paramStructure = $callback->params; + $callback = $callback->callback; + } + if (! $paramStructure) + return call_user_func_array($callback, $params); + $p = 0; + foreach($paramStructure as $i => $v) { + $paramStructure[$i] = $v instanceof CallbackParam + ? $params[$p++] + : $v; + } + return call_user_func_array($callback, $paramStructure); + } + /** + * Merge 2 phpQuery objects. + * @param array $one + * @param array $two + * @protected + * @todo node lists, phpQueryObject + */ + public static function merge($one, $two) { + $elements = $one->elements; + foreach($two->elements as $node) { + $exists = false; + foreach($elements as $node2) { + if ($node2->isSameNode($node)) + $exists = true; + } + if (! $exists) + $elements[] = $node; + } + return $elements; +// $one = $one->newInstance(); +// $one->elements = $elements; +// return $one; + } + /** + * + * @param $array + * @param $callback + * @param $invert + * @return unknown_type + * @link http://docs.jquery.com/Utilities/jQuery.grep + */ + public static function grep($array, $callback, $invert = false) { + $result = array(); + foreach($array as $k => $v) { + $r = call_user_func_array($callback, array($v, $k)); + if ($r === !(bool)$invert) + $result[] = $v; + } + return $result; + } + public static function unique($array) { + return array_unique($array); + } + /** + * + * @param $function + * @return unknown_type + * @TODO there are problems with non-static methods, second parameter pass it + * but doesnt verify is method is really callable + */ + public static function isFunction($function) { + return is_callable($function); + } + public static function trim($str) { + return trim($str); + } + /* PLUGINS NAMESPACE */ + /** + * + * @param $url + * @param $callback + * @param $param1 + * @param $param2 + * @param $param3 + * @return phpQueryObject + */ + public static function browserGet($url, $callback, $param1 = null, $param2 = null, $param3 = null) { + if (self::plugin('WebBrowser')) { + $params = func_get_args(); + return self::callbackRun(array(self::$plugins, 'browserGet'), $params); + } else { + self::debug('WebBrowser plugin not available...'); + } + } + /** + * + * @param $url + * @param $data + * @param $callback + * @param $param1 + * @param $param2 + * @param $param3 + * @return phpQueryObject + */ + public static function browserPost($url, $data, $callback, $param1 = null, $param2 = null, $param3 = null) { + if (self::plugin('WebBrowser')) { + $params = func_get_args(); + return self::callbackRun(array(self::$plugins, 'browserPost'), $params); + } else { + self::debug('WebBrowser plugin not available...'); + } + } + /** + * + * @param $ajaxSettings + * @param $callback + * @param $param1 + * @param $param2 + * @param $param3 + * @return phpQueryObject + */ + public static function browser($ajaxSettings, $callback, $param1 = null, $param2 = null, $param3 = null) { + if (self::plugin('WebBrowser')) { + $params = func_get_args(); + return self::callbackRun(array(self::$plugins, 'browser'), $params); + } else { + self::debug('WebBrowser plugin not available...'); + } + } + /** + * + * @param $code + * @return string + */ + public static function php($code) { + return self::code('php', $code); + } + /** + * + * @param $type + * @param $code + * @return string + */ + public static function code($type, $code) { + return "<$type>"; + } + + public static function __callStatic($method, $params) { + return call_user_func_array( + array(phpQuery::$plugins, $method), + $params + ); + } + protected static function dataSetupNode($node, $documentID) { + // search are return if alredy exists + foreach(phpQuery::$documents[$documentID]->dataNodes as $dataNode) { + if ($node->isSameNode($dataNode)) + return $dataNode; + } + // if doesn't, add it + phpQuery::$documents[$documentID]->dataNodes[] = $node; + return $node; + } + protected static function dataRemoveNode($node, $documentID) { + // search are return if alredy exists + foreach(phpQuery::$documents[$documentID]->dataNodes as $k => $dataNode) { + if ($node->isSameNode($dataNode)) { + unset(self::$documents[$documentID]->dataNodes[$k]); + unset(self::$documents[$documentID]->data[ $dataNode->dataID ]); + } + } + } + public static function data($node, $name, $data, $documentID = null) { + if (! $documentID) + // TODO check if this works + $documentID = self::getDocumentID($node); + $document = phpQuery::$documents[$documentID]; + $node = self::dataSetupNode($node, $documentID); + if (! isset($node->dataID)) + $node->dataID = ++phpQuery::$documents[$documentID]->uuid; + $id = $node->dataID; + if (! isset($document->data[$id])) + $document->data[$id] = array(); + if (! is_null($data)) + $document->data[$id][$name] = $data; + if ($name) { + if (isset($document->data[$id][$name])) + return $document->data[$id][$name]; + } else + return $id; + } + public static function removeData($node, $name, $documentID) { + if (! $documentID) + // TODO check if this works + $documentID = self::getDocumentID($node); + $document = phpQuery::$documents[$documentID]; + $node = self::dataSetupNode($node, $documentID); + $id = $node->dataID; + if ($name) { + if (isset($document->data[$id][$name])) + unset($document->data[$id][$name]); + $name = null; + foreach($document->data[$id] as $name) + break; + if (! $name) + self::removeData($node, $name, $documentID); + } else { + self::dataRemoveNode($node, $documentID); + } + } +} +/** + * Plugins static namespace class. + * + * @author Tobiasz Cudnik + * @package phpQuery + * @todo move plugin methods here (as statics) + */ +class phpQueryPlugins { + public function __call($method, $args) { + if (isset(phpQuery::$extendStaticMethods[$method])) { + $return = call_user_func_array( + phpQuery::$extendStaticMethods[$method], + $args + ); + } else if (isset(phpQuery::$pluginsStaticMethods[$method])) { + $class = phpQuery::$pluginsStaticMethods[$method]; + $realClass = "phpQueryPlugin_$class"; + $return = call_user_func_array( + array($realClass, $method), + $args + ); + return isset($return) + ? $return + : $this; + } else + throw new Exception("Method '{$method}' doesnt exist"); + } +} +/** + * Shortcut to phpQuery::pq($arg1, $context) + * Chainable. + * + * @see phpQuery::pq() + * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery + * @author Tobiasz Cudnik + * @package phpQuery + */ +function pq($arg1, $context = null) { + $args = func_get_args(); + return call_user_func_array( + array('phpQuery', 'pq'), + $args + ); +} +// add plugins dir and Zend framework to include path +set_include_path( + get_include_path() + .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/' + .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/plugins/' +); +// why ? no __call nor __get for statics in php... +// XXX __callStatic will be available in PHP 5.3 +phpQuery::$plugins = new phpQueryPlugins(); +// include bootstrap file (personal library config) +if (file_exists(dirname(__FILE__).'/phpQuery/bootstrap.php')) + require_once dirname(__FILE__).'/phpQuery/bootstrap.php'; diff --git a/_test/cases/inc/search/data/ns1/ns3/page3.txt b/_test/data/_dummy similarity index 100% rename from _test/cases/inc/search/data/ns1/ns3/page3.txt rename to _test/data/_dummy diff --git a/_test/cases/inc/search/data/ns1/page1.txt b/_test/data/attic/_dummy similarity index 100% rename from _test/cases/inc/search/data/ns1/page1.txt rename to _test/data/attic/_dummy diff --git a/_test/cases/inc/search/data/ns1/page2.txt b/_test/data/cache/_dummy similarity index 100% rename from _test/cases/inc/search/data/ns1/page2.txt rename to _test/data/cache/_dummy diff --git a/_test/cases/inc/search/data/ns2/nopage.ext b/_test/data/index/_dummy similarity index 100% rename from _test/cases/inc/search/data/ns2/nopage.ext rename to _test/data/index/_dummy diff --git a/_test/cases/inc/search/data/ns2/page1.txt b/_test/data/locks/_dummy similarity index 100% rename from _test/cases/inc/search/data/ns2/page1.txt rename to _test/data/locks/_dummy diff --git a/_test/data/media/wiki/dokuwiki-128.png b/_test/data/media/wiki/dokuwiki-128.png new file mode 100644 index 0000000000..b2306ac957 Binary files /dev/null and b/_test/data/media/wiki/dokuwiki-128.png differ diff --git a/_test/data/media_attic/_dummy b/_test/data/media_attic/_dummy new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/data/media_meta/_dummy b/_test/data/media_meta/_dummy new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/data/meta/_dummy b/_test/data/meta/_dummy new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/data/pages/wiki/dokuwiki.txt b/_test/data/pages/wiki/dokuwiki.txt new file mode 100644 index 0000000000..e6fac5b652 --- /dev/null +++ b/_test/data/pages/wiki/dokuwiki.txt @@ -0,0 +1,64 @@ +====== DokuWiki ====== + +[[doku>wiki:dokuwiki|{{wiki:dokuwiki-128.png }}]] DokuWiki is a standards compliant, simple to use [[wp>Wiki]], mainly aimed at creating documentation of any kind. It is targeted at developer teams, workgroups and small companies. It has a simple but powerful [[wiki:syntax]] which makes sure the datafiles remain readable outside the Wiki and eases the creation of structured texts. All data is stored in plain text files -- no database is required. + +Read the [[doku>manual|DokuWiki Manual]] to unleash the full power of DokuWiki. + +===== Download ===== + +DokuWiki is available at http://www.splitbrain.org/go/dokuwiki + + +===== Read More ===== + +All documentation and additional information besides the [[syntax|syntax description]] is maintained in the DokuWiki at [[doku>|www.dokuwiki.org]]. + +**About DokuWiki** + + * [[doku>features|A feature list]] :!: + * [[doku>users|Happy Users]] + * [[doku>press|Who wrote about it]] + * [[doku>blogroll|What Bloggers think]] + * [[http://www.wikimatrix.org/show/DokuWiki|Compare it with other wiki software]] + +**Installing DokuWiki** + + * [[doku>requirements|System Requirements]] + * [[http://www.splitbrain.org/go/dokuwiki|Download DokuWiki]] :!: + * [[doku>changes|Change Log]] + * [[doku>Install|How to install or upgrade]] :!: + * [[doku>config|Configuration]] + +**Using DokuWiki** + + * [[doku>syntax|Wiki Syntax]] + * [[doku>manual|The manual]] :!: + * [[doku>FAQ|Frequently Asked Questions (FAQ)]] + * [[doku>glossary|Glossary]] + * [[http://search.dokuwiki.org|Search for DokuWiki help and documentation]] + +**Customizing DokuWiki** + + * [[doku>tips|Tips and Tricks]] + * [[doku>Template|How to create and use templates]] + * [[doku>plugins|Installing plugins]] + * [[doku>development|Development Resources]] + +**DokuWiki Feedback and Community** + + * [[doku>newsletter|Subscribe to the newsletter]] :!: + * [[doku>mailinglist|Join the mailing list]] + * [[http://forum.dokuwiki.org|Check out the user forum]] + * [[doku>irc|Talk to other users in the IRC channel]] + * [[http://bugs.splitbrain.org/index.php?project=1|Submit bugs and feature wishes]] + * [[http://www.wikimatrix.org/forum/viewforum.php?id=10|Share your experiences in the WikiMatrix forum]] + * [[doku>thanks|Some humble thanks]] + + +===== Copyright ===== + +2004-2010 (c) Andreas Gohr ((Please do not contact me for help and support -- use the [[doku>mailinglist]] or [[http://forum.dokuwiki.org|forum]] instead)) and the DokuWiki Community + +The DokuWiki engine is licensed under [[http://www.gnu.org/licenses/gpl.html|GNU General Public License]] Version 2. If you use DokuWiki in your company, consider [[doku>donate|donating]] a few bucks ;-). + +Not sure what this means? See the [[doku>faq:license|FAQ on the Licenses]]. diff --git a/_test/data/pages/wiki/syntax.txt b/_test/data/pages/wiki/syntax.txt new file mode 100644 index 0000000000..0b54809492 --- /dev/null +++ b/_test/data/pages/wiki/syntax.txt @@ -0,0 +1,486 @@ +====== Formatting Syntax ====== + +[[doku>DokuWiki]] supports some simple markup language, which tries to make the datafiles to be as readable as possible. This page contains all possible syntax you may use when editing the pages. Simply have a look at the source of this page by pressing the //Edit this page// button at the top or bottom of the page. If you want to try something, just use the [[playground:playground|playground]] page. The simpler markup is easily accessible via [[doku>toolbar|quickbuttons]], too. + +===== Basic Text Formatting ===== + +DokuWiki supports **bold**, //italic//, __underlined__ and ''monospaced'' texts. Of course you can **__//''combine''//__** all these. + + DokuWiki supports **bold**, //italic//, __underlined__ and ''monospaced'' texts. + Of course you can **__//''combine''//__** all these. + +You can use subscript and superscript, too. + + You can use subscript and superscript, too. + +You can mark something as deleted as well. + + You can mark something as deleted as well. + +**Paragraphs** are created from blank lines. If you want to **force a newline** without a paragraph, you can use two backslashes followed by a whitespace or the end of line. + +This is some text with some linebreaks\\ Note that the +two backslashes are only recognized at the end of a line\\ +or followed by\\ a whitespace \\this happens without it. + + This is some text with some linebreaks\\ Note that the + two backslashes are only recognized at the end of a line\\ + or followed by\\ a whitespace \\this happens without it. + +You should use forced newlines only if really needed. + +===== Links ===== + +DokuWiki supports multiple ways of creating links. + +==== External ==== + +External links are recognized automagically: http://www.google.com or simply www.google.com - You can set the link text as well: [[http://www.google.com|This Link points to google]]. Email addresses like this one: are recognized, too. + + DokuWiki supports multiple ways of creating links. External links are recognized + automagically: http://www.google.com or simply www.google.com - You can set + link text as well: [[http://www.google.com|This Link points to google]]. Email + addresses like this one: are recognized, too. + +==== Internal ==== + +Internal links are created by using square brackets. You can either just give a [[pagename]] or use an additional [[pagename|link text]]. + + Internal links are created by using square brackets. You can either just give + a [[pagename]] or use an additional [[pagename|link text]]. + +[[doku>pagename|Wiki pagenames]] are converted to lowercase automatically, special characters are not allowed. + +You can use [[some:namespaces]] by using a colon in the pagename. + + You can use [[some:namespaces]] by using a colon in the pagename. + +For details about namespaces see [[doku>namespaces]]. + +Linking to a specific section is possible, too. Just add the section name behind a hash character as known from HTML. This links to [[syntax#internal|this Section]]. + + This links to [[syntax#internal|this Section]]. + +Notes: + + * Links to [[syntax|existing pages]] are shown in a different style from [[nonexisting]] ones. + * DokuWiki does not use [[wp>CamelCase]] to automatically create links by default, but this behavior can be enabled in the [[doku>config]] file. Hint: If DokuWiki is a link, then it's enabled. + * When a section's heading is changed, its bookmark changes, too. So don't rely on section linking too much. + +==== Interwiki ==== + +DokuWiki supports [[doku>Interwiki]] links. These are quick links to other Wikis. For example this is a link to Wikipedia's page about Wikis: [[wp>Wiki]]. + + DokuWiki supports [[doku>Interwiki]] links. These are quick links to other Wikis. + For example this is a link to Wikipedia's page about Wikis: [[wp>Wiki]]. + +==== Windows Shares ==== + +Windows shares like [[\\server\share|this]] are recognized, too. Please note that these only make sense in a homogeneous user group like a corporate [[wp>Intranet]]. + + Windows Shares like [[\\server\share|this]] are recognized, too. + +Notes: + + * For security reasons direct browsing of windows shares only works in Microsoft Internet Explorer per default (and only in the "local zone"). + * For Mozilla and Firefox it can be enabled through different workaround mentioned in the [[http://kb.mozillazine.org/Links_to_local_pages_do_not_work|Mozilla Knowledge Base]]. However, there will still be a JavaScript warning about trying to open a Windows Share. To remove this warning (for all users), put the following line in ''conf/local.protected.php'': + + $lang['js']['nosmblinks'] = ''; + +==== Image Links ==== + +You can also use an image to link to another internal or external page by combining the syntax for links and [[#images_and_other_files|images]] (see below) like this: + + [[http://www.php.net|{{wiki:dokuwiki-128.png}}]] + +[[http://www.php.net|{{wiki:dokuwiki-128.png}}]] + +Please note: The image formatting is the only formatting syntax accepted in link names. + +The whole [[#images_and_other_files|image]] and [[#links|link]] syntax is supported (including image resizing, internal and external images and URLs and interwiki links). + +===== Footnotes ===== + +You can add footnotes ((This is a footnote)) by using double parentheses. + + You can add footnotes ((This is a footnote)) by using double parentheses. + +===== Sectioning ===== + +You can use up to five different levels of headlines to structure your content. If you have more than three headlines, a table of contents is generated automatically -- this can be disabled by including the string ''~~NOTOC~~'' in the document. + +==== Headline Level 3 ==== +=== Headline Level 4 === +== Headline Level 5 == + + ==== Headline Level 3 ==== + === Headline Level 4 === + == Headline Level 5 == + +By using four or more dashes, you can make a horizontal line: + +---- + +===== Images and Other Files ===== + +You can include external and internal [[doku>images]] with curly brackets. Optionally you can specify the size of them. + +Real size: {{wiki:dokuwiki-128.png}} + +Resize to given width: {{wiki:dokuwiki-128.png?50}} + +Resize to given width and height((when the aspect ratio of the given width and height doesn't match that of the image, it will be cropped to the new ratio before resizing)): {{wiki:dokuwiki-128.png?200x50}} + +Resized external image: {{http://de3.php.net/images/php.gif?200x50}} + + Real size: {{wiki:dokuwiki-128.png}} + Resize to given width: {{wiki:dokuwiki-128.png?50}} + Resize to given width and height: {{wiki:dokuwiki-128.png?200x50}} + Resized external image: {{http://de3.php.net/images/php.gif?200x50}} + + +By using left or right whitespaces you can choose the alignment. + +{{ wiki:dokuwiki-128.png}} + +{{wiki:dokuwiki-128.png }} + +{{ wiki:dokuwiki-128.png }} + + {{ wiki:dokuwiki-128.png}} + {{wiki:dokuwiki-128.png }} + {{ wiki:dokuwiki-128.png }} + +Of course, you can add a title (displayed as a tooltip by most browsers), too. + +{{ wiki:dokuwiki-128.png |This is the caption}} + + {{ wiki:dokuwiki-128.png |This is the caption}} + +If you specify a filename (external or internal) that is not an image (''gif, jpeg, png''), then it will be displayed as a link instead. + +For linking an image to another page see [[#Image Links]] above. + +===== Lists ===== + +Dokuwiki supports ordered and unordered lists. To create a list item, indent your text by two spaces and use a ''*'' for unordered lists or a ''-'' for ordered ones. + + * This is a list + * The second item + * You may have different levels + * Another item + + - The same list but ordered + - Another item + - Just use indention for deeper levels + - That's it + + + * This is a list + * The second item + * You may have different levels + * Another item + + - The same list but ordered + - Another item + - Just use indention for deeper levels + - That's it + + +Also take a look at the [[doku>faq:lists|FAQ on list items]]. + +===== Text Conversions ===== + +DokuWiki can convert certain pre-defined characters or strings into images or other text or HTML. + +The text to image conversion is mainly done for smileys. And the text to HTML conversion is used for typography replacements, but can be configured to use other HTML as well. + +==== Text to Image Conversions ==== + +DokuWiki converts commonly used [[wp>emoticon]]s to their graphical equivalents. Those [[doku>Smileys]] and other images can be configured and extended. Here is an overview of Smileys included in DokuWiki: + + * 8-) %% 8-) %% + * 8-O %% 8-O %% + * :-( %% :-( %% + * :-) %% :-) %% + * =) %% =) %% + * :-/ %% :-/ %% + * :-\ %% :-\ %% + * :-? %% :-? %% + * :-D %% :-D %% + * :-P %% :-P %% + * :-O %% :-O %% + * :-X %% :-X %% + * :-| %% :-| %% + * ;-) %% ;-) %% + * ^_^ %% ^_^ %% + * :?: %% :?: %% + * :!: %% :!: %% + * LOL %% LOL %% + * FIXME %% FIXME %% + * DELETEME %% DELETEME %% + +==== Text to HTML Conversions ==== + +Typography: [[DokuWiki]] can convert simple text characters to their typographically correct entities. Here is an example of recognized characters. + +-> <- <-> => <= <=> >> << -- --- 640x480 (c) (tm) (r) +"He thought 'It's a man's world'..." + + +-> <- <-> => <= <=> >> << -- --- 640x480 (c) (tm) (r) +"He thought 'It's a man's world'..." + + +The same can be done to produce any kind of HTML, it just needs to be added to the [[doku>entities|pattern file]]. + +There are three exceptions which do not come from that pattern file: multiplication entity (640x480), 'single' and "double quotes". They can be turned off through a [[doku>config:typography|config option]]. + +===== Quoting ===== + +Some times you want to mark some text to show it's a reply or comment. You can use the following syntax: + + I think we should do it + + > No we shouldn't + + >> Well, I say we should + + > Really? + + >> Yes! + + >>> Then lets do it! + +I think we should do it + +> No we shouldn't + +>> Well, I say we should + +> Really? + +>> Yes! + +>>> Then lets do it! + +===== Tables ===== + +DokuWiki supports a simple syntax to create tables. + +^ Heading 1 ^ Heading 2 ^ Heading 3 ^ +| Row 1 Col 1 | Row 1 Col 2 | Row 1 Col 3 | +| Row 2 Col 1 | some colspan (note the double pipe) || +| Row 3 Col 1 | Row 3 Col 2 | Row 3 Col 3 | + +Table rows have to start and end with a ''|'' for normal rows or a ''^'' for headers. + + ^ Heading 1 ^ Heading 2 ^ Heading 3 ^ + | Row 1 Col 1 | Row 1 Col 2 | Row 1 Col 3 | + | Row 2 Col 1 | some colspan (note the double pipe) || + | Row 3 Col 1 | Row 3 Col 2 | Row 3 Col 3 | + +To connect cells horizontally, just make the next cell completely empty as shown above. Be sure to have always the same amount of cell separators! + +Vertical tableheaders are possible, too. + +| ^ Heading 1 ^ Heading 2 ^ +^ Heading 3 | Row 1 Col 2 | Row 1 Col 3 | +^ Heading 4 | no colspan this time | | +^ Heading 5 | Row 2 Col 2 | Row 2 Col 3 | + +As you can see, it's the cell separator before a cell which decides about the formatting: + + | ^ Heading 1 ^ Heading 2 ^ + ^ Heading 3 | Row 1 Col 2 | Row 1 Col 3 | + ^ Heading 4 | no colspan this time | | + ^ Heading 5 | Row 2 Col 2 | Row 2 Col 3 | + +You can have rowspans (vertically connected cells) by adding '':::'' into the cells below the one to which they should connect. + +^ Heading 1 ^ Heading 2 ^ Heading 3 ^ +| Row 1 Col 1 | this cell spans vertically | Row 1 Col 3 | +| Row 2 Col 1 | ::: | Row 2 Col 3 | +| Row 3 Col 1 | ::: | Row 2 Col 3 | + +Apart from the rowspan syntax those cells should not contain anything else. + + ^ Heading 1 ^ Heading 2 ^ Heading 3 ^ + | Row 1 Col 1 | this cell spans vertically | Row 1 Col 3 | + | Row 2 Col 1 | ::: | Row 2 Col 3 | + | Row 3 Col 1 | ::: | Row 2 Col 3 | + +You can align the table contents, too. Just add at least two whitespaces at the opposite end of your text: Add two spaces on the left to align right, two spaces on the right to align left and two spaces at least at both ends for centered text. + +^ Table with alignment ^^^ +| right| center |left | +|left | right| center | +| xxxxxxxxxxxx | xxxxxxxxxxxx | xxxxxxxxxxxx | + +This is how it looks in the source: + + ^ Table with alignment ^^^ + | right| center |left | + |left | right| center | + | xxxxxxxxxxxx | xxxxxxxxxxxx | xxxxxxxxxxxx | + +Note: Vertical alignment is not supported. + +===== No Formatting ===== + +If you need to display text exactly like it is typed (without any formatting), enclose the area either with ''%%%%'' tags or even simpler, with double percent signs ''%%''. + + +This is some text which contains addresses like this: http://www.splitbrain.org and **formatting**, but nothing is done with it. + +The same is true for %%//__this__ text// with a smiley ;-)%%. + + + This is some text which contains addresses like this: http://www.splitbrain.org and **formatting**, but nothing is done with it. + + The same is true for %%//__this__ text// with a smiley ;-)%%. + +===== Code Blocks ===== + +You can include code blocks into your documents by either indenting them by at least two spaces (like used for the previous examples) or by using the tags ''%%%%'' or ''%%%%''. + + This is text is indented by two spaces. + + +This is preformatted code all spaces are preserved: like <-this + + + +This is pretty much the same, but you could use it to show that you quoted a file. + + +Those blocks were created by this source: + + This is text is indented by two spaces. + + + This is preformatted code all spaces are preserved: like <-this + + + + This is pretty much the same, but you could use it to show that you quoted a file. + + +==== Syntax Highlighting ==== + +[[wiki:DokuWiki]] can highlight sourcecode, which makes it easier to read. It uses the [[http://qbnz.com/highlighter/|GeSHi]] Generic Syntax Highlighter -- so any language supported by GeSHi is supported. The syntax uses the same code and file blocks described in the previous section, but this time the name of the language syntax to be highlighted is included inside the tag, e.g. '''' or ''''. + + +/** + * The HelloWorldApp class implements an application that + * simply displays "Hello World!" to the standard output. + */ +class HelloWorldApp { + public static void main(String[] args) { + System.out.println("Hello World!"); //Display the string. + } +} + + +The following language strings are currently recognized: //4cs, abap, actionscript-french, actionscript, actionscript3, ada, apache, applescript, asm, asp, autoconf, autohotkey, autoit, avisynth, awk, bash, basic4gl, bf, bibtex, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cfdg, cfm, chaiscript, cil, clojure, cmake, cobol, cpp, cpp-qt, csharp, css, cuesheet, d, dcs, delphi, diff, div, dos, dot, ecmascript, eiffel, email, erlang, fo, fortran, freebasic, fsharp, gambas, genero, genie, gdb, glsl, gml, gnuplot, groovy, gettext, gwbasic, haskell, hicest, hq9plus, html, icon, idl, ini, inno, intercal, io, j, java5, java, javascript, jquery, kixtart, klonec, klonecpp, latex, lisp, locobasic, logtalk, lolcode, lotusformulas, lotusscript, lscript, lsl2, lua, m68k, magiksf, make, mapbasic, matlab, mirc, modula2, modula3, mmix, mpasm, mxml, mysql, newlisp, nsis, oberon2, objc, ocaml-brief, ocaml, oobas, oracle8, oracle11, oxygene, oz, pascal, pcre, perl, perl6, per, pf, php-brief, php, pike, pic16, pixelbender, plsql, postgresql, povray, powerbuilder, powershell, progress, prolog, properties, providex, purebasic, python, q, qbasic, rails, rebol, reg, robots, rpmspec, rsplus, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, systemverilog, tcl, teraterm, text, thinbasic, tsql, typoscript, unicon, vala, vbnet, vb, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, winbatch, whois, xbasic, xml, xorg_conf, xpp, z80// + +==== Downloadable Code Blocks ==== + +When you use the ''%%%%'' or ''%%%%'' syntax as above, you might want to make the shown code available for download as well. You can to this by specifying a file name after language code like this: + + + + + + + + + + + +If you don't want any highlighting but want a downloadable file, specify a dash (''-'') as the language code: ''%%%%''. + + +===== Embedding HTML and PHP ===== + +You can embed raw HTML or PHP code into your documents by using the ''%%%%'' or ''%%%%'' tags. (Use uppercase tags if you need to enclose block level elements.) + +HTML example: + + + +This is some inline HTML + + +

And this is some block HTML

+ +
+ + +This is some inline HTML + + +

And this is some block HTML

+ + +PHP example: + + + +echo 'A logo generated by PHP:'; +echo 'PHP Logo !'; +echo '(generated inline HTML)'; + + +echo ''; +echo ''; +echo '
The same, but inside a block level element:PHP Logo !
'; +
+
+ + +echo 'A logo generated by PHP:'; +echo 'PHP Logo !'; +echo '(inline HTML)'; + + +echo ''; +echo ''; +echo '
The same, but inside a block level element:PHP Logo !
'; +
+ +**Please Note**: HTML and PHP embedding is disabled by default in the configuration. If disabled, the code is displayed instead of executed. + +===== RSS/ATOM Feed Aggregation ===== +[[DokuWiki]] can integrate data from external XML feeds. For parsing the XML feeds, [[http://simplepie.org/|SimplePie]] is used. All formats understood by SimplePie can be used in DokuWiki as well. You can influence the rendering by multiple additional space separated parameters: + +^ Parameter ^ Description ^ +| any number | will be used as maximum number items to show, defaults to 8 | +| reverse | display the last items in the feed first | +| author | show item authors names | +| date | show item dates | +| description| show the item description. If [[doku>config:htmlok|HTML]] is disabled all tags will be stripped | +| //n//[dhm] | refresh period, where d=days, h=hours, m=minutes. (e.g. 12h = 12 hours). | + +The refresh period defaults to 4 hours. Any value below 10 minutes will be treated as 10 minutes. [[wiki:DokuWiki]] will generally try to supply a cached version of a page, obviously this is inappropriate when the page contains dynamic external content. The parameter tells [[wiki:DokuWiki]] to re-render the page if it is more than //refresh period// since the page was last rendered. + +**Example:** + + {{rss>http://slashdot.org/index.rss 5 author date 1h }} + +{{rss>http://slashdot.org/index.rss 5 author date 1h }} + + +===== Control Macros ===== + +Some syntax influences how DokuWiki renders a page without creating any output it self. The following control macros are availble: + +^ Macro ^ Description | +| %%~~NOTOC~~%% | If this macro is found on the page, no table of contents will be created | +| %%~~NOCACHE~~%% | DokuWiki caches all output by default. Sometimes this might not be wanted (eg. when the %%%% syntax above is used), adding this macro will force DokuWiki to rerender a page on every call | + +===== Syntax Plugins ===== + +DokuWiki's syntax can be extended by [[doku>plugins|Plugins]]. How the installed plugins are used is described on their appropriate description pages. The following syntax plugins are available in this particular DokuWiki installation: + +~~INFO:syntaxplugins~~ diff --git a/_test/data/tmp/_dummy b/_test/data/tmp/_dummy new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/debug.note b/_test/debug.note deleted file mode 100644 index 28c34d8eec..0000000000 --- a/_test/debug.note +++ /dev/null @@ -1,4 +0,0 @@ -print "-----------------------------------------------------\n"; -print_r(array_map('stripbyteindex',$this->H->calls)); -print "-----------------------------------------------------\n"; -print_r($calls); diff --git a/_test/index.php b/_test/index.php deleted file mode 100644 index 64ece47624..0000000000 --- a/_test/index.php +++ /dev/null @@ -1,228 +0,0 @@ - 'Simple Test', - 'path' => SIMPLE_TEST)); -} - -function & DW_TESTS_GetReporter() { - static $Reporter = NULL; - if ( !$Reporter ) { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - require_once SIMPLE_TEST . 'xml.php'; - $Reporter = new XmlReporter(); - break; - case DW_TESTS_OUTPUT_HTML: - default: - $Reporter = new HTMLReporter('utf-8'); - break; - } - } - return $Reporter; -} - -function DW_TESTS_PaintRunMore() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - break; - case DW_TESTS_OUTPUT_HTML: - default: - echo "

Run more tests

"; - break; - } -} - -function DW_TESTS_PaintHeader() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - header('Content-Type: text/xml; charset="utf-8"'); - break; - case DW_TESTS_OUTPUT_HTML: - $header = << - - - - - Dokuwiki: Unit Test Suite - - - - -EOD; - echo $header; - default: - break; - } -} - -function DW_TESTS_PaintSuiteHeader() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - break; - case DW_TESTS_OUTPUT_HTML: - default: - echo "

Dokuwiki: Unit Test Suite

\n"; - echo "

Test groups"; - echo " || Test cases

"; - break; - } -} - -function DW_TESTS_PaintCaseList() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - echo XMLTestManager::getTestCaseList(TEST_CASES); - break; - case DW_TESTS_OUTPUT_HTML: - default: - echo HTMLTestManager::getTestCaseList(TEST_CASES); - break; - } -} - -function DW_TESTS_PaintGroupTestList() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - echo XMLTestManager::getGroupTestList(TEST_GROUPS); - break; - case DW_TESTS_OUTPUT_HTML: - default: - echo HTMLTestManager::getGroupTestList(TEST_GROUPS); - break; - } -} - -function DW_TESTS_PaintPluginTestCaseList() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - echo XMLTestManager::getPluginTestCaseList(TEST_PLUGINS); - break; - case DW_TESTS_OUTPUT_HTML: - default: - echo HTMLTestManager::getPluginTestCaseList(TEST_PLUGINS); - break; - } -} - -function DW_TESTS_PaintPluginGroupTestList() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - echo XMLTestManager::getPluginGroupTestList(TEST_PLUGINS); - break; - case DW_TESTS_OUTPUT_HTML: - default: - echo HTMLTestManager::getPluginGroupTestList(TEST_PLUGINS); - break; - } -} - -function DW_TESTS_PaintFooter() { - switch ( DW_TESTS_OUTPUT ) { - case DW_TESTS_OUTPUT_XML: - break; - case DW_TESTS_OUTPUT_HTML: - default: - $footer = << - -EOD; - echo $footer; - break; - } -} - -/** OUTPUT STARTS HERE **/ - -// If it's a group test -if (isset($_GET['group'])) { - if ('all' == $_GET['group']) { - TestManager::runAllTests(DW_TESTS_GetReporter()); - } else { - TestManager::runGroupTest(ucfirst($_GET['group']), - TEST_GROUPS, - DW_TESTS_GetReporter()); - } - DW_TESTS_PaintRunMore(); - exit(); -} - -// If it's a plugin group test -if (isset($_GET['plugin_group'])) { - if ('all' == $_GET['plugin_group']) { - TestManager::runAllPluginTests(DW_TESTS_GetReporter()); - } else { - TestManager::runGroupTest(ucfirst($_GET['plugin_group']), - TEST_PLUGINS, - DW_TESTS_GetReporter()); - } - DW_TESTS_PaintRunMore(); - exit(); -} - -// If it's a single test case -if (isset($_GET['case'])) { - TestManager::runTestCase($_GET['case'], TEST_CASES, DW_TESTS_GetReporter()); - DW_TESTS_PaintRunMore(); - exit(); -} - -// If it's a single plugin test case -if (isset($_GET['plugin_case'])) { - TestManager::runTestCase($_GET['plugin_case'], TEST_PLUGINS, DW_TESTS_GetReporter()); - DW_TESTS_PaintRunMore(); - exit(); -} - -// Else it's the main page -DW_TESTS_PaintHeader(); - -DW_TESTS_PaintSuiteHeader(); - -if (isset($_GET['show']) && $_GET['show'] == 'cases') { - DW_TESTS_PaintCaseList(); - DW_TESTS_PaintPluginTestCaseList(); -} else { - /* no group specified, so list them all */ - DW_TESTS_PaintGroupTestList(); - DW_TESTS_PaintPluginGroupTestList(); -} - -DW_TESTS_PaintFooter(); diff --git a/_test/jslint.js b/_test/jslint.js deleted file mode 100644 index 730f8d8a8b..0000000000 --- a/_test/jslint.js +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copy to a JavaScript console on your DokuWiki instance and execute - * Runs JSLint on all our JavaScript files with our settings - */ - -(function () { -var globals = ['jQuery', 'SIG', 'NS', 'JSINFO', 'LANG', 'DOKU_BASE', - 'DOKU_UHC' // FIXME: Should be moved to JSINFO - ], files = { - 'scripts/behaviour.js': null, - //"scripts/compatibility.js": null, - "scripts/cookie.js": null, - //"scripts/delay.js": null, - //"scripts/drag.js": null, - "scripts/edit.js": null, - "scripts/editor.js": null, - "scripts/helpers.js": null, - "scripts/hotkeys.js": null, - "scripts/index.js": null, - "scripts/linkwiz.js": null, - "scripts/locktimer.js": null, - "scripts/media.js": null, - "scripts/page.js": null, - "scripts/qsearch.js": null, - "scripts/script.js": null, - "scripts/textselection.js": null, - "scripts/toolbar.js": null, - "scripts/tree.js": null //, - //"scripts/tw-sack.js": null - }, overwrites = { - "scripts/script.js": {evil: true}, - "scripts/media.js": {devel: true, windows: true}, - "scripts/locktimer.js": {devel: true}, - "scripts/behaviour.js": {devel: true}, - "scripts/helpers.js": {windows: true} - }; - -jQuery.ajax({ - dataType: 'script', - type: "GET", -// url: 'http://jshint.com/jshint.js' - url: 'https://raw.github.com/douglascrockford/JSLint/master/jslint.js', - success: function () { - for (var file in files) { - jQuery.ajax({ - cache: false, - async: false, - type: "GET", - url: DOKU_BASE + 'lib/' + file, - dataType: 'text', - success: function (res) { - files[file] = res; - var data = lint(files[file]); - jQuery.merge(globals, data.globals); - }}); - } - - for (var file in files) { - if (!files[file]) { - continue; - } - // FIXME more fine-grained write access - var data = lint('/*global ' + globals.join(':true, ') + - ':true*/\n' + files[file], overwrites[file]); - console.log(file); - jQuery.each(data.errors || [], function (_, val) { - if (val === null) { - return; - } - console.error(val.reason + ' (Line ' + (val.line - 1) + - ', character ' + val.character + '):\n' + - val.evidence); - }); - }; - } -}); - -function lint(txt, overwrite) { - JSLINT(txt, jQuery.extend({ - // These settings are necessary - browser: true, - - // Things we probably should learn someday - sloppy: true, white: true, eqeq: true, nomen: true, - plusplus: true, regexp: true - }, overwrite)); - return JSLINT.data(); -} -})(); diff --git a/_test/lib/cli_reporter.php b/_test/lib/cli_reporter.php deleted file mode 100644 index 3ad88119db..0000000000 --- a/_test/lib/cli_reporter.php +++ /dev/null @@ -1,114 +0,0 @@ -"); -} - -if (! defined('ST_FAILS_RETURN_CODE')) { - define('ST_FAILS_RETURN_CODE', 1); -} - -if (version_compare(phpversion(), '4.3.0', '<') || - php_sapi_name() == 'cgi') { - define('STDOUT', fopen('php://stdout', 'w')); - define('STDERR', fopen('php://stderr', 'w')); - register_shutdown_function( - create_function('', 'fclose(STDOUT); fclose(STDERR); return true;')); -} - -/** - * Minimal command line test displayer. Writes fail details to STDERR. Returns 0 - * to the shell if all tests pass, ST_FAILS_RETURN_CODE if any test fails. - */ -class CLIReporter extends SimpleReporter { - - var $faildetail_separator = ST_FAILDETAIL_SEPARATOR; - var $_failinfo; - - function CLIReporter($faildetail_separator = NULL) { - $this->SimpleReporter(); - if (! is_null($faildetail_separator)) { - $this->setFailDetailSeparator($faildetail_separator); - } - } - - function setFailDetailSeparator($separator) { - $this->faildetail_separator = $separator; - } - - /** - * Return a formatted faildetail for printing. - */ - function &_paintTestFailDetail(&$message) { - $buffer = ''; - $faildetail = $this->getTestList(); - array_shift($faildetail); - $buffer .= implode($this->faildetail_separator, $faildetail); - $buffer .= $this->faildetail_separator . "$message\n"; - return $buffer; - } - - /** - * Paint fail faildetail to STDERR. - */ - function paintFail($message) { - parent::paintFail($message); - fwrite(STDERR, 'FAIL' . $this->faildetail_separator . - $this->_paintTestFailDetail($message)); - if($this->_failinfo){ - fwrite(STDERR, ' additional info was: '.$this->_failinfo."\n"); - $this->_failinfo = ''; - } - } - - /** - * reset failinfo - */ - function paintPass($message) { - parent::paintPass($message); - $this->_failinfo = ''; - } - - /** - * Paint exception faildetail to STDERR. - */ - function paintException($message) { - parent::paintException($message); - fwrite(STDERR, 'EXCEPTION' . $this->faildetail_separator . - $this->_paintTestFailDetail($message)); - } - - /** - * Handle failinfo message - */ - function paintSignal($type,$message) { - parent::paintSignal($type,$message); - if($type = 'failinfo') $this->_failinfo = $message; - } - - - - /** - * Paint a footer with test case name, timestamp, counts of fails and - * exceptions. - */ - function paintFooter($test_name) { - $buffer = $this->getTestCaseProgress() . '/' . - $this->getTestCaseCount() . ' test cases complete: '; - - if (0 < ($this->getFailCount() + $this->getExceptionCount())) { - $buffer .= $this->getPassCount() . " passes"; - if (0 < $this->getFailCount()) { - $buffer .= ", " . $this->getFailCount() . " fails"; - } - if (0 < $this->getExceptionCount()) { - $buffer .= ", " . $this->getExceptionCount() . " exceptions"; - } - $buffer .= ".\n"; - fwrite(STDOUT, $buffer); - exit(ST_FAILS_RETURN_CODE); - } else { - fwrite(STDOUT, $buffer . $this->getPassCount() . " passes.\n"); - } - } -} diff --git a/_test/lib/mock_functions.php b/_test/lib/mock_functions.php deleted file mode 100644 index 9ef5b7b8f8..0000000000 --- a/_test/lib/mock_functions.php +++ /dev/null @@ -1,519 +0,0 @@ -deploy(); - return $mock; - } - - /** - * Removes the mock function implementation and restores - * the real implementation (if one existed) - * @TODO Would be good to have this called automatically - * @param string $function Function name - * @access public - * @static - */ - function restore($function) { - $mock = & MockFunction::_instance($function); - $mock->restore(); - } - - /** - * Fetch a singleton instance of SimpleMockFunction - * @param string $function Function name - * @param boolean $fresh Force a fresh instance - * @access private - * @static - */ - function &_instance($function, $fresh = FALSE) { - static $singleton = array(); - - $function = strtolower($function); - - if ( $fresh ) { - if ( isset($singleton[$function]) ) { - unset($singleton[$function]); - } - } - - if ( !isset($singleton[$function]) ) { - // TODO: case sensitivity issues - $class = $function."MockFunction"; - MockFunction::_generateSubClass($class, $function); - $singleton[$function] = new $class($function); - } - - return $singleton[$function]; - } - - /** - * Required for strict mode and SimpleMock - * @TODO Should perhaps be placed in SimpleFunctionGenerator - * @param string $class subclass name - * @param string $method method name - * @access private - * @static - */ - function _generateSubClass($class, $method) { - if ( class_exists($class) ) { - return; - } - $code = "class $class extends SimpleMockFunction {\n"; - $code .= " function $method () {}\n"; - $code .= "}\n"; - eval($code); - } - - /** - * Changes the default wildcard object. - * @param string $function Function name wildcard applies to - * @param mixed $wildcard Parameter matching wildcard. - * @access public - * @static - */ - function setWildcard($function, $wildcard) { - $mock = & MockFunction::_instance($function); - $mock->setWildcard($wildcard); - } - - /** - * Fetches the call count of a function so far. - * @param string $function Function name called. - * @return Number of calls so far. - * @access public - * @static - */ - function getCallCount($function) { - $mock = & MockFunction::_instance($function); - return $mock->getCallCount($function); - } - - /** - * Sets a return for a parameter list that will - * be passed by value for all calls to this function. - * @param string $function Function name. - * @param mixed $value Result of call passed by value. - * @param array $args List of parameters to match - * including wildcards. - * @access public - * @static - */ - function setReturnValue($function, $value, $args = false) { - $mock = & MockFunction::_instance($function); - $mock->setReturnValue($function, $value, $args); - } - - /** - * Sets a return for a parameter list that will - * be passed by value only when the required call count - * is reached. - * @param integer $timing Number of calls in the future - * to which the result applies. If - * not set then all calls will return - * the value. - * @param string $function Function name. - * @param mixed $value Result of call passed by value. - * @param array $args List of parameters to match - * including wildcards. - * @access public - * @static - */ - function setReturnValueAt($timing, $function, $value, $args = false) { - $mock = & MockFunction::_instance($function); - $mock->setReturnValueAt($timing, $function, $value, $args); - } - - /** - * Sets a return for a parameter list that will - * be passed by reference for all calls. - * @param string $function Function name. - * @param mixed $reference Result of the call will be this object. - * @param array $args List of parameters to match - * including wildcards. - * @access public - * @static - */ - function setReturnReference($function, &$reference, $args = false) { - $mock = & MockFunction::_instance($function); - $mock->setReturnReference($function, $reference, $args); - } - - /** - * Sets a return for a parameter list that will - * be passed by value only when the required call count - * is reached. - * @param integer $timing Number of calls in the future - * to which the result applies. If - * not set then all calls will return - * the value. - * @param string $function Function name. - * @param mixed $reference Result of the call will be this object. - * @param array $args List of parameters to match - * including wildcards. - * @access public - * @static - */ - function setReturnReferenceAt($timing, $function, &$reference, $args = false) { - $mock = & MockFunction::_instance($function); - $mock->setReturnReferenceAt($timing, $function, $reference, $args); - } - - /** - * Sets up an expected call with a set of - * expected parameters in that call. All - * calls will be compared to these expectations - * regardless of when the call is made. - * @param string $function Function call to test. - * @param array $args Expected parameters for the call - * including wildcards. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectArguments($function, $args, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectArguments($function, $args, $message); - } - - /** - * Sets up an expected call with a set of - * expected parameters in that call. The - * expected call count will be adjusted if it - * is set too low to reach this call. - * @param integer $timing Number of calls in the future at - * which to test. Next call is 0. - * @param string $function Function call to test. - * @param array $args Expected parameters for the call - * including wildcards. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectArgumentsAt($timing, $function, $args, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectArgumentsAt($timing, $function, $args, $message); - } - - /** - * Sets an expectation for the number of times - * a function will be called. - * @param string $function Function call to test. - * @param integer $count Number of times it should - * have been called at tally. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectCallCount($function, $count, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectCallCount($function, $count, $message); - } - - /** - * Sets the number of times a function may be called - * before a test failure is triggered. - * @param string $function Function call to test. - * @param integer $count Most number of times it should - * have been called. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectMaximumCallCount($function, $count, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectMaximumCallCount($function, $count, $message); - } - - /** - * Sets the minimum number of times the function must be called - * otherwise a test failure is triggered - * @param string $function Function call to test. - * @param integer $count Least number of times it should - * have been called. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectMinimumCallCount($function, $count, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectMinimumCallCount($function, $count, $message); - } - - /** - * Convenience method for barring a function - * call. - * @param string $function Function call to ban. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectNever($function, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectNever($function, $message); - } - - /** - * Convenience method for a single function - * call. - * @param string $function Function call to track. - * @param array $args Expected argument list or - * false for any arguments. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectOnce($function, $args = false, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectOnce($function, $args, $message); - } - - /** - * Convenience method for requiring a function - * call. - * @param string $function Function call to track. - * @param array $args Expected argument list or - * false for any arguments. - * @param string $message Overridden message. - * @access public - * @static - */ - function expectAtLeastOnce($function, $args = false, $message = '%s') { - $mock = & MockFunction::_instance($function); - $mock->expectAtLeastOnce($function, $args, $message); - } - - function atTestEnd($function) { - $mock = & MockFunction::_instance($function); - $mock->atTestEnd($function); - } - - } - - /** - * Represents a single, mocked function, tracking calls made to it - * @package SimpleTest - * @subpackage MockFunctions - */ - class SimpleMockFunction extends SimpleMock { - - var $_is_mocked = FALSE; - var $_generator; - - /** - * Sets up the mock, creating a generator depending on whether - * the function is already declared - * @param string $function Name of function being mocked - */ - function SimpleMockFunction($function) { - - SimpleMock :: SimpleMock(); - - if ( function_exists($function) ) { - $this->_generator = new SimpleDeclaredFunctionGenerator($function); - } else { - $this->_generator = new SimpleUndeclaredFunctionGenerator($function); - } - - } - - /** - * Deploys the mock function implementation into PHP's function - * table, replacing any existing implementation - * @access public - */ - function deploy() { - - if ( !$this->_is_mocked ) { - - $this->_is_mocked = TRUE; - $this->_generator->deploy(); - - } - - } - - /** - * Restores the state of PHP's function table to that before - * the mock function was deployed. Removes the mock function - * implementation and restores any existing implementation of - * that function - * @access public - */ - function restore() { - - if ( $this->_is_mocked ) { - - $this->_is_mocked = FALSE; - $this->_generator->restore(); - - } - - } - - } - - /** - * Base class for deploying and restoring from mock functions - * @package SimpleTest - * @subpackage MockFunctions - * @abstract - */ - class SimpleFunctionGenerator { - - var $_function; - - /** - * @TODO Validate the function name (as it's being used in eval) - * @TODO Add list of illegal functions (ones which must not be mocked - * as they will break SimpleTest, which uses them) - * @param string $function Name of function being mocked - */ - function SimpleFunctionGenerator($function) { - $this->_function = $function; - } - - /** - * Generates the mock function implementation, using eval - * @access private - */ - function _generateMockFunction() { - $code = "function " . $this->_function . "() {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " \$mock = & MockFunction::_instance('".$this->_function."');\n"; - $code .= " \$result = &\$mock->_invoke(\"".$this->_function."\", \$args);\n"; - $code .= " return \$result;\n"; - $code .= "}\n"; - eval($code); - } - } - - /** - * Mock function generator for functions which have already been declared - * @package SimpleTest - * @subpackage MockFunctions - */ - class SimpleDeclaredFunctionGenerator extends SimpleFunctionGenerator { - - var $_tmp_function = NULL; - - /** - * Invokes the _generateTmpFnFname - * @param string $function Name of function being mocked - */ - function SimpleDeclaredFunctionGenerator($function) { - - SimpleFunctionGenerator::SimpleFunctionGenerator($function); - $this->_generateTmpFnFname(); - - } - - /** - * Generates a temporary name for the declared function implementation - * which is will be renamed to while the mock function is in use - * @access private - */ - function _generateTmpFnFname() { - static $count = 1; - $this->_tmp_function = 'tmp_'.md5(time().$this->_function.$count); - $count++; - } - - /** - * Deploys the mock function implementation - * @access public - */ - function deploy() { - - runkit_function_rename( - $this->_function, - $this->_tmp_function - ) or - trigger_error('Error archiving real function implementation', - E_USER_ERROR); - - $this->_generateMockFunction(); - } - - /** - * Removes the mock function implementation and restores - * the previously declared implementation - * @access public - */ - function restore() { - - runkit_function_remove($this->_function) or - trigger_error('Error removing mock function', - E_USER_ERROR); - - runkit_function_rename( - $this->_tmp_function, - $this->_function - ) or - trigger_error('Error restoring real function', - E_USER_ERROR); - } - } - - /** - * Mock function generator for functions which have not - * already been declared - * @package SimpleTest - * @subpackage MockFunctions - */ - class SimpleUndeclaredFunctionGenerator extends SimpleFunctionGenerator { - - /** - * Deploys the mock function implementation - * @access public - */ - function deploy() { - $this->_generateMockFunction(); - } - - /** - * Removes the mock function implementation - * @access public - */ - function restore() { - runkit_function_remove($this->_function) or - trigger_error('Error removing mock function', - E_USER_ERROR); - } - - } - diff --git a/_test/lib/rss_writer_class.php b/_test/lib/rss_writer_class.php deleted file mode 100644 index 684acfcfac..0000000000 --- a/_test/lib/rss_writer_class.php +++ /dev/null @@ -1,369 +0,0 @@ -error=("required ".$scope." property \"".$property."\" is already set"); - return 0; - } - $required[$property]=1; - $required_properties++; - } - else - { - if(IsSet($optional[$property])) - { - if($optional[$property]) - { - $this->error=("optional ".$scope." property \"".$property."\" is already set"); - return 0; - } - $optional[$property]=1; - } - else - { - if(GetType($colon=strpos($property,":",0))=="integer") - { - $namespace=substr($property,0,$colon); - if(!(!strcmp($namespace,"rdf") || IsSet($this->rssnamespaces[$namespace]))) - $this->error=("the name space of property \"".$property."\" was not declared"); - } - else - $this->error=("\"".$property."\" is not a supported ".$scope." property"); - } - } - if(!($this->adddatatag($property,$noattributes,$properties[$property],$parent,$path))) - return 0; - Next($properties); - $end=(GetType($property=Key($properties))!="string"); - } - if($required_propertieserror=("it was not specified the required ".$scope." property \"".$property."\""); - return 0; - } - Next($required); - $end=(GetType($property=Key($required))!="string"); - } - } - return 1; - } - - /* - * Public functions - * - */ - Function addchannel(&$properties) - { - if(strcmp($this->error,"")) - return 0; - if(strcmp($this->channel,"")) - { - $this->error="a channel was already added"; - return 0; - } - $channel_attributes=array(); - switch($this->specification) - { - case "0.9": - $root="rdf:RDF"; - $attributes=array("xmlns:rdf"=>"http://www.w3.org/1999/02/22-rdf-syntax-ns#","xmlns"=>"http://my.netscape.com/rdf/simple/0.9/"); - $required=array("description"=>0,"link"=>0,"title"=>0); - $optional=array(); - break; - case "0.91": - $root="rss"; - $attributes=array("version"=>$this->specification); - $required=array("description"=>0,"language"=>0,"link"=>0,"title"=>0); - $optional=array("copyright"=>0,"docs"=>0,"lastBuildDate"=>0,"managingEditor"=>0,"pubDate"=>0,"rating"=>0,"webMaster"=>0); - break; - case "1.0": - if(!strcmp($this->about,"")) - { - $this->error="it was not specified the about URL attribute"; - return 0; - } - $root="rdf:RDF"; - $attributes=array("xmlns:rdf"=>"http://www.w3.org/1999/02/22-rdf-syntax-ns#","xmlns"=>"http://purl.org/rss/1.0/"); - Reset($this->rssnamespaces); - $end=(GetType($namespace=Key($this->rssnamespaces))!="string"); - for(;!$end;) - { - if(!strcmp($namespace,"rdf")) - { - $this->error="the rdf namespace is being redeclared"; - return 0; - } - $attributes[("xmlns:".$namespace)]=$this->rssnamespaces[$namespace]; - Next($this->rssnamespaces); - $end=(GetType($namespace=Key($this->rssnamespaces))!="string"); - } - $channel_attributes=array("rdf:about"=>$this->about); - $required=array("description"=>0,"link"=>0,"title"=>0); - $optional=array(); - break; - default: - $this->error="it was not specified a supported RSS specification version"; - return 0; - } - $this->addtag($root,$attributes,"",$path,1); - $this->root=$path; - if(!($this->addtag("channel",$channel_attributes,$this->root,$path,1))) - return 0; - if(!($this->addrssproperties($properties,$path,$required,$optional,"channel"))) - return 0; - $this->channel=$path; - return 1; - } - - Function additem(&$properties) - { - if(strcmp($this->error,"")) - return 0; - if(!strcmp($this->channel,"")) - { - $this->error="the channel was not yet added"; - return 0; - } - if(strcmp($this->textinput,"")) - { - $this->error="items can not be added to the channel after defining the textinput"; - return 0; - } - $attributes=array(); - switch($this->specification) - { - case "0.9": - $parent=$this->root; - break; - case "0.91": - $parent=$this->channel; - break; - case "1.0": - if(IsSet($properties["link"])) - $attributes["rdf:about"]=$properties["link"]; - $parent=$this->root; - break; - default: - $this->error="it was not specified a supported RSS specification version"; - return 0; - } - if(!($this->addtag("item",$attributes,$parent,$path,1))) - return 0; - $required=array("link"=>0,"title"=>0); - $optional=array("description"=>0); - if(!($this->addrssproperties($properties,$path,$required,$optional,"item"))) - return 0; - if(!strcmp($this->specification,"1.0")) - { - if(!strcmp($this->itemsequence,"")) - { - $attributes=array(); - if(!($this->addtag("items",$attributes,$this->channel,$path,1) && $this->addtag("rdf:Seq",$attributes,$path,$path,1))) - return 0; - $this->itemsequence=$path; - } - $attributes=array("rdf:resource"=>$properties["link"]); - if(!($this->addtag("rdf:li",$attributes,$this->itemsequence,$path,0))) - return 0; - } - $this->items++; - return 1; - } - - Function addimage(&$properties) - { - if(strcmp($this->error,"")) - return 0; - if(!strcmp($this->channel,"")) - { - $this->error="the channel was not yet added"; - return 0; - } - if(strcmp($this->image,"")) - { - $this->error="the channel image was already associated"; - return 0; - } - if($this->items!=0) - { - $this->error="the image can only be defined before adding the channel items"; - return 0; - } - $attributes=array(); - switch($this->specification) - { - case "0.9": - $parent=$this->root; - break; - case "0.91": - $parent=$this->channel; - break; - case "1.0": - if(IsSet($properties["url"])) - $attributes["rdf:about"]=$properties["url"]; - $parent=$this->root; - break; - default: - $this->error="it was not specified a supported RSS specification version"; - return 0; - } - if(!($this->addtag("image",$attributes,$parent,$path,1))) - return 0; - $this->image=$path; - $required=array("link"=>0,"title"=>0,"url"=>0); - $optional=array("description"=>0,"width"=>0,"height"=>0); - if(!($this->addrssproperties($properties,$this->image,$required,$optional,"image"))) - return 0; - if(!strcmp($this->specification,"1.0")) - { - $attributes=array("rdf:resource"=>$properties["url"]); - return $this->addtag("image",$attributes,$this->channel,$path,0); - } - return 1; - } - - Function addtextinput(&$properties) - { - if(strcmp($this->error,"")) - return 0; - if(!strcmp($this->channel,"")) - { - $this->error="the channel was not yet added"; - return 0; - } - if(strcmp($this->textinput,"")) - { - $this->error="the channel text input was already associated"; - return 0; - } - if($this->items==0 && !$this->allownoitems) - { - $this->error="it were not specified any items before defining the channel text input"; - return 0; - } - $attributes=array(); - switch($this->specification) - { - case "0.9": - $parent=$this->root; - break; - case "0.91": - $parent=$this->channel; - break; - case "1.0": - if(IsSet($properties["link"])) - $attributes["rdf:about"]=$properties["link"]; - $parent=$this->root; - break; - default: - $this->error="it was not specified a supported RSS specification version"; - return 0; - } - if(!($this->addtag("textinput",$attributes,$parent,$path,1))) - return 0; - $this->textinput=$path; - $required=array("description"=>0,"link"=>0,"name"=>0,"title"=>0); - $optional=array(); - if(!($this->addrssproperties($properties,$this->textinput,$required,$optional,"textinput"))) - return 0; - if(!strcmp($this->specification,"1.0")) - { - $attributes=array("rdf:resource"=>$properties["link"]); - return $this->addtag("textinput",$attributes,$this->channel,$path,0); - } - return 1; - } - - Function writerss(&$output) - { - if(strcmp($this->error,"")) - return 0; - if(!strcmp($this->channel,"")) - { - $this->error="it was not defined the RSS channel"; - return 0; - } - if($this->items==0 && !$this->allownoitems) - { - $this->error="it were not defined any RSS channel items"; - return 0; - } - switch($this->specification) - { - case "0.9": - $this->dtdtype="PUBLIC"; - $this->dtddefinition="-//Netscape Communications//DTD RSS 0.9//EN"; - $this->dtdurl="http://my.netscape.com/publish/formats/rss-0.9.dtd"; - break; - case "0.91": - $this->dtdtype="PUBLIC"; - $this->dtddefinition="-//Netscape Communications//DTD RSS 0.91//EN"; - $this->dtdurl="http://my.netscape.com/publish/formats/rss-0.91.dtd"; - break; - case "1.0": - $this->dtdtype=""; - break; - default: - $this->error="it was not specified a supported RSS specification version"; - return 0; - } - return $this->write($output); - } -}; - -} diff --git a/_test/lib/testmanager.php b/_test/lib/testmanager.php deleted file mode 100644 index 06efd26948..0000000000 --- a/_test/lib/testmanager.php +++ /dev/null @@ -1,579 +0,0 @@ - $value) { - define($key, $value); - } - TestManager::_installSimpleTest(); - - list($version) = file(SIMPLE_TEST.'VERSION'); - $version = trim($version); - if(!version_compare('1.0.1alpha',$version,'<')){ - echo "At least SimpleTest Version 1.0.1alpha is required."; - echo " Yours is $version\n"; - exit; - } - } - - function _installSimpleTest() { - require_once SIMPLE_TEST . 'unit_tester.php'; - require_once SIMPLE_TEST . 'web_tester.php'; - require_once SIMPLE_TEST . 'mock_objects.php'; - require_once 'web.inc.php'; - require_once 'mock_functions.php'; - } - - function runAllTests(&$reporter) { - $manager = new TestManager(); - $test_cases =& $manager->_getTestFileList(); - $test = new GroupTest('All Tests'); - foreach ($test_cases as $test_case) { - $test->addTestFile($test_case); - } - $test->run($reporter); - } - - function runAllPluginTests(&$reporter) { - $manager = new TestManager(); - $test_cases =& $manager->_getTestFileList(TEST_PLUGINS); - $test = new GroupTest('All Plugin Tests'); - foreach ($test_cases as $test_case) { - $test->addTestFile($test_case); - } - $test->run($reporter); - } - - - function runTestCase($testcase_name, $test_case_directory, &$reporter) { - $manager = new TestManager(); - - $testcase_name = preg_replace('/[^a-zA-Z0-9_:]/','',$testcase_name); - $testcase_name = str_replace(':',DIRECTORY_SEPARATOR,$testcase_name); - - $testcase_file = $test_case_directory . DIRECTORY_SEPARATOR . - strtolower($testcase_name) . $manager->_testcase_extension; - - if (! file_exists($testcase_file)) { - trigger_error("Test case {$testcase_file} cannot be found", - E_USER_ERROR); - } - - $test = new GroupTest("Individual test case: " . $testcase_name); - $test->addTestFile($testcase_file); - $test->run($reporter); - } - - function runTestFile($testcase_file, &$reporter) { - $manager = new TestManager(); - - if (! file_exists($testcase_file)) { - trigger_error("Test case {$testcase_file} cannot be found", - E_USER_ERROR); - } - - $test = new GroupTest("Individual test case: " . $testcase_file); - $test->addTestFile($testcase_file); - $test->run($reporter); - } - - function runGroupTest($group_test_name, $group_test_directory, &$reporter) { - $manager = new TestManager(); - $group_test_name = preg_replace('/[^a-zA-Z0-9_:]/','',$group_test_name); - $group_test_name = str_replace(':',DIRECTORY_SEPARATOR,$group_test_name); - $file_path = $group_test_directory . DIRECTORY_SEPARATOR . - strtolower($group_test_name) . $manager->_grouptest_extension; - - if (! file_exists($file_path)) { - trigger_error("Group test {$group_test_name} cannot be found at {$file_path}", - E_USER_ERROR); - } - - require_once $file_path; - $test = new GroupTest($group_test_name . ' group test'); - foreach ($manager->_getGroupTestClassNames($file_path) as $group_test) { - $test->addTestCase(new $group_test()); - } - $test->run($reporter); - } - - function addTestCasesFromDirectory(&$group_test, $directory = '.') { - $manager = new TestManager(); - $test_cases =& $manager->_getTestFileList($directory); - foreach ($test_cases as $test_case) { - $group_test->addTestFile($test_case); - } - } - - function &getTestCaseList($directory = '.') { - $manager = new TestManager(); - return $manager->_getTestCaseList($directory); - } - - function &_getTestCaseList($directory = '.') { - $file_list =& $this->_getTestFileList($directory); - $testcases = array(); - foreach ($file_list as $testcase_file) { - $case = str_replace($this->_testcase_extension, '',$testcase_file); - $case = str_replace(TEST_GROUPS . DIRECTORY_SEPARATOR, '', $case); - $case = str_replace(TEST_PLUGINS . DIRECTORY_SEPARATOR, '', $case); - $case = str_replace(DIRECTORY_SEPARATOR, ':', $case); - $testcases[$testcase_file] = $case; - } - return $testcases; - } - - function &_getTestFileList($directory = '.') { - return $this->_getRecursiveFileList($directory, - array(&$this, '_isTestCaseFile')); - } - - function &getPluginTestCaseList($directory = '.') { - $manager = new TestManager(); - return $manager->_getTestCaseList($directory); - } - - function &getPluginGroupTestList($directory = '.') { - $manager = new TestManager(); - return $manager->_getTestGroupList($directory); - } - - function &getGroupTestList($directory = '.') { - $manager = new TestManager(); - return $manager->_getTestGroupList($directory); - } - - function &_getTestGroupFileList($directory = '.') { - return $this->_getRecursiveFileList($directory, - array(&$this, '_isTestGroupFile')); - } - - function &_getTestGroupList($directory = '.') { - $file_list =& $this->_getTestGroupFileList($directory); - $grouptests = array(); - foreach ($file_list as $grouptest_file) { - $group = str_replace($this->_grouptest_extension, '',$grouptest_file); - $group = str_replace(TEST_GROUPS . DIRECTORY_SEPARATOR, '', $group); - $group = str_replace(TEST_PLUGINS . DIRECTORY_SEPARATOR, '', $group); - $group = str_replace(DIRECTORY_SEPARATOR, ':', $group); - $grouptests[$grouptest_file] = $group; - } - sort($grouptests); - return $grouptests; - } - - function &_getGroupTestClassNames($grouptest_file) { - $file = implode("\n", file($grouptest_file)); - preg_match("~lass\s+?(.*)\s+?extends .*?GroupTest~", $file, $matches); - if (! empty($matches)) { - unset($matches[0]); - return $matches; - } else { - return array(); - } - } - - function &_getRecursiveFileList($directory = '.', $file_test_function) { - $dh = opendir($directory); - if (! is_resource($dh)) { - trigger_error("Couldn't open {$directory}", E_USER_ERROR); - } - - $file_list = array(); - while ($file = readdir($dh)) { - $file_path = $directory . DIRECTORY_SEPARATOR . $file; - - if (0 === strpos($file, '.')) continue; - - if (is_dir($file_path)) { - $file_list = - array_merge($file_list, - $this->_getRecursiveFileList($file_path, - $file_test_function)); - } - if ($file_test_function[0]->$file_test_function[1]($file)) { - $file_list[] = $file_path; - } - } - closedir($dh); - return $file_list; - } - - function _isTestCaseFile($file) { - return $this->_hasExpectedExtension($file, $this->_testcase_extension); - } - - function _isTestGroupFile($file) { - return $this->_hasExpectedExtension($file, $this->_grouptest_extension); - } - - function _hasExpectedExtension($file, $extension) { - return $extension == - strtolower(substr($file, (0 - strlen($extension)))); - } -} - -/** -* @package WACT_TESTS -*/ -class CLITestManager extends TestManager { - function &getGroupTestList($directory = '.') { - $manager = new CLITestManager(); - $group_tests =& $manager->_getTestGroupList($directory); - - $buffer = "Available grouptests:\n"; - foreach ($group_tests as $group_test) { - $buffer .= " " . $group_test . "\n"; - } - return $buffer . "\n"; - } - - function &getTestCaseList($directory = '.') { - $manager = new CLITestManager(); - $test_cases =& $manager->_getTestCaseList($directory); - - $buffer = "Available test cases:\n"; - foreach ($test_cases as $test_case) { - $buffer .= " " . $test_case . "\n"; - } - return $buffer . "\n"; - } - - function &getPluginTestCaseList($directory = '.') { - $manager = new CLITestManager(); - $test_cases =& $manager->_getTestCaseList($directory); - - $buffer = "Available test cases:\n"; - foreach ($test_cases as $test_case) { - $buffer .= " " . $test_case . "\n"; - } - return $buffer . "\n"; - } - - function &getPluginGroupTestList($directory = '.') { - $manager = new CLITestManager(); - $test_cases =& $manager->_getTestGroupList($directory); - - $buffer = "Available test cases:\n"; - foreach ($test_cases as $test_case) { - $buffer .= " " . $test_case . "\n"; - } - return $buffer . "\n"; - } - -} - -class HTMLTestManager extends TestManager { - var $_url; - - function HTMLTestManager() { - $this->_url = $_SERVER['PHP_SELF']; - } - - function getBaseURL() { - return $this->_url; - } - - function &getGroupTestList($directory = '.') { - $manager = new HTMLTestManager(); - $group_tests =& $manager->_getTestGroupList($directory); - if (1 > count($group_tests)) { - return "

No test groups set up!

"; - } - $buffer = "

Available test groups:

\n\n"; - return $buffer; - } - - function &getTestCaseList($directory = '.') { - $manager = new HTMLTestManager(); - $testcases =& $manager->_getTestCaseList($directory); - - if (1 > count($testcases)) { - return "

No test cases set up!

"; - } - $buffer = "

Available test cases:

\n
    "; - foreach ($testcases as $testcase) { - $buffer .= "
  • " . - $testcase . "
  • \n"; - } - - $buffer .= "
\n"; - return $buffer; - } - - function &getPluginTestCaseList($directory = '.') { - $manager = new HTMLTestManager(); - $testcases =& $manager->_getTestCaseList($directory); - - if (1 > count($testcases)) { - return "

No plugin test cases set up!

"; - } - $buffer = "

Available plugin test cases:

\n
    "; - foreach ($testcases as $testcase) { - $buffer .= "
  • " . - $testcase . "
  • \n"; - } - - $buffer .= "
\n"; - return $buffer; - } - - function &getPluginGroupTestList($directory = '.') { - $manager = new HTMLTestManager(); - $group_tests =& $manager->_getTestGroupList($directory); - if (1 > count($group_tests)) { - return "

No plugin test groups set up!

"; - } - $buffer = "

Available plugin groups:

\n\n"; - return $buffer; - } - -} - -/** -* @package WACT_TESTS -*/ -class XMLTestManager extends HTMLTestManager { - - function XMLTestManager() { - parent::HTMLTestManager(); - } - - function &getGroupTestList($directory = '.') { - - $manager = new XMLTestManager(); - $group_tests =& $manager->_getTestGroupList($directory); - - $rss = & $manager->_getRssWriter(); - - if (1 > count($group_tests)) { - $rss->writeRss($output); - return $output; - } - - $properties["title"]="All Tests"; - $properties["description"]="All Tests"; - $properties["link"]='http://'.$_SERVER['SERVER_NAME']. - $manager->getBaseURL()."?group=all&output=xml"; - - $rss->additem($properties); - - foreach ($group_tests as $group_test) { - $properties["title"]=$group_test; - $properties["description"]=$group_test; - $properties["link"]='http://'.$_SERVER['SERVER_NAME']. - $manager->getBaseURL(). - "?group={$group_test}&output=xml"; - - $rss->additem($properties); - } - if ( !$rss->writeRss($output) ) { - die ( $rss->error ); - } - return $output; - - } - - function &getTestCaseList($directory = '.') { - - $manager = new XMLTestManager(); - $testcases =& $manager->_getTestCaseList($directory); - - $rss = & $manager->_getRssWriter(); - - if (1 > count($testcases)) { - $rss->writeRss($output); - return $output; - } - - foreach ($testcases as $testfile => $testcase) { - $properties["title"]=$testcase; - $properties["description"]=$testcase; - $properties["link"]='http://'.$_SERVER['SERVER_NAME']. - $manager->getBaseURL()."?case=" . - urlencode($testcase) . "&output=xml"; - - // Comment this out for performance? - $properties["dc:date"]=gmdate("Y-m-d\TH:i:sO",filemtime($testfile)); - - $rss->additem($properties); - } - - $rss->writeRss($output); - return $output; - } - - function &_getRssWriter() { - - $url = 'http://'.$_SERVER['SERVER_NAME'].str_replace('index.php','',$_SERVER['PHP_SELF']); - - require_once TEST_ROOT . '/lib/xml_writer_class.php'; - require_once TEST_ROOT . '/lib/rss_writer_class.php'; - - $rss_writer_object= new rss_writer_class(); - $rss_writer_object->specification="1.0"; - $rss_writer_object->about=$url."index.php?output=xml"; - $rss_writer_object->stylesheet=$url."rss2html.xsl"; - $rss_writer_object->rssnamespaces["dc"]="http://purl.org/dc/elements/1.1/"; - - // Channel Properties - $properties=array(); - $properties["title"]="Dokuwiki Unit Test Cases"; - $properties["description"]="Dokuwiki Unit Test Cases"; - $properties["link"]="http://wiki.splitbrain.org/"; - $properties["dc:date"]=gmdate("Y-m-d\TH:i:sO"); - $rss_writer_object->addchannel($properties); - - // Logo like this (if we had one) - /* - $properties=array(); - - $properties["link"]="http://www.phpclasses.org/"; - $properties["title"]="PHP Classes repository logo"; - $properties["description"]="Repository of components and other resources for PHP developers"; - $rss_writer_object->addimage($properties); - */ - - return $rss_writer_object; - } - -} - -/** -* @package WACT_TESTS -*/ -class RemoteTestManager extends TestManager { - - function RemoteTestManager() { - RemoteTestManager::_installSimpleTest(); - } - - function _installSimpleTest() { - require_once SIMPLE_TEST . 'remote.php'; - } - - function runAllTests(&$reporter, $url = FALSE) { - $groups = RemoteTestManager::getGroupTestList($url); - $T = new RemoteTestCase($groups['All Tests']); - $T->run($reporter); - } - - function runTestUrl($case_url,& $reporter, $url = FALSE) { - RemoteTestManager::_installSimpleTest(); - $T = new RemoteTestCase($case_url); - $T->run($reporter); - } - - function runTestCase($case_id,& $reporter, $url = FALSE) { - $cases = RemoteTestManager::getTestCaseList($url); - if ( !array_key_exists($case_id, $cases) ) { - trigger_error("Unknown test id $case_id\n",E_USER_ERROR); - } - $T = new RemoteTestCase($cases[$case_id]); - $T->run($reporter); - } - - function runGroupTest($group_name, &$reporter, $url = FALSE) { - $groups = RemoteTestManager::getGroupTestList($url); - if ( !array_key_exists($group_name, $groups) ) { - trigger_error("Unknown group $group_name\n",E_USER_ERROR); - } - $T = new RemoteTestCase($groups[$group_name]); - $T->run($reporter); - } - - function & getGroupTestList($url = FALSE) { - - if ( !$url ) { - $url = REMOTE_TEST_URL; - } - - $url .= '?output=xml'; - - $manager = new RemoteTestManager(); - $rss = & $manager->_getRssReader($url); - - $groupList = array(); - - foreach ($rss->getItems() as $item) { - $groupList[$item['title']] = $item['link']; - } - - return $groupList; - } - - function &getTestCaseList($url = FALSE) { - if ( !$url ) { - $url = REMOTE_TEST_URL; - } - - $url .= '?show=cases&output=xml'; - $manager = new RemoteTestManager(); - $rss = & $manager->_getRssReader($url); - - $caseList = array(); - - foreach ($rss->getItems() as $item) { - $caseList[$item['title']] = $item['link']; - } - - return $caseList; - } - - function &_getRssReader($url) { - require_once "XML/RSS.php"; - - $rss_reader = new XML_RSS($url); - - $status = $rss_reader->parse(); - - if (PEAR::isError($status) ) { - trigger_error($status->getMessage(),E_USER_WARNING); - } - - return $rss_reader; - } - -} diff --git a/_test/lib/unittest.php b/_test/lib/unittest.php deleted file mode 100644 index 220aa6c1bf..0000000000 --- a/_test/lib/unittest.php +++ /dev/null @@ -1,5 +0,0 @@ -assertResponse(array(200)); - $this->assertNoUnwantedPattern('/Warning:/i'); - $this->assertNoUnwantedPattern('/Error:/i'); - $this->assertNoUnwantedPattern('/Fatal error/i'); - } - - function assertWantedLiteral($str) { - $this->assertWantedPattern('/' . preg_quote($str, '/'). '/'); - } - - function assertNoUnWantedLiteral($str) { - $this->assertNoUnWantedPattern('/' . preg_quote($str, '/'). '/'); - } - - function &_fileToPattern($file) { - $file_as_array = file($file); - $pattern = '#^'; - foreach ($file_as_array as $line) { - /* strip trailing newline */ - if ($line[strlen($line) - 1] == "\n") { - $line = substr($line, 0, strlen($line) - 1); - } - $line = preg_quote($line, '#'); - - /* replace paths with wildcard */ - $line = preg_replace("#'/[^']*#", "'.*", $line); - - $pattern .= $line . '\n'; - } - /* strip final newline */ - $pattern = substr($pattern, 0, strlen($pattern) - 2); - $pattern .= '$#i'; - return $pattern; - } - -} diff --git a/_test/lib/xml_writer_class.php b/_test/lib/xml_writer_class.php deleted file mode 100644 index 97fb1bee03..0000000000 --- a/_test/lib/xml_writer_class.php +++ /dev/null @@ -1,292 +0,0 @@ -inputencoding,$this->outputencoding)) - $encodeddata=$this->escapedata($data); - else - { - switch(strtolower($this->outputencoding)) - { - case "utf-8": - if(!strcmp(strtolower($this->inputencoding),"iso-8859-1")) - { - $encoded_data=utf8_encode($this->escapedata($data)); - $encodeddata=$encoded_data; - } - else - { - $this->error=("can not encode iso-8859-1 data in ".$this->outputencoding); - return 0; - } - break; - case "iso-8859-1": - if(!strcmp(strtolower($this->inputencoding),"utf-8")) - { - $decoded=utf8_decode($data); - $encodeddata=$this->escapedata($decoded); - } - else - { - $this->error=("can not encode utf-8 data in ".$this->outputencoding); - return 0; - } - break; - default: - $this->error=("can not encode data in ".$this->inputencoding); - return 0; - } - } - return 1; - } - - Function writetag(&$output,$path,$indent) - { - $tag=$this->structure[$path]["Tag"]; - $output.=("<".$tag); - $attributecount=count($this->structure[$path]["Attributes"]); - if($attributecount>0) - { - $attributes=$this->structure[$path]["Attributes"]; - Reset($attributes); - $end=(GetType($key=Key($attributes))!="string"); - for(;!$end;) - { - $output.=(" ".$key."=\"".$attributes[$key]."\""); - Next($attributes); - $end=(GetType($key=Key($attributes))!="string"); - } - } - $elements=$this->structure[$path]["Elements"]; - if($elements>0) - { - $output.=">"; - $doindent=$this->structure[$path]["Indent"]; - $elementindent=(($doindent) ? $this->linebreak.$indent.$this->indenttext : ""); - $element=0; - for(;$element<$elements;) - { - $elementpath=($path.",".strval($element)); - $output.=$elementindent; - if(IsSet($this->nodes[$elementpath])) - { - if(!($this->writetag($output,$elementpath,$indent.$this->indenttext))) - return 0; - } - else - $output.=$this->structure[$elementpath]; - $element++; - } - $output.=((($doindent) ? $this->linebreak.$indent : "").""); - } - else - $output.="/>"; - return 1; - } - - /* - * Public functions - * - */ - Function write(&$output) - { - if(strcmp($this->error,"")) - return 0; - if(!(IsSet($this->structure["0"]))) - { - $this->error="XML document structure is empty"; - return 0; - } - $output=("outputencoding."\"?>".$this->linebreak); - if(strcmp($this->dtdtype,"")) - { - $output.=("structure["0"]["Tag"]." "); - switch($this->dtdtype) - { - case "INTERNAL": - if(!strcmp($this->dtddefinition,"")) - { - $this->error="it was not specified a valid internal DTD definition"; - return 0; - } - $output.=("[".$this->linebreak.$this->dtddefinition.$this->linebreak."]"); - break; - case "SYSTEM": - if(!strcmp($this->dtdurl,"")) - { - $this->error="it was not specified a valid system DTD url"; - return 0; - } - $output.="SYSTEM"; - if(strcmp($this->dtddefinition,"")) - $output.=(" \"".$this->dtddefinition."\""); - $output.=(" \"".$this->dtdurl."\""); - break; - case "PUBLIC": - if(!strcmp($this->dtddefinition,"")) - { - $this->error="it was not specified a valid public DTD definition"; - return 0; - } - $output.=("PUBLIC \"".$this->dtddefinition."\""); - if(strcmp($this->dtdurl,"")) - $output.=(" \"".$this->dtdurl."\""); - break; - default: - $this->error="it was not specified a valid DTD type"; - return 0; - } - $output.=(">".$this->linebreak); - } - if(strcmp($this->stylesheet,"")) - { - if(!strcmp($this->stylesheettype,"")) - { - $this->error="it was not specified a valid stylesheet type"; - return 0; - } - $output.=("stylesheettype."\" href=\"".$this->stylesheet."\"?>".$this->linebreak); - } - if(strcmp($this->generatedcomment,"")) - $output.=("".$this->linebreak); - return $this->writetag($output,"0",""); - } - - Function addtag($tag,&$attributes,$parent,&$path,$indent) - { - if(strcmp($this->error,"")) - return 0; - $path=((!strcmp($parent,"")) ? "0" : ($parent.",".strval($this->structure[$parent]["Elements"]))); - if(IsSet($this->structure[$path])) - { - $this->error=("tag with path ".$path." is already defined"); - return 0; - } - $encodedattributes=array(); - Reset($attributes); - $end=(GetType($attribute_name=Key($attributes))!="string"); - for(;!$end;) - { - $encodedattributes[$attribute_name]=""; - if(!($this->encodedata($attributes[$attribute_name],$encoded_data))) - return 0; - $encodedattributes[$attribute_name]=$encoded_data; - Next($attributes); - $end=(GetType($attribute_name=Key($attributes))!="string"); - } - $this->structure[$path]=array( - "Tag"=>$tag, - "Attributes"=>$encodedattributes, - "Elements"=>0, - "Indent"=>$indent - ); - $this->nodes[$path]=1; - if(strcmp($parent,"")) - $this->structure[$parent]["Elements"]=($this->structure[$parent]["Elements"]+1); - return 1; - } - - Function adddata($data,$parent,&$path) - { - if(strcmp($this->error,"")) - return 0; - if(!(IsSet($this->structure[$parent]))) - { - $this->error=("the parent tag path".$path."is not defined"); - return 0; - } - if(!strcmp($data,"")) - return 1; - $path=($parent.",".strval($this->structure[$parent]["Elements"])); - if(!($this->encodedata($data,$encoded_data))) - return 0; - $this->structure[$path]=$encoded_data; - $this->structure[$parent]["Elements"]=($this->structure[$parent]["Elements"]+1); - return 1; - } - - Function adddatatag($tag,&$attributes,$data,$parent,&$path) - { - return $this->addtag($tag,$attributes,$parent,$path,0) && $this->adddata($data,$path,$datapath); - } -}; - -} diff --git a/_test/phpunit.xml b/_test/phpunit.xml new file mode 100644 index 0000000000..13676f207c --- /dev/null +++ b/_test/phpunit.xml @@ -0,0 +1,26 @@ + + + + + + tests/ + + + ../lib/plugins/*/_test + + + + + + ../ + + ../_cs/ + ../_test/ + ../lib/plugins/*/_test/ + + + + + diff --git a/_test/remotetests.php b/_test/remotetests.php deleted file mode 100755 index 3dd290712c..0000000000 --- a/_test/remotetests.php +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/php -q -'; -$opt_caselist = FALSE; -$opt_grouplist = FALSE; -$opt_caseid = FALSE; -$opt_caseurl = FALSE; -$opt_groupfile = FALSE; -$opt_url = FALSE; - -include_once(DOKU_INC.'inc/cliopts.php'); -$short_opts = "c:f:g:hils:p:u:"; -$long_opts = array("case=","caselist","help", "caseurl=", "group=", "grouplist", "separator=", "path=","url="); -$OPTS = Doku_Cli_Opts::getOptions(__FILE__,$short_opts,$long_opts); -if ( $OPTS->isError() ) { - fwrite( STDERR, $OPTS->getMessage() . "\n"); - usage($available_grouptests); - exit(1); -} - -foreach ($OPTS->options as $key => $val) { - switch ($key) { - case 'c': - case 'case': - $opt_caseid = $val; - break; - case 'h': - case 'help': - usage(); - break; - case 'f': - case 'caseurl': - $opt_caseurl = $val; - break; - case 'g': - case 'group': - $opt_groupfile = $val; - break; - case 'i': - case 'caselist': - $opt_caselist = TRUE; - break; - case 'l': - case 'grouplist': - $opt_grouplist = TRUE; - break; - case 's': - case 'separator': - $opt_separator = $val; - break; - case 'p': - case 'path': - if (file_exists($val)) { - define('SIMPLE_TEST', $val); - } - break; - case 'u': - case '--url': - $opt_url = $val; - break; - } -} - -if ( ! $opt_url ) { - if ( !defined('REMOTE_TEST_URL') ) { - fwrite( STDERR, "No test URL defined. Either modify tests.ini or use -u option\n"); - exit(1); - } else { - $opt_url = REMOTE_TEST_URL; - } -} - - -if (!@include_once SIMPLE_TEST . 'reporter.php') { - if ( defined(SIMPLE_TEST) ) { - fwrite( STDERR, "Where's Simple Test ?!? Not at ".SIMPLE_TEST." \n"); - } else { - fwrite( STDERR, "Where's Simple Test ?!? SIMPLE_TEST not even defined!\n"); - } - exit(1); -} - -require_once 'lib/cli_reporter.php'; - -/* list grouptests */ -if ($opt_grouplist) { - $groups = RemoteTestManager::getGroupTestList($opt_url); - fwrite( STDOUT, "Available grouptests:\n"); - foreach ( array_keys($groups) as $group ) { - fwrite( STDOUT, $group."\n"); - } -} - -/* list test cases */ -if ($opt_caselist) { - $cases = RemoteTestManager::getTestCaseList($opt_url); - fwrite( STDOUT, "Available tests tests:\n"); - foreach ( array_keys($cases) as $case ) { - fwrite( STDOUT, $case."\n"); - } -} - -/* exit if we've displayed a list */ -if ( $opt_grouplist || $opt_caselist ) { - exit(0); -} - -/* run a test case given it's URL */ -if ($opt_caseurl) { - RemoteTestManager::runTestUrl($opt_caseurl, new CLIReporter($opt_separator), $opt_url); - exit(0); -} - -/* run a test case by id*/ -if ($opt_caseid) { - RemoteTestManager::runTestCase($opt_caseid, new CLIReporter($opt_separator), $opt_url); - exit(0); -} - -/* run a grouptest */ -if ($opt_groupfile) { - RemoteTestManager::runGroupTest( - $opt_groupfile, new CLIReporter($opt_separator), $opt_url - ); - exit(0); -} -/* run all tests */ -RemoteTestManager::runAllTests(new CLIReporter($opt_separator), $opt_url); -exit(0); -?> \ No newline at end of file diff --git a/_test/rss2html.xsl b/_test/rss2html.xsl deleted file mode 100644 index ae56d2c203..0000000000 --- a/_test/rss2html.xsl +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - - - - - - - - - - - - -<xsl:for-each select="rdf:RDF/rss:channel"> -<xsl:value-of select="rss:description"/> -</xsl:for-each> - - - - - -
- - - - - - 0 - - -
-
- -
-
- - -
- - - - ( - - ) - -
-
- -
    -
    - -
  • - - - - - ( - -) -
  • -
    -
    -
    -
- - -
- - - POST -
- - - text - - - - - submit - -
-
-
- - - -
- -
\ No newline at end of file diff --git a/_test/runtests.php b/_test/runtests.php deleted file mode 100755 index 8b93efec3d..0000000000 --- a/_test/runtests.php +++ /dev/null @@ -1,187 +0,0 @@ -#!/usr/bin/php -q -'; -$opt_caselist = FALSE; -$opt_grouplist = FALSE; -$opt_plugincaselist = FALSE; -$opt_plugingrouplist = FALSE; -$opt_caseid = FALSE; -$top_plugincaseid = FALSE; -$opt_casefile = FALSE; -$opt_groupfile = FALSE; -$opt_plugingroupfile = FALSE; - -include_once(DOKU_INC.'inc/cliopts.php'); - -$short_opts = "c:f:g:hils:p:"; -$long_opts = array("case=","pcase=","caselist","help", "file=", "group=", "pgroup=", "grouplist", "plugincaselist", "plugingrouplist", "separator=", "path="); -$OPTS = Doku_Cli_Opts::getOptions(__FILE__,$short_opts,$long_opts); -if ( $OPTS->isError() ) { - fwrite( STDERR, $OPTS->getMessage() . "\n"); - usage($available_grouptests); - exit(1); -} - -foreach ($OPTS->options as $key => $val) { - switch ($key) { - case 'c': - case 'case': - $opt_caseid = $val; - break; - case 'pcase': - $opt_plugincaseid = $val; - break; - case 'h': - case 'help': - usage(); - break; - case 'f': - case 'file': - $opt_casefile = $val; - break; - case 'g': - case 'group': - $opt_groupfile = $val; - break; - case 'pgroup': - $opt_plugingroupfile = $val; - break; - case 'i': - case 'caselist': - $opt_caselist = TRUE; - break; - case 'l': - case 'grouplist': - $opt_grouplist = TRUE; - break; - case 'plugincaselist': - $opt_plugincaselist = TRUE; - break; - case 'plugingrouplist': - $opt_plugingrouplist = TRUE; - break; - case 's': - case 'separator': - $opt_separator = $val; - break; - case 'p': - case 'path': - if (file_exists($val)) { - define('SIMPLE_TEST', $val); - } - break; - } -} - -if (!@include_once SIMPLE_TEST . 'reporter.php') { - die("Where's Simple Test ?!? Not at ".SIMPLE_TEST); -} - -require_once 'lib/cli_reporter.php'; - -/* list grouptests */ -if ($opt_grouplist) { - echo CLITestManager::getGroupTestList(TEST_GROUPS); -} - -/* list test cases */ -if ($opt_caselist) { - echo CLITestManager::getTestCaseList(TEST_CASES); -} - -/* list plugin test cases */ -if ($opt_plugincaselist) { - echo CLITestManager::getPluginTestCaseList(TEST_PLUGINS); -} - -/* list plugin group tests */ -if($opt_plugingrouplist) { - echo CLITestManager::getPluginGroupTestList(TEST_PLUGINS); -} - -/* exit if we've displayed a list */ -if ( $opt_grouplist || $opt_caselist || $opt_plugincaselist || $opt_plugingrouplist ) { - exit(0); -} - -/* run a test case */ -if ($opt_casefile) { - TestManager::runTestFile($opt_casefile, new CLIReporter($opt_separator)); - exit(0); -} - -/* run a test case by id */ -if ($opt_caseid) { - TestManager::runTestCase($opt_caseid, TEST_CASES, new CLIReporter($opt_separator)); - exit(0); -} - -/* run a plugin test by case id */ -if ($opt_plugincaseid) { - TestManager::runTestCase($opt_plugincaseid, TEST_PLUGINS, new CLIReporter($opt_separator)); - exit(0); -} - -/* run a grouptest */ -if ($opt_groupfile) { - TestManager::runGroupTest($opt_groupfile, TEST_GROUPS, - new CLIReporter($opt_separator)); - exit(0); -} - -/* run a plugin grouptest */ -if ($opt_plugingroupfile) { - TestManager::runGroupTest($opt_plugingroupfile, TEST_PLUGINS, - new CLIReporter($opt_separator)); - exit(0); -} - -/* run a plugin group test */ -//FIXME -/* run all tests */ -TestManager::runAllTests(new CLIReporter($opt_separator)); -exit(0); -?> diff --git a/_test/tests.css b/_test/tests.css deleted file mode 100644 index c20d8bb4f9..0000000000 --- a/_test/tests.css +++ /dev/null @@ -1,27 +0,0 @@ -body { - background-color:#eee; - color:#000; - font:100%/1.2em Georgia,Verdana,Arial,Helvetica,sans-serif; - margin-left:20ex; - max-width:120ex; - } - -#sf { float:right; } - -h1 { - background-image:url(rephlux.png); - background-repeat:no-repeat; - margin-top:0; - padding:20px 0 0 90px; - color:#600; - font-size:3em; - line-height: 1em; - background-color:inherit; - border-bottom:9px double #333; - } - -pre { - font-size:120%; - line-height:1.2em; - color:#006; - } \ No newline at end of file diff --git a/_test/tests.ini b/_test/tests.ini deleted file mode 100644 index cb16d4f1b4..0000000000 --- a/_test/tests.ini +++ /dev/null @@ -1,12 +0,0 @@ -TEST_ENABLED = 0 - -; For performing "web tests" - PHP scripts acting as web browser -WEB_TEST_URL = http://localhost/dokuwiki - -; See http://www.sitepoint.com/blogs/2004/06/15/simple-test-remote-testing/ -REMOTE_TEST_URL = http://localhost/dokuwiki/test/index.php - -;PROXY = http://proxyuser:proxypwd@proxy.yourdomain.com:8080 - -; Path to Simple Test -SIMPLE_TEST = ../../simpletest/ diff --git a/_test/tests/inc/auth_aclcheck.test.php b/_test/tests/inc/auth_aclcheck.test.php new file mode 100644 index 0000000000..837926904b --- /dev/null +++ b/_test/tests/inc/auth_aclcheck.test.php @@ -0,0 +1,244 @@ +oldConf = $conf; + $this->oldAuthAcl = $AUTH_ACL; + $auth = new auth_basic(); + } + + function teardown() { + global $conf; + global $AUTH_ACL; + $conf = $this->oldConf; + $AUTH_ACL = $this->oldAuthAcl; + + } + + function test_restricted(){ + global $conf; + global $AUTH_ACL; + $conf['superuser'] = 'john'; + $conf['useacl'] = 1; + + $AUTH_ACL = array( + '* @ALL 0', + '* @user 8', + ); + + // anonymous user + $this->assertEquals(auth_aclcheck('page', '',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); + + // user with no matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); + + // user with matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_UPLOAD); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); + + // super user + $this->assertEquals(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); + } + + function test_restricted_ropage(){ + global $conf; + global $AUTH_ACL; + $conf['superuser'] = 'john'; + $conf['useacl'] = 1; + + $AUTH_ACL = array( + '* @ALL 0', + '* @user 8', + 'namespace:page @user 1', + ); + + // anonymous user + $this->assertEquals(auth_aclcheck('page', '',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); + + // user with no matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); + + // user with matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_READ); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); + + // super user + $this->assertEquals(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); + } + + function test_aclexample(){ + global $conf; + global $AUTH_ACL; + $conf['superuser'] = 'john'; + $conf['useacl'] = 1; + + $AUTH_ACL = array( + '* @ALL 4', + '* bigboss 16', + 'start @ALL 1', + 'marketing:* @marketing 8', + 'devel:* @ALL 0', + 'devel:* @devel 8', + 'devel:* bigboss 16', + 'devel:funstuff bigboss 0', + 'devel:* @marketing 1', + 'devel:marketing @marketing 2', + ); + + + $this->assertEquals(auth_aclcheck('page', '' ,array()) , AUTH_CREATE); + $this->assertEquals(auth_aclcheck('page', 'bigboss' ,array('foo')) , AUTH_DELETE); + $this->assertEquals(auth_aclcheck('page', 'jill' ,array('marketing')) , AUTH_CREATE); + $this->assertEquals(auth_aclcheck('page', 'jane' ,array('devel')) , AUTH_CREATE); + + $this->assertEquals(auth_aclcheck('start', '' ,array()) , AUTH_READ); + $this->assertEquals(auth_aclcheck('start', 'bigboss' ,array('foo')) , AUTH_READ); + $this->assertEquals(auth_aclcheck('start', 'jill' ,array('marketing')) , AUTH_READ); + $this->assertEquals(auth_aclcheck('start', 'jane' ,array('devel')) , AUTH_READ); + + $this->assertEquals(auth_aclcheck('marketing:page', '' ,array()) , AUTH_CREATE); + $this->assertEquals(auth_aclcheck('marketing:page', 'bigboss' ,array('foo')) , AUTH_DELETE); + $this->assertEquals(auth_aclcheck('marketing:page', 'jill' ,array('marketing')) , AUTH_UPLOAD); + $this->assertEquals(auth_aclcheck('marketing:page', 'jane' ,array('devel')) , AUTH_CREATE); + + + $this->assertEquals(auth_aclcheck('devel:page', '' ,array()) , AUTH_NONE); + $this->assertEquals(auth_aclcheck('devel:page', 'bigboss' ,array('foo')) , AUTH_DELETE); + $this->assertEquals(auth_aclcheck('devel:page', 'jill' ,array('marketing')) , AUTH_READ); + $this->assertEquals(auth_aclcheck('devel:page', 'jane' ,array('devel')) , AUTH_UPLOAD); + + $this->assertEquals(auth_aclcheck('devel:funstuff', '' ,array()) , AUTH_NONE); + $this->assertEquals(auth_aclcheck('devel:funstuff', 'bigboss' ,array('foo')) , AUTH_NONE); + $this->assertEquals(auth_aclcheck('devel:funstuff', 'jill' ,array('marketing')) , AUTH_READ); + $this->assertEquals(auth_aclcheck('devel:funstuff', 'jane' ,array('devel')) , AUTH_UPLOAD); + + $this->assertEquals(auth_aclcheck('devel:marketing', '' ,array()) , AUTH_NONE); + $this->assertEquals(auth_aclcheck('devel:marketing', 'bigboss' ,array('foo')) , AUTH_DELETE); + $this->assertEquals(auth_aclcheck('devel:marketing', 'jill' ,array('marketing')) , AUTH_EDIT); + $this->assertEquals(auth_aclcheck('devel:marketing', 'jane' ,array('devel')) , AUTH_UPLOAD); + + } + + function test_multiadmin_restricted(){ + global $conf; + global $AUTH_ACL; + $conf['superuser'] = 'john,@admin,doe,@roots'; + $conf['useacl'] = 1; + + $AUTH_ACL = array( + '* @ALL 0', + '* @user 8', + ); + + // anonymous user + $this->assertEquals(auth_aclcheck('page', '',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); + + // user with no matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); + + // user with matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_UPLOAD); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); + + // super user john + $this->assertEquals(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); + + // super user doe + $this->assertEquals(auth_aclcheck('page', 'doe',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','doe',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'doe',array('foo')), AUTH_ADMIN); + + // user with matching admin group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','admin')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','admin')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','admin')), AUTH_ADMIN); + + // user with matching another admin group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','roots')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','roots')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','roots')), AUTH_ADMIN); + } + + function test_multiadmin_restricted_ropage(){ + global $conf; + global $AUTH_ACL; + $conf['superuser'] = 'john,@admin,doe,@roots'; + $conf['useacl'] = 1; + + $AUTH_ACL = array( + '* @ALL 0', + '* @user 8', + 'namespace:page @user 1', + ); + + // anonymous user + $this->assertEquals(auth_aclcheck('page', '',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','',array()), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', '',array()), AUTH_NONE); + + // user with no matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo')), AUTH_NONE); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo')), AUTH_NONE); + + // user with matching group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','user')), AUTH_UPLOAD); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','user')), AUTH_READ); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','user')), AUTH_UPLOAD); + + // super user john + $this->assertEquals(auth_aclcheck('page', 'john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','john',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'john',array('foo')), AUTH_ADMIN); + + // super user doe + $this->assertEquals(auth_aclcheck('page', 'doe',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','doe',array('foo')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'doe',array('foo')), AUTH_ADMIN); + + // user with matching admin group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','admin')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','admin')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','admin')), AUTH_ADMIN); + + // user with matching another admin group + $this->assertEquals(auth_aclcheck('page', 'jill',array('foo','roots')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:page','jill',array('foo','roots')), AUTH_ADMIN); + $this->assertEquals(auth_aclcheck('namespace:*', 'jill',array('foo','roots')), AUTH_ADMIN); + } + +} + +//Setup VIM: ex: et ts=4 : diff --git a/_test/tests/inc/auth_admincheck.test.php b/_test/tests/inc/auth_admincheck.test.php new file mode 100644 index 0000000000..c108c60c06 --- /dev/null +++ b/_test/tests/inc/auth_admincheck.test.php @@ -0,0 +1,130 @@ +oldauth = $auth; + } + + function setSensitive() { + global $auth; + $auth = new auth_basic(); + } + + function setInSensitive() { + global $auth; + $auth = new auth_admin_test_AuthInSensitive(); + } + + function teardown() { + global $auth; + global $conf; + global $AUTH_ACL; + unset($conf); + unset($AUTH_ACL); + $auth = $this->oldauth; + } + + function test_ismanager_insensitive(){ + $this->setInSensitive(); + global $conf; + $conf['superuser'] = 'john,@admin,@Mötly Görls, Dörte'; + $conf['manager'] = 'john,@managers,doe, @Mötly Böys, Dänny'; + + // anonymous user + $this->assertEquals(auth_ismanager('jill', null,false), false); + + // admin or manager users + $this->assertEquals(auth_ismanager('john', null,false), true); + $this->assertEquals(auth_ismanager('doe', null,false), true); + + $this->assertEquals(auth_ismanager('dörte', null,false), true); + $this->assertEquals(auth_ismanager('dänny', null,false), true); + + // admin or manager groups + $this->assertEquals(auth_ismanager('jill', array('admin'),false), true); + $this->assertEquals(auth_ismanager('jill', array('managers'),false), true); + + $this->assertEquals(auth_ismanager('jill', array('mötly görls'),false), true); + $this->assertEquals(auth_ismanager('jill', array('mötly böys'),false), true); + } + + function test_isadmin_insensitive(){ + $this->setInSensitive(); + global $conf; + $conf['superuser'] = 'john,@admin,doe,@roots'; + + // anonymous user + $this->assertEquals(auth_ismanager('jill', null,true), false); + + // admin user + $this->assertEquals(auth_ismanager('john', null,true), true); + $this->assertEquals(auth_ismanager('doe', null,true), true); + + // admin groups + $this->assertEquals(auth_ismanager('jill', array('admin'),true), true); + $this->assertEquals(auth_ismanager('jill', array('roots'),true), true); + $this->assertEquals(auth_ismanager('john', array('admin'),true), true); + $this->assertEquals(auth_ismanager('doe', array('admin'),true), true); + } + + function test_ismanager_sensitive(){ + $this->setSensitive(); + global $conf; + $conf['superuser'] = 'john,@admin,@Mötly Görls, Dörte'; + $conf['manager'] = 'john,@managers,doe, @Mötly Böys, Dänny'; + + // anonymous user + $this->assertEquals(auth_ismanager('jill', null,false), false); + + // admin or manager users + $this->assertEquals(auth_ismanager('john', null,false), true); + $this->assertEquals(auth_ismanager('doe', null,false), true); + + $this->assertEquals(auth_ismanager('dörte', null,false), false); + $this->assertEquals(auth_ismanager('dänny', null,false), false); + + // admin or manager groups + $this->assertEquals(auth_ismanager('jill', array('admin'),false), true); + $this->assertEquals(auth_ismanager('jill', array('managers'),false), true); + + $this->assertEquals(auth_ismanager('jill', array('mötly görls'),false), false); + $this->assertEquals(auth_ismanager('jill', array('mötly böys'),false), false); + } + + function test_isadmin_sensitive(){ + $this->setSensitive(); + global $conf; + $conf['superuser'] = 'john,@admin,doe,@roots'; + + // anonymous user + $this->assertEquals(auth_ismanager('jill', null,true), false); + + // admin user + $this->assertEquals(auth_ismanager('john', null,true), true); + $this->assertEquals(auth_ismanager('Doe', null,true), false); + + // admin groups + $this->assertEquals(auth_ismanager('jill', array('admin'),true), true); + $this->assertEquals(auth_ismanager('jill', array('roots'),true), true); + $this->assertEquals(auth_ismanager('john', array('admin'),true), true); + $this->assertEquals(auth_ismanager('doe', array('admin'),true), true); + $this->assertEquals(auth_ismanager('Doe', array('admin'),true), true); + } + +} + +//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/auth_nameencode.test.php b/_test/tests/inc/auth_nameencode.test.php similarity index 68% rename from _test/cases/inc/auth_nameencode.test.php rename to _test/tests/inc/auth_nameencode.test.php index 56806a862a..a3df6ac8c0 100644 --- a/_test/cases/inc/auth_nameencode.test.php +++ b/_test/tests/inc/auth_nameencode.test.php @@ -3,7 +3,7 @@ require_once DOKU_INC.'inc/init.php'; require_once DOKU_INC.'inc/auth.php'; -class auth_nameencode_test extends UnitTestCase { +class auth_nameencode_test extends DokuWikiTest { function teardown() { global $cache_authname; @@ -13,37 +13,37 @@ function teardown() { function test_simple(){ $in = 'hey$you'; $out = 'hey%24you'; - $this->assertEqual(auth_nameencode($in),$out); + $this->assertEquals(auth_nameencode($in),$out); } function test_quote(){ $in = 'hey"you'; $out = 'hey%22you'; - $this->assertEqual(auth_nameencode($in),$out); + $this->assertEquals(auth_nameencode($in),$out); } function test_complex(){ $in = 'hey $ you !$%! foo '; $out = 'hey%20%24%20you%20%21%24%25%21%20foo%20'; - $this->assertEqual(auth_nameencode($in),$out); + $this->assertEquals(auth_nameencode($in),$out); } function test_complexutf8(){ $in = 'häü $ yü !$%! foo '; $out = 'häü%20%24%20yü%20%21%24%25%21%20foo%20'; - $this->assertEqual(auth_nameencode($in),$out); + $this->assertEquals(auth_nameencode($in),$out); } function test_groupskipon(){ $in = '@hey$you'; $out = '@hey%24you'; - $this->assertEqual(auth_nameencode($in,true),$out); + $this->assertEquals(auth_nameencode($in,true),$out); } function test_groupskipoff(){ $in = '@hey$you'; $out = '%40hey%24you'; - $this->assertEqual(auth_nameencode($in),$out); + $this->assertEquals(auth_nameencode($in),$out); } } diff --git a/_test/cases/inc/auth_password.test.php b/_test/tests/inc/auth_password.test.php similarity index 75% rename from _test/cases/inc/auth_password.test.php rename to _test/tests/inc/auth_password.test.php index d4a4d2bdbd..515adc8f5d 100644 --- a/_test/cases/inc/auth_password.test.php +++ b/_test/tests/inc/auth_password.test.php @@ -3,7 +3,7 @@ require_once DOKU_INC.'inc/init.php'; require_once DOKU_INC.'inc/auth.php'; -class auth_password_test extends UnitTestCase { +class auth_password_test extends PHPUnit_Framework_TestCase { // hashes for the password foo$method, using abcdefgh as salt var $passes = array( @@ -17,8 +17,6 @@ class auth_password_test extends UnitTestCase { 'mysql' => '4a1fa3780bd6fd55', 'my411' => '*e5929347e25f82e19e4ebe92f1dc6b6e7c2dbd29', 'kmd5' => 'a579299436d7969791189acadd86fcb716', - 'pmd5' => '$P$abcdefgh1RC6Fd32heUzl7EYCG9uGw.', - 'hmd5' => '$H$abcdefgh1ZbJodHxmeXVAhEzTG7IAp.', 'djangomd5' => 'md5$abcde$d0fdddeda8cd92725d2b54148ac09158', 'djangosha1' => 'sha1$abcde$c8e65a7f0acc9158843048a53dcc5a6bc4d17678', ); @@ -27,25 +25,24 @@ class auth_password_test extends UnitTestCase { function test_cryptPassword(){ foreach($this->passes as $method => $hash){ $info = "testing method $method"; - $this->signal('failinfo',$info); - $this->assertEqual(auth_cryptPassword('foo'.$method,$method,'abcdefgh12345678912345678912345678'),$hash); + $this->assertEquals(auth_cryptPassword('foo'.$method, $method,'abcdefgh12345678912345678912345678'), + $hash, $info); } } function test_verifyPassword(){ foreach($this->passes as $method => $hash){ $info = "testing method $method"; - $this->signal('failinfo',$info); - $this->assertTrue(auth_verifyPassword('foo'.$method,$hash)); + $this->assertTrue(auth_verifyPassword('foo'.$method, $hash), $info); + $this->assertFalse(auth_verifyPassword('bar'.$method, $hash), $info); } } function test_verifySelf(){ foreach($this->passes as $method => $hash){ $info = "testing method $method"; - $this->signal('failinfo',$info); $hash = auth_cryptPassword('foo'.$method,$method); - $this->assertTrue(auth_verifyPassword('foo'.$method,$hash)); + $this->assertTrue(auth_verifyPassword('foo'.$method, $hash), $info); } } @@ -67,6 +64,20 @@ function test_verifyPassword_fixedpmd5(){ $this->assertTrue(auth_verifyPassword('test12345','$H$9IQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0')); } + /** + * pmd5 checking should throw an exception when a hash with a too high + * iteration count is passed + */ + function test_verifyPassword_pmd5Exception(){ + $except = false; + try{ + auth_verifyPassword('foopmd5', '$H$abcdefgh1ZbJodHxmeXVAhEzTG7IAp.'); + }catch (Exception $e){ + $except = true; + } + $this->assertTrue($except); + } + } //Setup VIM: ex: et ts=4 : diff --git a/_test/tests/inc/common_cleanText.test.php b/_test/tests/inc/common_cleanText.test.php new file mode 100644 index 0000000000..58f38d9bfc --- /dev/null +++ b/_test/tests/inc/common_cleanText.test.php @@ -0,0 +1,28 @@ +assertEquals($unix,cleanText($unix)); + } + + function test_win(){ + $unix = "one\ntwo\nthree"; + $win = "one\r\ntwo\r\nthree"; + + $this->assertEquals(bin2hex($unix), '6f6e650a74776f0a7468726565'); + $this->assertEquals(bin2hex($win), '6f6e650d0a74776f0d0a7468726565'); + $this->assertNotEquals($unix, $win); + $this->assertEquals($unix, cleanText($win)); + } +} + +//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/common_clientip.test.php b/_test/tests/inc/common_clientip.test.php similarity index 83% rename from _test/cases/inc/common_clientip.test.php rename to _test/tests/inc/common_clientip.test.php index 68c1081657..680050e428 100644 --- a/_test/cases/inc/common_clientip.test.php +++ b/_test/tests/inc/common_clientip.test.php @@ -3,14 +3,14 @@ require_once DOKU_INC.'inc/init.php'; require_once DOKU_INC.'inc/common.php'; -class common_clientIP_test extends UnitTestCase { +class common_clientIP_test extends DokuWikiTest { function test_simple_all(){ $_SERVER['REMOTE_ADDR'] = '123.123.123.123'; $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $out = '123.123.123.123'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } function test_proxy1_all(){ @@ -18,7 +18,7 @@ function test_proxy1_all(){ $_SERVER['HTTP_X_REAL_IP'] = '77.77.77.77'; $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $out = '123.123.123.123,77.77.77.77'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } function test_proxy2_all(){ @@ -26,7 +26,7 @@ function test_proxy2_all(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '77.77.77.77'; $out = '123.123.123.123,77.77.77.77'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } function test_proxyhops_all(){ @@ -34,7 +34,7 @@ function test_proxyhops_all(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '77.77.77.77,66.66.66.66'; $out = '123.123.123.123,77.77.77.77,66.66.66.66'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } function test_simple_single(){ @@ -42,7 +42,7 @@ function test_simple_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $out = '123.123.123.123'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_proxy1_single(){ @@ -50,7 +50,7 @@ function test_proxy1_single(){ $_SERVER['HTTP_X_REAL_IP'] = '77.77.77.77'; $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $out = '77.77.77.77'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_proxy2_single(){ @@ -58,7 +58,7 @@ function test_proxy2_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '77.77.77.77'; $out = '77.77.77.77'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_proxyhops_single(){ @@ -66,7 +66,7 @@ function test_proxyhops_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '77.77.77.77,66.66.66.66'; $out = '66.66.66.66'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_local_all(){ @@ -74,7 +74,7 @@ function test_local_all(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1'; $out = '123.123.123.123,127.0.0.1'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } function test_local1_single(){ @@ -82,7 +82,7 @@ function test_local1_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1'; $out = '123.123.123.123'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_local2_single(){ @@ -90,7 +90,7 @@ function test_local2_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '123.123.123.123'; $out = '123.123.123.123'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_local3_single(){ @@ -98,7 +98,7 @@ function test_local3_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,10.0.0.1,192.168.0.2,172.17.1.1,172.21.1.1,172.31.1.1'; $out = '123.123.123.123'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_local4_single(){ @@ -106,7 +106,7 @@ function test_local4_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.0.5'; $out = '192.168.0.5'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_garbage_all(){ @@ -114,7 +114,7 @@ function test_garbage_all(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = 'some garbage, or something, 222'; $out = '123.123.123.123'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } function test_garbage_single(){ @@ -122,7 +122,7 @@ function test_garbage_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = 'some garbage, or something, 222'; $out = '123.123.123.123'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_garbageonly_all(){ @@ -130,7 +130,7 @@ function test_garbageonly_all(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = 'some garbage, or something, 222'; $out = '0.0.0.0'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } function test_garbageonly_single(){ @@ -138,7 +138,7 @@ function test_garbageonly_single(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = 'some garbage, or something, 222'; $out = '0.0.0.0'; - $this->assertEqual(clientIP(true),$out); + $this->assertEquals(clientIP(true),$out); } function test_malicious(){ @@ -146,10 +146,9 @@ function test_malicious(){ $_SERVER['HTTP_X_REAL_IP'] = ''; $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $out = '0.0.0.0'; - $this->assertEqual(clientIP(),$out); + $this->assertEquals(clientIP(),$out); } - } //Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/common_obfuscate.test.php b/_test/tests/inc/common_obfuscate.test.php similarity index 58% rename from _test/cases/inc/common_obfuscate.test.php rename to _test/tests/inc/common_obfuscate.test.php index 31321bea12..19dd2ff2c2 100644 --- a/_test/cases/inc/common_obfuscate.test.php +++ b/_test/tests/inc/common_obfuscate.test.php @@ -1,26 +1,27 @@ assertEqual(obfuscate('jon-doe@example.com'), 'jon-doe@example.com'); + $this->assertEquals(obfuscate('jon-doe@example.com'), 'jon-doe@example.com'); } function test_hex(){ global $conf; $conf['mailguard'] = 'hex'; - $this->assertEqual(obfuscate('jon-doe@example.com'), + $this->assertEquals(obfuscate('jon-doe@example.com'), 'jon-doe@example.com'); } function test_visible(){ global $conf; $conf['mailguard'] = 'visible'; - $this->assertEqual(obfuscate('jon-doe@example.com'), 'jon [dash] doe [at] example [dot] com'); + $this->assertEquals(obfuscate('jon-doe@example.com'), 'jon [dash] doe [at] example [dot] com'); } diff --git a/_test/cases/inc/common_pagetemplate.test.php b/_test/tests/inc/common_pagetemplate.test.php similarity index 54% rename from _test/cases/inc/common_pagetemplate.test.php rename to _test/tests/inc/common_pagetemplate.test.php index 2db8b64aeb..c4a2dfdf9f 100644 --- a/_test/cases/inc/common_pagetemplate.test.php +++ b/_test/tests/inc/common_pagetemplate.test.php @@ -1,8 +1,9 @@ 'page-id-long', 'tpl' => '"@PAGE@" "@!PAGE@" "@!!PAGE@" "@!PAGE!@"', ); - $old = error_reporting(E_ALL & ~E_NOTICE); - $this->assertEqual(parsePageTemplate($data), '"page id long" "Page id long" "Page Id Long" "PAGE ID LONG"'); - error_reporting($old); + $this->assertEquals(parsePageTemplate($data), '"page id long" "Page id long" "Page Id Long" "PAGE ID LONG"'); } } //Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/form_form.test.php b/_test/tests/inc/form_form.test.php similarity index 85% rename from _test/cases/inc/form_form.test.php rename to _test/tests/inc/form_form.test.php index 5d5fa72afc..f55f161066 100644 --- a/_test/cases/inc/form_form.test.php +++ b/_test/tests/inc/form_form.test.php @@ -1,9 +1,8 @@ 'dw__testform', 'action' => '/test')); @@ -52,13 +51,13 @@ function test_form_print() { $output = ob_get_contents(); ob_end_clean(); $form->addHidden('sectok', getSecurityToken()); - $this->assertEqual($this->_ignoreTagWS($output),$this->_ignoreTagWS($this->_realoutput())); + $this->assertEquals($this->_ignoreTagWS($output),$this->_ignoreTagWS($this->_realoutput())); } function test_get_element_at() { $form = $this->_testform(); $e1 =& $form->getElementAt(1); - $this->assertEqual($e1, array('_elem'=>'textfield', + $this->assertEquals($e1, array('_elem'=>'textfield', '_text'=>'Text', '_class'=>'block', 'id'=>'text__id', @@ -66,24 +65,24 @@ function test_get_element_at() { 'value'=>'v', 'class'=>'edit')); $e2 =& $form->getElementAt(99); - $this->assertEqual($e2, array('_elem'=>'closefieldset')); + $this->assertEquals($e2, array('_elem'=>'closefieldset')); } function test_find_element_by_type() { $form = $this->_testform(); - $this->assertEqual($form->findElementByType('button'), 3); + $this->assertEquals($form->findElementByType('button'), 3); $this->assertFalse($form->findElementByType('text')); } function test_find_element_by_id() { $form = $this->_testform(); - $this->assertEqual($form->findElementById('check__id'), 2); + $this->assertEquals($form->findElementById('check__id'), 2); $this->assertFalse($form->findElementById('dw__testform')); } function test_find_element_by_attribute() { $form = $this->_testform(); - $this->assertEqual($form->findElementByAttribute('value','Cancel'), 4); + $this->assertEquals($form->findElementByAttribute('value','Cancel'), 4); $this->assertFalse($form->findElementByAttribute('name','cancel')); } @@ -99,7 +98,7 @@ function test_close_fieldset() { $form->printForm(); $output = ob_get_contents(); ob_end_clean(); - $this->assertEqual($this->_ignoreTagWS($output),$this->_ignoreTagWS($this->_realoutput())); + $this->assertEquals($this->_ignoreTagWS($output),$this->_ignoreTagWS($this->_realoutput())); } } diff --git a/_test/tests/inc/html_hilight.test.php b/_test/tests/inc/html_hilight.test.php new file mode 100644 index 0000000000..bb0cdd4248 --- /dev/null +++ b/_test/tests/inc/html_hilight.test.php @@ -0,0 +1,100 @@ +assertRegExp( + '/Foo bar<\/span> Foo/', + html_hilight($html,'bar') + ); + } + + function testHighlightTwoWords() { + $html = 'Foo bar Foo php Foo'; + $this->assertRegExp( + '/Foo bar<\/span> Foo php<\/span> Foo/', + html_hilight($html,array('bar','php')) + ); + } + + function testHighlightTwoWordsHtml() { + $html = 'Foo bar Foo php Foo'; + $this->assertRegExp( + '/Foo bar<\/span><\/b> Foo<\/i> php<\/span> Foo/', + html_hilight($html,array('bar','php')) + ); + } + + function testNoMatchHtml() { + $html = 'Foo font Bar'; + $this->assertRegExp( + '/Foo font<\/span><\/font> Bar/', + html_hilight($html,'font') + ); + } + + function testWildcardRight() { + $html = 'foo bar foobar barfoo foobarfoo foo'; + $this->assertRegExp( + '/foo bar<\/span> foobar bar<\/span>foo foobarfoo foo/', + html_hilight($html,'bar*') + ); + } + + function testWildcardLeft() { + $html = 'foo bar foobar barfoo foobarfoo foo'; + $this->assertRegExp( + '/foo bar<\/span> foobar<\/span> barfoo foobarfoo foo/', + html_hilight($html,'*bar') + ); + } + + function testWildcardBoth() { + $html = 'foo bar foobar barfoo foobarfoo foo'; + $this->assertRegExp( + '/foo bar<\/span> foobar<\/span> bar<\/span>foo foobar<\/span>foo foo/', + html_hilight($html,'*bar*') + ); + } + + function testNoHighlight() { + $html = 'Foo bar Foo'; + $this->assertRegExp( + '/Foo bar Foo/', + html_hilight($html,'php') + ); + } + + function testMatchAttribute() { + $html = 'Foo bar Foo'; + $this->assertRegExp( + '/Foo bar<\/b> Foo/', + html_hilight($html,'class="x"') + ); + } + + function testMatchAttributeWord() { + $html = 'Foo bar Foo'; + $this->assertEquals( + 'Foo bar Foo', + html_hilight($html,'class="x">bar') + ); + } + + function testRegexInjection() { + $html = 'Foo bar Foo'; + $this->assertRegExp( + '/Foo bar Foo/', + html_hilight($html,'*') + ); + } + + function testRegexInjectionSlash() { + $html = 'Foo bar Foo'; + $this->assertRegExp( + '/Foo bar Foo/', + html_hilight($html,'x/') + ); + } +} diff --git a/_test/tests/inc/httpclient_http.test.php b/_test/tests/inc/httpclient_http.test.php new file mode 100644 index 0000000000..9cae3736a7 --- /dev/null +++ b/_test/tests/inc/httpclient_http.test.php @@ -0,0 +1,180 @@ +get($this->server.'/get?foo=bar'); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('args',$resp); + $this->assertEquals(array('foo'=>'bar'), $resp['args']); + } + + /** + * @group internet + */ + function test_dget(){ + $http = new HTTPClient(); + $data = $http->dget($this->server.'/get',array('foo'=>'bar')); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('args',$resp); + $this->assertEquals(array('foo'=>'bar'), $resp['args']); + } + + /** + * @group internet + */ + function test_gzip(){ + $http = new HTTPClient(); + $data = $http->get($this->server.'/gzip'); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('gzipped',$resp); + $this->assertTrue($resp['gzipped']); + } + + /** + * @group internet + */ + function test_simplepost(){ + $http = new HTTPClient(); + $data = $http->post($this->server.'/post',array('foo'=>'bar')); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('form',$resp); + $this->assertEquals(array('foo'=>'bar'), $resp['form']); + } + + /** + * @group internet + */ + function test_redirect(){ + $http = new HTTPClient(); + $data = $http->get($this->server.'/redirect/3'); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('url',$resp); + $this->assertRegExp('/\/get$/', $resp['url']); + } + + /** + * @group internet + */ + function test_relredirect(){ + $http = new HTTPClient(); + $data = $http->get($this->server.'/relative-redirect/3'); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('url',$resp); + $this->assertRegExp('/\/get$/', $resp['url']); + } + + /** + * @group internet + */ + function test_redirectfail(){ + $http = new HTTPClient(); + $data = $http->get($this->server.'/redirect/5'); + $this->assertTrue($data === false, 'HTTP response'); + $this->assertEquals('Maximum number of redirects exceeded',$http->error); + } + + /** + * @group internet + */ + function test_cookies(){ + $http = new HTTPClient(); + $http->get($this->server.'/cookies/set/foo/bar'); + $this->assertEquals(array('foo' => 'bar'), $http->cookies); + $data = $http->get($this->server.'/cookies'); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('cookies',$resp); + $this->assertEquals(array('foo'=>'bar'), $resp['cookies']); + } + + /** + * @group internet + */ + function test_teapot(){ + $http = new HTTPClient(); + $data = $http->get($this->server.'/status/418'); + $this->assertTrue($data === false, 'HTTP response'); + $this->assertEquals(418,$http->status); + } + + /** + * @group internet + */ + function test_maxbody(){ + $http = new HTTPClient(); + $http->max_bodysize = 250; + $data = $http->get($this->server.'/stream/30'); + $this->assertTrue($data === false, 'HTTP response'); + } + + /** + * @group internet + */ + function test_basicauth(){ + $http = new HTTPClient(); + $http->user = 'user'; + $http->pass = 'pass'; + $data = $http->get($this->server.'/basic-auth/user/pass'); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertEquals(array('authenticated'=>true,'user'=>'user'), $resp); + } + + /** + * @group internet + */ + function test_basicauthfail(){ + $http = new HTTPClient(); + $http->user = 'user'; + $http->pass = 'invalid'; + $data = $http->get($this->server.'/basic-auth/user/pass'); + $this->assertTrue($data === false, 'HTTP response'); + $this->assertEquals(401,$http->status); + } + + /** + * @group internet + */ + function test_timeout(){ + $http = new HTTPClient(); + $http->timeout = 5; + $data = $http->get($this->server.'/delay/10'); + $this->assertTrue($data === false, 'HTTP response'); + $this->assertEquals(-100,$http->status); + } + + /** + * @group internet + */ + function test_headers(){ + $http = new HTTPClient(); + $data = $http->get($this->server.'/response-headers?baz=&foo=bar'); + $this->assertFalse($data === false, 'HTTP response'); + $resp = json_decode($data, true); + $this->assertTrue(is_array($resp), 'JSON response'); + $this->assertArrayHasKey('baz',$http->resp_headers); + $this->assertArrayHasKey('foo',$http->resp_headers); + $this->assertEquals('bar',$http->resp_headers['foo']); + } +} +//Setup VIM: ex: et ts=4 : diff --git a/_test/tests/inc/httpclient_https.test.php b/_test/tests/inc/httpclient_https.test.php new file mode 100644 index 0000000000..c51cd4904b --- /dev/null +++ b/_test/tests/inc/httpclient_https.test.php @@ -0,0 +1,17 @@ +markTestSkipped('No SSL support available.'); + } + parent::setUp(); + } +} +//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/init_fullpath.test.php b/_test/tests/inc/init_fullpath.test.php similarity index 93% rename from _test/cases/inc/init_fullpath.test.php rename to _test/tests/inc/init_fullpath.test.php index aa63b0ce97..e5b322874e 100644 --- a/_test/cases/inc/init_fullpath.test.php +++ b/_test/tests/inc/init_fullpath.test.php @@ -1,7 +1,7 @@ $to){ $info = "Testing '$from' resulted in '".fullpath($from)."'"; - $this->signal('failinfo',$info); - $this->assertEqual(fullpath($from),$to); + $this->assertEquals(fullpath($from), $to, $info); } @@ -75,9 +74,8 @@ function test_windows_paths(){ foreach($tests as $from => $to){ $info = "Testing '$from' resulted in '".fullpath($from)."'"; - $this->signal('failinfo',$info); - $this->assertEqual(fullpath($from),$to); + $this->assertEquals(fullpath($from), $to, $info); } diff --git a/_test/cases/inc/init_getbaseurl.test.php b/_test/tests/inc/init_getbaseurl.test.php similarity index 92% rename from _test/cases/inc/init_getbaseurl.test.php rename to _test/tests/inc/init_getbaseurl.test.php index a22172febe..9d1377b3cb 100644 --- a/_test/cases/inc/init_getbaseurl.test.php +++ b/_test/tests/inc/init_getbaseurl.test.php @@ -2,7 +2,7 @@ require_once DOKU_INC.'inc/init.php'; -class init_getBaseURL_test extends UnitTestCase { +class init_getBaseURL_test extends DokuWikiTest { /** * Apache, mod_php, subdirectory @@ -24,7 +24,7 @@ function test1(){ $_SERVER['PATH_TRANSLATED'] = '/var/www/dokuwiki/doku.php'; $_SERVER['PHP_SELF'] = '/dokuwiki/doku.php'; - $this->assertEqual(getBaseURL(),'/dokuwiki/'); + $this->assertEquals(getBaseURL(),'/dokuwiki/'); } /** @@ -47,7 +47,7 @@ function test2(){ $_SERVER['PATH_TRANSLATED'] = '/home/bengen/public_html/dokuwiki/doku.php'; $_SERVER['PHP_SELF'] = '/~bengen/dokuwiki/doku.php'; - $this->assertEqual(getBaseURL(),'/~bengen/dokuwiki/'); + $this->assertEquals(getBaseURL(),'/~bengen/dokuwiki/'); } /** @@ -70,7 +70,7 @@ function test3(){ $_SERVER['PATH_TRANSLATED'] = '/home/bengen/public_html/dokuwiki/doku.php'; $_SERVER['PHP_SELF'] = '/~bengen/dokuwiki/doku.php'; - $this->assertEqual(getBaseURL(),'/~bengen/dokuwiki/'); + $this->assertEquals(getBaseURL(),'/~bengen/dokuwiki/'); } /** @@ -93,7 +93,7 @@ function test4(){ $_SERVER['PATH_TRANSLATED'] = '/home/bengen/public_html/dokuwiki/doku.php'; $_SERVER['PHP_SELF'] = '/~bengen/dokuwiki/doku.php'; - $this->assertEqual(getBaseURL(),'/~bengen/dokuwiki/'); + $this->assertEquals(getBaseURL(),'/~bengen/dokuwiki/'); } /** @@ -116,7 +116,7 @@ function test5(){ $_SERVER['PATH_TRANSLATED'] = 'C:\\Inetpub\\wwwroot\\wiki\\doku.php'; $_SERVER['PHP_SELF'] = '/wiki/doku.php'; - $this->assertEqual(getBaseURL(),'/wiki/'); + $this->assertEquals(getBaseURL(),'/wiki/'); } /** @@ -139,7 +139,7 @@ function test6(){ $_SERVER['PATH_TRANSLATED'] = null; $_SERVER['PHP_SELF'] = '/wiki/syntax'; - $this->assertEqual(getBaseURL(),'/'); + $this->assertEquals(getBaseURL(),'/'); } /** @@ -162,7 +162,7 @@ function test7(){ $_SERVER['PATH_TRANSLATED'] = null; $_SERVER['PHP_SELF'] = ''; - $this->assertEqual(getBaseURL(),'/dokuwiki/'); + $this->assertEquals(getBaseURL(),'/dokuwiki/'); } /** @@ -185,7 +185,7 @@ function test8(){ $_SERVER['PATH_TRANSLATED'] = '/var/www/wiki/syntax'; $_SERVER['PHP_SELF'] = '/dokuwiki/doku.php/wiki/syntax'; - $this->assertEqual(getBaseURL(),'/dokuwiki/'); + $this->assertEquals(getBaseURL(),'/dokuwiki/'); } /** @@ -208,7 +208,7 @@ function test9(){ $_SERVER['PATH_TRANSLATED'] = '/var/www/dokuwiki/doku.php'; $_SERVER['PHP_SELF'] = '/dokuwiki/doku.php'; - $this->assertEqual(getBaseURL(),'/dokuwiki/'); + $this->assertEquals(getBaseURL(),'/dokuwiki/'); } /** @@ -240,7 +240,7 @@ function test10(){ foreach ($tests as $test => $correct_result) { $conf['baseurl'] = $test; - $this->assertEqual(getBaseURL(true),$correct_result); + $this->assertEquals(getBaseURL(true),$correct_result); } } /** @@ -272,7 +272,7 @@ function test11(){ foreach ($tests as $test => $correct_result) { $conf['baseurl'] = $test; - $this->assertEqual(getBaseURL(true),$correct_result); + $this->assertEquals(getBaseURL(true),$correct_result); } } @@ -298,7 +298,7 @@ function test12() { $_SERVER['PHP_SELF'] = '/~michitux/dokuwiki/doku.php'; $_SERVER['SERVER_PORT'] = '80'; $_SERVER['SERVER_NAME'] = '[fd00'; - $this->assertEqual(getBaseURL(true), 'http://[fd00::6592:39ed:a2ed:2c78]/~michitux/dokuwiki/'); + $this->assertEquals(getBaseURL(true), 'http://[fd00::6592:39ed:a2ed:2c78]/~michitux/dokuwiki/'); } } diff --git a/_test/cases/inc/IXR_Library_date.test.php b/_test/tests/inc/ixr_library_date.test.php similarity index 86% rename from _test/cases/inc/IXR_Library_date.test.php rename to _test/tests/inc/ixr_library_date.test.php index 28fa86486d..377b0fd33a 100644 --- a/_test/cases/inc/IXR_Library_date.test.php +++ b/_test/tests/inc/ixr_library_date.test.php @@ -1,7 +1,9 @@ assertEqual($dt->getTimeStamp(),$test[1]); + $this->assertEquals($dt->getTimeStamp(),$test[1]); } } diff --git a/_test/cases/inc/IXR_Library_IXR_Message.test.php b/_test/tests/inc/ixr_library_ixr_message.test.php similarity index 69% rename from _test/cases/inc/IXR_Library_IXR_Message.test.php rename to _test/tests/inc/ixr_library_ixr_message.test.php index bc9be572d7..ea7646b6a7 100644 --- a/_test/cases/inc/IXR_Library_IXR_Message.test.php +++ b/_test/tests/inc/ixr_library_ixr_message.test.php @@ -1,7 +1,8 @@ parse(); - $this->assertEqual($ixrmsg->messageType,'methodCall'); - $this->assertEqual($ixrmsg->methodName,'wiki.getBackLinks'); - $this->assertEqual($ixrmsg->params,array(' change ')); + $this->assertEquals($ixrmsg->messageType,'methodCall'); + $this->assertEquals($ixrmsg->methodName,'wiki.getBackLinks'); + $this->assertEquals($ixrmsg->params,array(' change ')); } function test_untypedvalue2(){ @@ -32,9 +33,9 @@ function test_untypedvalue2(){ $ixrmsg = new IXR_Message($xml); $ixrmsg->parse(); - $this->assertEqual($ixrmsg->messageType,'methodCall'); - $this->assertEqual($ixrmsg->methodName,'wiki.getBackLinks'); - $this->assertEqual($ixrmsg->params,array(' change ')); + $this->assertEquals($ixrmsg->messageType,'methodCall'); + $this->assertEquals($ixrmsg->methodName,'wiki.getBackLinks'); + $this->assertEquals($ixrmsg->params,array(' change ')); } function test_stringvalue1(){ @@ -43,9 +44,9 @@ function test_stringvalue1(){ $ixrmsg = new IXR_Message($xml); $ixrmsg->parse(); - $this->assertEqual($ixrmsg->messageType,'methodCall'); - $this->assertEqual($ixrmsg->methodName,'wiki.getBackLinks'); - $this->assertEqual($ixrmsg->params,array(' change ')); + $this->assertEquals($ixrmsg->messageType,'methodCall'); + $this->assertEquals($ixrmsg->methodName,'wiki.getBackLinks'); + $this->assertEquals($ixrmsg->params,array(' change ')); } function test_stringvalue2(){ @@ -64,9 +65,9 @@ function test_stringvalue2(){ $ixrmsg = new IXR_Message($xml); $ixrmsg->parse(); - $this->assertEqual($ixrmsg->messageType,'methodCall'); - $this->assertEqual($ixrmsg->methodName,'wiki.getBackLinks'); - $this->assertEqual($ixrmsg->params,array(' change ')); + $this->assertEquals($ixrmsg->messageType,'methodCall'); + $this->assertEquals($ixrmsg->methodName,'wiki.getBackLinks'); + $this->assertEquals($ixrmsg->params,array(' change ')); } function test_emptyvalue1(){ @@ -75,9 +76,9 @@ function test_emptyvalue1(){ $ixrmsg = new IXR_Message($xml); $ixrmsg->parse(); - $this->assertEqual($ixrmsg->messageType,'methodCall'); - $this->assertEqual($ixrmsg->methodName,'wiki.getBackLinks'); - $this->assertEqual($ixrmsg->params,array('')); + $this->assertEquals($ixrmsg->messageType,'methodCall'); + $this->assertEquals($ixrmsg->methodName,'wiki.getBackLinks'); + $this->assertEquals($ixrmsg->params,array('')); } function test_emptyvalue2(){ @@ -96,9 +97,9 @@ function test_emptyvalue2(){ $ixrmsg = new IXR_Message($xml); $ixrmsg->parse(); - $this->assertEqual($ixrmsg->messageType,'methodCall'); - $this->assertEqual($ixrmsg->methodName,'wiki.getBackLinks'); - $this->assertEqual($ixrmsg->params,array('')); + $this->assertEquals($ixrmsg->messageType,'methodCall'); + $this->assertEquals($ixrmsg->methodName,'wiki.getBackLinks'); + $this->assertEquals($ixrmsg->params,array('')); } function test_struct(){ @@ -130,9 +131,9 @@ function test_struct(){ $ixrmsg = new IXR_Message($xml); $ixrmsg->parse(); - $this->assertEqual($ixrmsg->messageType,'methodCall'); - $this->assertEqual($ixrmsg->methodName,'wiki.putPage'); - $this->assertEqual($ixrmsg->params,array('start','test text',array('sum'=>'xmlrpc edit','minor'=>'1'))); + $this->assertEquals($ixrmsg->messageType,'methodCall'); + $this->assertEquals($ixrmsg->methodName,'wiki.putPage'); + $this->assertEquals($ixrmsg->params,array('start','test text',array('sum'=>'xmlrpc edit','minor'=>'1'))); } } diff --git a/_test/cases/inc/mail_isvalid.test.php b/_test/tests/inc/mail_isvalid.test.php similarity index 95% rename from _test/cases/inc/mail_isvalid.test.php rename to _test/tests/inc/mail_isvalid.test.php index d8c88765e3..58f8e69d79 100644 --- a/_test/cases/inc/mail_isvalid.test.php +++ b/_test/tests/inc/mail_isvalid.test.php @@ -1,8 +1,8 @@ signal('failinfo',$info); if($test[1]){ - $this->assertTrue((bool) mail_isvalid($test[0])); + $this->assertTrue((bool) mail_isvalid($test[0]), $info); }else{ - $this->assertFalse((bool) mail_isvalid($test[0])); + $this->assertFalse((bool) mail_isvalid($test[0]), $info); } } } diff --git a/_test/cases/inc/mail_quoted_printable_encode.php b/_test/tests/inc/mail_quoted_printable_encode.test.php similarity index 71% rename from _test/cases/inc/mail_quoted_printable_encode.php rename to _test/tests/inc/mail_quoted_printable_encode.test.php index a5a36e35b4..888b1d1bf4 100644 --- a/_test/cases/inc/mail_quoted_printable_encode.php +++ b/_test/tests/inc/mail_quoted_printable_encode.test.php @@ -2,42 +2,42 @@ require_once DOKU_INC.'inc/mail.php'; -class mail_quotedprintable_encode extends UnitTestCase { +class mail_quotedprintable_encode extends DokuWikiTest { function test_simple(){ $in = 'hello'; $out = 'hello'; - $this->assertEqual(mail_quotedprintable_encode($in),$out); + $this->assertEquals(mail_quotedprintable_encode($in),$out); } function test_spaceend(){ $in = "hello \nhello"; $out = "hello=20\nhello"; - $this->assertEqual(mail_quotedprintable_encode($in),$out); + $this->assertEquals(mail_quotedprintable_encode($in),$out); } function test_german_utf8(){ $in = 'hello überlänge'; $out = 'hello =C3=BCberl=C3=A4nge'; - $this->assertEqual(mail_quotedprintable_encode($in),$out); + $this->assertEquals(mail_quotedprintable_encode($in),$out); } function test_wrap(){ $in = '123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789'; $out = "123456789 123456789 123456789 123456789 123456789 123456789 123456789 1234=\n56789 123456789"; - $this->assertEqual(mail_quotedprintable_encode($in,74),$out); + $this->assertEquals(mail_quotedprintable_encode($in,74),$out); } function test_nowrap(){ $in = '123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789'; $out = '123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789'; - $this->assertEqual(mail_quotedprintable_encode($in,0),$out); + $this->assertEquals(mail_quotedprintable_encode($in,0),$out); } function test_russian_utf8(){ $in = 'Ваш пароль для системы Доку Вики'; $out = '=D0=92=D0=B0=D1=88 =D0=BF=D0=B0=D1=80=D0=BE=D0=BB=D1=8C =D0=B4=D0=BB=D1=8F =D1=81=D0=B8=D1=81=D1=82=D0=B5=D0=BC=D1=8B =D0=94=D0=BE=D0=BA=D1=83 =D0=92=D0=B8=D0=BA=D0=B8'; - $this->assertEqual(mail_quotedprintable_encode($in,0),$out); + $this->assertEquals(mail_quotedprintable_encode($in,0),$out); } } diff --git a/_test/tests/inc/mailer.test.php b/_test/tests/inc/mailer.test.php new file mode 100644 index 0000000000..b2c74a257d --- /dev/null +++ b/_test/tests/inc/mailer.test.php @@ -0,0 +1,94 @@ +$name; + } +} + +class mailer_test extends DokuWikiTest { + + + function test_userheader(){ + $mail = new TestMailer(); + $headers = $mail->prop('headers'); + $this->assertArrayNotHasKey('X-Dokuwiki-User',$headers); + + $_SERVER['REMOTE_USER'] = 'andi'; + $mail = new TestMailer(); + $headers = $mail->prop('headers'); + $this->assertArrayHasKey('X-Dokuwiki-User',$headers); + } + + function test_setHeader(){ + $mail = new TestMailer(); + + // check existance of default headers + $headers = $mail->prop('headers'); + $this->assertArrayHasKey('X-Mailer',$headers); + $this->assertArrayHasKey('X-Dokuwiki-Title',$headers); + $this->assertArrayHasKey('X-Dokuwiki-Server',$headers); + $this->assertArrayHasKey('X-Auto-Response-Suppress',$headers); + $this->assertArrayHasKey('List-Id',$headers); + + // set a bunch of test headers + $mail->setHeader('test-header','bla'); + $mail->setHeader('to','A valid ASCII name '); + $mail->setHeader('from',"Thös ne\needs\x00serious cleaning$§%."); + $mail->setHeader('bad',"Thös ne\needs\x00serious cleaning$§%.",false); + $mail->setHeader("weird\n*+\x00foo.-_@bar?",'now clean'); + + // are they set? + $headers = $mail->prop('headers'); + $this->assertArrayHasKey('Test-Header',$headers); + $this->assertEquals('bla',$headers['Test-Header']); + $this->assertArrayHasKey('To',$headers); + $this->assertEquals('A valid ASCII name ',$headers['To']); + $this->assertArrayHasKey('From',$headers); + $this->assertEquals('Ths neeedsserious cleaning.',$headers['From']); + $this->assertArrayHasKey('Bad',$headers); + $this->assertEquals("Thös ne\needs\x00serious cleaning$§%.",$headers['Bad']); + $this->assertArrayHasKey('Weird+foo.-_@bar',$headers); + + // unset a header again + $mail->setHeader('test-header',''); + $headers = $mail->prop('headers'); + $this->assertArrayNotHasKey('Test-Header',$headers); + } + + function test_simplemail(){ + global $conf; + $conf['htmlmail'] = 0; + $mail = new TestMailer(); + $mail->to('test@example.com'); + $mail->setBody('A test mail in ASCII'); + + $dump = $mail->dump(); + $this->assertNotRegexp('/Content-Type: multipart/',$dump); + $this->assertRegexp('#Content-Type: text/plain; charset=UTF-8#',$dump); + $this->assertRegexp('/'.base64_encode('A test mail in ASCII').'/',$dump); + + $conf['htmlmail'] = 1; + } + + function test_replacements(){ + $mail = new TestMailer(); + + $replacements = array( '@DATE@','@BROWSER@','@IPADDRESS@','@HOSTNAME@', + '@TITLE@','@DOKUWIKIURL@','@USER@','@NAME@','@MAIL@'); + $mail->setBody('A test mail in with replacements '.join(' ',$replacements)); + + $text = $mail->prop('text'); + $html = $mail->prop('html'); + + foreach($replacements as $repl){ + $this->assertNotRegexp("/$repl/",$text,"$repl replacement still in text"); + $this->assertNotRegexp("/$repl/",$html,"$repl replacement still in html"); + } + } + +} +//Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/pageutils_clean_id.test.php b/_test/tests/inc/pageutils_clean_id.test.php similarity index 87% rename from _test/cases/inc/pageutils_clean_id.test.php rename to _test/tests/inc/pageutils_clean_id.test.php index 167229c7f8..37debfa0a9 100644 --- a/_test/cases/inc/pageutils_clean_id.test.php +++ b/_test/tests/inc/pageutils_clean_id.test.php @@ -2,7 +2,7 @@ require_once DOKU_INC.'inc/utf8.php'; require_once DOKU_INC.'inc/pageutils.php'; -class init_clean_id_test extends UnitTestCase { +class init_clean_id_test extends DokuWikiTest { function teardown() { global $cache_cleanid; @@ -50,7 +50,7 @@ function test_default(){ $tests[] = array('page/page',false,'page_page'); foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } $conf['useslash'] = 1; @@ -60,7 +60,7 @@ function test_default(){ $this->teardown(); foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } } @@ -77,7 +77,7 @@ function test_sepchar(){ $tests[] = array('pa%ge',false,'pa-ge'); foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } } @@ -97,7 +97,7 @@ function test_deaccent_keep(){ $tests[] = array('ښ侧化并곦ঝഈβ',false,'ښ侧化并곦ঝഈβ'); foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } } @@ -117,7 +117,7 @@ function test_deaccent_romanize(){ $tests[] = array('ښ侧化并곦ঝഈβ',false,'ښ侧化并곦ঝഈβ'); foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } } @@ -137,19 +137,19 @@ function test_deaccent_ascii(){ $tests[] = array('ښ侧化并곦ঝഈβ',true,''); foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } $conf['deaccent'] = 1; foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } $conf['deaccent'] = 2; foreach($tests as $test){ - $this->assertEqual(cleanID($test[0],$test[1]),$test[2]); + $this->assertEquals(cleanID($test[0],$test[1]),$test[2]); } } diff --git a/_test/cases/inc/pageutils_getid.test.php b/_test/tests/inc/pageutils_getid.test.php similarity index 87% rename from _test/cases/inc/pageutils_getid.test.php rename to _test/tests/inc/pageutils_getid.test.php index 6eddeb5ea5..608760298d 100644 --- a/_test/cases/inc/pageutils_getid.test.php +++ b/_test/tests/inc/pageutils_getid.test.php @@ -2,7 +2,7 @@ require_once DOKU_INC.'inc/utf8.php'; require_once DOKU_INC.'inc/pageutils.php'; -class init_getID_test extends UnitTestCase { +class init_getID_test extends DokuWikiTest { /** * fetch media files with basedir and urlrewrite=2 @@ -19,7 +19,7 @@ function test1(){ $_SERVER['SCRIPT_FILENAME'] = '/lib/exe/fetch.php'; $_SERVER['REQUEST_URI'] = '/lib/exe/fetch.php/myhdl-0.5dev1.tar.gz?id=snapshots&cache=cache'; - $this->assertEqual(getID('media'), 'myhdl-0.5dev1.tar.gz'); + $this->assertEquals(getID('media'), 'myhdl-0.5dev1.tar.gz'); } @@ -41,8 +41,8 @@ function test2(){ $_SERVER['PATH_INFO'] = '/wiki/discussion/button-dw.png'; $_SERVER['PATH_TRANSLATED'] = '/var/www/wiki/discussion/button-dw.png'; - $this->assertEqual(getID('media',true), 'wiki:discussion:button-dw.png'); - $this->assertEqual(getID('media',false), 'wiki/discussion/button-dw.png'); + $this->assertEquals(getID('media',true), 'wiki:discussion:button-dw.png'); + $this->assertEquals(getID('media',false), 'wiki/discussion/button-dw.png'); } /** @@ -61,7 +61,7 @@ function test3() { $_SERVER['PATH_TRANSLATED'] = '/var/www/wiki:dokuwiki'; $_SERVER['PHP_SELF'] = '/dokuwiki/doku.php/wiki:dokuwiki'; - $this->assertEqual(getID(), 'wiki:dokuwiki'); + $this->assertEquals(getID(), 'wiki:dokuwiki'); } /** @@ -72,6 +72,8 @@ function test4() { $conf['basedir'] = ''; $conf['userewrite'] = '2'; $conf['baseurl'] = ''; + $conf['useslash'] = '1'; + $_SERVER['DOCUMENT_ROOT'] = '/var/www/vhosts/example.com/htdocs'; $_SERVER['SCRIPT_FILENAME'] = '/var/www/vhosts/example.com/htdocs/doku.php'; $_SERVER['SCRIPT_NAME'] = '/doku.php'; @@ -80,7 +82,7 @@ function test4() { $_SERVER['PATH_TRANSLATED'] = '/var/www/vhosts/example.com/htdocs/doku.php'; $_SERVER['PHP_SELF'] = '/doku.php/wiki/dokuwiki'; - $this->assertEqual(getID(), 'wiki:dokuwiki'); + $this->assertEquals(getID(), 'wiki:dokuwiki'); } /** @@ -99,7 +101,7 @@ function test5() { $_SERVER['PATH_TRANSLATED'] = '/var/www/index.html'; $_SERVER['PHP_SELF'] = '/dokuwiki/doku.php/'; - $this->assertEqual(getID(), cleanID($conf['start'])); + $this->assertEquals(getID(), cleanID($conf['start'])); } } diff --git a/_test/cases/inc/pageutils_resolve_id.test.php b/_test/tests/inc/pageutils_resolve_id.test.php similarity index 92% rename from _test/cases/inc/pageutils_resolve_id.test.php rename to _test/tests/inc/pageutils_resolve_id.test.php index 9aa4ee8b7c..91f8dc696f 100644 --- a/_test/cases/inc/pageutils_resolve_id.test.php +++ b/_test/tests/inc/pageutils_resolve_id.test.php @@ -2,7 +2,7 @@ require_once DOKU_INC.'inc/utf8.php'; require_once DOKU_INC.'inc/pageutils.php'; -class init_resolve_id_test extends UnitTestCase { +class init_resolve_id_test extends DokuWikiTest { function test1(){ @@ -37,7 +37,7 @@ function test1(){ $tests[] = array('lev1:lev2','..:..:lev3:..:page:....:...','page'); foreach($tests as $test){ - $this->assertEqual(resolve_id($test[0],$test[1]),$test[2]); + $this->assertEquals(resolve_id($test[0],$test[1]),$test[2]); } } diff --git a/_test/cases/inc/pageutils_resolve_pageid.test.php b/_test/tests/inc/pageutils_resolve_pageid.test.php similarity index 91% rename from _test/cases/inc/pageutils_resolve_pageid.test.php rename to _test/tests/inc/pageutils_resolve_pageid.test.php index c65ed1866e..32e5f841fc 100644 --- a/_test/cases/inc/pageutils_resolve_pageid.test.php +++ b/_test/tests/inc/pageutils_resolve_pageid.test.php @@ -5,7 +5,7 @@ global $conf; if (!isset($conf['datadir'])) $conf['datadir'] = $conf['savedir'].'/pages'; -class init_resolve_pageid_test extends UnitTestCase { +class init_resolve_pageid_test extends DokuWikiTest { function test1(){ @@ -48,7 +48,6 @@ function test1(){ $tests[] = array('foo','.:','foo:start'); $tests[] = array('','foo:','foo:start'); $tests[] = array('foo','foo:','foo:start'); - $tests[] = array('foo','playground:','playground:playground'); // empty $page global $ID; @@ -59,7 +58,7 @@ function test1(){ $page = $test[1]; resolve_pageid($test[0],$page,$foo); - $this->assertEqual($page,$test[2]); + $this->assertEquals($page,$test[2]); } } @@ -69,7 +68,6 @@ function test1(){ function test_resolve_pageid_empty_homepage() { global $ID; $ID = ''; - global $conf; $conf['start'] = 'someverystrangestartname'; @@ -78,7 +76,7 @@ function test_resolve_pageid_empty_homepage() { $exist = true; resolve_pageid($ns, $page, $exist); - $this->assertEqual($page, $conf['start']); + $this->assertEquals($page, $conf['start']); } } diff --git a/_test/tests/inc/parser/lexer.test.php b/_test/tests/inc/parser/lexer.test.php new file mode 100644 index 0000000000..9b914fbd4c --- /dev/null +++ b/_test/tests/inc/parser/lexer.test.php @@ -0,0 +1,531 @@ +assertFalse($regex->match("Hello", $match)); + $this->assertEquals($match, ""); + } + function testNoSubject() { + $regex = new Doku_LexerParallelRegex(false); + $regex->addPattern(".*"); + $this->assertTrue($regex->match("", $match)); + $this->assertEquals($match, ""); + } + function testMatchAll() { + $regex = new Doku_LexerParallelRegex(false); + $regex->addPattern(".*"); + $this->assertTrue($regex->match("Hello", $match)); + $this->assertEquals($match, "Hello"); + } + function testCaseSensitive() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("abc"); + $this->assertTrue($regex->match("abcdef", $match)); + $this->assertEquals($match, "abc"); + $this->assertTrue($regex->match("AAABCabcdef", $match)); + $this->assertEquals($match, "abc"); + } + function testCaseInsensitive() { + $regex = new Doku_LexerParallelRegex(false); + $regex->addPattern("abc"); + $this->assertTrue($regex->match("abcdef", $match)); + $this->assertEquals($match, "abc"); + $this->assertTrue($regex->match("AAABCabcdef", $match)); + $this->assertEquals($match, "ABC"); + } + function testMatchMultiple() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("abc"); + $regex->addPattern("ABC"); + $this->assertTrue($regex->match("abcdef", $match)); + $this->assertEquals($match, "abc"); + $this->assertTrue($regex->match("AAABCabcdef", $match)); + $this->assertEquals($match, "ABC"); + $this->assertFalse($regex->match("Hello", $match)); + } + function testPatternLabels() { + $regex = new Doku_LexerParallelRegex(false); + $regex->addPattern("abc", "letter"); + $regex->addPattern("123", "number"); + $this->assertEquals($regex->match("abcdef", $match), "letter"); + $this->assertEquals($match, "abc"); + $this->assertEquals($regex->match("0123456789", $match), "number"); + $this->assertEquals($match, "123"); + } + function testMatchMultipleWithLookaheadNot() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("abc"); + $regex->addPattern("ABC"); + $regex->addPattern("a(?!\n).{1}"); + $this->assertTrue($regex->match("abcdef", $match)); + $this->assertEquals($match, "abc"); + $this->assertTrue($regex->match("AAABCabcdef", $match)); + $this->assertEquals($match, "ABC"); + $this->assertTrue($regex->match("a\nab", $match)); + $this->assertEquals($match, "ab"); + $this->assertFalse($regex->match("Hello", $match)); + } + function testMatchSetOptionCaseless() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("a(?i)b(?i)c"); + $this->assertTrue($regex->match("aBc", $match)); + $this->assertEquals($match, "aBc"); + } + function testMatchSetOptionUngreedy() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("(?U)\w+"); + $this->assertTrue($regex->match("aaaaaa", $match)); + $this->assertEquals($match, "a"); + } + function testMatchLookaheadEqual() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("\w(?=c)"); + $this->assertTrue($regex->match("xbyczd", $match)); + $this->assertEquals($match, "y"); + } + function testMatchLookaheadNot() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("\w(?!b|c)"); + $this->assertTrue($regex->match("xbyczd", $match)); + $this->assertEquals($match, "b"); + } + function testMatchLookbehindEqual() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("(?<=c)\w"); + $this->assertTrue($regex->match("xbyczd", $match)); + $this->assertEquals($match, "z"); + } + function testMatchLookbehindNot() { + $regex = new Doku_LexerParallelRegex(true); + $regex->addPattern("(?assertTrue($regex->match("xbyczd", $match)); + $this->assertEquals($match, "c"); + } +} + + +class TestOfLexerStateStack extends DokuWikiTest { + function testStartState() { + $stack = new Doku_LexerStateStack("one"); + $this->assertEquals($stack->getCurrent(), "one"); + } + function testExhaustion() { + $stack = new Doku_LexerStateStack("one"); + $this->assertFalse($stack->leave()); + } + function testStateMoves() { + $stack = new Doku_LexerStateStack("one"); + $stack->enter("two"); + $this->assertEquals($stack->getCurrent(), "two"); + $stack->enter("three"); + $this->assertEquals($stack->getCurrent(), "three"); + $this->assertTrue($stack->leave()); + $this->assertEquals($stack->getCurrent(), "two"); + $stack->enter("third"); + $this->assertEquals($stack->getCurrent(), "third"); + $this->assertTrue($stack->leave()); + $this->assertTrue($stack->leave()); + $this->assertEquals($stack->getCurrent(), "one"); + } +} + +class TestParser { + function TestParser() { + } + function accept() { + } + function a() { + } + function b() { + } +} + +class TestOfLexer extends DokuWikiTest { + function testNoPatterns() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->never())->method('accept'); + $lexer = new Doku_Lexer($handler); + $this->assertFalse($lexer->parse("abcdef")); + } + function testEmptyPage() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->never())->method('accept'); + $lexer = new Doku_Lexer($handler); + $lexer->addPattern("a+"); + $this->assertTrue($lexer->parse("")); + } + function testSinglePattern() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->at(0))->method('accept') + ->with("aaa", DOKU_LEXER_MATCHED, 0)->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('accept') + ->with("x", DOKU_LEXER_UNMATCHED, 3)->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('accept') + ->with("a", DOKU_LEXER_MATCHED, 4)->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('accept') + ->with("yyy", DOKU_LEXER_UNMATCHED, 5)->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('accept') + ->with("a", DOKU_LEXER_MATCHED, 8)->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('accept') + ->with("x", DOKU_LEXER_UNMATCHED, 9)->will($this->returnValue(true)); + $handler->expects($this->at(6))->method('accept') + ->with("aaa", DOKU_LEXER_MATCHED, 10)->will($this->returnValue(true)); + $handler->expects($this->at(7))->method('accept') + ->with("z", DOKU_LEXER_UNMATCHED, 13)->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler); + $lexer->addPattern("a+"); + $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); + } + function testMultiplePattern() { + $handler = $this->getMock('TestParser', array('accept')); + $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); + $positions = array(0, 1, 2, 3, 5, 6, 7, 8, 14, 15); + for ($i = 0; $i < count($target); $i++) { + $handler->expects($this->at($i))->method('accept') + ->with($target[$i], $this->anything(), $positions[$i])->will($this->returnValue(true)); + } + $lexer = new Doku_Lexer($handler); + $lexer->addPattern("a+"); + $lexer->addPattern("b+"); + $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); + } +} + +class TestOfLexerModes extends DokuWikiTest { + function testIsolatedPattern() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->at(0))->method('a') + ->with("a", DOKU_LEXER_MATCHED,0)->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('a') + ->with("b", DOKU_LEXER_UNMATCHED,1)->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,2)->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('a') + ->with("bxb", DOKU_LEXER_UNMATCHED,4)->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('a') + ->with("aaa", DOKU_LEXER_MATCHED,7)->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('a') + ->with("x", DOKU_LEXER_UNMATCHED,10)->will($this->returnValue(true)); + $handler->expects($this->at(6))->method('a') + ->with("aaaa", DOKU_LEXER_MATCHED,11)->will($this->returnValue(true)); + $handler->expects($this->at(7))->method('a') + ->with("x", DOKU_LEXER_UNMATCHED,15)->will($this->returnValue(true)); + $lexer = new Doku_Lexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addPattern("b+", "b"); + $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); + } + function testModeChange() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->at(0))->method('a') + ->with("a", DOKU_LEXER_MATCHED,0)->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('a') + ->with("b", DOKU_LEXER_UNMATCHED,1)->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,2)->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('a') + ->with("b", DOKU_LEXER_UNMATCHED,4)->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('a') + ->with("aaa", DOKU_LEXER_MATCHED,5)->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('b') + ->with(":", DOKU_LEXER_ENTER,8)->will($this->returnValue(true)); + $handler->expects($this->at(6))->method('b') + ->with("a", DOKU_LEXER_UNMATCHED,9)->will($this->returnValue(true)); + $handler->expects($this->at(7))->method('b') + ->with("b", DOKU_LEXER_MATCHED, 10)->will($this->returnValue(true)); + $handler->expects($this->at(8))->method('b') + ->with("a", DOKU_LEXER_UNMATCHED,11)->will($this->returnValue(true)); + $handler->expects($this->at(9))->method('b') + ->with("bb", DOKU_LEXER_MATCHED,12)->will($this->returnValue(true)); + $handler->expects($this->at(10))->method('b') + ->with("a", DOKU_LEXER_UNMATCHED,14)->will($this->returnValue(true)); + $handler->expects($this->at(11))->method('b') + ->with("bbb", DOKU_LEXER_MATCHED,15)->will($this->returnValue(true)); + $handler->expects($this->at(12))->method('b') + ->with("a", DOKU_LEXER_UNMATCHED,18)->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addEntryPattern(":", "a", "b"); + $lexer->addPattern("b+", "b"); + $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); + } + function testNesting() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->at(0))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,0)->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('a') + ->with("b", DOKU_LEXER_UNMATCHED,2)->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,3)->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('a') + ->with("b", DOKU_LEXER_UNMATCHED,5)->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('b') + ->with("(", DOKU_LEXER_ENTER,6)->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('b') + ->with("bb", DOKU_LEXER_MATCHED,7)->will($this->returnValue(true)); + $handler->expects($this->at(6))->method('b') + ->with("a", DOKU_LEXER_UNMATCHED,9)->will($this->returnValue(true)); + $handler->expects($this->at(7))->method('b') + ->with("bb", DOKU_LEXER_MATCHED,10)->will($this->returnValue(true)); + $handler->expects($this->at(8))->method('b') + ->with(")", DOKU_LEXER_EXIT,12)->will($this->returnValue(true)); + $handler->expects($this->at(9))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,13)->will($this->returnValue(true)); + $handler->expects($this->at(10))->method('a') + ->with("b", DOKU_LEXER_UNMATCHED,15)->will($this->returnValue(true)); + + + $lexer = new Doku_Lexer($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 = $this->getMock('TestParser'); + $handler->expects($this->at(0))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,0)->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('b') + ->with("b", DOKU_LEXER_SPECIAL,2)->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,3)->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('a') + ->with("xx", DOKU_LEXER_UNMATCHED,5)->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('b') + ->with("bbb", DOKU_LEXER_SPECIAL,7)->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('a') + ->with("xx", DOKU_LEXER_UNMATCHED,10)->will($this->returnValue(true)); + $lexer = new Doku_Lexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addSpecialPattern("b+", "a", "b"); + $this->assertTrue($lexer->parse("aabaaxxbbbxx")); + } + function testUnwindTooFar() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->at(0))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,0)->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('a') + ->with(")", DOKU_LEXER_EXIT,2)->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, "a"); + $lexer->addPattern("a+", "a"); + $lexer->addExitPattern(")", "a"); + $this->assertFalse($lexer->parse("aa)aa")); + } +} + +class TestOfLexerHandlers extends DokuWikiTest { + function testModeMapping() { + $handler = $this->getMock('TestParser'); + $handler->expects($this->at(0))->method('a') + ->with("aa", DOKU_LEXER_MATCHED,0)->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('a') + ->with("(", DOKU_LEXER_ENTER,2)->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('a') + ->with("bb", DOKU_LEXER_MATCHED,3)->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('a') + ->with("a", DOKU_LEXER_UNMATCHED,5)->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('a') + ->with("bb", DOKU_LEXER_MATCHED,6)->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('a') + ->with(")", DOKU_LEXER_EXIT,8)->will($this->returnValue(true)); + $handler->expects($this->at(6))->method('a') + ->with("b", DOKU_LEXER_UNMATCHED,9)->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($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 TestParserByteIndex { + + function TestParserByteIndex() {} + + function ignore() {} + + function caught() {} +} + +class TestOfLexerByteIndices extends DokuWikiTest { + + function testIndex() { + $doc = "aaabcdeee"; + + $handler = $this->getMock('TestParserByteIndex'); + $handler->expects($this->any())->method('ignore')->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('caught') + ->with("", DOKU_LEXER_ENTER, strpos($doc,''))->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('caught') + ->with("b", DOKU_LEXER_SPECIAL, strpos($doc,'b'))->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('caught') + ->with("c", DOKU_LEXER_MATCHED, strpos($doc,'c'))->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('caught') + ->with("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d'))->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('caught') + ->with("", DOKU_LEXER_EXIT, strpos($doc,''))->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, "ignore"); + $lexer->addEntryPattern("", "ignore", "caught"); + $lexer->addExitPattern("", "caught"); + $lexer->addSpecialPattern('b','caught','special'); + $lexer->mapHandler('special','caught'); + $lexer->addPattern('c','caught'); + + $this->assertTrue($lexer->parse($doc)); + } + + function testIndexLookaheadEqual() { + $doc = "aaabcdeee"; + + $handler = $this->getMock('TestParserByteIndex'); + $handler->expects($this->any())->method('ignore')->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('caught') + ->with("", DOKU_LEXER_ENTER, strpos($doc,''))->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('caught') + ->with("b", DOKU_LEXER_SPECIAL, strpos($doc,'b'))->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('caught') + ->with("c", DOKU_LEXER_MATCHED, strpos($doc,'c'))->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('caught') + ->with("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d'))->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('caught') + ->with("", DOKU_LEXER_EXIT, strpos($doc,''))->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, "ignore"); + $lexer->addEntryPattern('(?=.*)', "ignore", "caught"); + $lexer->addExitPattern("
", "caught"); + $lexer->addSpecialPattern('b','caught','special'); + $lexer->mapHandler('special','caught'); + $lexer->addPattern('c','caught'); + + $this->assertTrue($lexer->parse($doc)); + } + + function testIndexLookaheadNotEqual() { + $doc = "aaabcdeee"; + + $handler = $this->getMock('TestParserByteIndex'); + $handler->expects($this->any())->method('ignore')->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('caught') + ->with("", DOKU_LEXER_ENTER, strpos($doc,''))->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('caught') + ->with("b", DOKU_LEXER_SPECIAL, strpos($doc,'b'))->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('caught') + ->with("c", DOKU_LEXER_MATCHED, strpos($doc,'c'))->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('caught') + ->with("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d'))->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('caught') + ->with("", DOKU_LEXER_EXIT, strpos($doc,''))->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, "ignore"); + $lexer->addEntryPattern('(?!foo)', "ignore", "caught"); + $lexer->addExitPattern("", "caught"); + $lexer->addSpecialPattern('b','caught','special'); + $lexer->mapHandler('special','caught'); + $lexer->addPattern('c','caught'); + + $this->assertTrue($lexer->parse($doc)); + } + + function testIndexLookbehindEqual() { + $doc = "aaabcdeee"; + + $handler = $this->getMock('TestParserByteIndex'); + $handler->expects($this->any())->method('ignore')->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('caught') + ->with("", DOKU_LEXER_ENTER, strpos($doc,''))->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('caught') + ->with("b", DOKU_LEXER_SPECIAL, strpos($doc,'b'))->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('caught') + ->with("c", DOKU_LEXER_MATCHED, strpos($doc,'c'))->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('caught') + ->with("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d'))->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('caught') + ->with("", DOKU_LEXER_EXIT, strpos($doc,''))->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, "ignore"); + $lexer->addEntryPattern('', "ignore", "caught"); + $lexer->addExitPattern("(?<=d)", "caught"); + $lexer->addSpecialPattern('b','caught','special'); + $lexer->mapHandler('special','caught'); + $lexer->addPattern('c','caught'); + + $this->assertTrue($lexer->parse($doc)); + } + + function testIndexLookbehindNotEqual() { + $doc = "aaabcdeee"; + + $handler = $this->getMock('TestParserByteIndex'); + $handler->expects($this->any())->method('ignore')->will($this->returnValue(true)); + $handler->expects($this->at(1))->method('caught') + ->with("", DOKU_LEXER_ENTER, strpos($doc,''))->will($this->returnValue(true)); + $handler->expects($this->at(2))->method('caught') + ->with("b", DOKU_LEXER_SPECIAL, strpos($doc,'b'))->will($this->returnValue(true)); + $handler->expects($this->at(3))->method('caught') + ->with("c", DOKU_LEXER_MATCHED, strpos($doc,'c'))->will($this->returnValue(true)); + $handler->expects($this->at(4))->method('caught') + ->with("d", DOKU_LEXER_UNMATCHED, strpos($doc,'d'))->will($this->returnValue(true)); + $handler->expects($this->at(5))->method('caught') + ->with("", DOKU_LEXER_EXIT, strpos($doc,''))->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, 'ignore'); + $lexer->addEntryPattern('', 'ignore', 'caught'); + $lexer->addExitPattern('(?', 'caught'); + $lexer->addSpecialPattern('b','caught','special'); + $lexer->mapHandler('special','caught'); + $lexer->addPattern('c','caught'); + + $this->assertTrue($lexer->parse($doc)); + } + + /** + * This test is primarily to ensure the correct match is chosen + * when there are non-captured elements in the pattern. + */ + function testIndexSelectCorrectMatch() { + $doc = "ALL FOOLS ARE FOO"; + $pattern = '\bFOO\b'; + + $handler = $this->getMock('TestParserByteIndex'); + $handler->expects($this->any())->method('ignore')->will($this->returnValue(true)); + + $matches = array(); + preg_match('/'.$pattern.'/',$doc,$matches,PREG_OFFSET_CAPTURE); + + $handler->expects($this->once())->method('caught') + ->with("FOO", DOKU_LEXER_SPECIAL, $matches[0][1])->will($this->returnValue(true)); + + $lexer = new Doku_Lexer($handler, "ignore"); + $lexer->addSpecialPattern($pattern,'ignore','caught'); + + $this->assertTrue($lexer->parse($doc)); + } + +} + +?> diff --git a/_test/cases/inc/parser/parser.inc.php b/_test/tests/inc/parser/parser.inc.php similarity index 79% rename from _test/cases/inc/parser/parser.inc.php rename to _test/tests/inc/parser/parser.inc.php index 74d956f431..06c314ac67 100644 --- a/_test/cases/inc/parser/parser.inc.php +++ b/_test/tests/inc/parser/parser.inc.php @@ -15,23 +15,15 @@ require_once DOKU_INC . 'inc/events.php'; require_once DOKU_INC . 'inc/mail.php'; -//require_once DOKU . 'parser/renderer.php'; - -//Mock::generate('Doku_Renderer'); - /** * @package Doku * @subpackage Tests */ -class TestOfDoku_Parser extends UnitTestCase { +abstract class TestOfDoku_Parser extends PHPUnit_Framework_TestCase { var $P; var $H; - function TestOfDoku_Parser() { - $this->UnitTestCase('TestOfDoku_Parser'); - } - function setup() { $this->P = new Doku_Parser(); $this->H = new Doku_Handler(); diff --git a/_test/cases/inc/parser/parser_eol.test.php b/_test/tests/inc/parser/parser_eol.test.php similarity index 83% rename from _test/cases/inc/parser/parser_eol.test.php rename to _test/tests/inc/parser/parser_eol.test.php index 692882c6c6..03569bb623 100644 --- a/_test/cases/inc/parser/parser_eol.test.php +++ b/_test/tests/inc/parser/parser_eol.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Eol extends TestOfDoku_Parser { - function TestOfDoku_Parser_Eol() { - $this->UnitTestCase('TestOfDoku_Parser_Eol'); - } - function testEol() { $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); $this->P->parse("Foo\nBar"); @@ -17,7 +13,7 @@ function testEol() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testEolMultiple() { @@ -33,7 +29,7 @@ function testEolMultiple() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testWinEol() { @@ -46,7 +42,7 @@ function testWinEol() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testLinebreak() { @@ -61,7 +57,7 @@ function testLinebreak() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testLinebreakPlusEol() { @@ -80,7 +76,7 @@ function testLinebreakPlusEol() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testLinebreakInvalid() { @@ -93,7 +89,7 @@ function testLinebreakInvalid() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_footnote.test.php b/_test/tests/inc/parser/parser_footnote.test.php similarity index 90% rename from _test/cases/inc/parser/parser_footnote.test.php rename to _test/tests/inc/parser/parser_footnote.test.php index e3571d8e77..f3b5ddf56b 100644 --- a/_test/cases/inc/parser/parser_footnote.test.php +++ b/_test/tests/inc/parser/parser_footnote.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { - function TestOfDoku_Parser_Footnote() { - $this->UnitTestCase('TestOfDoku_Parser_Footnote'); - } - function setup() { parent::setup(); $this->P->addMode('footnote',new Doku_Parser_Mode_Footnote()); @@ -27,7 +23,7 @@ function testFootnote() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testNotAFootnote() { @@ -39,7 +35,7 @@ function testNotAFootnote() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteLinefeed() { @@ -58,7 +54,7 @@ function testFootnoteLinefeed() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteNested() { @@ -76,7 +72,7 @@ function testFootnoteNested() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteEol() { @@ -95,7 +91,7 @@ function testFootnoteEol() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteStrong() { @@ -118,7 +114,7 @@ function testFootnoteStrong() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteHr() { @@ -139,7 +135,7 @@ function testFootnoteHr() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteCode() { @@ -160,7 +156,7 @@ function testFootnoteCode() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnotePreformatted() { @@ -181,7 +177,7 @@ function testFootnotePreformatted() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnotePreformattedEol() { @@ -204,7 +200,7 @@ function testFootnotePreformattedEol() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteUnformatted() { @@ -225,7 +221,7 @@ function testFootnoteUnformatted() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteNotHeader() { @@ -244,7 +240,7 @@ function testFootnoteNotHeader() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteTable() { @@ -290,7 +286,7 @@ function testFootnoteTable() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteList() { @@ -332,7 +328,7 @@ function testFootnoteList() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteQuote() { @@ -361,7 +357,7 @@ function testFootnoteQuote() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testFootnoteNesting() { @@ -386,7 +382,7 @@ function testFootnoteNesting() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_headers.test.php b/_test/tests/inc/parser/parser_headers.test.php similarity index 88% rename from _test/cases/inc/parser/parser_headers.test.php rename to _test/tests/inc/parser/parser_headers.test.php index 688bac2ebb..d7e5f0e42b 100644 --- a/_test/cases/inc/parser/parser_headers.test.php +++ b/_test/tests/inc/parser/parser_headers.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { - function TestOfDoku_Parser_Headers() { - $this->UnitTestCase('TestOfDoku_Parser_Headers'); - } - function testHeader1() { $this->P->addMode('header',new Doku_Parser_Mode_Header()); $this->P->parse("abc \n ====== Header ====== \n def"); @@ -23,7 +19,7 @@ function testHeader1() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeader2() { @@ -42,7 +38,7 @@ function testHeader2() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeader3() { @@ -61,7 +57,7 @@ function testHeader3() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeader4() { @@ -80,7 +76,7 @@ function testHeader4() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeader5() { @@ -99,7 +95,7 @@ function testHeader5() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeader2UnevenSmaller() { @@ -118,7 +114,7 @@ function testHeader2UnevenSmaller() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeader2UnevenBigger() { @@ -137,7 +133,7 @@ function testHeader2UnevenBigger() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeaderLarge() { @@ -156,7 +152,7 @@ function testHeaderLarge() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeaderSmall() { @@ -169,7 +165,7 @@ function testHeaderSmall() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } @@ -189,7 +185,7 @@ function testHeader1Mixed() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeader5Mixed() { @@ -208,7 +204,7 @@ function testHeader5Mixed() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testHeaderMultiline() { @@ -227,7 +223,7 @@ function testHeaderMultiline() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } # function testNoToc() { @@ -253,7 +249,7 @@ function testHeader1Eol() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } @@ -279,7 +275,7 @@ function testHeaderMulti2() { array('section_close',array()), array('document_end',array()) ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_i18n.test.php b/_test/tests/inc/parser/parser_i18n.test.php similarity index 91% rename from _test/cases/inc/parser/parser_i18n.test.php rename to _test/tests/inc/parser/parser_i18n.test.php index 27ec3c78bc..096f2e227c 100644 --- a/_test/cases/inc/parser/parser_i18n.test.php +++ b/_test/tests/inc/parser/parser_i18n.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_i18n extends TestOfDoku_Parser { - function TestOfDoku_Parser_i18n() { - $this->UnitTestCase('TestOfDoku_Parser_i18n'); - } - function testFormatting() { $formats = array ( 'strong', 'emphasis', 'underline', 'monospace', @@ -51,7 +47,7 @@ function testFormatting() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testHeader() { @@ -70,7 +66,7 @@ function testHeader() { array('section_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testTable() { @@ -114,7 +110,7 @@ function testTable() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testAcronym() { @@ -130,7 +126,7 @@ function testAcronym() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testInterwiki() { @@ -145,7 +141,7 @@ function testInterwiki() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInternalLink() { @@ -160,7 +156,7 @@ function testInternalLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_links.test.php b/_test/tests/inc/parser/parser_links.test.php similarity index 87% rename from _test/cases/inc/parser/parser_links.test.php rename to _test/tests/inc/parser/parser_links.test.php index d0fb19570b..529efac6e6 100644 --- a/_test/cases/inc/parser/parser_links.test.php +++ b/_test/tests/inc/parser/parser_links.test.php @@ -3,11 +3,6 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { - function TestOfDoku_Parser_Links() { - $this->UnitTestCase('TestOfDoku_Parser_Links'); - } - - function testExternalLinkSimple() { $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); $this->P->parse("Foo http://www.google.com Bar"); @@ -20,7 +15,7 @@ function testExternalLinkSimple() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testExternalLinkCase() { @@ -35,7 +30,7 @@ function testExternalLinkCase() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testExternalIPv4() { @@ -50,7 +45,7 @@ function testExternalIPv4() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testExternalIPv6() { @@ -65,7 +60,7 @@ function testExternalIPv6() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testExternalMulti(){ @@ -95,8 +90,6 @@ function testExternalMulti(){ $source = "[[$link|$title]]"; $name = $title; } - $this->signal('failinfo',$source); - $this->setup(); $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); @@ -110,7 +103,7 @@ function testExternalMulti(){ array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls), $calls, $source); $this->teardown(); } } @@ -128,7 +121,7 @@ function testExternalLinkJavascript() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testExternalWWWLink() { @@ -143,7 +136,7 @@ function testExternalWWWLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testExternalFTPLink() { @@ -158,7 +151,7 @@ function testExternalFTPLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testEmail() { $this->P->addMode('emaillink',new Doku_Parser_Mode_Emaillink()); @@ -172,7 +165,7 @@ function testEmail() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testEmailRFC2822() { @@ -187,7 +180,7 @@ function testEmailRFC2822() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testEmailCase() { @@ -202,7 +195,7 @@ function testEmailCase() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } @@ -218,7 +211,7 @@ function testInternalLinkOneChar() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInternalLinkNoChar() { @@ -233,7 +226,7 @@ function testInternalLinkNoChar() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInternalLinkNamespaceNoTitle() { @@ -248,7 +241,7 @@ function testInternalLinkNamespaceNoTitle() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInternalLinkNamespace() { @@ -263,7 +256,7 @@ function testInternalLinkNamespace() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInternalLinkSectionRef() { @@ -278,7 +271,7 @@ function testInternalLinkSectionRef() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testExternalInInternalLink() { @@ -293,7 +286,7 @@ function testExternalInInternalLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInterwikiLink() { @@ -308,7 +301,7 @@ function testInterwikiLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInterwikiLinkCase() { @@ -323,7 +316,7 @@ function testInterwikiLinkCase() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testInterwikiPedia() { @@ -338,7 +331,7 @@ function testInterwikiPedia() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testCamelCase() { @@ -353,7 +346,7 @@ function testCamelCase() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testFileLink() { @@ -368,7 +361,7 @@ function testFileLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testFileLinkInternal() { @@ -383,7 +376,7 @@ function testFileLinkInternal() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testWindowsShareLink() { @@ -398,7 +391,7 @@ function testWindowsShareLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testWindowsShareLinkHyphen() { @@ -413,7 +406,7 @@ function testWindowsShareLinkHyphen() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testWindowsShareLinkInternal() { @@ -428,7 +421,7 @@ function testWindowsShareLinkInternal() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInternal() { @@ -443,7 +436,7 @@ function testMediaInternal() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInternalLinkOnly() { @@ -458,7 +451,7 @@ function testMediaInternalLinkOnly() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaNotImage() { @@ -473,7 +466,7 @@ function testMediaNotImage() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInternalLAlign() { @@ -488,7 +481,7 @@ function testMediaInternalLAlign() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInternalRAlign() { @@ -503,7 +496,7 @@ function testMediaInternalRAlign() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInternalCenter() { @@ -518,7 +511,7 @@ function testMediaInternalCenter() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInternalParams() { @@ -533,7 +526,7 @@ function testMediaInternalParams() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInternalTitle() { @@ -548,7 +541,7 @@ function testMediaInternalTitle() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaExternal() { @@ -563,7 +556,7 @@ function testMediaExternal() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaExternalParams() { @@ -578,7 +571,7 @@ function testMediaExternalParams() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaExternalTitle() { @@ -594,7 +587,7 @@ function testMediaExternalTitle() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInInternalLink() { @@ -621,7 +614,7 @@ function testMediaInInternalLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaNoImageInInternalLink() { @@ -648,7 +641,7 @@ function testMediaNoImageInInternalLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testMediaInEmailLink() { @@ -675,7 +668,7 @@ function testMediaInEmailLink() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } function testNestedMedia() { @@ -691,7 +684,7 @@ function testNestedMedia() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_lists.test.php b/_test/tests/inc/parser/parser_lists.test.php similarity index 92% rename from _test/cases/inc/parser/parser_lists.test.php rename to _test/tests/inc/parser/parser_lists.test.php index 6e61da1a14..e4ef1f83e5 100644 --- a/_test/cases/inc/parser/parser_lists.test.php +++ b/_test/tests/inc/parser/parser_lists.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { - function TestOfDoku_Parser_Lists() { - $this->UnitTestCase('TestOfDoku_Parser_Lists'); - } - function testUnorderedList() { $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); $this->P->parse(' @@ -37,7 +33,7 @@ function testUnorderedList() { array('listu_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testOrderedList() { @@ -70,7 +66,7 @@ function testOrderedList() { array('listo_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } @@ -104,7 +100,7 @@ function testMixedList() { array('listo_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testUnorderedListWinEOL() { @@ -133,7 +129,7 @@ function testUnorderedListWinEOL() { array('listu_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testOrderedListWinEOL() { @@ -162,7 +158,7 @@ function testOrderedListWinEOL() { array('listo_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testNotAList() { @@ -175,7 +171,7 @@ function testNotAList() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testUnorderedListParagraph() { @@ -215,7 +211,7 @@ function testUnorderedListParagraph() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } // This is really a failing test - formatting able to spread across list items @@ -250,7 +246,7 @@ function testUnorderedListStrong() { array('listu_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } // This is really a failing test - unformatted able to spread across list items @@ -281,7 +277,7 @@ function testUnorderedListUnformatted() { array('listu_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testUnorderedListLinebreak() { @@ -317,7 +313,7 @@ function testUnorderedListLinebreak() { array('listu_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testUnorderedListLinebreak2() { @@ -344,7 +340,7 @@ function testUnorderedListLinebreak2() { array('listu_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testUnorderedListFootnote() { @@ -391,7 +387,7 @@ function testUnorderedListFootnote() { array('document_end',array()) ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_preformatted.test.php b/_test/tests/inc/parser/parser_preformatted.test.php similarity index 88% rename from _test/cases/inc/parser/parser_preformatted.test.php rename to _test/tests/inc/parser/parser_preformatted.test.php index 7a00f3599a..f7a01a7e58 100644 --- a/_test/cases/inc/parser/parser_preformatted.test.php +++ b/_test/tests/inc/parser/parser_preformatted.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { - function TestOfDoku_Parser_Preformatted() { - $this->UnitTestCase('TestOfDoku_Parser_Preformatted'); - } - function testFile() { $this->P->addMode('file',new Doku_Parser_Mode_File()); $this->P->parse('Foo testing Bar'); @@ -22,7 +18,7 @@ function testFile() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testCode() { @@ -39,7 +35,7 @@ function testCode() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testCodeWhitespace() { @@ -56,7 +52,7 @@ function testCodeWhitespace() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testCodeLang() { @@ -73,7 +69,7 @@ function testCodeLang() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testPreformatted() { @@ -90,7 +86,7 @@ function testPreformatted() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testPreformattedWinEOL() { @@ -107,7 +103,7 @@ function testPreformattedWinEOL() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testPreformattedTab() { @@ -124,7 +120,7 @@ function testPreformattedTab() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testPreformattedTabWinEOL() { @@ -141,7 +137,7 @@ function testPreformattedTabWinEOL() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testPreformattedList() { @@ -173,7 +169,7 @@ function testPreformattedList() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } // test for php @@ -190,7 +186,7 @@ function testPHP() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } // test with for HTML @@ -207,7 +203,7 @@ function testHTML() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } @@ -229,7 +225,7 @@ function testPreformattedPlusHeaderAndEol() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_quote.test.php b/_test/tests/inc/parser/parser_quote.test.php similarity index 87% rename from _test/cases/inc/parser/parser_quote.test.php rename to _test/tests/inc/parser/parser_quote.test.php index ebc5da6044..4d77f2a39e 100644 --- a/_test/cases/inc/parser/parser_quote.test.php +++ b/_test/tests/inc/parser/parser_quote.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Quote extends TestOfDoku_Parser { - function TestOfDoku_Parser_Quote() { - $this->UnitTestCase('TestOfDoku_Parser_Quote'); - } - function testQuote() { $this->P->addMode('quote',new Doku_Parser_Mode_Quote()); $this->P->parse("abc\n> def\n>>ghi\nklm"); @@ -27,7 +23,7 @@ function testQuote() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testQuoteWinCr() { @@ -50,7 +46,7 @@ function testQuoteWinCr() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testQuoteMinumumContext() { @@ -67,7 +63,7 @@ function testQuoteMinumumContext() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testQuoteEol() { @@ -91,7 +87,7 @@ function testQuoteEol() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_quotes.test.php b/_test/tests/inc/parser/parser_quotes.test.php similarity index 86% rename from _test/cases/inc/parser/parser_quotes.test.php rename to _test/tests/inc/parser/parser_quotes.test.php index 77e323799e..b2dae1039a 100644 --- a/_test/cases/inc/parser/parser_quotes.test.php +++ b/_test/tests/inc/parser/parser_quotes.test.php @@ -9,10 +9,6 @@ function setup() { $conf['typography'] = 2; } - function TestOfDoku_Parser_Quotes() { - $this->UnitTestCase('TestOfDoku_Parser_Quotes'); - } - function testSingleQuoteOpening() { $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); $this->P->parse("Foo 'hello Bar"); @@ -27,7 +23,7 @@ function testSingleQuoteOpening() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleQuoteOpeningSpecial() { @@ -44,7 +40,7 @@ function testSingleQuoteOpeningSpecial() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleQuoteClosing() { @@ -61,7 +57,7 @@ function testSingleQuoteClosing() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleQuoteClosingSpecial() { @@ -78,7 +74,7 @@ function testSingleQuoteClosingSpecial() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleQuotes() { @@ -97,7 +93,7 @@ function testSingleQuotes() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testApostrophe() { @@ -114,7 +110,7 @@ function testApostrophe() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } @@ -134,7 +130,7 @@ function testSingleQuotesSpecial() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testDoubleQuoteOpening() { @@ -151,7 +147,7 @@ function testDoubleQuoteOpening() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testDoubleQuoteOpeningSpecial() { @@ -168,7 +164,7 @@ function testDoubleQuoteOpeningSpecial() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testDoubleQuoteClosing() { @@ -185,7 +181,7 @@ function testDoubleQuoteClosing() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testDoubleQuoteClosingSpecial() { @@ -202,7 +198,7 @@ function testDoubleQuoteClosingSpecial() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testDoubleQuotes() { @@ -221,7 +217,7 @@ function testDoubleQuotes() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testDoubleQuotesSpecial() { @@ -240,7 +236,7 @@ function testDoubleQuotesSpecial() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testAllQuotes() { @@ -266,7 +262,7 @@ function testAllQuotes() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_replacements.test.php b/_test/tests/inc/parser/parser_replacements.test.php similarity index 86% rename from _test/cases/inc/parser/parser_replacements.test.php rename to _test/tests/inc/parser/parser_replacements.test.php index d277560c74..f0367dac05 100644 --- a/_test/cases/inc/parser/parser_replacements.test.php +++ b/_test/tests/inc/parser/parser_replacements.test.php @@ -3,11 +3,6 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { - function TestOfDoku_Parser_Replacements() { - $this->UnitTestCase('TestOfDoku_Parser_Replacements'); - } - - function testSingleAcronym() { $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym(array('FOOBAR'))); $this->P->parse('abc FOOBAR xyz'); @@ -22,7 +17,7 @@ function testSingleAcronym() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testAlmostAnAcronym() { @@ -37,7 +32,7 @@ function testAlmostAnAcronym() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testPickAcronymCorrectly() { @@ -54,7 +49,7 @@ function testPickAcronymCorrectly() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultipleAcronyms() { @@ -73,7 +68,7 @@ function testMultipleAcronyms() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } @@ -97,7 +92,7 @@ function testMultipleAcronymsWithSubset1() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultipleAcronymsWithSubset2() { @@ -120,7 +115,7 @@ function testMultipleAcronymsWithSubset2() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleSmileyFail() { @@ -135,7 +130,7 @@ function testSingleSmileyFail() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleSmiley() { @@ -152,7 +147,7 @@ function testSingleSmiley() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultipleSmileysFail() { @@ -167,7 +162,7 @@ function testMultipleSmileysFail() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultipleSmileys() { @@ -186,7 +181,7 @@ function testMultipleSmileys() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testBackslashSmileyFail() { @@ -202,7 +197,7 @@ function testBackslashSmileyFail() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testBackslashSmiley() { @@ -220,7 +215,7 @@ function testBackslashSmiley() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleWordblock() { @@ -237,7 +232,7 @@ function testSingleWordblock() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testWordblockCase() { @@ -254,7 +249,7 @@ function testWordblockCase() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultipleWordblock() { @@ -273,7 +268,7 @@ function testMultipleWordblock() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testSingleEntity() { @@ -290,7 +285,7 @@ function testSingleEntity() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultipleEntities() { @@ -309,7 +304,7 @@ function testMultipleEntities() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultiplyEntity() { @@ -326,7 +321,7 @@ function testMultiplyEntity() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testMultiplyEntityHex() { @@ -342,7 +337,7 @@ function testMultiplyEntityHex() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testHR() { @@ -360,7 +355,7 @@ function testHR() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testHREol() { @@ -378,7 +373,7 @@ function testHREol() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_table.test.php b/_test/tests/inc/parser/parser_table.test.php similarity index 95% rename from _test/cases/inc/parser/parser_table.test.php rename to _test/tests/inc/parser/parser_table.test.php index 12898860cd..96789c38c9 100644 --- a/_test/cases/inc/parser/parser_table.test.php +++ b/_test/tests/inc/parser/parser_table.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Table extends TestOfDoku_Parser { - function TestOfDoku_Parser_Table() { - $this->UnitTestCase('TestOfDoku_Parser_Table'); - } - function testTable() { $this->P->addMode('table',new Doku_Parser_Mode_Table()); $this->P->parse(' @@ -48,7 +44,7 @@ function testTable() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testTableWinEOL() { @@ -88,7 +84,7 @@ function testTableWinEOL() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testEmptyTable() { @@ -113,7 +109,7 @@ function testEmptyTable() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testTableHeaders() { @@ -147,7 +143,7 @@ function testTableHeaders() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } @@ -182,7 +178,7 @@ function testCellAlignment() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testCellSpan() { @@ -224,7 +220,7 @@ function testCellSpan() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testCellRowSpan() { @@ -272,7 +268,7 @@ function testCellRowSpan() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testCellAlignmentFormatting() { @@ -311,7 +307,7 @@ function testCellAlignmentFormatting() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } @@ -357,7 +353,7 @@ function testTableEol() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } // This is really a failing test - formatting able to spread across cols @@ -412,7 +408,7 @@ function testTableStrong() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } // This is really a failing test - unformatted able to spread across cols @@ -463,7 +459,7 @@ function testTableUnformatted() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } function testTableLinebreak() { @@ -511,7 +507,7 @@ function testTableLinebreak() { array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } // This is really a failing test - footnote able to spread across cols @@ -570,7 +566,7 @@ function testTableFootnote() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripbyteindex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parser/parser_unformatted.test.php b/_test/tests/inc/parser/parser_unformatted.test.php similarity index 80% rename from _test/cases/inc/parser/parser_unformatted.test.php rename to _test/tests/inc/parser/parser_unformatted.test.php index dd69564b44..7608cfd1cb 100644 --- a/_test/cases/inc/parser/parser_unformatted.test.php +++ b/_test/tests/inc/parser/parser_unformatted.test.php @@ -3,10 +3,6 @@ class TestOfDoku_Parser_Unformatted extends TestOfDoku_Parser { - function TestOfDoku_Parser_Unformatted() { - $this->UnitTestCase('TestOfDoku_Parser_Unformatted'); - } - function testNowiki() { $this->P->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); $this->P->parse("Foo testing Bar"); @@ -20,7 +16,7 @@ function testNowiki() { array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } @@ -36,7 +32,7 @@ function testDoublePercent() { array('p_close',array()), array('document_end',array()), ); - $this->assertEqual(array_map('stripByteIndex',$this->H->calls),$calls); + $this->assertEquals(array_map('stripByteIndex',$this->H->calls),$calls); } } diff --git a/_test/cases/inc/parserutils_set_metadata_during_rendering.test.php b/_test/tests/inc/parserutils_set_metadata_during_rendering.test.php similarity index 86% rename from _test/cases/inc/parserutils_set_metadata_during_rendering.test.php rename to _test/tests/inc/parserutils_set_metadata_during_rendering.test.php index 8319da2983..66371509c7 100644 --- a/_test/cases/inc/parserutils_set_metadata_during_rendering.test.php +++ b/_test/tests/inc/parserutils_set_metadata_during_rendering.test.php @@ -2,7 +2,7 @@ require_once DOKU_INC.'inc/init.php'; -class parserutils_set_metadata_during_rendering_test extends UnitTestCase { +class parserutils_set_metadata_during_rendering_test extends DokuWikiTest { // the id used for this test case private $id; // if the test case is currently running @@ -35,15 +35,15 @@ function test_p_set_metadata_during_rendering() { $plugin_controller = $this->plugin_controller; // assert that all three calls to p_set_metadata have been successful - $this->assertEqual($newMeta['test_before_set'], 'test'); - $this->assertEqual($newMeta['test_after_set'], 'test'); - $this->assertEqual($newMeta['test_during_rendering'], 'test'); + $this->assertEquals($newMeta['test_before_set'], 'test'); + $this->assertEquals($newMeta['test_after_set'], 'test'); + $this->assertEquals($newMeta['test_during_rendering'], 'test'); // clean up $this->active = false; // make sure the saved metadata is the one that has been rendered - $this->assertEqual($newMeta, p_get_metadata($this->id)); + $this->assertEquals($newMeta, p_get_metadata($this->id)); saveWikiText($this->id, '', 'Test data remove'); } @@ -55,7 +55,7 @@ function helper_set_metadata($event, $meta) { $key = array_pop(array_keys($meta)); $this->assertTrue(is_string($meta[$key])); // ensure we really have a key // ensure that the metadata property hasn't been set previously - $this->assertNotEqual($meta[$key], p_get_metadata($this->id, $key)); + $this->assertNotEquals($meta[$key], p_get_metadata($this->id, $key)); } } @@ -71,7 +71,7 @@ function render($format, &$renderer, $data) { $key = 'test_during_rendering'; p_set_metadata($this->id, array($key => 'test'), false, true); // ensure that the metadata property hasn't been set previously - $this->assertNotEqual($key, p_get_metadata($this->id, $key)); + $this->assertNotEquals($key, p_get_metadata($this->id, $key)); } } diff --git a/_test/cases/inc/remote.test.php b/_test/tests/inc/remote.test.php similarity index 81% rename from _test/cases/inc/remote.test.php rename to _test/tests/inc/remote.test.php index f03d13ce14..5dc8682959 100644 --- a/_test/cases/inc/remote.test.php +++ b/_test/tests/inc/remote.test.php @@ -4,8 +4,6 @@ require_once DOKU_INC . 'inc/RemoteAPICore.php'; require_once DOKU_INC . 'inc/auth/basic.class.php'; -Mock::generate('Doku_Plugin_Controller'); - class MockAuth extends auth_basic { function isCaseSensitive() { return true; } } @@ -116,7 +114,7 @@ function publicCall() {return true;} } -class remote_test extends UnitTestCase { +class remote_test extends DokuWikiTest { var $originalConf; var $userinfo; @@ -130,9 +128,11 @@ function setUp() { global $auth; parent::setUp(); - $pluginManager = new MockDoku_Plugin_Controller(); - $pluginManager->setReturnValue('getList', array('testplugin')); - $pluginManager->setReturnValue('load', new remote_plugin_testplugin()); + + $pluginManager = $this->getMock('Doku_Plugin_Controller'); + $pluginManager->expects($this->any())->method('getList')->will($this->returnValue(array('testplugin'))); + $pluginManager->expects($this->any())->method('load')->will($this->returnValue(new remote_plugin_testplugin())); + $plugin_controller = $pluginManager; $this->originalConf = $conf; @@ -160,7 +160,7 @@ function test_pluginMethods() { sort($actual); $expect = array('plugin.testplugin.method1', 'plugin.testplugin.method2', 'plugin.testplugin.methodString', 'plugin.testplugin.method2ext', 'plugin.testplugin.publicCall'); sort($expect); - $this->assertEqual($expect,$actual); + $this->assertEquals($expect,$actual); } function test_hasAccessSuccess() { @@ -213,10 +213,12 @@ function test_forceAccessSuccess() { $this->remote->forceAccess(); // no exception should occur } + /** + * @expectedException RemoteException + */ function test_forceAccessFail() { global $conf; $conf['remote'] = 0; - $this->expectException('RemoteException'); $this->remote->forceAccess(); } @@ -226,21 +228,23 @@ function test_generalCoreFunctionWithoutArguments() { $remoteApi = new RemoteApi(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); - $this->assertEqual($remoteApi->call('wiki.stringTestMethod'), 'success'); - $this->assertEqual($remoteApi->call('wiki.intTestMethod'), 42); - $this->assertEqual($remoteApi->call('wiki.floatTestMethod'), 3.14159265); - $this->assertEqual($remoteApi->call('wiki.dateTestMethod'), 2623452346); - $this->assertEqual($remoteApi->call('wiki.fileTestMethod'), 'file content'); - $this->assertEqual($remoteApi->call('wiki.voidTestMethod'), null); + $this->assertEquals($remoteApi->call('wiki.stringTestMethod'), 'success'); + $this->assertEquals($remoteApi->call('wiki.intTestMethod'), 42); + $this->assertEquals($remoteApi->call('wiki.floatTestMethod'), 3.14159265); + $this->assertEquals($remoteApi->call('wiki.dateTestMethod'), 2623452346); + $this->assertEquals($remoteApi->call('wiki.fileTestMethod'), 'file content'); + $this->assertEquals($remoteApi->call('wiki.voidTestMethod'), null); } + /** + * @expectedException RemoteException + */ function test_generalCoreFunctionOnArgumentMismatch() { global $conf; $conf['remote'] = 1; $remoteApi = new RemoteApi(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); - $this->expectException('RemoteException'); $remoteApi->call('wiki.voidTestMethod', array('something')); } @@ -251,10 +255,10 @@ function test_generalCoreFunctionWithArguments() { $remoteApi = new RemoteApi(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); - $this->assertEqual($remoteApi->call('wiki.oneStringArgMethod', array('string')), 'string'); - $this->assertEqual($remoteApi->call('wiki.twoArgMethod', array('string', 1)), array('string' , 1)); - $this->assertEqual($remoteApi->call('wiki.twoArgWithDefaultArg', array('string')), array('string', 'default')); - $this->assertEqual($remoteApi->call('wiki.twoArgWithDefaultArg', array('string', 'another')), array('string', 'another')); + $this->assertEquals($remoteApi->call('wiki.oneStringArgMethod', array('string')), 'string'); + $this->assertEquals($remoteApi->call('wiki.twoArgMethod', array('string', 1)), array('string' , 1)); + $this->assertEquals($remoteApi->call('wiki.twoArgWithDefaultArg', array('string')), array('string', 'default')); + $this->assertEquals($remoteApi->call('wiki.twoArgWithDefaultArg', array('string', 'another')), array('string', 'another')); } function test_pluginCallMethods() { @@ -262,18 +266,20 @@ function test_pluginCallMethods() { $conf['remote'] = 1; $remoteApi = new RemoteApi(); - $this->assertEqual($remoteApi->call('plugin.testplugin.method1'), null); - $this->assertEqual($remoteApi->call('plugin.testplugin.method2', array('string', 7)), array('string', 7, false)); - $this->assertEqual($remoteApi->call('plugin.testplugin.method2ext', array('string', 7, true)), array('string', 7, true)); - $this->assertEqual($remoteApi->call('plugin.testplugin.methodString'), 'success'); + $this->assertEquals($remoteApi->call('plugin.testplugin.method1'), null); + $this->assertEquals($remoteApi->call('plugin.testplugin.method2', array('string', 7)), array('string', 7, false)); + $this->assertEquals($remoteApi->call('plugin.testplugin.method2ext', array('string', 7, true)), array('string', 7, true)); + $this->assertEquals($remoteApi->call('plugin.testplugin.methodString'), 'success'); } + /** + * @expectedException RemoteException + */ function test_notExistingCall() { global $conf; $conf['remote'] = 1; $remoteApi = new RemoteApi(); - $this->expectException('RemoteException'); $remoteApi->call('dose not exist'); } @@ -292,20 +298,24 @@ function test_publicCallPlugin() { $this->assertTrue($remoteApi->call('plugin.testplugin.publicCall')); } + /** + * @expectedException RemoteAccessDeniedException + */ function test_publicCallCoreDeny() { global $conf; $conf['useacl'] = 1; $remoteApi = new RemoteApi(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); - $this->expectException('RemoteAccessDeniedException'); $remoteApi->call('wiki.stringTestMethod'); } + /** + * @expectedException RemoteAccessDeniedException + */ function test_publicCallPluginDeny() { global $conf; $conf['useacl'] = 1; $remoteApi = new RemoteApi(); - $this->expectException('RemoteAccessDeniedException'); $remoteApi->call('plugin.testplugin.methodString'); } @@ -315,7 +325,7 @@ function test_pluginCallCustomPath() { $remoteApi = new RemoteAPI(); $result = $remoteApi->call('custom.path'); - $this->assertEqual($result, 'success'); + $this->assertEquals($result, 'success'); } function pluginCallCustomPathRegister(&$event, $param) { diff --git a/_test/cases/inc/safefn.test.php b/_test/tests/inc/safefn.test.php similarity index 89% rename from _test/cases/inc/safefn.test.php rename to _test/tests/inc/safefn.test.php index 1227e55783..78e08fec65 100644 --- a/_test/cases/inc/safefn.test.php +++ b/_test/tests/inc/safefn.test.php @@ -4,7 +4,7 @@ require_once DOKU_INC.'inc/utf8.php'; require_once DOKU_INC.'inc/SafeFN.class.php'; -class safeFN_test extends UnitTestCase { +class safeFN_test extends DokuWikiTest { function test1(){ @@ -30,8 +30,8 @@ function test1(){ foreach($tests as $test){ list($utf8,$safe) = $test; - $this->assertEqual(SafeFN::encode($utf8),$safe); - $this->assertEqual(SafeFN::decode($safe),$utf8); + $this->assertEquals(SafeFN::encode($utf8),$safe); + $this->assertEquals(SafeFN::decode($safe),$utf8); } } @@ -40,7 +40,7 @@ function test2(){ foreach($tests as $test){ list($utf8,$safe) = $test; - $this->assertEqual(SafeFN::decode($safe),$utf8); + $this->assertEquals(SafeFN::decode($safe),$utf8); } } diff --git a/_test/tests/inc/search/data/ns1/ns3/page3.txt b/_test/tests/inc/search/data/ns1/ns3/page3.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/tests/inc/search/data/ns1/page1.txt b/_test/tests/inc/search/data/ns1/page1.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/tests/inc/search/data/ns1/page2.txt b/_test/tests/inc/search/data/ns1/page2.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/tests/inc/search/data/ns2/nopage.ext b/_test/tests/inc/search/data/ns2/nopage.ext new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/tests/inc/search/data/ns2/page1.txt b/_test/tests/inc/search/data/ns2/page1.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/_test/cases/inc/search/search.test.php b/_test/tests/inc/search/search.test.php similarity index 92% rename from _test/cases/inc/search/search.test.php rename to _test/tests/inc/search/search.test.php index a6f15e9b68..f7ea469b91 100644 --- a/_test/cases/inc/search/search.test.php +++ b/_test/tests/inc/search/search.test.php @@ -1,7 +1,7 @@ 'ns2')); - $this->assertEqual(array_map(array($this, 'strip_index_data'), $data), + $this->assertEquals(array_map(array($this, 'strip_index_data'), $data), array( array( 'id' => 'ns1', @@ -35,7 +35,7 @@ function test_search_index(){ $data = array(); search($data, dirname(__FILE__) . '/data', 'search_index', array('ns' => 'ns1/ns3')); - $this->assertEqual(array_map(array($this, 'strip_index_data'), $data), + $this->assertEquals(array_map(array($this, 'strip_index_data'), $data), array( array( 'id' => 'ns1', @@ -76,7 +76,7 @@ function test_search_index(){ $data = array(); search($data, dirname(__FILE__) . '/data', 'search_index', array('ns' => 'ns1/ns3', 'nofiles' => true)); - $this->assertEqual(array_map(array($this, 'strip_index_data'), $data), + $this->assertEquals(array_map(array($this, 'strip_index_data'), $data), array( array( 'id' => 'ns1', diff --git a/_test/cases/inc/utf8_correctidx.test.php b/_test/tests/inc/utf8_correctidx.test.php similarity index 86% rename from _test/cases/inc/utf8_correctidx.test.php rename to _test/tests/inc/utf8_correctidx.test.php index 20f6ba3a38..5c37627b6a 100644 --- a/_test/cases/inc/utf8_correctidx.test.php +++ b/_test/tests/inc/utf8_correctidx.test.php @@ -3,7 +3,7 @@ if(!defined('UTF8_NOMBSTRING')) define('UTF8_NOMBSTRING',1); require_once DOKU_INC.'inc/utf8.php'; -class utf8_correctidx_test extends UnitTestCase { +class utf8_correctidx_test extends DokuWikiTest { function test_singlebyte(){ @@ -16,7 +16,7 @@ function test_singlebyte(){ $tests[] = array('aaживπά우리をあöä',1,true,1); foreach($tests as $test){ - $this->assertEqual(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); + $this->assertEquals(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); } } @@ -34,7 +34,7 @@ function test_twobyte(){ $tests[] = array('aaживπά우리をあöä',4,true,4); foreach($tests as $test){ - $this->assertEqual(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); + $this->assertEquals(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); } } @@ -54,7 +54,7 @@ function test_threebyte(){ $tests[] = array('aaживπά우리をあöä',13,true,13); foreach($tests as $test){ - $this->assertEqual(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); + $this->assertEquals(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); } } @@ -70,7 +70,7 @@ function test_bounds(){ $tests[] = array('aaживπά우리をあöä',128,true,29); foreach($tests as $test){ - $this->assertEqual(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); + $this->assertEquals(utf8_correctIdx($test[0],$test[1],$test[2]),$test[3]); } } diff --git a/_test/cases/inc/utf8_html.test.php b/_test/tests/inc/utf8_html.test.php similarity index 66% rename from _test/cases/inc/utf8_html.test.php rename to _test/tests/inc/utf8_html.test.php index 3e6d35bc72..94acc6d6c2 100644 --- a/_test/cases/inc/utf8_html.test.php +++ b/_test/tests/inc/utf8_html.test.php @@ -5,66 +5,66 @@ // use no mbstring help here if(!defined('UTF8_NOMBSTRING')) define('UTF8_NOMBSTRING',1); -class utf8_html_test extends UnitTestCase { +class utf8_html_test extends DokuWikiTest { function test_from_1byte(){ $in = 'a'; $out = 'a'; - $this->assertEqual(utf8_tohtml($in),$out); + $this->assertEquals(utf8_tohtml($in),$out); } function test_from_2byte(){ $in = "\xc3\xbc"; $out = 'ü'; - $this->assertEqual(utf8_tohtml($in),$out); + $this->assertEquals(utf8_tohtml($in),$out); } function test_from_3byte(){ $in = "\xe2\x99\x8a"; $out = '♊'; - $this->assertEqual(utf8_tohtml($in),$out); + $this->assertEquals(utf8_tohtml($in),$out); } function test_from_4byte(){ $in = "\xf4\x80\x80\x81"; $out = '􀀁'; - $this->assertEqual(utf8_tohtml($in),$out); + $this->assertEquals(utf8_tohtml($in),$out); } function test_to_1byte(){ $out = 'a'; $in = 'a'; - $this->assertEqual(utf8_unhtml($in),$out); + $this->assertEquals(utf8_unhtml($in),$out); } function test_to_2byte(){ $out = "\xc3\xbc"; $in = 'ü'; - $this->assertEqual(utf8_unhtml($in),$out); + $this->assertEquals(utf8_unhtml($in),$out); } function test_to_3byte(){ $out = "\xe2\x99\x8a"; $in = '♊'; - $this->assertEqual(utf8_unhtml($in),$out); + $this->assertEquals(utf8_unhtml($in),$out); } function test_to_4byte(){ $out = "\xf4\x80\x80\x81"; $in = '􀀁'; - $this->assertEqual(utf8_unhtml($in),$out); + $this->assertEquals(utf8_unhtml($in),$out); } function test_without_entities(){ $out = '&#38;&#38;'; $in = '&#38;&amp;#38;'; - $this->assertEqual(utf8_unhtml($in),$out); + $this->assertEquals(utf8_unhtml($in),$out); } function test_with_entities(){ $out = '&&#38;'; $in = '&#38;&amp;#38;'; - $this->assertEqual(utf8_unhtml($in,HTML_ENTITIES),$out); + $this->assertEquals(utf8_unhtml($in,HTML_ENTITIES),$out); } } diff --git a/_test/cases/inc/utf8_kanaromaji.txt b/_test/tests/inc/utf8_kanaromaji.txt similarity index 100% rename from _test/cases/inc/utf8_kanaromaji.txt rename to _test/tests/inc/utf8_kanaromaji.txt diff --git a/_test/cases/inc/utf8_romanize.test.php b/_test/tests/inc/utf8_romanize.test.php similarity index 72% rename from _test/cases/inc/utf8_romanize.test.php rename to _test/tests/inc/utf8_romanize.test.php index 950c8842a4..d08346faae 100644 --- a/_test/cases/inc/utf8_romanize.test.php +++ b/_test/tests/inc/utf8_romanize.test.php @@ -1,9 +1,11 @@ \t$chk\t!=\t$rom\t($line)\n"; - $this->assertEqual($chk,$rom); + $this->assertEquals($rom,$chk,"$jap\t->\t$chk\t!=\t$rom\t($line)"); $line++; } } @@ -30,7 +31,7 @@ function test_japanese(){ * @author Andreas Gohr */ function test_deaccented(){ - $this->assertEqual("a A a A a o O",utf8_romanize("å Å ä Ä ä ö Ö")); + $this->assertEquals("a A a A a o O",utf8_romanize("å Å ä Ä ä ö Ö")); } } //Setup VIM: ex: et ts=4 : diff --git a/_test/cases/inc/utf8_stripspecials.test.php b/_test/tests/inc/utf8_stripspecials.test.php similarity index 87% rename from _test/cases/inc/utf8_stripspecials.test.php rename to _test/tests/inc/utf8_stripspecials.test.php index 481f476506..532430b603 100644 --- a/_test/cases/inc/utf8_stripspecials.test.php +++ b/_test/tests/inc/utf8_stripspecials.test.php @@ -3,7 +3,7 @@ if(!defined('UTF8_NOMBSTRING')) define('UTF8_NOMBSTRING',1); require_once DOKU_INC.'inc/utf8.php'; -class utf8_stripspecials extends UnitTestCase { +class utf8_stripspecials extends DokuWikiTest { function test1(){ @@ -20,7 +20,7 @@ function test1(){ $tests[] = array('string with nbsps','_','\*','string_with_nbsps'); foreach($tests as $test){ - $this->assertEqual(utf8_stripspecials($test[0],$test[1],$test[2]),$test[3]); + $this->assertEquals(utf8_stripspecials($test[0],$test[1],$test[2]),$test[3]); } } diff --git a/_test/cases/inc/utf8_substr.test.php b/_test/tests/inc/utf8_substr.test.php similarity index 86% rename from _test/cases/inc/utf8_substr.test.php rename to _test/tests/inc/utf8_substr.test.php index 2806d34f10..19eea4eb4e 100644 --- a/_test/cases/inc/utf8_substr.test.php +++ b/_test/tests/inc/utf8_substr.test.php @@ -3,7 +3,7 @@ if(!defined('UTF8_NOMBSTRING')) define('UTF8_NOMBSTRING',1); require_once DOKU_INC.'inc/utf8.php'; -class utf8_substr_test extends UnitTestCase { +class utf8_substr_test extends DokuWikiTest { function test1(){ @@ -22,7 +22,7 @@ function test1(){ $tests[] = array('живπά우리をあöä',-6,-2,'우리をあ'); foreach($tests as $test){ - $this->assertEqual(utf8_substr($test[0],$test[1],$test[2]),$test[3]); + $this->assertEquals(utf8_substr($test[0],$test[1],$test[2]),$test[3]); } } @@ -35,7 +35,7 @@ function test2_bug891() { $tests[] = array($str,0,66002,$str); foreach($tests as $test){ - $this->assertEqual(utf8_substr($test[0],$test[1],$test[2]),$test[3]); + $this->assertEquals(utf8_substr($test[0],$test[1],$test[2]),$test[3]); } } diff --git a/_test/cases/inc/utf8_unicode.test.php b/_test/tests/inc/utf8_unicode.test.php similarity index 65% rename from _test/cases/inc/utf8_unicode.test.php rename to _test/tests/inc/utf8_unicode.test.php index 424f47d11e..a34fec86de 100644 --- a/_test/cases/inc/utf8_unicode.test.php +++ b/_test/tests/inc/utf8_unicode.test.php @@ -5,54 +5,54 @@ // use no mbstring help here if(!defined('UTF8_NOMBSTRING')) define('UTF8_NOMBSTRING',1); -class utf8_unicode_test extends UnitTestCase { +class utf8_unicode_test extends DokuWikiTest { function test_from_1byte(){ $in = 'a'; $out = array(97); - $this->assertEqual(utf8_to_unicode($in),$out); + $this->assertEquals(utf8_to_unicode($in),$out); } function test_from_2byte(){ $in = "\xc3\xbc"; $out = array(252); - $this->assertEqual(utf8_to_unicode($in),$out); + $this->assertEquals(utf8_to_unicode($in),$out); } function test_from_3byte(){ $in = "\xe2\x99\x8a"; $out = array(9802); - $this->assertEqual(utf8_to_unicode($in),$out); + $this->assertEquals(utf8_to_unicode($in),$out); } function test_from_4byte(){ $in = "\xf4\x80\x80\x81"; $out = array(1048577); - $this->assertEqual(utf8_to_unicode($in),$out); + $this->assertEquals(utf8_to_unicode($in),$out); } function test_to_1byte(){ $out = 'a'; $in = array(97); - $this->assertEqual(unicode_to_utf8($in),$out); + $this->assertEquals(unicode_to_utf8($in),$out); } function test_to_2byte(){ $out = "\xc3\xbc"; $in = array(252); - $this->assertEqual(unicode_to_utf8($in),$out); + $this->assertEquals(unicode_to_utf8($in),$out); } function test_to_3byte(){ $out = "\xe2\x99\x8a"; $in = array(9802); - $this->assertEqual(unicode_to_utf8($in),$out); + $this->assertEquals(unicode_to_utf8($in),$out); } function test_to_4byte(){ $out = "\xf4\x80\x80\x81"; $in = array(1048577); - $this->assertEqual(unicode_to_utf8($in),$out); + $this->assertEquals(unicode_to_utf8($in),$out); } } diff --git a/_test/cases/inc/utf8_utf16be.test.php b/_test/tests/inc/utf8_utf16be.test.php similarity index 71% rename from _test/cases/inc/utf8_utf16be.test.php rename to _test/tests/inc/utf8_utf16be.test.php index d8b8746f2b..0150a8e4a2 100644 --- a/_test/cases/inc/utf8_utf16be.test.php +++ b/_test/tests/inc/utf8_utf16be.test.php @@ -5,7 +5,7 @@ // use no mbstring help here if(!defined('UTF8_NOMBSTRING')) define('UTF8_NOMBSTRING',1); -class utf8_utf16be_test extends UnitTestCase { +class utf8_utf16be_test extends DokuWikiTest { // some chars from various code regions var $utf8 = '鈩ℵŁöx'; var $utf16 = "\x92\x29\x21\x35\x1\x41\x0\xf6\x0\x78"; @@ -14,14 +14,14 @@ class utf8_utf16be_test extends UnitTestCase { * Convert from UTF-8 to UTF-16BE */ function test_to16be(){ - $this->assertEqual(utf8_to_utf16be($this->utf8), $this->utf16); + $this->assertEquals(utf8_to_utf16be($this->utf8), $this->utf16); } /** * Convert from UTF-16BE to UTF-8 */ function test_from16be(){ - $this->assertEqual(utf16be_to_utf8($this->utf16),$this->utf8); + $this->assertEquals(utf16be_to_utf8($this->utf16),$this->utf8); } } diff --git a/_test/cases/lib/exe/css_css_compress.test.php b/_test/tests/lib/exe/css_css_compress.test.php similarity index 65% rename from _test/cases/lib/exe/css_css_compress.test.php rename to _test/tests/lib/exe/css_css_compress.test.php index 527071bbe8..811b0cee86 100644 --- a/_test/cases/lib/exe/css_css_compress.test.php +++ b/_test/tests/lib/exe/css_css_compress.test.php @@ -3,7 +3,7 @@ require_once DOKU_INC.'lib/exe/css.php'; -class css_css_compress_test extends UnitTestCase { +class css_css_compress_test extends DokuWikiTest { function test_mlcom1(){ $text = '/** @@ -11,33 +11,33 @@ function test_mlcom1(){ * line *test* * check */'; - $this->assertEqual(css_compress($text), ''); + $this->assertEquals(css_compress($text), ''); } function test_mlcom2(){ $text = '#comment/* */ { color: lime; }'; - $this->assertEqual(css_compress($text), '#comment/* */{color:lime;}'); + $this->assertEquals(css_compress($text), '#comment/* */{color:lime;}'); } function test_slcom1(){ $text = '// this is a comment'; - $this->assertEqual(css_compress($text), ''); + $this->assertEquals(css_compress($text), ''); } function test_slcom2(){ $text = '#foo { color: lime; // another comment }'; - $this->assertEqual(css_compress($text), '#foo{color:lime;}'); + $this->assertEquals(css_compress($text), '#foo{color:lime;}'); } function test_slcom3(){ $text = '#foo { background-image: url(http://foo.bar/baz.jpg); }'; - $this->assertEqual(css_compress($text), '#foo{background-image:url(http://foo.bar/baz.jpg);}'); + $this->assertEquals(css_compress($text), '#foo{background-image:url(http://foo.bar/baz.jpg);}'); } function test_hack(){ @@ -45,7 +45,7 @@ function test_hack(){ /* \\*/ display: inline; /* */'; - $this->assertEqual(css_compress($text), '/* \\*/display:inline;/* */'); + $this->assertEquals(css_compress($text), '/* \\*/display:inline;/* */'); } function test_hack2(){ @@ -55,12 +55,12 @@ function test_hack2(){ height: 450px; } /**/'; - $this->assertEqual(css_compress($text), '/*\\*/* html .page{height:450px;}/**/'); + $this->assertEquals(css_compress($text), '/*\\*/* html .page{height:450px;}/**/'); } function test_nl1(){ $text = "a{left:20px;\ntop:20px}"; - $this->assertEqual(css_compress($text), 'a{left:20px;top:20px}'); + $this->assertEquals(css_compress($text), 'a{left:20px;top:20px}'); } } diff --git a/_test/cases/lib/exe/css_css_loadfile.test.php b/_test/tests/lib/exe/css_css_loadfile.test.php similarity index 91% rename from _test/cases/lib/exe/css_css_loadfile.test.php rename to _test/tests/lib/exe/css_css_loadfile.test.php index a444d00866..c89b69b2c5 100644 --- a/_test/cases/lib/exe/css_css_loadfile.test.php +++ b/_test/tests/lib/exe/css_css_loadfile.test.php @@ -2,15 +2,14 @@ require_once DOKU_INC.'lib/exe/css.php'; -class css_css_loadfile_test extends UnitTestCase { +class css_css_loadfile_test extends DokuWikiTest { public function setUp() { $this->file = tempnam('/tmp', 'css'); - parent::setUp(); } private function csstest($input, $output = null, $location = 'http://www.example.com/') { io_saveFile($this->file, $input); - $this->assertEqual(css_loadfile($this->file, $location), (is_null($output) ? $input : $output)); + $this->assertEquals(css_loadfile($this->file, $location), (is_null($output) ? $input : $output)); } public function test_url_relative() { @@ -50,7 +49,6 @@ public function test_import_with_protocol() { public function tearDown() { unlink($this->file); unset($this->file); - parent::tearDown(); } } diff --git a/_test/cases/lib/exe/js_js_compress.test.php b/_test/tests/lib/exe/js_js_compress.test.php similarity index 65% rename from _test/cases/lib/exe/js_js_compress.test.php rename to _test/tests/lib/exe/js_js_compress.test.php index 4702d35d38..75c69c3471 100644 --- a/_test/cases/lib/exe/js_js_compress.test.php +++ b/_test/tests/lib/exe/js_js_compress.test.php @@ -3,7 +3,7 @@ require_once DOKU_INC.'lib/exe/js.php'; -class js_js_compress_test extends UnitTestCase { +class js_js_compress_test extends DokuWikiTest { function test_mlcom1(){ $text = '/** @@ -11,104 +11,104 @@ function test_mlcom1(){ * line *test* * check */'; - $this->assertEqual(js_compress($text), ''); + $this->assertEquals(js_compress($text), ''); } function test_mlcom2(){ $text = 'var foo=6;/* another comment */'; - $this->assertEqual(js_compress($text), 'var foo=6;'); + $this->assertEquals(js_compress($text), 'var foo=6;'); } function test_mlcomcond(){ $text = '/*@if (@_win32)'; - $this->assertEqual(js_compress($text), '/*@if(@_win32)'); + $this->assertEquals(js_compress($text), '/*@if(@_win32)'); } function test_slcom1(){ $text = '// an comment'; - $this->assertEqual(js_compress($text), ''); + $this->assertEquals(js_compress($text), ''); } function test_slcom2(){ $text = 'var foo=6;// another comment '; - $this->assertEqual(js_compress($text), 'var foo=6;'); + $this->assertEquals(js_compress($text), 'var foo=6;'); } function test_slcom3(){ $text = 'var foo=6;// another comment / or something with // comments '; - $this->assertEqual(js_compress($text), 'var foo=6;'); + $this->assertEquals(js_compress($text), 'var foo=6;'); } function test_regex1(){ $text = 'foo.split( /[a-Z\/]*/ );'; - $this->assertEqual(js_compress($text), 'foo.split(/[a-Z\/]*/);'); + $this->assertEquals(js_compress($text), 'foo.split(/[a-Z\/]*/);'); } function test_regex_in_array(){ $text = '[/"/ , /"/ , /"/]'; - $this->assertEqual(js_compress($text), '[/"/,/"/,/"/]'); + $this->assertEquals(js_compress($text), '[/"/,/"/,/"/]'); } function test_regex_in_hash(){ $text = '{ a : /"/ }'; - $this->assertEqual(js_compress($text), '{a:/"/}'); + $this->assertEquals(js_compress($text), '{a:/"/}'); } function test_regex_preceded_by_spaces_caracters(){ $text = "text.replace( \t \r\n /\"/ , ".'"//" )'; - $this->assertEqual(js_compress($text), 'text.replace(/"/,"//")'); + $this->assertEquals(js_compress($text), 'text.replace(/"/,"//")'); } function test_dquot1(){ $text = 'var foo="Now what \\" \'do we//get /*here*/ ?";'; - $this->assertEqual(js_compress($text), $text); + $this->assertEquals(js_compress($text), $text); } function test_dquot2(){ $text = 'var foo="Now what \\\\\\" \'do we//get /*here*/ ?";'; - $this->assertEqual(js_compress($text), $text); + $this->assertEquals(js_compress($text), $text); } function test_dquotrunaway(){ $text = 'var foo="Now where does it end'; - $this->assertEqual(js_compress($text), $text); + $this->assertEquals(js_compress($text), $text); } function test_squot1(){ $text = "var foo='Now what \\' \"do we//get /*here*/ ?';"; - $this->assertEqual(js_compress($text), $text); + $this->assertEquals(js_compress($text), $text); } function test_squotrunaway(){ $text = "var foo='Now where does it end"; - $this->assertEqual(js_compress($text), $text); + $this->assertEquals(js_compress($text), $text); } function test_nl1(){ $text = "var foo=6;\nvar baz=7;"; - $this->assertEqual(js_compress($text), 'var foo=6;var baz=7;'); + $this->assertEquals(js_compress($text), 'var foo=6;var baz=7;'); } function test_lws1(){ $text = " \t var foo=6;"; - $this->assertEqual(js_compress($text), 'var foo=6;'); + $this->assertEquals(js_compress($text), 'var foo=6;'); } function test_tws1(){ $text = "var foo=6; \t "; - $this->assertEqual(js_compress($text), 'var foo=6;'); + $this->assertEquals(js_compress($text), 'var foo=6;'); } function test_shortcond(){ $text = "var foo = (baz) ? 'bar' : 'bla';"; - $this->assertEqual(js_compress($text), "var foo=(baz)?'bar':'bla';"); + $this->assertEquals(js_compress($text), "var foo=(baz)?'bar':'bla';"); } function test_complexminified(){ $text = 'if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;foo="text/*";bla="*/"'; - $this->assertEqual(js_compress($text),$text); + $this->assertEquals(js_compress($text),$text); } /** @@ -119,9 +119,8 @@ function test_original(){ foreach($files as $file){ $info = "Using file $file"; - $this->signal('failinfo',$info); - $this->assertEqual(js_compress(file_get_contents($file)), - file_get_contents(substr($file,0,-5).'out.js')); + $this->assertEquals(js_compress(file_get_contents($file)), + file_get_contents(substr($file,0,-5).'out.js'), $info); }; } } diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-in.js b/_test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-in.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-out.js b/_test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-out.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes1-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-in.js b/_test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-in.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-out.js b/_test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-out.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInDoubleQuotes2-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes1-in.js b/_test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes1-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes1-in.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes1-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes1-out.js b/_test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes1-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes1-out.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes1-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes2-in.js b/_test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes2-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes2-in.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes2-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes2-out.js b/_test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes2-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentInSingleQuotes2-out.js rename to _test/tests/lib/exe/js_js_compress/test-CommentInSingleQuotes2-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentMultiline-in.js b/_test/tests/lib/exe/js_js_compress/test-CommentMultiline-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentMultiline-in.js rename to _test/tests/lib/exe/js_js_compress/test-CommentMultiline-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentMultiline-out.js b/_test/tests/lib/exe/js_js_compress/test-CommentMultiline-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentMultiline-out.js rename to _test/tests/lib/exe/js_js_compress/test-CommentMultiline-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentSingleLine-in.js b/_test/tests/lib/exe/js_js_compress/test-CommentSingleLine-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentSingleLine-in.js rename to _test/tests/lib/exe/js_js_compress/test-CommentSingleLine-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-CommentSingleLine-out.js b/_test/tests/lib/exe/js_js_compress/test-CommentSingleLine-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-CommentSingleLine-out.js rename to _test/tests/lib/exe/js_js_compress/test-CommentSingleLine-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-IfThenElseBraces-in.js b/_test/tests/lib/exe/js_js_compress/test-IfThenElseBraces-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-IfThenElseBraces-in.js rename to _test/tests/lib/exe/js_js_compress/test-IfThenElseBraces-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-IfThenElseBraces-out.js b/_test/tests/lib/exe/js_js_compress/test-IfThenElseBraces-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-IfThenElseBraces-out.js rename to _test/tests/lib/exe/js_js_compress/test-IfThenElseBraces-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-IfThenElseNoBraces-in.js b/_test/tests/lib/exe/js_js_compress/test-IfThenElseNoBraces-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-IfThenElseNoBraces-in.js rename to _test/tests/lib/exe/js_js_compress/test-IfThenElseNoBraces-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-IfThenElseNoBraces-out.js b/_test/tests/lib/exe/js_js_compress/test-IfThenElseNoBraces-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-IfThenElseNoBraces-out.js rename to _test/tests/lib/exe/js_js_compress/test-IfThenElseNoBraces-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpBackslash-in.js b/_test/tests/lib/exe/js_js_compress/test-RegexpBackslash-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpBackslash-in.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpBackslash-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpBackslash-out.js b/_test/tests/lib/exe/js_js_compress/test-RegexpBackslash-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpBackslash-out.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpBackslash-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpSimple-in.js b/_test/tests/lib/exe/js_js_compress/test-RegexpSimple-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpSimple-in.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpSimple-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpSimple-out.js b/_test/tests/lib/exe/js_js_compress/test-RegexpSimple-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpSimple-out.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpSimple-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-in.js b/_test/tests/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-in.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-out.js b/_test/tests/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-out.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpSimpleWhitespace-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpString-in.js b/_test/tests/lib/exe/js_js_compress/test-RegexpString-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpString-in.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpString-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-RegexpString-out.js b/_test/tests/lib/exe/js_js_compress/test-RegexpString-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-RegexpString-out.js rename to _test/tests/lib/exe/js_js_compress/test-RegexpString-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementDoWhile-in.js b/_test/tests/lib/exe/js_js_compress/test-StatementDoWhile-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementDoWhile-in.js rename to _test/tests/lib/exe/js_js_compress/test-StatementDoWhile-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementDoWhile-out.js b/_test/tests/lib/exe/js_js_compress/test-StatementDoWhile-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementDoWhile-out.js rename to _test/tests/lib/exe/js_js_compress/test-StatementDoWhile-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementForIn-in.js b/_test/tests/lib/exe/js_js_compress/test-StatementForIn-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementForIn-in.js rename to _test/tests/lib/exe/js_js_compress/test-StatementForIn-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementForIn-out.js b/_test/tests/lib/exe/js_js_compress/test-StatementForIn-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementForIn-out.js rename to _test/tests/lib/exe/js_js_compress/test-StatementForIn-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementNew-in.js b/_test/tests/lib/exe/js_js_compress/test-StatementNew-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementNew-in.js rename to _test/tests/lib/exe/js_js_compress/test-StatementNew-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementNew-out.js b/_test/tests/lib/exe/js_js_compress/test-StatementNew-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementNew-out.js rename to _test/tests/lib/exe/js_js_compress/test-StatementNew-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementSwitchCase-in.js b/_test/tests/lib/exe/js_js_compress/test-StatementSwitchCase-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementSwitchCase-in.js rename to _test/tests/lib/exe/js_js_compress/test-StatementSwitchCase-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StatementSwitchCase-out.js b/_test/tests/lib/exe/js_js_compress/test-StatementSwitchCase-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StatementSwitchCase-out.js rename to _test/tests/lib/exe/js_js_compress/test-StatementSwitchCase-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StringDoubleQuotes-in.js b/_test/tests/lib/exe/js_js_compress/test-StringDoubleQuotes-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StringDoubleQuotes-in.js rename to _test/tests/lib/exe/js_js_compress/test-StringDoubleQuotes-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StringDoubleQuotes-out.js b/_test/tests/lib/exe/js_js_compress/test-StringDoubleQuotes-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StringDoubleQuotes-out.js rename to _test/tests/lib/exe/js_js_compress/test-StringDoubleQuotes-out.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StringSingleQuotes-in.js b/_test/tests/lib/exe/js_js_compress/test-StringSingleQuotes-in.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StringSingleQuotes-in.js rename to _test/tests/lib/exe/js_js_compress/test-StringSingleQuotes-in.js diff --git a/_test/cases/lib/exe/js_js_compress/test-StringSingleQuotes-out.js b/_test/tests/lib/exe/js_js_compress/test-StringSingleQuotes-out.js similarity index 100% rename from _test/cases/lib/exe/js_js_compress/test-StringSingleQuotes-out.js rename to _test/tests/lib/exe/js_js_compress/test-StringSingleQuotes-out.js diff --git a/_test/tests/test/basic.test.php b/_test/tests/test/basic.test.php new file mode 100644 index 0000000000..b4926d2ba5 --- /dev/null +++ b/_test/tests/test/basic.test.php @@ -0,0 +1,22 @@ +execute(); + + $this->assertTrue( + strpos($response->getContent(), 'DokuWiki') >= 0, + 'DokuWiki was not a word in the output' + ); + } +} diff --git a/_test/tests/test/globals.test.php b/_test/tests/test/globals.test.php new file mode 100644 index 0000000000..180fd0d0d7 --- /dev/null +++ b/_test/tests/test/globals.test.php @@ -0,0 +1,49 @@ +setServer('testvar', true); + + $self = $this; + $EVENT_HANDLER->register_hook('TPL_CONTENT_DISPLAY', 'AFTER', null, + function() use ($self) { + $self->assertTrue($_SERVER['testvar'], 'Server variable not set correctly: testvar'); + $self->assertEquals('87.142.120.6', $_SERVER['REMOTE_ADDR'], 'Server variable not set correctly: REMOTE_ADDR'); + $_SERVER['tmpvar'] = true; + } + ); + + $request->execute(); + } + + /** + * @depends testFirstRun + */ + function testSecondRun() { + global $EVENT_HANDLER; + + $request = new TestRequest(); + $request->setServer('testvar', false); + + $self = $this; + $EVENT_HANDLER->register_hook('TPL_CONTENT_DISPLAY', 'AFTER', null, + function() use ($self) { + $self->assertFalse($_SERVER['testvar'], 'Server variable not set correctly: testvar'); + $self->assertEquals('87.142.120.6', $_SERVER['REMOTE_ADDR'], 'Server variable not set correctly: REMOTE_ADDR'); + $self->assertFalse(isset($_SERVER['tmpvar'])); + } + ); + + $request->execute(); + } +} diff --git a/_test/tests/test/hooks.test.php b/_test/tests/test/hooks.test.php new file mode 100644 index 0000000000..621b9f9b88 --- /dev/null +++ b/_test/tests/test/hooks.test.php @@ -0,0 +1,24 @@ +register_hook('TPL_CONTENT_DISPLAY', 'AFTER', null, + function() use (&$hookTriggered) { + $hookTriggered = true; + } + ); + + $request->execute(); + + $this->assertTrue($hookTriggered, 'Hook was not triggered as expected!'); + } +} diff --git a/_test/tests/test/phpquery.test.php b/_test/tests/test/phpquery.test.php new file mode 100644 index 0000000000..188d834cbf --- /dev/null +++ b/_test/tests/test/phpquery.test.php @@ -0,0 +1,18 @@ +execute(); + + $this->assertEquals('DokuWiki', $response->queryHTML('meta[name="generator"]')->attr('content') ); + } +} diff --git a/_test/tests/test/plugins.test.php b/_test/tests/test/plugins.test.php new file mode 100644 index 0000000000..ac6d1ee45a --- /dev/null +++ b/_test/tests/test/plugins.test.php @@ -0,0 +1,32 @@ +pluginsEnabled = array( + 'testing' + ); + + parent::setUp(); + } + + function testTestingPluginEnabled() { + global $EVENT_HANDLER; + + $request = new TestRequest(); + $hookTriggered = false; + + $EVENT_HANDLER->register_hook('TESTING_PLUGIN_INSTALLED', 'AFTER', null, + function() use (&$hookTriggered) { + $hookTriggered = true; + } + ); + + $request->execute(); + + $this->assertTrue($hookTriggered, 'Testing plugin did not trigger!'); + } +} diff --git a/_test/tests/test/plugins_defaults.test.php b/_test/tests/test/plugins_defaults.test.php new file mode 100644 index 0000000000..953960bb7d --- /dev/null +++ b/_test/tests/test/plugins_defaults.test.php @@ -0,0 +1,24 @@ +register_hook('TESTING_PLUGIN_INSTALLED', 'AFTER', null, + function() use (&$hookTriggered) { + $hookTriggered = true; + } + ); + + $request->execute(); + + $this->assertFalse($hookTriggered, 'Testing plugin did trigger!'); + } +} diff --git a/_test/tests/test/reset.test.php b/_test/tests/test/reset.test.php new file mode 100644 index 0000000000..39c43cd3b5 --- /dev/null +++ b/_test/tests/test/reset.test.php @@ -0,0 +1,38 @@ +register_hook('DOKUWIKI_STARTED', 'AFTER', null, + function() use ($self) { + $self->triggered = true; + } + ); + $request = new TestRequest(); + $request->execute(); + $this->assertTrue($this->triggered); + } + + /** + * @depends testFirstRun + */ + function testSecondRun(){ + global $conf; + $this->assertFalse(isset($conf['foo']), 'conf setting'); + + $request = new TestRequest(); + $request->execute(); + + $this->assertFalse($this->triggered, 'trigger'); + } +} diff --git a/_test/tests/test/scope.test.php b/_test/tests/test/scope.test.php new file mode 100644 index 0000000000..8c4ad9cf81 --- /dev/null +++ b/_test/tests/test/scope.test.php @@ -0,0 +1,49 @@ +execute(); + $this->assertTrue( + strpos($response->getContent(), 'DokuWiki') >= 0, + 'DokuWiki was not a word in the output' + ); + } + + /** + * @depends testFirstRun + */ + function testSecondRun() { + $request = new TestRequest(); + $response = $request->execute(); + $this->assertTrue( + strpos($response->getContent(), 'DokuWiki') >= 0, + 'DokuWiki was not a word in the output' + ); + } + + /** + * two requests within the same test case should be possible + */ + function testMultipleRequests() { + $request = new TestRequest(); + $response = $request->execute(); + $this->assertTrue( + strpos($response->getContent(), 'DokuWiki') >= 0, + 'DokuWiki was not a word in the output' + ); + + $request = new TestRequest(); + $response = $request->execute(); + $this->assertTrue( + strpos($response->getContent(), 'DokuWiki') >= 0, + 'DokuWiki was not a word in the output' + ); + } +} diff --git a/_test/webtest-stripper.sh b/_test/webtest-stripper.sh deleted file mode 100755 index f7991cc0bf..0000000000 --- a/_test/webtest-stripper.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/sh -################################################################################ -# Quick script to make simpletest web test fail output more legible -# -# Run the web test group from the command line w/ the command: -# -# $ ./runtests.php -g [GROUP] 2> tmp -# -# redirecting the error messages to the file tmp -# -# Then run this command on the tmp file -# -# $ ./webtest-stripper.sh tmp -# -################################################################################ - -usage="Usage: ${0} [WEB_TEST_OUTPUT_FILE]"; - -if [ -z "$1" ]; then - echo $usage; - exit 1; -elif [ ! -f "$1" ]; then - echo "${1} is not a file!"; - echo $usage; - exit 1; -fi - -sed -e 's/\\n/\ -/g' "${1}" |\ -sed -e 's/\\//g' |\ -sed -e 's/FAIL.*Pattern \[\#\^/EXPECTED:\ -/g' |\ -sed -e 's/\$#i\].*string \[/\ -\ -GOT:\ -/g' |\ -sed -e 's/\]$/\ -----------------------------------------------------------------\ -/g' - -exit 0 \ No newline at end of file diff --git a/conf/plugins.php b/conf/plugins.php new file mode 100644 index 0000000000..b2c79970d8 --- /dev/null +++ b/conf/plugins.php @@ -0,0 +1,6 @@ + 1073741824). If a higher one is given, the function throws + * an exception. + * + * @link http://www.openwall.com/phpass/ * @param string $clear - the clear text to hash * @param string $salt - the salt to use, null for random * @param string $magic - the hash identifier (P or H) @@ -330,6 +335,12 @@ public function hash_pmd5($clear, $salt=null, $magic='P',$compute=8){ } $iterc = $salt[0]; // pos 0 of salt is iteration count $iter = strpos($itoa64,$iterc); + + if($iter > 30){ + throw new Exception("Too high iteration count ($iter) in ". + __class__.'::'.__function__); + } + $iter = 1 << $iter; $salt = substr($salt,1,8); diff --git a/inc/config_cascade.php b/inc/config_cascade.php index 79567fc56a..e4a3df353b 100644 --- a/inc/config_cascade.php +++ b/inc/config_cascade.php @@ -66,6 +66,7 @@ ), 'plugins' => array( + 'default' => array(DOKU_CONF.'plugins.php'), 'local' => array(DOKU_CONF.'plugins.local.php'), 'protected' => array( DOKU_CONF.'plugins.required.php', diff --git a/inc/events.php b/inc/events.php index 621cb64c1e..09f3f3c0c7 100644 --- a/inc/events.php +++ b/inc/events.php @@ -149,8 +149,8 @@ function Doku_Event_Handler() { * @param $method (function) event handler function * @param $param (mixed) data passed to the event handler */ - function register_hook($event, $advise, &$obj, $method, $param=null) { - $this->_hooks[$event.'_'.$advise][] = array(&$obj, $method, $param); + function register_hook($event, $advise, $obj, $method, $param=null) { + $this->_hooks[$event.'_'.$advise][] = array($obj, $method, $param); } function process_event(&$event,$advise='') { diff --git a/inc/load.php b/inc/load.php index 0572b5760f..9f54034a38 100644 --- a/inc/load.php +++ b/inc/load.php @@ -49,6 +49,7 @@ function load_autoload($name){ static $classes = null; if(is_null($classes)) $classes = array( 'DokuHTTPClient' => DOKU_INC.'inc/HTTPClient.php', + 'HTTPClient' => DOKU_INC.'inc/HTTPClient.php', 'JSON' => DOKU_INC.'inc/JSON.php', 'adLDAP' => DOKU_INC.'inc/adLDAP.php', 'Diff' => DOKU_INC.'inc/DifferenceEngine.php', diff --git a/lib/plugins/testing/_test/dummy_plugin_integration_test.test.php b/lib/plugins/testing/_test/dummy_plugin_integration_test.test.php new file mode 100644 index 0000000000..5982c69335 --- /dev/null +++ b/lib/plugins/testing/_test/dummy_plugin_integration_test.test.php @@ -0,0 +1,32 @@ +pluginsEnabled = array( + 'testing' + ); + + parent::setUp(); + } + + function testTestingPluginEnabled() { + global $EVENT_HANDLER; + + $request = new TestRequest(); + $hookTriggered = false; + + $EVENT_HANDLER->register_hook('TESTING_PLUGIN_INSTALLED', 'AFTER', null, + function() use (&$hookTriggered) { + $hookTriggered = true; + } + ); + + $request->execute(); + + $this->assertTrue($hookTriggered, 'Testing plugin did not trigger!'); + } +} diff --git a/lib/plugins/testing/_test/dummy_plugin_test.test.php b/lib/plugins/testing/_test/dummy_plugin_test.test.php new file mode 100644 index 0000000000..eee825fbde --- /dev/null +++ b/lib/plugins/testing/_test/dummy_plugin_test.test.php @@ -0,0 +1,9 @@ +assertTrue(true, 'wow, you really fucked up'); + } + +} diff --git a/lib/plugins/testing/action.php b/lib/plugins/testing/action.php new file mode 100644 index 0000000000..e829847b6b --- /dev/null +++ b/lib/plugins/testing/action.php @@ -0,0 +1,19 @@ + + */ +class action_plugin_testing extends DokuWiki_Action_Plugin { + function register(&$controller) { + $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'dokuwikiStarted'); + } + + function dokuwikiStarted() { + $param = array(); + trigger_event('TESTING_PLUGIN_INSTALLED', $param); + msg('The testing plugin is enabled and should be disabled.',-1); + } +} diff --git a/lib/plugins/testing/plugin.info.txt b/lib/plugins/testing/plugin.info.txt new file mode 100644 index 0000000000..a514d77744 --- /dev/null +++ b/lib/plugins/testing/plugin.info.txt @@ -0,0 +1,6 @@ +base testing +author Tobias Sarnowski +email tobias@trustedco.de +date 2012-04-24 +name Testing Plugin +desc Used to test the test framework. Should always be disabled.