UtilTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 [
  177. // valid names
  178. ['boringname', true],
  179. ['something.with.extension', true],
  180. ['now with spaces', true],
  181. ['.a', true],
  182. ['..a', true],
  183. ['.dotfile', true],
  184. ['single\'quote', true],
  185. [' spaces before', true],
  186. ['spaces after ', true],
  187. ['allowed chars including the crazy ones $%&_-^@!,()[]{}=;#', true],
  188. ['汉字也能用', true],
  189. ['und Ümläüte sind auch willkommen', true],
  190. // disallowed names
  191. ['', false],
  192. [' ', false],
  193. ['.', false],
  194. ['..', false],
  195. ['back\\slash', false],
  196. ['sl/ash', false],
  197. ['lt<lt', true],
  198. ['gt>gt', true],
  199. ['col:on', true],
  200. ['double"quote', true],
  201. ['pi|pe', true],
  202. ['dont?ask?questions?', true],
  203. ['super*star', true],
  204. ['new\nline', false],
  205. // better disallow these to avoid unexpected trimming to have side effects
  206. [' ..', false],
  207. ['.. ', false],
  208. ['. ', false],
  209. [' .', false],
  210. // part files not allowed
  211. ['.part', false],
  212. ['notallowed.part', false],
  213. ['neither.filepart', false],
  214. // part in the middle is ok
  215. ['super movie part one.mkv', true],
  216. ['super.movie.part.mkv', true],
  217. ];
  218. }
  219. /**
  220. * @dataProvider dataProviderForTestIsSharingDisabledForUser
  221. * @param array $groups existing groups
  222. * @param array $membership groups the user belong to
  223. * @param array $excludedGroups groups which should be excluded from sharing
  224. * @param bool $expected expected result
  225. */
  226. function testIsSharingDisabledForUser($groups, $membership, $excludedGroups, $expected) {
  227. $config = $this->getMockBuilder('OCP\IConfig')->disableOriginalConstructor()->getMock();
  228. $groupManager = $this->getMockBuilder('OCP\IGroupManager')->disableOriginalConstructor()->getMock();
  229. $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock();
  230. $config
  231. ->expects($this->at(0))
  232. ->method('getAppValue')
  233. ->with('core', 'shareapi_exclude_groups', 'no')
  234. ->will($this->returnValue('yes'));
  235. $config
  236. ->expects($this->at(1))
  237. ->method('getAppValue')
  238. ->with('core', 'shareapi_exclude_groups_list')
  239. ->will($this->returnValue(json_encode($excludedGroups)));
  240. $groupManager
  241. ->expects($this->at(0))
  242. ->method('getUserGroupIds')
  243. ->with($user)
  244. ->will($this->returnValue($membership));
  245. $result = \OC_Util::isSharingDisabledForUser($config, $groupManager, $user);
  246. $this->assertSame($expected, $result);
  247. }
  248. public function dataProviderForTestIsSharingDisabledForUser() {
  249. return array(
  250. // existing groups, groups the user belong to, groups excluded from sharing, expected result
  251. array(array('g1', 'g2', 'g3'), array(), array('g1'), false),
  252. array(array('g1', 'g2', 'g3'), array(), array(), false),
  253. array(array('g1', 'g2', 'g3'), array('g2'), array('g1'), false),
  254. array(array('g1', 'g2', 'g3'), array('g2'), array(), false),
  255. array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1'), false),
  256. array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2'), true),
  257. array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2', 'g3'), true),
  258. );
  259. }
  260. /**
  261. * Test default apps
  262. *
  263. * @dataProvider defaultAppsProvider
  264. * @group DB
  265. */
  266. function testDefaultApps($defaultAppConfig, $expectedPath, $enabledApps) {
  267. $oldDefaultApps = \OCP\Config::getSystemValue('defaultapp', '');
  268. // CLI is doing messy stuff with the webroot, so need to work it around
  269. $oldWebRoot = \OC::$WEBROOT;
  270. \OC::$WEBROOT = '';
  271. $appManager = $this->createMock(IAppManager::class);
  272. $appManager->expects($this->any())
  273. ->method('isEnabledForUser')
  274. ->will($this->returnCallback(function($appId) use ($enabledApps){
  275. return in_array($appId, $enabledApps);
  276. }));
  277. Dummy_OC_Util::$appManager = $appManager;
  278. // need to set a user id to make sure enabled apps are read from cache
  279. \OC_User::setUserId($this->getUniqueID());
  280. \OCP\Config::setSystemValue('defaultapp', $defaultAppConfig);
  281. $this->assertEquals('http://localhost/' . $expectedPath, Dummy_OC_Util::getDefaultPageUrl());
  282. // restore old state
  283. \OC::$WEBROOT = $oldWebRoot;
  284. \OCP\Config::setSystemValue('defaultapp', $oldDefaultApps);
  285. \OC_User::setUserId(null);
  286. }
  287. function defaultAppsProvider() {
  288. return array(
  289. // none specified, default to files
  290. array(
  291. '',
  292. 'index.php/apps/files/',
  293. array('files'),
  294. ),
  295. // unexisting or inaccessible app specified, default to files
  296. array(
  297. 'unexist',
  298. 'index.php/apps/files/',
  299. array('files'),
  300. ),
  301. // non-standard app
  302. array(
  303. 'calendar',
  304. 'index.php/apps/calendar/',
  305. array('files', 'calendar'),
  306. ),
  307. // non-standard app with fallback
  308. array(
  309. 'contacts,calendar',
  310. 'index.php/apps/calendar/',
  311. array('files', 'calendar'),
  312. ),
  313. );
  314. }
  315. public function testGetDefaultPageUrlWithRedirectUrlWithoutFrontController() {
  316. putenv('front_controller_active=false');
  317. \OC::$server->getConfig()->deleteSystemValue('htaccess.IgnoreFrontController');
  318. $_REQUEST['redirect_url'] = 'myRedirectUrl.com';
  319. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/myRedirectUrl.com', OC_Util::getDefaultPageUrl());
  320. }
  321. public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithoutFrontController() {
  322. putenv('front_controller_active=false');
  323. \OC::$server->getConfig()->deleteSystemValue('htaccess.IgnoreFrontController');
  324. $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a';
  325. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/index.php/apps/files/', OC_Util::getDefaultPageUrl());
  326. }
  327. public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithFrontController() {
  328. putenv('front_controller_active=true');
  329. $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a';
  330. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/apps/files/', OC_Util::getDefaultPageUrl());
  331. }
  332. public function testGetDefaultPageUrlWithRedirectUrlWithIgnoreFrontController() {
  333. putenv('front_controller_active=false');
  334. \OC::$server->getConfig()->setSystemValue('htaccess.IgnoreFrontController', true);
  335. $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a';
  336. $this->assertSame('http://localhost'.\OC::$WEBROOT.'/apps/files/', OC_Util::getDefaultPageUrl());
  337. }
  338. /**
  339. * Test needUpgrade() when the core version is increased
  340. */
  341. public function testNeedUpgradeCore() {
  342. $config = \OC::$server->getConfig();
  343. $oldConfigVersion = $config->getSystemValue('version', '0.0.0');
  344. $oldSessionVersion = \OC::$server->getSession()->get('OC_Version');
  345. $this->assertFalse(\OCP\Util::needUpgrade());
  346. $config->setSystemValue('version', '7.0.0.0');
  347. \OC::$server->getSession()->set('OC_Version', array(7, 0, 0, 1));
  348. self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null));
  349. $this->assertTrue(\OCP\Util::needUpgrade());
  350. $config->setSystemValue('version', $oldConfigVersion);
  351. \OC::$server->getSession()->set('OC_Version', $oldSessionVersion);
  352. self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null));
  353. $this->assertFalse(\OCP\Util::needUpgrade());
  354. }
  355. public function testCheckDataDirectoryValidity() {
  356. $dataDir = \OCP\Files::tmpFolder();
  357. touch($dataDir . '/.ocdata');
  358. $errors = \OC_Util::checkDataDirectoryValidity($dataDir);
  359. $this->assertEmpty($errors);
  360. \OCP\Files::rmdirr($dataDir);
  361. $dataDir = \OCP\Files::tmpFolder();
  362. // no touch
  363. $errors = \OC_Util::checkDataDirectoryValidity($dataDir);
  364. $this->assertNotEmpty($errors);
  365. \OCP\Files::rmdirr($dataDir);
  366. $errors = \OC_Util::checkDataDirectoryValidity('relative/path');
  367. $this->assertNotEmpty($errors);
  368. }
  369. protected function setUp() {
  370. parent::setUp();
  371. \OC_Util::$scripts = [];
  372. \OC_Util::$styles = [];
  373. }
  374. protected function tearDown() {
  375. parent::tearDown();
  376. \OC_Util::$scripts = [];
  377. \OC_Util::$styles = [];
  378. }
  379. public function testAddScript() {
  380. \OC_Util::addScript('core', 'myFancyJSFile1');
  381. \OC_Util::addScript('myApp', 'myFancyJSFile2');
  382. \OC_Util::addScript('core', 'myFancyJSFile0', true);
  383. \OC_Util::addScript('core', 'myFancyJSFile10', true);
  384. // add duplicate
  385. \OC_Util::addScript('core', 'myFancyJSFile1');
  386. $this->assertEquals([
  387. 'core/js/myFancyJSFile10',
  388. 'core/js/myFancyJSFile0',
  389. 'core/js/myFancyJSFile1',
  390. 'myApp/l10n/en',
  391. 'myApp/js/myFancyJSFile2',
  392. ], \OC_Util::$scripts);
  393. $this->assertEquals([], \OC_Util::$styles);
  394. }
  395. public function testAddVendorScript() {
  396. \OC_Util::addVendorScript('core', 'myFancyJSFile1');
  397. \OC_Util::addVendorScript('myApp', 'myFancyJSFile2');
  398. \OC_Util::addVendorScript('core', 'myFancyJSFile0', true);
  399. \OC_Util::addVendorScript('core', 'myFancyJSFile10', true);
  400. // add duplicate
  401. \OC_Util::addVendorScript('core', 'myFancyJSFile1');
  402. $this->assertEquals([
  403. 'core/vendor/myFancyJSFile10',
  404. 'core/vendor/myFancyJSFile0',
  405. 'core/vendor/myFancyJSFile1',
  406. 'myApp/vendor/myFancyJSFile2',
  407. ], \OC_Util::$scripts);
  408. $this->assertEquals([], \OC_Util::$styles);
  409. }
  410. public function testAddTranslations() {
  411. \OC_Util::addTranslations('appId', 'de');
  412. $this->assertEquals([
  413. 'appId/l10n/de'
  414. ], \OC_Util::$scripts);
  415. $this->assertEquals([], \OC_Util::$styles);
  416. }
  417. public function testAddStyle() {
  418. \OC_Util::addStyle('core', 'myFancyCSSFile1');
  419. \OC_Util::addStyle('myApp', 'myFancyCSSFile2');
  420. \OC_Util::addStyle('core', 'myFancyCSSFile0', true);
  421. \OC_Util::addStyle('core', 'myFancyCSSFile10', true);
  422. // add duplicate
  423. \OC_Util::addStyle('core', 'myFancyCSSFile1');
  424. $this->assertEquals([], \OC_Util::$scripts);
  425. $this->assertEquals([
  426. 'core/css/myFancyCSSFile10',
  427. 'core/css/myFancyCSSFile0',
  428. 'core/css/myFancyCSSFile1',
  429. 'myApp/css/myFancyCSSFile2',
  430. ], \OC_Util::$styles);
  431. }
  432. public function testAddVendorStyle() {
  433. \OC_Util::addVendorStyle('core', 'myFancyCSSFile1');
  434. \OC_Util::addVendorStyle('myApp', 'myFancyCSSFile2');
  435. \OC_Util::addVendorStyle('core', 'myFancyCSSFile0', true);
  436. \OC_Util::addVendorStyle('core', 'myFancyCSSFile10', true);
  437. // add duplicate
  438. \OC_Util::addVendorStyle('core', 'myFancyCSSFile1');
  439. $this->assertEquals([], \OC_Util::$scripts);
  440. $this->assertEquals([
  441. 'core/vendor/myFancyCSSFile10',
  442. 'core/vendor/myFancyCSSFile0',
  443. 'core/vendor/myFancyCSSFile1',
  444. 'myApp/vendor/myFancyCSSFile2',
  445. ], \OC_Util::$styles);
  446. }
  447. }
  448. /**
  449. * Dummy OC Util class to make it possible to override the app manager
  450. */
  451. class Dummy_OC_Util extends OC_Util {
  452. /**
  453. * @var \OCP\App\IAppManager
  454. */
  455. public static $appManager;
  456. protected static function getAppManager() {
  457. return self::$appManager;
  458. }
  459. }