1
0

UtilTest.php 16 KB

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