UtilTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. <?php
  2. /**
  3. * Copyright (c) 2012 Lukas Reschke <lukas@statuscode.ch>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace Test;
  9. use OC_Util;
  10. use OCP\App\IAppManager;
  11. /**
  12. * Class UtilTest
  13. *
  14. * @package Test
  15. * @group DB
  16. */
  17. class UtilTest extends \Test\TestCase {
  18. public function testGetVersion() {
  19. $version = \OCP\Util::getVersion();
  20. $this->assertTrue(is_array($version));
  21. foreach ($version as $num) {
  22. $this->assertTrue(is_int($num));
  23. }
  24. }
  25. public function testGetVersionString() {
  26. $version = \OC_Util::getVersionString();
  27. $this->assertTrue(is_string($version));
  28. }
  29. public function testGetEditionString() {
  30. $edition = \OC_Util::getEditionString();
  31. $this->assertTrue(is_string($edition));
  32. }
  33. /**
  34. * @group DB
  35. */
  36. function testFormatDate() {
  37. date_default_timezone_set("UTC");
  38. $result = OC_Util::formatDate(1350129205);
  39. $expected = 'October 13, 2012 at 11:53:25 AM GMT+0';
  40. $this->assertEquals($expected, $result);
  41. $result = OC_Util::formatDate(1102831200, true);
  42. $expected = 'December 12, 2004';
  43. $this->assertEquals($expected, $result);
  44. }
  45. /**
  46. * @group DB
  47. */
  48. function testFormatDateWithTZ() {
  49. date_default_timezone_set("UTC");
  50. $result = OC_Util::formatDate(1350129205, false, 'Europe/Berlin');
  51. $expected = 'October 13, 2012 at 1:53:25 PM GMT+2';
  52. $this->assertEquals($expected, $result);
  53. }
  54. /**
  55. * @expectedException \Exception
  56. */
  57. function testFormatDateWithInvalidTZ() {
  58. OC_Util::formatDate(1350129205, false, 'Mordor/Barad-dûr');
  59. }
  60. public function formatDateWithTZFromSessionData() {
  61. return array(
  62. array(3, 'October 13, 2012 at 2:53:25 PM GMT+3', 'Etc/GMT-3'),
  63. array(15, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'),
  64. array(-13, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'),
  65. array(9.5, 'October 13, 2012 at 9:23:25 PM GMT+9:30', 'Australia/Darwin'),
  66. array(-4.5, 'October 13, 2012 at 7:23:25 AM GMT-4:30', 'America/Caracas'),
  67. array(15.5, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'),
  68. );
  69. }
  70. /**
  71. * @dataProvider formatDateWithTZFromSessionData
  72. * @group DB
  73. */
  74. function testFormatDateWithTZFromSession($offset, $expected, $expectedTimeZone) {
  75. date_default_timezone_set("UTC");
  76. \OC::$server->getSession()->set('timezone', $offset);
  77. $selectedTimeZone = \OC::$server->getDateTimeZone()->getTimeZone(1350129205);
  78. $this->assertEquals($expectedTimeZone, $selectedTimeZone->getName());
  79. $newDateTimeFormatter = new \OC\DateTimeFormatter($selectedTimeZone, \OC::$server->getL10N('lib', 'en'));
  80. $this->overwriteService('DateTimeFormatter', $newDateTimeFormatter);
  81. $result = OC_Util::formatDate(1350129205, false);
  82. $this->assertEquals($expected, $result);
  83. $this->restoreService('DateTimeFormatter');
  84. }
  85. function testSanitizeHTML() {
  86. $badArray = [
  87. 'While it is unusual to pass an array',
  88. 'this function actually <blink>supports</blink> it.',
  89. 'And therefore there needs to be a <script>alert("Unit"+\'test\')</script> for it!',
  90. [
  91. 'And It Even May <strong>Nest</strong>',
  92. ],
  93. ];
  94. $goodArray = [
  95. 'While it is unusual to pass an array',
  96. 'this function actually &lt;blink&gt;supports&lt;/blink&gt; it.',
  97. 'And therefore there needs to be a &lt;script&gt;alert(&quot;Unit&quot;+&#039;test&#039;)&lt;/script&gt; for it!',
  98. [
  99. 'And It Even May &lt;strong&gt;Nest&lt;/strong&gt;'
  100. ],
  101. ];
  102. $result = OC_Util::sanitizeHTML($badArray);
  103. $this->assertEquals($goodArray, $result);
  104. $badString = '<img onload="alert(1)" />';
  105. $result = OC_Util::sanitizeHTML($badString);
  106. $this->assertEquals('&lt;img onload=&quot;alert(1)&quot; /&gt;', $result);
  107. $badString = "<script>alert('Hacked!');</script>";
  108. $result = OC_Util::sanitizeHTML($badString);
  109. $this->assertEquals('&lt;script&gt;alert(&#039;Hacked!&#039;);&lt;/script&gt;', $result);
  110. $goodString = 'This is a good string without HTML.';
  111. $result = OC_Util::sanitizeHTML($goodString);
  112. $this->assertEquals('This is a good string without HTML.', $result);
  113. }
  114. function testEncodePath() {
  115. $component = '/§#@test%&^ä/-child';
  116. $result = OC_Util::encodePath($component);
  117. $this->assertEquals("/%C2%A7%23%40test%25%26%5E%C3%A4/-child", $result);
  118. }
  119. public function testFileInfoLoaded() {
  120. $expected = function_exists('finfo_open');
  121. $this->assertEquals($expected, \OC_Util::fileInfoLoaded());
  122. }
  123. function testGetDefaultEmailAddress() {
  124. $email = \OCP\Util::getDefaultEmailAddress("no-reply");
  125. $this->assertEquals('no-reply@localhost', $email);
  126. }
  127. function testGetDefaultEmailAddressFromConfig() {
  128. $config = \OC::$server->getConfig();
  129. $config->setSystemValue('mail_domain', 'example.com');
  130. $email = \OCP\Util::getDefaultEmailAddress("no-reply");
  131. $this->assertEquals('no-reply@example.com', $email);
  132. $config->deleteSystemValue('mail_domain');
  133. }
  134. function testGetConfiguredEmailAddressFromConfig() {
  135. $config = \OC::$server->getConfig();
  136. $config->setSystemValue('mail_domain', 'example.com');
  137. $config->setSystemValue('mail_from_address', 'owncloud');
  138. $email = \OCP\Util::getDefaultEmailAddress("no-reply");
  139. $this->assertEquals('owncloud@example.com', $email);
  140. $config->deleteSystemValue('mail_domain');
  141. $config->deleteSystemValue('mail_from_address');
  142. }
  143. function testGetInstanceIdGeneratesValidId() {
  144. \OC::$server->getConfig()->deleteSystemValue('instanceid');
  145. $instanceId = OC_Util::getInstanceId();
  146. $this->assertStringStartsWith('oc', $instanceId);
  147. $matchesRegex = preg_match('/^[a-z0-9]+$/', $instanceId);
  148. $this->assertSame(1, $matchesRegex);
  149. }
  150. /**
  151. * @dataProvider baseNameProvider
  152. */
  153. public function testBaseName($expected, $file) {
  154. $base = \OC_Util::basename($file);
  155. $this->assertEquals($expected, $base);
  156. }
  157. public function baseNameProvider() {
  158. return array(
  159. array('public_html', '/home/user/public_html/'),
  160. array('public_html', '/home/user/public_html'),
  161. array('', '/'),
  162. array('public_html', 'public_html'),
  163. array('442aa682de2a64db1e010f50e60fd9c9', 'local::C:\Users\ADMINI~1\AppData\Local\Temp\2/442aa682de2a64db1e010f50e60fd9c9/')
  164. );
  165. }
  166. /**
  167. * @dataProvider filenameValidationProvider
  168. */
  169. public function testFilenameValidation($file, $valid) {
  170. // private API
  171. $this->assertEquals($valid, \OC_Util::isValidFileName($file));
  172. // public API
  173. $this->assertEquals($valid, \OCP\Util::isValidFileName($file));
  174. }
  175. public function filenameValidationProvider() {
  176. return array(
  177. // valid names
  178. array('boringname', true),
  179. array('something.with.extension', true),
  180. array('now with spaces', true),
  181. array('.a', true),
  182. array('..a', true),
  183. array('.dotfile', true),
  184. array('single\'quote', true),
  185. array(' spaces before', true),
  186. array('spaces after ', true),
  187. array('allowed chars including the crazy ones $%&_-^@!,()[]{}=;#', true),
  188. array('汉字也能用', true),
  189. array('und Ümläüte sind auch willkommen', true),
  190. // disallowed names
  191. array('', false),
  192. array(' ', false),
  193. array('.', false),
  194. array('..', false),
  195. array('back\\slash', false),
  196. array('sl/ash', false),
  197. array('lt<lt', true),
  198. array('gt>gt', true),
  199. array('col:on', true),
  200. array('double"quote', true),
  201. array('pi|pe', true),
  202. array('dont?ask?questions?', true),
  203. array('super*star', true),
  204. array('new\nline', false),
  205. // better disallow these to avoid unexpected trimming to have side effects
  206. array(' ..', false),
  207. array('.. ', false),
  208. array('. ', false),
  209. array(' .', false),
  210. );
  211. }
  212. /**
  213. * @dataProvider dataProviderForTestIsSharingDisabledForUser
  214. * @param array $groups existing groups
  215. * @param array $membership groups the user belong to
  216. * @param array $excludedGroups groups which should be excluded from sharing
  217. * @param bool $expected expected result
  218. */
  219. function testIsSharingDisabledForUser($groups, $membership, $excludedGroups, $expected) {
  220. $config = $this->getMockBuilder('OCP\IConfig')->disableOriginalConstructor()->getMock();
  221. $groupManager = $this->getMockBuilder('OCP\IGroupManager')->disableOriginalConstructor()->getMock();
  222. $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock();
  223. $config
  224. ->expects($this->at(0))
  225. ->method('getAppValue')
  226. ->with('core', 'shareapi_exclude_groups', 'no')
  227. ->will($this->returnValue('yes'));
  228. $config
  229. ->expects($this->at(1))
  230. ->method('getAppValue')
  231. ->with('core', 'shareapi_exclude_groups_list')
  232. ->will($this->returnValue(json_encode($excludedGroups)));
  233. $groupManager
  234. ->expects($this->at(0))
  235. ->method('getUserGroupIds')
  236. ->with($user)
  237. ->will($this->returnValue($membership));
  238. $result = \OC_Util::isSharingDisabledForUser($config, $groupManager, $user);
  239. $this->assertSame($expected, $result);
  240. }
  241. public function dataProviderForTestIsSharingDisabledForUser() {
  242. return array(
  243. // existing groups, groups the user belong to, groups excluded from sharing, expected result
  244. array(array('g1', 'g2', 'g3'), array(), array('g1'), false),
  245. array(array('g1', 'g2', 'g3'), array(), array(), false),
  246. array(array('g1', 'g2', 'g3'), array('g2'), array('g1'), false),
  247. array(array('g1', 'g2', 'g3'), array('g2'), array(), false),
  248. array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1'), false),
  249. array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2'), true),
  250. array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2', 'g3'), true),
  251. );
  252. }
  253. /**
  254. * Test default apps
  255. *
  256. * @dataProvider defaultAppsProvider
  257. * @group DB
  258. */
  259. function testDefaultApps($defaultAppConfig, $expectedPath, $enabledApps) {
  260. $oldDefaultApps = \OCP\Config::getSystemValue('defaultapp', '');
  261. // CLI is doing messy stuff with the webroot, so need to work it around
  262. $oldWebRoot = \OC::$WEBROOT;
  263. \OC::$WEBROOT = '';
  264. $appManager = $this->createMock(IAppManager::class);
  265. $appManager->expects($this->any())
  266. ->method('isEnabledForUser')
  267. ->will($this->returnCallback(function($appId) use ($enabledApps){
  268. return in_array($appId, $enabledApps);
  269. }));
  270. Dummy_OC_Util::$appManager = $appManager;
  271. // need to set a user id to make sure enabled apps are read from cache
  272. \OC_User::setUserId($this->getUniqueID());
  273. \OCP\Config::setSystemValue('defaultapp', $defaultAppConfig);
  274. $this->assertEquals('http://localhost/' . $expectedPath, Dummy_OC_Util::getDefaultPageUrl());
  275. // restore old state
  276. \OC::$WEBROOT = $oldWebRoot;
  277. \OCP\Config::setSystemValue('defaultapp', $oldDefaultApps);
  278. \OC_User::setUserId(null);
  279. }
  280. function defaultAppsProvider() {
  281. return array(
  282. // none specified, default to files
  283. array(
  284. '',
  285. 'index.php/apps/files/',
  286. array('files'),
  287. ),
  288. // unexisting or inaccessible app specified, default to files
  289. array(
  290. 'unexist',
  291. 'index.php/apps/files/',
  292. array('files'),
  293. ),
  294. // non-standard app
  295. array(
  296. 'calendar',
  297. 'index.php/apps/calendar/',
  298. array('files', 'calendar'),
  299. ),
  300. // non-standard app with fallback
  301. array(
  302. 'contacts,calendar',
  303. 'index.php/apps/calendar/',
  304. array('files', 'calendar'),
  305. ),
  306. );
  307. }
  308. public function testGetDefaultPageUrlWithRedirectUrlWithoutFrontController() {
  309. putenv('front_controller_active=false');
  310. \OC::$server->getConfig()->deleteSystemValue('htaccess.IgnoreFrontController');
  311. $_REQUEST['redirect_url'] = 'myRedirectUrl.com';
  312. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/myRedirectUrl.com', OC_Util::getDefaultPageUrl());
  313. }
  314. public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithoutFrontController() {
  315. putenv('front_controller_active=false');
  316. \OC::$server->getConfig()->deleteSystemValue('htaccess.IgnoreFrontController');
  317. $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a';
  318. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/index.php/apps/files/', OC_Util::getDefaultPageUrl());
  319. }
  320. public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithFrontController() {
  321. putenv('front_controller_active=true');
  322. $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a';
  323. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/apps/files/', OC_Util::getDefaultPageUrl());
  324. }
  325. public function testGetDefaultPageUrlWithRedirectUrlWithIgnoreFrontController() {
  326. putenv('front_controller_active=false');
  327. \OC::$server->getConfig()->setSystemValue('htaccess.IgnoreFrontController', true);
  328. $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a';
  329. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/apps/files/', OC_Util::getDefaultPageUrl());
  330. }
  331. /**
  332. * Test needUpgrade() when the core version is increased
  333. */
  334. public function testNeedUpgradeCore() {
  335. $config = \OC::$server->getConfig();
  336. $oldConfigVersion = $config->getSystemValue('version', '0.0.0');
  337. $oldSessionVersion = \OC::$server->getSession()->get('OC_Version');
  338. $this->assertFalse(\OCP\Util::needUpgrade());
  339. $config->setSystemValue('version', '7.0.0.0');
  340. \OC::$server->getSession()->set('OC_Version', array(7, 0, 0, 1));
  341. self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null));
  342. $this->assertTrue(\OCP\Util::needUpgrade());
  343. $config->setSystemValue('version', $oldConfigVersion);
  344. \OC::$server->getSession()->set('OC_Version', $oldSessionVersion);
  345. self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null));
  346. $this->assertFalse(\OCP\Util::needUpgrade());
  347. }
  348. public function testCheckDataDirectoryValidity() {
  349. $dataDir = \OCP\Files::tmpFolder();
  350. touch($dataDir . '/.ocdata');
  351. $errors = \OC_Util::checkDataDirectoryValidity($dataDir);
  352. $this->assertEmpty($errors);
  353. \OCP\Files::rmdirr($dataDir);
  354. $dataDir = \OCP\Files::tmpFolder();
  355. // no touch
  356. $errors = \OC_Util::checkDataDirectoryValidity($dataDir);
  357. $this->assertNotEmpty($errors);
  358. \OCP\Files::rmdirr($dataDir);
  359. $errors = \OC_Util::checkDataDirectoryValidity('relative/path');
  360. $this->assertNotEmpty($errors);
  361. }
  362. protected function setUp() {
  363. parent::setUp();
  364. \OC_Util::$scripts = [];
  365. \OC_Util::$styles = [];
  366. }
  367. protected function tearDown() {
  368. parent::tearDown();
  369. \OC_Util::$scripts = [];
  370. \OC_Util::$styles = [];
  371. }
  372. public function testAddScript() {
  373. \OC_Util::addScript('core', 'myFancyJSFile1');
  374. \OC_Util::addScript('myApp', 'myFancyJSFile2');
  375. \OC_Util::addScript('core', 'myFancyJSFile0', true);
  376. \OC_Util::addScript('core', 'myFancyJSFile10', true);
  377. // add duplicate
  378. \OC_Util::addScript('core', 'myFancyJSFile1');
  379. $this->assertEquals([
  380. 'core/js/myFancyJSFile10',
  381. 'core/js/myFancyJSFile0',
  382. 'core/js/myFancyJSFile1',
  383. 'myApp/l10n/en',
  384. 'myApp/js/myFancyJSFile2',
  385. ], \OC_Util::$scripts);
  386. $this->assertEquals([], \OC_Util::$styles);
  387. }
  388. public function testAddVendorScript() {
  389. \OC_Util::addVendorScript('core', 'myFancyJSFile1');
  390. \OC_Util::addVendorScript('myApp', 'myFancyJSFile2');
  391. \OC_Util::addVendorScript('core', 'myFancyJSFile0', true);
  392. \OC_Util::addVendorScript('core', 'myFancyJSFile10', true);
  393. // add duplicate
  394. \OC_Util::addVendorScript('core', 'myFancyJSFile1');
  395. $this->assertEquals([
  396. 'core/vendor/myFancyJSFile10',
  397. 'core/vendor/myFancyJSFile0',
  398. 'core/vendor/myFancyJSFile1',
  399. 'myApp/vendor/myFancyJSFile2',
  400. ], \OC_Util::$scripts);
  401. $this->assertEquals([], \OC_Util::$styles);
  402. }
  403. public function testAddTranslations() {
  404. \OC_Util::addTranslations('appId', 'de');
  405. $this->assertEquals([
  406. 'appId/l10n/de'
  407. ], \OC_Util::$scripts);
  408. $this->assertEquals([], \OC_Util::$styles);
  409. }
  410. public function testAddStyle() {
  411. \OC_Util::addStyle('core', 'myFancyCSSFile1');
  412. \OC_Util::addStyle('myApp', 'myFancyCSSFile2');
  413. \OC_Util::addStyle('core', 'myFancyCSSFile0', true);
  414. \OC_Util::addStyle('core', 'myFancyCSSFile10', true);
  415. // add duplicate
  416. \OC_Util::addStyle('core', 'myFancyCSSFile1');
  417. $this->assertEquals([], \OC_Util::$scripts);
  418. $this->assertEquals([
  419. 'core/css/myFancyCSSFile10',
  420. 'core/css/myFancyCSSFile0',
  421. 'core/css/myFancyCSSFile1',
  422. 'myApp/css/myFancyCSSFile2',
  423. ], \OC_Util::$styles);
  424. }
  425. public function testAddVendorStyle() {
  426. \OC_Util::addVendorStyle('core', 'myFancyCSSFile1');
  427. \OC_Util::addVendorStyle('myApp', 'myFancyCSSFile2');
  428. \OC_Util::addVendorStyle('core', 'myFancyCSSFile0', true);
  429. \OC_Util::addVendorStyle('core', 'myFancyCSSFile10', true);
  430. // add duplicate
  431. \OC_Util::addVendorStyle('core', 'myFancyCSSFile1');
  432. $this->assertEquals([], \OC_Util::$scripts);
  433. $this->assertEquals([
  434. 'core/vendor/myFancyCSSFile10',
  435. 'core/vendor/myFancyCSSFile0',
  436. 'core/vendor/myFancyCSSFile1',
  437. 'myApp/vendor/myFancyCSSFile2',
  438. ], \OC_Util::$styles);
  439. }
  440. }
  441. /**
  442. * Dummy OC Util class to make it possible to override the app manager
  443. */
  444. class Dummy_OC_Util extends OC_Util {
  445. /**
  446. * @var \OCP\App\IAppManager
  447. */
  448. public static $appManager;
  449. protected static function getAppManager() {
  450. return self::$appManager;
  451. }
  452. }