<commit_before><?php
/**
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

namespace OCA\Provisioning_API;

use \OC_OCS_Result;
use \OC_SubAdmin;
use \OC_Helper;
use OCP\Files\NotFoundException;

class Users {

	/** @var \OCP\IUserManager */
	private $userManager;

	/** @var \OCP\IConfig */
	private $config;

	/** @var \OCP\IGroupManager */
	private $groupManager;

	/** @var \OCP\IUserSession */
	private $userSession;

	/**
	 * @param \OCP\IUserManager $userManager
	 * @param \OCP\IConfig $config
	 * @param \OCP\IGroupManager $groupManager
	 * @param \OCP\IUserSession $user
	 */
	public function __construct(\OCP\IUserManager $userManager,
	                            \OCP\IConfig $config,
								\OCP\IGroupManager $groupManager,
								\OCP\IUserSession $userSession) {
		$this->userManager = $userManager;
		$this->config = $config;
		$this->groupManager = $groupManager;
		$this->userSession = $userSession;
	}

	/**
	 * returns a list of users
	 */
	public function getUsers(){
		$search = !empty($_GET['search']) ? $_GET['search'] : '';
		$limit = !empty($_GET['limit']) ? $_GET['limit'] : null;
		$offset = !empty($_GET['offset']) ? $_GET['offset'] : null;

		$users = $this->userManager->search($search, $limit, $offset);
		$users = array_keys($users);

		return new OC_OCS_Result([
			'users' => $users
		]);
	}

	public function addUser(){
		$userId = isset($_POST['userid']) ? $_POST['userid'] : null;
		$password = isset($_POST['password']) ? $_POST['password'] : null;
		if($this->userManager->userExists($userId)) {
			\OCP\Util::writeLog('ocs_api', 'Failed addUser attempt: User already exists.', \OCP\Util::ERROR);
			return new OC_OCS_Result(null, 102, 'User already exists');
		} else {
			try {
				$this->userManager->createUser($userId, $password);
				\OCP\Util::writeLog('ocs_api', 'Successful addUser call with userid: '.$_POST['userid'], \OCP\Util::INFO);
				return new OC_OCS_Result(null, 100);
			} catch (\Exception $e) {
				\OCP\Util::writeLog('ocs_api', 'Failed addUser attempt with exception: '.$e->getMessage(), \OCP\Util::ERROR);
				return new OC_OCS_Result(null, 101, 'Bad request');
			}
		}
	}

	/**
	 * gets user info
	 */
	public function getUser($parameters){
		$userId = $parameters['userid'];
		// Admin? Or SubAdmin?
		if($this->groupManager->isAdmin($this->userSession->getUser()->getUID()) || OC_SubAdmin::isUserAccessible($this->userSession->getUser()->getUID(), $userId)) {
			// Check they exist
			if(!$this->userManager->userExists($userId)) {
				return new OC_OCS_Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The requested user could not be found');
			}
			// Show all
			$return = array(
				'email',
				'enabled',
				);
			if($this->userSession->getUser()->getUID() !== $userId) {
				$return[] = 'quota';
			}
		} else {
			// Check they are looking up themselves
			if($this->userSession->getUser()->getUID() !== $userId) {
				return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED);
			}
			// Return some additional information compared to the core route
			$return = array(
				'email',
				'displayname',
				);
		}

		// Find the data
		$data = [];
		$data = self::fillStorageInfo($userId, $data);
		$data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
		$data['email'] = $this->config->getUserValue($userId, 'settings', 'email');
		$data['displayname'] = $this->userManager->get($parameters['userid']);

		// Return the appropriate data
		$responseData = array();
		foreach($return as $key) {
			$responseData[$key] = $data[$key];
		}

		return new OC_OCS_Result($responseData);
	}

	/** 
	 * edit users
	 */
	public function editUser($parameters){
		$userId = $parameters['userid'];
		if($userId === $this->userSession->getUser()->getUID()) {
			// Editing self (display, email)
			$permittedFields[] = 'display';
			$permittedFields[] = 'email';
			$permittedFields[] = 'password';
			// If admin they can edit their own quota
			if($this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
				$permittedFields[] = 'quota';
			}
		} else {
			// Check if admin / subadmin
			if(OC_SubAdmin::isUserAccessible($this->userSession->getUser()->getUID(), $userId)
			|| $this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
				// They have permissions over the user
				$permittedFields[] = 'display';
				$permittedFields[] = 'quota';
				$permittedFields[] = 'password';
				$permittedFields[] = 'email';
			} else {
				// No rights
				return new OC_OCS_Result(null, 997);
			}
		}
		// Check if permitted to edit this field
		if(!in_array($parameters['_put']['key'], $permittedFields)) {
			return new OC_OCS_Result(null, 997);
		}
		// Process the edit
		switch($parameters['_put']['key']){
			case 'display':
				$this->userManager->get($userId)->setDisplayName($parameters['_put']['value']);
				break;
			case 'quota':
				$quota = $parameters['_put']['value'];
				if($quota !== 'none' and $quota !== 'default') {
					if (is_numeric($quota)) {
						$quota = floatval($quota);
					} else {
						$quota = OC_Helper::computerFileSize($quota);
					}
					if ($quota === false) {
						return new OC_OCS_Result(null, 103, "Invalid quota value {$parameters['_put']['value']}");
					}
					if($quota === 0) {
						$quota = 'default';
					}else if($quota === -1){
						$quota = 'none';
					} else {
						$quota = OC_Helper::humanFileSize($quota);
					}
				}
				$this->config->setUserValue($userId, 'files', 'quota', $quota);
				break;
			case 'password':
				$this->userManager->get($userId)->setPassword($parameters['_put']['value']);
				break;
			case 'email':
				if(filter_var($parameters['_put']['value'], FILTER_VALIDATE_EMAIL)) {<commit_msg>[provisioning api] Move away from OC\Util to OCP\Util<commit_after><?php
/**
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

namespace OCA\Provisioning_API;

use \OC_OCS_Result;
use \OC_SubAdmin;
use \OC_Helper;
use OCP\Files\NotFoundException;

class Users {

	/** @var \OCP\IUserManager */
	private $userManager;

	/** @var \OCP\IConfig */
	private $config;

	/** @var \OCP\IGroupManager */
	private $groupManager;

	/** @var \OCP\IUserSession */
	private $userSession;

	/**
	 * @param \OCP\IUserManager $userManager
	 * @param \OCP\IConfig $config
	 * @param \OCP\IGroupManager $groupManager
	 * @param \OCP\IUserSession $user
	 */
	public function __construct(\OCP\IUserManager $userManager,
	                            \OCP\IConfig $config,
								\OCP\IGroupManager $groupManager,
								\OCP\IUserSession $userSession) {
		$this->userManager = $userManager;
		$this->config = $config;
		$this->groupManager = $groupManager;
		$this->userSession = $userSession;
	}

	/**
	 * returns a list of users
	 */
	public function getUsers(){
		$search = !empty($_GET['search']) ? $_GET['search'] : '';
		$limit = !empty($_GET['limit']) ? $_GET['limit'] : null;
		$offset = !empty($_GET['offset']) ? $_GET['offset'] : null;

		$users = $this->userManager->search($search, $limit, $offset);
		$users = array_keys($users);

		return new OC_OCS_Result([
			'users' => $users
		]);
	}

	public function addUser(){
		$userId = isset($_POST['userid']) ? $_POST['userid'] : null;
		$password = isset($_POST['password']) ? $_POST['password'] : <PASSWORD>;
		if($this->userManager->userExists($userId)) {
			\OCP\Util::writeLog('ocs_api', 'Failed addUser attempt: User already exists.', \OCP\Util::ERROR);
			return new OC_OCS_Result(null, 102, 'User already exists');
		} else {
			try {
				$this->userManager->createUser($userId, $password);
				\OCP\Util::writeLog('ocs_api', 'Successful addUser call with userid: '.$_POST['userid'], \OCP\Util::INFO);
				return new OC_OCS_Result(null, 100);
			} catch (\Exception $e) {
				\OCP\Util::writeLog('ocs_api', 'Failed addUser attempt with exception: '.$e->getMessage(), \OCP\Util::ERROR);
				return new OC_OCS_Result(null, 101, 'Bad request');
			}
		}
	}

	/**
	 * gets user info
	 */
	public function getUser($parameters){
		$userId = $parameters['userid'];
		// Admin? Or SubAdmin?
		if($this->groupManager->isAdmin($this->userSession->getUser()->getUID()) || OC_SubAdmin::isUserAccessible($this->userSession->getUser()->getUID(), $userId)) {
			// Check they exist
			if(!$this->userManager->userExists($userId)) {
				return new OC_OCS_Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The requested user could not be found');
			}
			// Show all
			$return = array(
				'email',
				'enabled',
				);
			if($this->userSession->getUser()->getUID() !== $userId) {
				$return[] = 'quota';
			}
		} else {
			// Check they are looking up themselves
			if($this->userSession->getUser()->getUID() !== $userId) {
				return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED);
			}
			// Return some additional information compared to the core route
			$return = array(
				'email',
				'displayname',
				);
		}

		// Find the data
		$data = [];
		$data = self::fillStorageInfo($userId, $data);
		$data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
		$data['email'] = $this->config->getUserValue($userId, 'settings', 'email');
		$data['displayname'] = $this->userManager->get($parameters['userid']);

		// Return the appropriate data
		$responseData = array();
		foreach($return as $key) {
			$responseData[$key] = $data[$key];
		}

		return new OC_OCS_Result($responseData);
	}

	/** 
	 * edit users
	 */
	public function editUser($parameters){
		$userId = $parameters['userid'];
		if($userId === $this->userSession->getUser()->getUID()) {
			// Editing self (display, email)
			$permittedFields[] = 'display';
			$permittedFields[] = 'email';
			$permittedFields[] = 'password';
			// If admin they can edit their own quota
			if($this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
				$permittedFields[] = 'quota';
			}
		} else {
			// Check if admin / subadmin
			if(OC_SubAdmin::isUserAccessible($this->userSession->getUser()->getUID(), $userId)
			|| $this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
				// They have permissions over the user
				$permittedFields[] = 'display';
				$permittedFields[] = 'quota';
				$permittedFields[] = 'password';
				$permittedFields[] = 'email';
			} else {
				// No rights
				return new OC_OCS_Result(null, 997);
			}
		}
		// Check if permitted to edit this field
		if(!in_array($parameters['_put']['key'], $permittedFields)) {
			return new OC_OCS_Result(null, 997);
		}
		// Process the edit
		switch($parameters['_put']['key']){
			case 'display':
				$this->userManager->get($userId)->setDisplayName($parameters['_put']['value']);
				break;
			case 'quota':
				$quota = $parameters['_put']['value'];
				if($quota !== 'none' and $quota !== 'default') {
					if (is_numeric($quota)) {
						$quota = floatval($quota);
					} else {
						$quota = \OCP\Util::computerFileSize($quota);
					}
					if ($quota === false) {
						return new OC_OCS_Result(null, 103, "Invalid quota value {$parameters['_put']['value']}");
					}
					if($quota === 0) {
						$quota = 'default';
					}else if($quota === -1){
						$quota = 'none';
					} else {
						$quota = \OCP\Util::humanFileSize($quota);
					}
				}
				$this->config->setUserValue($userId, 'files', 'quota', $quota);
				break;
			case 'password':
				$this->userManager->get($userId)->setPassword($parameters['_put']['value']);
				break;
			case 'email':
				if(filter_var($parameters['_put']['value'], FILTER_VALIDATE_EMAIL)) {
{'fraction_non_alphanumeric': 0.18052147239263805, 'fraction_numerical': 0.004294478527607362, 'mean_word_length': 3.752551020408163, 'pattern_counts': {'":': 0, '<': 38, '<?xml version=': 0, '>': 152, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5610466', 'n_tokens_mistral': 4952, 'n_tokens_neox': 4273, 'n_words': 995}