You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UtilTest.php 16KB

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