bootstrap.test 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. <?php
  2. class BootstrapIPAddressTestCase extends DrupalWebTestCase {
  3. protected $oldserver;
  4. protected $remote_ip;
  5. protected $proxy_ip;
  6. protected $proxy2_ip;
  7. protected $forwarded_ip;
  8. protected $cluster_ip;
  9. protected $untrusted_ip;
  10. public static function getInfo() {
  11. return array(
  12. 'name' => 'IP address and HTTP_HOST test',
  13. 'description' => 'Get the IP address from the current visitor from the server variables, check hostname validation.',
  14. 'group' => 'Bootstrap'
  15. );
  16. }
  17. function setUp() {
  18. $this->oldserver = $_SERVER;
  19. $this->remote_ip = '127.0.0.1';
  20. $this->proxy_ip = '127.0.0.2';
  21. $this->proxy2_ip = '127.0.0.3';
  22. $this->forwarded_ip = '127.0.0.4';
  23. $this->cluster_ip = '127.0.0.5';
  24. $this->untrusted_ip = '0.0.0.0';
  25. drupal_static_reset('ip_address');
  26. $_SERVER['REMOTE_ADDR'] = $this->remote_ip;
  27. unset($_SERVER['HTTP_X_FORWARDED_FOR']);
  28. unset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']);
  29. parent::setUp();
  30. }
  31. function tearDown() {
  32. $_SERVER = $this->oldserver;
  33. drupal_static_reset('ip_address');
  34. parent::tearDown();
  35. }
  36. /**
  37. * test IP Address and hostname
  38. */
  39. function testIPAddressHost() {
  40. // Test the normal IP address.
  41. $this->assertTrue(
  42. ip_address() == $this->remote_ip,
  43. 'Got remote IP address.'
  44. );
  45. // Proxy forwarding on but no proxy addresses defined.
  46. variable_set('reverse_proxy', 1);
  47. $this->assertTrue(
  48. ip_address() == $this->remote_ip,
  49. 'Proxy forwarding without trusted proxies got remote IP address.'
  50. );
  51. // Proxy forwarding on and proxy address not trusted.
  52. variable_set('reverse_proxy_addresses', array($this->proxy_ip, $this->proxy2_ip));
  53. drupal_static_reset('ip_address');
  54. $_SERVER['REMOTE_ADDR'] = $this->untrusted_ip;
  55. $this->assertTrue(
  56. ip_address() == $this->untrusted_ip,
  57. 'Proxy forwarding with untrusted proxy got remote IP address.'
  58. );
  59. // Proxy forwarding on and proxy address trusted.
  60. $_SERVER['REMOTE_ADDR'] = $this->proxy_ip;
  61. $_SERVER['HTTP_X_FORWARDED_FOR'] = $this->forwarded_ip;
  62. drupal_static_reset('ip_address');
  63. $this->assertTrue(
  64. ip_address() == $this->forwarded_ip,
  65. 'Proxy forwarding with trusted proxy got forwarded IP address.'
  66. );
  67. // Proxy forwarding on and proxy address trusted and visiting from proxy.
  68. $_SERVER['REMOTE_ADDR'] = $this->proxy_ip;
  69. $_SERVER['HTTP_X_FORWARDED_FOR'] = $this->proxy_ip;
  70. drupal_static_reset('ip_address');
  71. $this->assertTrue(
  72. ip_address() == $this->proxy_ip,
  73. 'Visiting from trusted proxy got proxy IP address.'
  74. );
  75. // Multi-tier architecture with comma separated values in header.
  76. $_SERVER['REMOTE_ADDR'] = $this->proxy_ip;
  77. $_SERVER['HTTP_X_FORWARDED_FOR'] = implode(', ', array($this->untrusted_ip, $this->forwarded_ip, $this->proxy2_ip));
  78. drupal_static_reset('ip_address');
  79. $this->assertTrue(
  80. ip_address() == $this->forwarded_ip,
  81. 'Proxy forwarding with trusted 2-tier proxy got forwarded IP address.'
  82. );
  83. // Custom client-IP header.
  84. variable_set('reverse_proxy_header', 'HTTP_X_CLUSTER_CLIENT_IP');
  85. $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'] = $this->cluster_ip;
  86. drupal_static_reset('ip_address');
  87. $this->assertTrue(
  88. ip_address() == $this->cluster_ip,
  89. 'Cluster environment got cluster client IP.'
  90. );
  91. // Verifies that drupal_valid_http_host() prevents invalid characters.
  92. $this->assertFalse(drupal_valid_http_host('security/.drupal.org:80'), 'HTTP_HOST with / is invalid');
  93. $this->assertFalse(drupal_valid_http_host('security\\.drupal.org:80'), 'HTTP_HOST with \\ is invalid');
  94. $this->assertFalse(drupal_valid_http_host('security<.drupal.org:80'), 'HTTP_HOST with &lt; is invalid');
  95. $this->assertFalse(drupal_valid_http_host('security..drupal.org:80'), 'HTTP_HOST with .. is invalid');
  96. // Verifies that host names are shorter than 1000 characters.
  97. $this->assertFalse(drupal_valid_http_host(str_repeat('x', 1001)), 'HTTP_HOST with more than 1000 characters is invalid.');
  98. $this->assertFalse(drupal_valid_http_host(str_repeat('.', 101)), 'HTTP_HOST with more than 100 subdomains is invalid.');
  99. $this->assertFalse(drupal_valid_http_host(str_repeat(':', 101)), 'HTTP_HOST with more than 100 portseparators is invalid.');
  100. // IPv6 loopback address
  101. $this->assertTrue(drupal_valid_http_host('[::1]:80'), 'HTTP_HOST containing IPv6 loopback is valid');
  102. }
  103. }
  104. class BootstrapPageCacheTestCase extends DrupalWebTestCase {
  105. public static function getInfo() {
  106. return array(
  107. 'name' => 'Page cache test',
  108. 'description' => 'Enable the page cache and test it with various HTTP requests.',
  109. 'group' => 'Bootstrap'
  110. );
  111. }
  112. function setUp() {
  113. parent::setUp('system_test');
  114. }
  115. /**
  116. * Test support for requests containing If-Modified-Since and If-None-Match headers.
  117. */
  118. function testConditionalRequests() {
  119. variable_set('cache', 1);
  120. // Fill the cache.
  121. $this->drupalGet('');
  122. $this->drupalHead('');
  123. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  124. $etag = $this->drupalGetHeader('ETag');
  125. $last_modified = $this->drupalGetHeader('Last-Modified');
  126. $this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified, 'If-None-Match: ' . $etag));
  127. $this->assertResponse(304, 'Conditional request returned 304 Not Modified.');
  128. $this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC822, strtotime($last_modified)), 'If-None-Match: ' . $etag));
  129. $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
  130. $this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC850, strtotime($last_modified)), 'If-None-Match: ' . $etag));
  131. $this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
  132. $this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified));
  133. $this->assertResponse(200, 'Conditional request without If-None-Match returned 200 OK.');
  134. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  135. $this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC7231, strtotime($last_modified) + 1), 'If-None-Match: ' . $etag));
  136. $this->assertResponse(200, 'Conditional request with new a If-Modified-Since date newer than Last-Modified returned 200 OK.');
  137. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  138. $user = $this->drupalCreateUser();
  139. $this->drupalLogin($user);
  140. $this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified, 'If-None-Match: ' . $etag));
  141. $this->assertResponse(200, 'Conditional request returned 200 OK for authenticated user.');
  142. $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Absence of Page was not cached.');
  143. $this->assertFalse($this->drupalGetHeader('ETag'), 'ETag HTTP headers are not present for logged in users.');
  144. $this->assertFalse($this->drupalGetHeader('Last-Modified'), 'Last-Modified HTTP headers are not present for logged in users.');
  145. }
  146. /**
  147. * Test cache headers.
  148. */
  149. function testPageCache() {
  150. variable_set('cache', 1);
  151. // Fill the cache.
  152. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
  153. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  154. $this->assertEqual($this->drupalGetHeader('Vary'), 'Cookie,Accept-Encoding', 'Vary header was sent.');
  155. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'public, max-age=0', 'Cache-Control header was sent.');
  156. $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
  157. $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
  158. // Check cache.
  159. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
  160. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  161. $this->assertEqual($this->drupalGetHeader('Vary'), 'Cookie,Accept-Encoding', 'Vary: Cookie header was sent.');
  162. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'public, max-age=0', 'Cache-Control header was sent.');
  163. $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
  164. $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
  165. $this->assertEqual($this->drupalGetHeader('X-Content-Type-Options'), 'nosniff', 'X-Content-Type-Options header was sent.');
  166. // Check replacing default headers.
  167. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Expires', 'value' => 'Fri, 19 Nov 2008 05:00:00 GMT')));
  168. $this->assertEqual($this->drupalGetHeader('Expires'), 'Fri, 19 Nov 2008 05:00:00 GMT', 'Default header was replaced.');
  169. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Vary', 'value' => 'User-Agent')));
  170. $this->assertEqual($this->drupalGetHeader('Vary'), 'User-Agent,Accept-Encoding', 'Default header was replaced.');
  171. // Check that authenticated users bypass the cache.
  172. $user = $this->drupalCreateUser();
  173. $this->drupalLogin($user);
  174. $this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
  175. $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Caching was bypassed.');
  176. $this->assertTrue(strpos($this->drupalGetHeader('Vary'), 'Cookie') === FALSE, 'Vary: Cookie header was not sent.');
  177. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'no-cache, must-revalidate', 'Cache-Control header was sent.');
  178. $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
  179. $this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
  180. }
  181. /**
  182. * Test page compression.
  183. *
  184. * The test should pass even if zlib.output_compression is enabled in php.ini,
  185. * .htaccess or similar, or if compression is done outside PHP, e.g. by the
  186. * mod_deflate Apache module.
  187. */
  188. function testPageCompression() {
  189. variable_set('cache', 1);
  190. // Fill the cache and verify that output is compressed.
  191. $this->drupalGet('', array(), array('Accept-Encoding: gzip,deflate'));
  192. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  193. $this->drupalSetContent(gzinflate(substr($this->drupalGetContent(), 10, -8)));
  194. $this->assertRaw('</html>', 'Page was gzip compressed.');
  195. // Verify that cached output is compressed.
  196. $this->drupalGet('', array(), array('Accept-Encoding: gzip,deflate'));
  197. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  198. $this->assertEqual($this->drupalGetHeader('Content-Encoding'), 'gzip', 'A Content-Encoding header was sent.');
  199. $this->drupalSetContent(gzinflate(substr($this->drupalGetContent(), 10, -8)));
  200. $this->assertRaw('</html>', 'Page was gzip compressed.');
  201. // Verify that a client without compression support gets an uncompressed page.
  202. $this->drupalGet('');
  203. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  204. $this->assertFalse($this->drupalGetHeader('Content-Encoding'), 'A Content-Encoding header was not sent.');
  205. $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), 'Site title matches.');
  206. $this->assertRaw('</html>', 'Page was not compressed.');
  207. // Verify that an empty page doesn't throw an error when being decompressed.
  208. $this->drupalGet('system-test/empty-page');
  209. // Disable compression mode.
  210. variable_set('page_compression', FALSE);
  211. // Verify if cached page is still available for a client with compression support.
  212. $this->drupalGet('', array(), array('Accept-Encoding: gzip,deflate'));
  213. $this->drupalSetContent(gzinflate(substr($this->drupalGetContent(), 10, -8)));
  214. $this->assertRaw('</html>', 'Page was delivered after compression mode is changed (compression support enabled).');
  215. // Verify if cached page is still available for a client without compression support.
  216. $this->drupalGet('');
  217. $this->assertRaw('</html>', 'Page was delivered after compression mode is changed (compression support disabled).');
  218. }
  219. /**
  220. * Test page cache headers.
  221. */
  222. function testPageCacheHeaders() {
  223. variable_set('cache', 1);
  224. // First request should store a response in the page cache.
  225. $this->drupalGet('system-test/page-cache-headers');
  226. // The test callback should remove the query string leaving the same path
  227. // as the previous request, which we'll try to retrieve from cache_page.
  228. $this->drupalGet('system-test/page-cache-headers', array('query' => array('return_headers' => 'TRUE')));
  229. $headers = json_decode($this->drupalGetHeader('Page-Cache-Headers'), TRUE);
  230. if (is_null($headers)) {
  231. $this->fail('No headers were retrieved from the page cache.');
  232. }
  233. else {
  234. $this->assertEqual($headers['X-Content-Type-Options'], 'nosniff', 'X-Content-Type-Options header retrieved from response in the page cache.');
  235. }
  236. }
  237. }
  238. class BootstrapVariableTestCase extends DrupalWebTestCase {
  239. function setUp() {
  240. parent::setUp('system_test');
  241. }
  242. public static function getInfo() {
  243. return array(
  244. 'name' => 'Variable test',
  245. 'description' => 'Make sure the variable system functions correctly.',
  246. 'group' => 'Bootstrap'
  247. );
  248. }
  249. /**
  250. * testVariable
  251. */
  252. function testVariable() {
  253. // Setting and retrieving values.
  254. $variable = $this->randomName();
  255. variable_set('simpletest_bootstrap_variable_test', $variable);
  256. $this->assertIdentical($variable, variable_get('simpletest_bootstrap_variable_test'), 'Setting and retrieving values');
  257. // Make sure the variable persists across multiple requests.
  258. $this->drupalGet('system-test/variable-get');
  259. $this->assertText($variable, 'Variable persists across multiple requests');
  260. // Deleting variables.
  261. $default_value = $this->randomName();
  262. variable_del('simpletest_bootstrap_variable_test');
  263. $variable = variable_get('simpletest_bootstrap_variable_test', $default_value);
  264. $this->assertIdentical($variable, $default_value, 'Deleting variables');
  265. }
  266. /**
  267. * Makes sure that the default variable parameter is passed through okay.
  268. */
  269. function testVariableDefaults() {
  270. // Tests passing nothing through to the default.
  271. $this->assertIdentical(NULL, variable_get('simpletest_bootstrap_variable_test'), 'Variables are correctly defaulting to NULL.');
  272. // Tests passing 5 to the default parameter.
  273. $this->assertIdentical(5, variable_get('simpletest_bootstrap_variable_test', 5), 'The default variable parameter is passed through correctly.');
  274. }
  275. }
  276. /**
  277. * Tests the auto-loading behavior of the code registry.
  278. */
  279. class BootstrapAutoloadTestCase extends DrupalWebTestCase {
  280. public static function getInfo() {
  281. return array(
  282. 'name' => 'Code registry',
  283. 'description' => 'Test that the code registry functions correctly.',
  284. 'group' => 'Bootstrap',
  285. );
  286. }
  287. function setUp() {
  288. parent::setUp('drupal_autoload_test');
  289. }
  290. /**
  291. * Tests that autoloader name matching is not case sensitive.
  292. */
  293. function testAutoloadCase() {
  294. // Test interface autoloader.
  295. $this->assertTrue(drupal_autoload_interface('drupalautoloadtestinterface'), 'drupal_autoload_interface() recognizes <em>DrupalAutoloadTestInterface</em> in lower case.');
  296. // Test class autoloader.
  297. $this->assertTrue(drupal_autoload_class('drupalautoloadtestclass'), 'drupal_autoload_class() recognizes <em>DrupalAutoloadTestClass</em> in lower case.');
  298. // Test trait autoloader.
  299. if (version_compare(PHP_VERSION, '5.4') >= 0) {
  300. $this->assertTrue(drupal_autoload_trait('drupalautoloadtesttrait'), 'drupal_autoload_trait() recognizes <em>DrupalAutoloadTestTrait</em> in lower case.');
  301. }
  302. }
  303. }
  304. /**
  305. * Test hook_boot() and hook_exit().
  306. */
  307. class HookBootExitTestCase extends DrupalWebTestCase {
  308. public static function getInfo() {
  309. return array(
  310. 'name' => 'Boot and exit hook invocation',
  311. 'description' => 'Test that hook_boot() and hook_exit() are called correctly.',
  312. 'group' => 'Bootstrap',
  313. );
  314. }
  315. function setUp() {
  316. parent::setUp('system_test', 'dblog');
  317. }
  318. /**
  319. * Test calling of hook_boot() and hook_exit().
  320. */
  321. function testHookBootExit() {
  322. // Test with cache disabled. Boot and exit should always fire.
  323. variable_set('cache', 0);
  324. $this->drupalGet('');
  325. $calls = 1;
  326. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot called with disabled cache.'));
  327. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit called with disabled cache.'));
  328. // Test with normal cache. Boot and exit should be called.
  329. variable_set('cache', 1);
  330. $this->drupalGet('');
  331. $calls++;
  332. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot called with normal cache.'));
  333. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit called with normal cache.'));
  334. // Boot and exit should not fire since the page is cached.
  335. variable_set('page_cache_invoke_hooks', FALSE);
  336. $this->assertTrue(cache_get(url('', array('absolute' => TRUE)), 'cache_page'), t('Page has been cached.'));
  337. $this->drupalGet('');
  338. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot not called with aggressive cache and a cached page.'));
  339. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit not called with aggressive cache and a cached page.'));
  340. // Test with page cache cleared, boot and exit should be called.
  341. $this->assertTrue(db_delete('cache_page')->execute(), t('Page cache cleared.'));
  342. $this->drupalGet('');
  343. $calls++;
  344. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_boot'))->fetchField(), $calls, t('hook_boot called with aggressive cache and no cached page.'));
  345. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND message = :message', array(':type' => 'system_test', ':message' => 'hook_exit'))->fetchField(), $calls, t('hook_exit called with aggressive cache and no cached page.'));
  346. }
  347. }
  348. /**
  349. * Test drupal_get_filename()'s availability.
  350. */
  351. class BootstrapGetFilenameTestCase extends DrupalUnitTestCase {
  352. public static function getInfo() {
  353. return array(
  354. 'name' => 'Get filename test (without the system table)',
  355. 'description' => 'Test that drupal_get_filename() works correctly when the database is not available.',
  356. 'group' => 'Bootstrap',
  357. );
  358. }
  359. /**
  360. * The last file-related error message triggered by the filename test.
  361. *
  362. * Used by BootstrapGetFilenameTestCase::testDrupalGetFilename().
  363. */
  364. protected $getFilenameTestTriggeredError;
  365. /**
  366. * Test that drupal_get_filename() works correctly when the file is not found in the database.
  367. */
  368. function testDrupalGetFilename() {
  369. // Reset the static cache so we can test the "db is not active" code of
  370. // drupal_get_filename().
  371. drupal_static_reset('drupal_get_filename');
  372. // Retrieving the location of a module.
  373. $this->assertIdentical(drupal_get_filename('module', 'php'), 'modules/php/php.module', t('Retrieve module location.'));
  374. // Retrieving the location of a theme.
  375. $this->assertIdentical(drupal_get_filename('theme', 'stark'), 'themes/stark/stark.info', t('Retrieve theme location.'));
  376. // Retrieving the location of a theme engine.
  377. $this->assertIdentical(drupal_get_filename('theme_engine', 'phptemplate'), 'themes/engines/phptemplate/phptemplate.engine', t('Retrieve theme engine location.'));
  378. // Retrieving the location of a profile. Profiles are a special case with
  379. // a fixed location and naming.
  380. $this->assertIdentical(drupal_get_filename('profile', 'standard'), 'profiles/standard/standard.profile', t('Retrieve install profile location.'));
  381. // When a file is not found in the database cache, drupal_get_filename()
  382. // searches several locations on the filesystem, including the DRUPAL_ROOT
  383. // directory. We use the '.script' extension below because this is a
  384. // non-existent filetype that will definitely not exist in the database.
  385. // Since there is already a scripts directory, drupal_get_filename() will
  386. // automatically check there for 'script' files, just as it does for (e.g.)
  387. // 'module' files in modules.
  388. $this->assertIdentical(drupal_get_filename('script', 'test'), 'scripts/test.script', t('Retrieve test script location.'));
  389. // When searching for a module that does not exist, drupal_get_filename()
  390. // should return NULL and trigger an appropriate error message.
  391. $this->getFilenameTestTriggeredError = NULL;
  392. set_error_handler(array($this, 'fileNotFoundErrorHandler'));
  393. $non_existing_module = $this->randomName();
  394. $this->assertNull(drupal_get_filename('module', $non_existing_module), 'Searching for a module that does not exist returns NULL.');
  395. $this->assertTrue(strpos($this->getFilenameTestTriggeredError, format_string('The following module is missing from the file system: %name', array('%name' => $non_existing_module))) === 0, 'Searching for an item that does not exist triggers the correct error.');
  396. restore_error_handler();
  397. // Check that the result is stored in the file system scan cache.
  398. $file_scans = _drupal_file_scan_cache();
  399. $this->assertIdentical($file_scans['module'][$non_existing_module], FALSE, 'Searching for a module that does not exist creates a record in the missing and moved files static variable.');
  400. // Performing the search again in the same request still should not find
  401. // the file, but the error message should not be repeated (therefore we do
  402. // not override the error handler here).
  403. $this->assertNull(drupal_get_filename('module', $non_existing_module), 'Searching for a module that does not exist returns NULL during the second search.');
  404. }
  405. /**
  406. * Skips handling of "file not found" errors.
  407. */
  408. public function fileNotFoundErrorHandler($error_level, $message, $filename, $line) {
  409. // Skip error handling if this is a "file not found" error.
  410. if (strpos($message, 'is missing from the file system:') !== FALSE || strpos($message, 'has moved within the file system:') !== FALSE) {
  411. $this->getFilenameTestTriggeredError = $message;
  412. return;
  413. }
  414. _drupal_error_handler($error_level, $message, $filename, $line);
  415. }
  416. }
  417. /**
  418. * Test drupal_get_filename() in the context of a full Drupal installation.
  419. */
  420. class BootstrapGetFilenameWebTestCase extends DrupalWebTestCase {
  421. public static function getInfo() {
  422. return array(
  423. 'name' => 'Get filename test (full installation)',
  424. 'description' => 'Test that drupal_get_filename() works correctly in the context of a full Drupal installation.',
  425. 'group' => 'Bootstrap',
  426. );
  427. }
  428. function setUp() {
  429. parent::setUp('system_test');
  430. }
  431. /**
  432. * The last file-related error message triggered by the filename test.
  433. *
  434. * Used by BootstrapGetFilenameWebTestCase::testDrupalGetFilename().
  435. */
  436. protected $getFilenameTestTriggeredError;
  437. /**
  438. * Test that drupal_get_filename() works correctly with a full Drupal site.
  439. */
  440. function testDrupalGetFilename() {
  441. // Search for a module that exists in the file system and the {system}
  442. // table and make sure that it is found.
  443. $this->assertIdentical(drupal_get_filename('module', 'node'), 'modules/node/node.module', 'Module found at expected location.');
  444. // Search for a module that does not exist in either the file system or the
  445. // {system} table. Make sure that an appropriate error is triggered and
  446. // that the module winds up in the static and persistent cache.
  447. $this->getFilenameTestTriggeredError = NULL;
  448. set_error_handler(array($this, 'fileNotFoundErrorHandler'));
  449. $non_existing_module = $this->randomName();
  450. $this->assertNull(drupal_get_filename('module', $non_existing_module), 'Searching for a module that does not exist returns NULL.');
  451. $this->assertTrue(strpos($this->getFilenameTestTriggeredError, format_string('The following module is missing from the file system: %name', array('%name' => $non_existing_module))) === 0, 'Searching for a module that does not exist triggers the correct error.');
  452. restore_error_handler();
  453. $file_scans = _drupal_file_scan_cache();
  454. $this->assertIdentical($file_scans['module'][$non_existing_module], FALSE, 'Searching for a module that does not exist creates a record in the missing and moved files static variable.');
  455. drupal_file_scan_write_cache();
  456. $cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
  457. $this->assertIdentical($cache->data['module'][$non_existing_module], FALSE, 'Searching for a module that does not exist creates a record in the missing and moved files persistent cache.');
  458. // Simulate moving a module to a location that does not match the location
  459. // in the {system} table and perform similar tests as above.
  460. db_update('system')
  461. ->fields(array('filename' => 'modules/simpletest/tests/fake_location/module_test.module'))
  462. ->condition('name', 'module_test')
  463. ->condition('type', 'module')
  464. ->execute();
  465. $this->getFilenameTestTriggeredError = NULL;
  466. set_error_handler(array($this, 'fileNotFoundErrorHandler'));
  467. $this->assertIdentical(drupal_get_filename('module', 'module_test'), 'modules/simpletest/tests/module_test.module', 'Searching for a module that has moved finds the module at its new location.');
  468. $this->assertTrue(strpos($this->getFilenameTestTriggeredError, format_string('The following module has moved within the file system: %name', array('%name' => 'module_test'))) === 0, 'Searching for a module that has moved triggers the correct error.');
  469. restore_error_handler();
  470. $file_scans = _drupal_file_scan_cache();
  471. $this->assertIdentical($file_scans['module']['module_test'], 'modules/simpletest/tests/module_test.module', 'Searching for a module that has moved creates a record in the missing and moved files static variable.');
  472. drupal_file_scan_write_cache();
  473. $cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
  474. $this->assertIdentical($cache->data['module']['module_test'], 'modules/simpletest/tests/module_test.module', 'Searching for a module that has moved creates a record in the missing and moved files persistent cache.');
  475. // Simulate a module that exists in the {system} table but does not exist
  476. // in the file system and perform similar tests as above.
  477. $non_existing_module = $this->randomName();
  478. db_update('system')
  479. ->fields(array('name' => $non_existing_module))
  480. ->condition('name', 'module_test')
  481. ->condition('type', 'module')
  482. ->execute();
  483. $this->getFilenameTestTriggeredError = NULL;
  484. set_error_handler(array($this, 'fileNotFoundErrorHandler'));
  485. $this->assertNull(drupal_get_filename('module', $non_existing_module), 'Searching for a module that exists in the system table but not in the file system returns NULL.');
  486. $this->assertTrue(strpos($this->getFilenameTestTriggeredError, format_string('The following module is missing from the file system: %name', array('%name' => $non_existing_module))) === 0, 'Searching for a module that exists in the system table but not in the file system triggers the correct error.');
  487. restore_error_handler();
  488. $file_scans = _drupal_file_scan_cache();
  489. $this->assertIdentical($file_scans['module'][$non_existing_module], FALSE, 'Searching for a module that exists in the system table but not in the file system creates a record in the missing and moved files static variable.');
  490. drupal_file_scan_write_cache();
  491. $cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
  492. $this->assertIdentical($cache->data['module'][$non_existing_module], FALSE, 'Searching for a module that exists in the system table but not in the file system creates a record in the missing and moved files persistent cache.');
  493. // Simulate a module that exists in the file system but not in the {system}
  494. // table and perform similar tests as above.
  495. db_delete('system')
  496. ->condition('name', 'common_test')
  497. ->condition('type', 'module')
  498. ->execute();
  499. system_list_reset();
  500. $this->getFilenameTestTriggeredError = NULL;
  501. set_error_handler(array($this, 'fileNotFoundErrorHandler'));
  502. $this->assertIdentical(drupal_get_filename('module', 'common_test'), 'modules/simpletest/tests/common_test.module', 'Searching for a module that does not exist in the system table finds the module at its actual location.');
  503. $this->assertTrue(strpos($this->getFilenameTestTriggeredError, format_string('The following module has moved within the file system: %name', array('%name' => 'common_test'))) === 0, 'Searching for a module that does not exist in the system table triggers the correct error.');
  504. restore_error_handler();
  505. $file_scans = _drupal_file_scan_cache();
  506. $this->assertIdentical($file_scans['module']['common_test'], 'modules/simpletest/tests/common_test.module', 'Searching for a module that does not exist in the system table creates a record in the missing and moved files static variable.');
  507. drupal_file_scan_write_cache();
  508. $cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
  509. $this->assertIdentical($cache->data['module']['common_test'], 'modules/simpletest/tests/common_test.module', 'Searching for a module that does not exist in the system table creates a record in the missing and moved files persistent cache.');
  510. }
  511. /**
  512. * Skips handling of "file not found" errors.
  513. */
  514. public function fileNotFoundErrorHandler($error_level, $message, $filename, $line) {
  515. // Skip error handling if this is a "file not found" error.
  516. if (strpos($message, 'is missing from the file system:') !== FALSE || strpos($message, 'has moved within the file system:') !== FALSE) {
  517. $this->getFilenameTestTriggeredError = $message;
  518. return;
  519. }
  520. _drupal_error_handler($error_level, $message, $filename, $line);
  521. }
  522. /**
  523. * Test that watchdog messages about missing files are correctly recorded.
  524. */
  525. public function testWatchdog() {
  526. // Search for a module that does not exist in either the file system or the
  527. // {system} table. Make sure that an appropriate warning is recorded in the
  528. // logs.
  529. $non_existing_module = $this->randomName();
  530. $query_parameters = array(
  531. ':type' => 'php',
  532. ':severity' => WATCHDOG_WARNING,
  533. );
  534. $this->assertEqual(db_query('SELECT COUNT(*) FROM {watchdog} WHERE type = :type AND severity = :severity', $query_parameters)->fetchField(), 0, 'No warning message appears in the logs before searching for a module that does not exist.');
  535. // Trigger the drupal_get_filename() call. This must be done via a request
  536. // to a separate URL since the watchdog() will happen in a shutdown
  537. // function, and so that SimpleTest can be told to ignore (and not fail as
  538. // a result of) the expected PHP warnings generated during this process.
  539. variable_set('system_test_drupal_get_filename_test_module_name', $non_existing_module);
  540. $this->drupalGet('system-test/drupal-get-filename');
  541. $message_variables = db_query('SELECT variables FROM {watchdog} WHERE type = :type AND severity = :severity', $query_parameters)->fetchCol();
  542. $this->assertEqual(count($message_variables), 1, 'A single warning message appears in the logs after searching for a module that does not exist.');
  543. $variables = reset($message_variables);
  544. $variables = unserialize($variables);
  545. $this->assertTrue(isset($variables['!message']) && strpos($variables['!message'], format_string('The following module is missing from the file system: %name', array('%name' => $non_existing_module))) !== FALSE, 'The warning message that appears in the logs after searching for a module that does not exist contains the expected text.');
  546. }
  547. /**
  548. * Test that drupal_get_filename() does not break recursive rebuilds.
  549. */
  550. public function testRecursiveRebuilds() {
  551. // Ensure that the drupal_get_filename() call due to a missing module does
  552. // not break the data returned by an attempted recursive rebuild. The code
  553. // path which is tested is as follows:
  554. // - Call drupal_get_schema().
  555. // - Within a hook_schema() implementation, trigger a drupal_get_filename()
  556. // search for a nonexistent module.
  557. // - In the watchdog() call that results from that, trigger
  558. // drupal_get_schema() again.
  559. // Without some kind of recursion protection, this could cause the second
  560. // drupal_get_schema() call to return incomplete results. This test ensures
  561. // that does not happen.
  562. $non_existing_module = $this->randomName();
  563. variable_set('system_test_drupal_get_filename_test_module_name', $non_existing_module);
  564. $this->drupalGet('system-test/drupal-get-filename-with-schema-rebuild');
  565. $original_drupal_get_schema_tables = variable_get('system_test_drupal_get_filename_with_schema_rebuild_original_tables');
  566. $final_drupal_get_schema_tables = variable_get('system_test_drupal_get_filename_with_schema_rebuild_final_tables');
  567. $this->assertTrue(!empty($original_drupal_get_schema_tables));
  568. $this->assertTrue(!empty($final_drupal_get_schema_tables));
  569. $this->assertEqual($original_drupal_get_schema_tables, $final_drupal_get_schema_tables);
  570. }
  571. }
  572. class BootstrapTimerTestCase extends DrupalUnitTestCase {
  573. public static function getInfo() {
  574. return array(
  575. 'name' => 'Timer test',
  576. 'description' => 'Test that timer_read() works both when a timer is running and when a timer is stopped.',
  577. 'group' => 'Bootstrap',
  578. );
  579. }
  580. /**
  581. * Test timer_read() to ensure it properly accumulates time when the timer
  582. * started and stopped multiple times.
  583. * @return
  584. */
  585. function testTimer() {
  586. timer_start('test');
  587. sleep(1);
  588. $this->assertTrue(timer_read('test') >= 1000, 'Timer measured 1 second of sleeping while running.');
  589. sleep(1);
  590. timer_stop('test');
  591. $this->assertTrue(timer_read('test') >= 2000, 'Timer measured 2 seconds of sleeping after being stopped.');
  592. timer_start('test');
  593. sleep(1);
  594. $this->assertTrue(timer_read('test') >= 3000, 'Timer measured 3 seconds of sleeping after being restarted.');
  595. sleep(1);
  596. $timer = timer_stop('test');
  597. $this->assertTrue(timer_read('test') >= 4000, 'Timer measured 4 seconds of sleeping after being stopped for a second time.');
  598. $this->assertEqual($timer['count'], 2, 'Timer counted 2 instances of being started.');
  599. }
  600. }
  601. /**
  602. * Test that resetting static variables works.
  603. */
  604. class BootstrapResettableStaticTestCase extends DrupalUnitTestCase {
  605. public static function getInfo() {
  606. return array(
  607. 'name' => 'Resettable static variables test',
  608. 'description' => 'Test that drupal_static() and drupal_static_reset() work.',
  609. 'group' => 'Bootstrap',
  610. );
  611. }
  612. /**
  613. * Test that a variable reference returned by drupal_static() gets reset when
  614. * drupal_static_reset() is called.
  615. */
  616. function testDrupalStatic() {
  617. $name = __CLASS__ . '_' . __METHOD__;
  618. $var = &drupal_static($name, 'foo');
  619. $this->assertEqual($var, 'foo', 'Variable returned by drupal_static() was set to its default.');
  620. // Call the specific reset and the global reset each twice to ensure that
  621. // multiple resets can be issued without odd side effects.
  622. $var = 'bar';
  623. drupal_static_reset($name);
  624. $this->assertEqual($var, 'foo', 'Variable was reset after first invocation of name-specific reset.');
  625. $var = 'bar';
  626. drupal_static_reset($name);
  627. $this->assertEqual($var, 'foo', 'Variable was reset after second invocation of name-specific reset.');
  628. $var = 'bar';
  629. drupal_static_reset();
  630. $this->assertEqual($var, 'foo', 'Variable was reset after first invocation of global reset.');
  631. $var = 'bar';
  632. drupal_static_reset();
  633. $this->assertEqual($var, 'foo', 'Variable was reset after second invocation of global reset.');
  634. }
  635. }
  636. /**
  637. * Test miscellaneous functions in bootstrap.inc.
  638. */
  639. class BootstrapMiscTestCase extends DrupalUnitTestCase {
  640. public static function getInfo() {
  641. return array(
  642. 'name' => 'Miscellaneous bootstrap unit tests',
  643. 'description' => 'Test miscellaneous functions in bootstrap.inc.',
  644. 'group' => 'Bootstrap',
  645. );
  646. }
  647. /**
  648. * Test miscellaneous functions in bootstrap.inc.
  649. */
  650. function testMisc() {
  651. // Test drupal_array_merge_deep().
  652. $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => 'X', 'class' => array('a', 'b')), 'language' => 'en');
  653. $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => 'Y', 'class' => array('c', 'd')), 'html' => TRUE);
  654. $expected = array('fragment' => 'y', 'attributes' => array('title' => 'Y', 'class' => array('a', 'b', 'c', 'd')), 'language' => 'en', 'html' => TRUE);
  655. $this->assertIdentical(drupal_array_merge_deep($link_options_1, $link_options_2), $expected, 'drupal_array_merge_deep() returned a properly merged array.');
  656. }
  657. /**
  658. * Tests that the drupal_check_memory_limit() function works as expected.
  659. */
  660. function testCheckMemoryLimit() {
  661. // Test that a very reasonable amount of memory is available.
  662. $this->assertTrue(drupal_check_memory_limit('30MB'), '30MB of memory tested available.');
  663. // Test an unlimited memory limit.
  664. // The function should always return true if the memory limit is set to -1.
  665. $this->assertTrue(drupal_check_memory_limit('9999999999YB', -1), 'drupal_check_memory_limit() returns TRUE when a limit of -1 (none) is supplied');
  666. // Test that even though we have 30MB of memory available - the function
  667. // returns FALSE when given an upper limit for how much memory can be used.
  668. $this->assertFalse(drupal_check_memory_limit('30MB', '16MB'), 'drupal_check_memory_limit() returns FALSE with a 16MB upper limit on a 30MB requirement.');
  669. // Test that an equal amount of memory to the amount requested returns TRUE.
  670. $this->assertTrue(drupal_check_memory_limit('30MB', '30MB'), 'drupal_check_memory_limit() returns TRUE when requesting 30MB on a 30MB requirement.');
  671. }
  672. }
  673. /**
  674. * Tests for overriding server variables via the API.
  675. */
  676. class BootstrapOverrideServerVariablesTestCase extends DrupalUnitTestCase {
  677. public static function getInfo() {
  678. return array(
  679. 'name' => 'Overriding server variables',
  680. 'description' => 'Test that drupal_override_server_variables() works correctly.',
  681. 'group' => 'Bootstrap',
  682. );
  683. }
  684. /**
  685. * Test providing a direct URL to to drupal_override_server_variables().
  686. */
  687. function testDrupalOverrideServerVariablesProvidedURL() {
  688. $tests = array(
  689. 'http://example.com' => array(
  690. 'HTTP_HOST' => 'example.com',
  691. 'SCRIPT_NAME' => isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : NULL,
  692. ),
  693. 'http://example.com/index.php' => array(
  694. 'HTTP_HOST' => 'example.com',
  695. 'SCRIPT_NAME' => '/index.php',
  696. ),
  697. 'http://example.com/subdirectory/index.php' => array(
  698. 'HTTP_HOST' => 'example.com',
  699. 'SCRIPT_NAME' => '/subdirectory/index.php',
  700. ),
  701. );
  702. foreach ($tests as $url => $expected_server_values) {
  703. // Remember the original value of $_SERVER, since the function call below
  704. // will modify it.
  705. $original_server = $_SERVER;
  706. // Call drupal_override_server_variables() and ensure that all expected
  707. // $_SERVER variables were modified correctly.
  708. drupal_override_server_variables(array('url' => $url));
  709. foreach ($expected_server_values as $key => $value) {
  710. $this->assertIdentical($_SERVER[$key], $value);
  711. }
  712. // Restore the original value of $_SERVER.
  713. $_SERVER = $original_server;
  714. }
  715. }
  716. }
  717. /**
  718. * Tests for $_GET['destination'] and $_REQUEST['destination'] validation.
  719. */
  720. class BootstrapDestinationTestCase extends DrupalWebTestCase {
  721. public static function getInfo() {
  722. return array(
  723. 'name' => 'URL destination validation',
  724. 'description' => 'Test that $_GET[\'destination\'] and $_REQUEST[\'destination\'] cannot contain external URLs.',
  725. 'group' => 'Bootstrap',
  726. );
  727. }
  728. function setUp() {
  729. parent::setUp('system_test');
  730. }
  731. /**
  732. * Tests that $_GET/$_REQUEST['destination'] only contain internal URLs.
  733. *
  734. * @see _drupal_bootstrap_variables()
  735. * @see system_test_get_destination()
  736. * @see system_test_request_destination()
  737. */
  738. public function testDestination() {
  739. $test_cases = array(
  740. array(
  741. 'input' => 'node',
  742. 'output' => 'node',
  743. 'message' => "Standard internal example node path is present in the 'destination' parameter.",
  744. ),
  745. array(
  746. 'input' => '/example.com',
  747. 'output' => '/example.com',
  748. 'message' => 'Internal path with one leading slash is allowed.',
  749. ),
  750. array(
  751. 'input' => '//example.com/test',
  752. 'output' => '',
  753. 'message' => 'External URL without scheme is not allowed.',
  754. ),
  755. array(
  756. 'input' => 'example:test',
  757. 'output' => 'example:test',
  758. 'message' => 'Internal URL using a colon is allowed.',
  759. ),
  760. array(
  761. 'input' => 'http://example.com',
  762. 'output' => '',
  763. 'message' => 'External URL is not allowed.',
  764. ),
  765. array(
  766. 'input' => 'javascript:alert(0)',
  767. 'output' => 'javascript:alert(0)',
  768. 'message' => 'Javascript URL is allowed because it is treated as an internal URL.',
  769. ),
  770. );
  771. foreach ($test_cases as $test_case) {
  772. // Test $_GET['destination'].
  773. $this->drupalGet('system-test/get-destination', array('query' => array('destination' => $test_case['input'])));
  774. $this->assertIdentical($test_case['output'], $this->drupalGetContent(), $test_case['message']);
  775. // Test $_REQUEST['destination']. There's no form to submit to, so
  776. // drupalPost() won't work here; this just tests a direct $_POST request
  777. // instead.
  778. $curl_parameters = array(
  779. CURLOPT_URL => $this->getAbsoluteUrl('system-test/request-destination'),
  780. CURLOPT_POST => TRUE,
  781. CURLOPT_POSTFIELDS => 'destination=' . urlencode($test_case['input']),
  782. CURLOPT_HTTPHEADER => array(),
  783. );
  784. $post_output = $this->curlExec($curl_parameters);
  785. $this->assertIdentical($test_case['output'], $post_output, $test_case['message']);
  786. }
  787. // Make sure that 404 pages do not populate $_GET['destination'] with
  788. // external URLs.
  789. variable_set('site_404', 'system-test/get-destination');
  790. $this->drupalGet('http://example.com', array('external' => FALSE));
  791. $this->assertIdentical('', $this->drupalGetContent(), 'External URL is not allowed on 404 pages.');
  792. }
  793. }
  794. /**
  795. * Tests DrupalCacheArray functionality.
  796. */
  797. class BootstrapDrupalCacheArrayTestCase extends DrupalWebTestCase {
  798. public static function getInfo() {
  799. return array(
  800. 'name' => 'DrupalCacheArray tests',
  801. 'description' => 'Test DrupalCacheArray functionality.',
  802. 'group' => 'Bootstrap',
  803. );
  804. }
  805. /**
  806. * Simulate unsafe deserialization of payload prepared by the phpggc project.
  807. *
  808. * @see https://github.com/ambionics/phpggc/pull/28
  809. */
  810. public function testGadgetChainDrupal7RCE1() {
  811. // phpggc -s Drupal7/RCE1 phpinfo 2
  812. $payload = 'O:11:"SchemaCache":4:{s:6:"%00*%00cid"%3Bs:14:"form_DrupalRCE"%3Bs:6:"%00*%00bin"%3Bs:10:"cache_form"%3Bs:16:"%00*%00keysToPersist"%3Ba:3:{s:8:"#form_id"%3Bb:1%3Bs:8:"#process"%3Bb:1%3Bs:9:"#attached"%3Bb:1%3B}s:10:"%00*%00storage"%3Ba:3:{s:8:"#form_id"%3Bs:9:"DrupalRCE"%3Bs:8:"#process"%3Ba:1:{i:0%3Bs:23:"drupal_process_attached"%3B}s:9:"#attached"%3Ba:1:{s:7:"phpinfo"%3Ba:1:{i:0%3Ba:1:{i:0%3Bs:1:"2"%3B}}}}}';
  813. $object = unserialize(urldecode($payload));
  814. // The object then needs to be destructed.
  815. unset($object);
  816. // If the exploit was successful, there should now be a row in cache_form.
  817. $payload2 = db_query_range('SELECT data FROM {cache_form} WHERE cid LIKE :cid', 0, 1, array(':cid' => 'form_DrupalRCE'))->fetchField();
  818. $this->assertFalse(is_string($payload2) && (strpos($payload2, 'phpinfo') !== FALSE), 'Second stage payload was not written to cache_form.');
  819. // The final exploit is executed via the ajax system, but is not a
  820. // sufficiently valid ajax form submission to use drupalPost for testing.
  821. $headers = array(
  822. 'Content-Type: application/x-www-form-urlencoded',
  823. );
  824. $curl_options = array(
  825. CURLOPT_URL => url('system/ajax', array('absolute' => TRUE)),
  826. CURLOPT_POST => TRUE,
  827. CURLOPT_POSTFIELDS => 'form_build_id=DrupalRCE',
  828. CURLOPT_HTTPHEADER => $headers,
  829. );
  830. // The second stage payload causes several PHP warnings / notices if it is
  831. // there in cache_form.
  832. $content = $this->curlExec($curl_options);
  833. $this->assertFalse((strpos($content, 'Rasmus Lerdorf') !== FALSE), 'Remote Code Execution was not successful.');
  834. // Now opt-out of the cache_form protection.
  835. variable_set('drupal_cache_array_persist_cache_form', TRUE);
  836. $object = unserialize(urldecode($payload));
  837. // The object then needs to be destructed.
  838. unset($object);
  839. // If the exploit was successful, there should now be a row in cache_form.
  840. $payload2 = db_query_range('SELECT data FROM {cache_form} WHERE cid LIKE :cid', 0, 1, array(':cid' => 'form_DrupalRCE'))->fetchField();
  841. $this->assertTrue(is_string($payload2) && (strpos($payload2, 'phpinfo') !== FALSE), 'DrupalCacheArray persisted data to cache_form.');
  842. }
  843. }