config.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Frank Karlitschek <frank@karlitschek.de>
  9. * @author Jesús Macias <jmacias@solidgear.es>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Vincent Petry <pvince81@owncloud.com>
  20. *
  21. * @license AGPL-3.0
  22. *
  23. * This code is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU Affero General Public License, version 3,
  25. * as published by the Free Software Foundation.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU Affero General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU Affero General Public License, version 3,
  33. * along with this program. If not, see <http://www.gnu.org/licenses/>
  34. *
  35. */
  36. use phpseclib\Crypt\AES;
  37. use \OCA\Files_External\AppInfo\Application;
  38. use \OCA\Files_External\Lib\Backend\LegacyBackend;
  39. use \OCA\Files_External\Lib\StorageConfig;
  40. use \OCA\Files_External\Lib\Backend\Backend;
  41. use \OCP\Files\StorageNotAvailableException;
  42. /**
  43. * Class to configure mount.json globally and for users
  44. */
  45. class OC_Mount_Config {
  46. // TODO: make this class non-static and give it a proper namespace
  47. const MOUNT_TYPE_GLOBAL = 'global';
  48. const MOUNT_TYPE_GROUP = 'group';
  49. const MOUNT_TYPE_USER = 'user';
  50. const MOUNT_TYPE_PERSONAL = 'personal';
  51. // whether to skip backend test (for unit tests, as this static class is not mockable)
  52. public static $skipTest = false;
  53. /** @var Application */
  54. public static $app;
  55. /**
  56. * @param string $class
  57. * @param array $definition
  58. * @return bool
  59. * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
  60. */
  61. public static function registerBackend($class, $definition) {
  62. $backendService = self::$app->getContainer()->query('OCA\Files_External\Service\BackendService');
  63. $auth = self::$app->getContainer()->query('OCA\Files_External\Lib\Auth\Builtin');
  64. $backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
  65. return true;
  66. }
  67. /**
  68. * Returns the mount points for the given user.
  69. * The mount point is relative to the data directory.
  70. *
  71. * @param string $uid user
  72. * @return array of mount point string as key, mountpoint config as value
  73. *
  74. * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
  75. */
  76. public static function getAbsoluteMountPoints($uid) {
  77. $mountPoints = array();
  78. $userGlobalStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserGlobalStoragesService');
  79. $userStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
  80. $user = self::$app->getContainer()->query('OCP\IUserManager')->get($uid);
  81. $userGlobalStoragesService->setUser($user);
  82. $userStoragesService->setUser($user);
  83. foreach ($userGlobalStoragesService->getStorages() as $storage) {
  84. /** @var \OCA\Files_External\Lib\StorageConfig $storage */
  85. $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
  86. $mountEntry = self::prepareMountPointEntry($storage, false);
  87. foreach ($mountEntry['options'] as &$option) {
  88. $option = self::setUserVars($uid, $option);
  89. }
  90. $mountPoints[$mountPoint] = $mountEntry;
  91. }
  92. foreach ($userStoragesService->getStorages() as $storage) {
  93. $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
  94. $mountEntry = self::prepareMountPointEntry($storage, true);
  95. foreach ($mountEntry['options'] as &$option) {
  96. $option = self::setUserVars($uid, $option);
  97. }
  98. $mountPoints[$mountPoint] = $mountEntry;
  99. }
  100. $userGlobalStoragesService->resetUser();
  101. $userStoragesService->resetUser();
  102. return $mountPoints;
  103. }
  104. /**
  105. * Get the system mount points
  106. *
  107. * @return array
  108. *
  109. * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
  110. */
  111. public static function getSystemMountPoints() {
  112. $mountPoints = [];
  113. $service = self::$app->getContainer()->query('OCA\Files_External\Service\GlobalStoragesService');
  114. foreach ($service->getStorages() as $storage) {
  115. $mountPoints[] = self::prepareMountPointEntry($storage, false);
  116. }
  117. return $mountPoints;
  118. }
  119. /**
  120. * Get the personal mount points of the current user
  121. *
  122. * @return array
  123. *
  124. * @deprecated 8.2.0 use UserStoragesService::getStorages()
  125. */
  126. public static function getPersonalMountPoints() {
  127. $mountPoints = [];
  128. $service = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
  129. foreach ($service->getStorages() as $storage) {
  130. $mountPoints[] = self::prepareMountPointEntry($storage, true);
  131. }
  132. return $mountPoints;
  133. }
  134. /**
  135. * Convert a StorageConfig to the legacy mountPoints array format
  136. * There's a lot of extra information in here, to satisfy all of the legacy functions
  137. *
  138. * @param StorageConfig $storage
  139. * @param bool $isPersonal
  140. * @return array
  141. */
  142. private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
  143. $mountEntry = [];
  144. $mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
  145. $mountEntry['class'] = $storage->getBackend()->getIdentifier();
  146. $mountEntry['backend'] = $storage->getBackend()->getText();
  147. $mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
  148. $mountEntry['personal'] = $isPersonal;
  149. $mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
  150. $mountEntry['mountOptions'] = $storage->getMountOptions();
  151. $mountEntry['priority'] = $storage->getPriority();
  152. $mountEntry['applicable'] = [
  153. 'groups' => $storage->getApplicableGroups(),
  154. 'users' => $storage->getApplicableUsers(),
  155. ];
  156. // if mountpoint is applicable to all users the old API expects ['all']
  157. if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
  158. $mountEntry['applicable']['users'] = ['all'];
  159. }
  160. $mountEntry['id'] = $storage->getId();
  161. return $mountEntry;
  162. }
  163. /**
  164. * fill in the correct values for $user
  165. *
  166. * @param string $user user value
  167. * @param string|array $input
  168. * @return string
  169. */
  170. public static function setUserVars($user, $input) {
  171. if (is_array($input)) {
  172. foreach ($input as &$value) {
  173. if (is_string($value)) {
  174. $value = str_replace('$user', $user, $value);
  175. }
  176. }
  177. } else {
  178. if (is_string($input)) {
  179. $input = str_replace('$user', $user, $input);
  180. }
  181. }
  182. return $input;
  183. }
  184. /**
  185. * Test connecting using the given backend configuration
  186. *
  187. * @param string $class backend class name
  188. * @param array $options backend configuration options
  189. * @param boolean $isPersonal
  190. * @return int see self::STATUS_*
  191. * @throws Exception
  192. */
  193. public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
  194. if (self::$skipTest) {
  195. return StorageNotAvailableException::STATUS_SUCCESS;
  196. }
  197. foreach ($options as &$option) {
  198. $option = self::setUserVars(OCP\User::getUser(), $option);
  199. }
  200. if (class_exists($class)) {
  201. try {
  202. /** @var \OC\Files\Storage\Common $storage */
  203. $storage = new $class($options);
  204. try {
  205. $result = $storage->test($isPersonal, $testOnly);
  206. $storage->setAvailability($result);
  207. if ($result) {
  208. return StorageNotAvailableException::STATUS_SUCCESS;
  209. }
  210. } catch (\Exception $e) {
  211. $storage->setAvailability(false);
  212. throw $e;
  213. }
  214. } catch (Exception $exception) {
  215. \OCP\Util::logException('files_external', $exception);
  216. throw $exception;
  217. }
  218. }
  219. return StorageNotAvailableException::STATUS_ERROR;
  220. }
  221. /**
  222. * Read the mount points in the config file into an array
  223. *
  224. * @param string|null $user If not null, personal for $user, otherwise system
  225. * @return array
  226. */
  227. public static function readData($user = null) {
  228. if (isset($user)) {
  229. $jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
  230. } else {
  231. $config = \OC::$server->getConfig();
  232. $datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
  233. $jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
  234. }
  235. if (is_file($jsonFile)) {
  236. $mountPoints = json_decode(file_get_contents($jsonFile), true);
  237. if (is_array($mountPoints)) {
  238. return $mountPoints;
  239. }
  240. }
  241. return array();
  242. }
  243. /**
  244. * Get backend dependency message
  245. * TODO: move into AppFramework along with templates
  246. *
  247. * @param Backend[] $backends
  248. * @return string
  249. */
  250. public static function dependencyMessage($backends) {
  251. $l = \OC::$server->getL10N('files_external');
  252. $message = '';
  253. $dependencyGroups = [];
  254. foreach ($backends as $backend) {
  255. foreach ($backend->checkDependencies() as $dependency) {
  256. if ($message = $dependency->getMessage()) {
  257. $message .= '<p>' . $message . '</p>';
  258. } else {
  259. $dependencyGroups[$dependency->getDependency()][] = $backend;
  260. }
  261. }
  262. }
  263. foreach ($dependencyGroups as $module => $dependants) {
  264. $backends = implode(', ', array_map(function($backend) {
  265. return '"' . $backend->getText() . '"';
  266. }, $dependants));
  267. $message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
  268. }
  269. return $message;
  270. }
  271. /**
  272. * Returns a dependency missing message
  273. *
  274. * @param \OCP\IL10N $l
  275. * @param string $module
  276. * @param string $backend
  277. * @return string
  278. */
  279. private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
  280. switch (strtolower($module)) {
  281. case 'curl':
  282. return (string)$l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', $backend);
  283. case 'ftp':
  284. return (string)$l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', $backend);
  285. default:
  286. return (string)$l->t('"%s" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it.', array($module, $backend));
  287. }
  288. }
  289. /**
  290. * Encrypt passwords in the given config options
  291. *
  292. * @param array $options mount options
  293. * @return array updated options
  294. */
  295. public static function encryptPasswords($options) {
  296. if (isset($options['password'])) {
  297. $options['password_encrypted'] = self::encryptPassword($options['password']);
  298. // do not unset the password, we want to keep the keys order
  299. // on load... because that's how the UI currently works
  300. $options['password'] = '';
  301. }
  302. return $options;
  303. }
  304. /**
  305. * Decrypt passwords in the given config options
  306. *
  307. * @param array $options mount options
  308. * @return array updated options
  309. */
  310. public static function decryptPasswords($options) {
  311. // note: legacy options might still have the unencrypted password in the "password" field
  312. if (isset($options['password_encrypted'])) {
  313. $options['password'] = self::decryptPassword($options['password_encrypted']);
  314. unset($options['password_encrypted']);
  315. }
  316. return $options;
  317. }
  318. /**
  319. * Encrypt a single password
  320. *
  321. * @param string $password plain text password
  322. * @return string encrypted password
  323. */
  324. private static function encryptPassword($password) {
  325. $cipher = self::getCipher();
  326. $iv = \OCP\Util::generateRandomBytes(16);
  327. $cipher->setIV($iv);
  328. return base64_encode($iv . $cipher->encrypt($password));
  329. }
  330. /**
  331. * Decrypts a single password
  332. *
  333. * @param string $encryptedPassword encrypted password
  334. * @return string plain text password
  335. */
  336. private static function decryptPassword($encryptedPassword) {
  337. $cipher = self::getCipher();
  338. $binaryPassword = base64_decode($encryptedPassword);
  339. $iv = substr($binaryPassword, 0, 16);
  340. $cipher->setIV($iv);
  341. $binaryPassword = substr($binaryPassword, 16);
  342. return $cipher->decrypt($binaryPassword);
  343. }
  344. /**
  345. * Returns the encryption cipher
  346. *
  347. * @return AES
  348. */
  349. private static function getCipher() {
  350. $cipher = new AES(AES::MODE_CBC);
  351. $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
  352. return $cipher;
  353. }
  354. /**
  355. * Computes a hash based on the given configuration.
  356. * This is mostly used to find out whether configurations
  357. * are the same.
  358. *
  359. * @param array $config
  360. * @return string
  361. */
  362. public static function makeConfigHash($config) {
  363. $data = json_encode(
  364. array(
  365. 'c' => $config['backend'],
  366. 'a' => $config['authMechanism'],
  367. 'm' => $config['mountpoint'],
  368. 'o' => $config['options'],
  369. 'p' => isset($config['priority']) ? $config['priority'] : -1,
  370. 'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
  371. )
  372. );
  373. return hash('md5', $data);
  374. }
  375. }