UtilTest.php 16 KB

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