1
0

config.php 13 KB

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