config.php 13 KB

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