1
0

util.php 14 KB

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