private function getFreeSpace()
 {
     $usedSpace = OC_Filesystem::filesize('');
     $totalSpace = OC_Preferences::getValue(OC_User::getUser(), 'files', 'quota', 0);
     if ($totalSpace == 0) {
         return 0;
     }
     return $totalSpace - $usedSpace;
 }
Exemplo n.º 2
0
 public function tearDown()
 {
     $userId = OCA_mozilla_sync\User::userHashToId($this->userHash);
     if ($userId != false) {
         OCA_mozilla_sync\User::deleteUser($userId);
     }
     OC_Preferences::deleteUser($this->userName);
     OC_User::deleteUser($this->userName);
 }
Exemplo n.º 3
0
 /**
  * gets user info
  */
 public static function getUser($parameters)
 {
     $userid = $parameters['userid'];
     $return = array();
     $return['email'] = OC_Preferences::getValue($userid, 'settings', 'email', '');
     $default = OC_Appconfig::getValue('files', 'default_quota', 0);
     $return['quota'] = OC_Preferences::getValue($userid, 'files', 'quota', $default);
     return $return;
 }
Exemplo n.º 4
0
 public static function setupFS($user = '')
 {
     // configure the initial filesystem based on the configuration
     if (self::$fsSetup) {
         //setting up the filesystem twice can only lead to trouble
         return false;
     }
     // If we are not forced to load a specific user we load the one that is logged in
     if ($user == "" && OC_User::isLoggedIn()) {
         $user = OC_User::getUser();
     }
     // the filesystem will finish when $user is not empty,
     // mark fs setup here to avoid doing the setup from loading
     // OC_Filesystem
     if ($user != '') {
         self::$fsSetup = true;
     }
     $CONFIG_DATADIRECTORY = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data");
     //first set up the local "root" storage
     if (!self::$rootMounted) {
         OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $CONFIG_DATADIRECTORY), '/');
         self::$rootMounted = true;
     }
     if ($user != "") {
         //if we aren't logged in, there is no use to set up the filesystem
         $user_dir = '/' . $user . '/files';
         $user_root = OC_User::getHome($user);
         $userdirectory = $user_root . '/files';
         if (!is_dir($userdirectory)) {
             mkdir($userdirectory, 0755, true);
         }
         //jail the user into his "home" directory
         OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $user_root), $user);
         OC_Filesystem::init($user_dir);
         $quotaProxy = new OC_FileProxy_Quota();
         OC_FileProxy::register($quotaProxy);
         // Load personal mount config
         if (is_file($user_root . '/mount.php')) {
             $mountConfig = (include $user_root . '/mount.php');
             if (isset($mountConfig['user'][$user])) {
                 foreach ($mountConfig['user'][$user] as $mountPoint => $options) {
                     OC_Filesystem::mount($options['class'], $options['options'], $mountPoint);
                 }
             }
             $mtime = filemtime($user_root . '/mount.php');
             $previousMTime = OC_Preferences::getValue($user, 'files', 'mountconfigmtime', 0);
             if ($mtime > $previousMTime) {
                 //mount config has changed, filecache needs to be updated
                 OC_FileCache::triggerUpdate($user);
                 OC_Preferences::setValue($user, 'files', 'mountconfigmtime', $mtime);
             }
         }
         OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir));
     }
 }
	/**
	 * inform users if a file was shared with them
	 *
	 * @param array $recipientList list of recipients
	 * @param string $itemSource shared item source
	 * @param string $itemType shared item type
	 * @return array list of user to whom the mail send operation failed
	 */
	public function sendInternalShareMail($recipientList, $itemSource, $itemType) {

		$noMail = array();

		foreach ($recipientList as $recipient) {
			$recipientDisplayName = \OCP\User::getDisplayName($recipient);
			$to = \OC_Preferences::getValue($recipient, 'settings', 'email', '');

			if ($to === '') {
				$noMail[] = $recipientDisplayName;
				continue;
			}

			$items = \OCP\Share::getItemSharedWithUser($itemType, $itemSource, $recipient);
			$filename = trim($items[0]['file_target'], '/');
			$subject = (string) $this->l->t('%s shared »%s« with you', array($this->senderDisplayName, $filename));
			$expiration = null;
			if (isset($items[0]['expiration'])) {
				try {
					$date = new DateTime($items[0]['expiration']);
					$expiration = $date->getTimestamp();
				} catch (\Exception $e) {
					\OCP\Util::writeLog('sharing', "Couldn't read date: " . $e->getMessage(), \OCP\Util::ERROR);
				}
			}

			// Link to folder, or root folder if a file

			if ($itemType === 'folder') {
				$args = array(
					'dir' => $filename,
				);
			} else {
				$args = array(
					'dir' => '/',
					'scrollto' => $filename,
				);
			}

			$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);

			list($htmlMail, $alttextMail) = $this->createMailBody($filename, $link, $expiration);

			// send it out now
			try {
				\OCP\Util::sendMail($to, $recipientDisplayName, $subject, $htmlMail, $this->from, $this->senderDisplayName, 1, $alttextMail);
			} catch (\Exception $e) {
				\OCP\Util::writeLog('sharing', "Can't send mail to inform the user about an internal share: " . $e->getMessage() , \OCP\Util::ERROR);
				$noMail[] = $recipientDisplayName;
			}
		}

		return $noMail;

	}
Exemplo n.º 6
0
 public static function getUserQuota($user)
 {
     $userQuota = OC_Preferences::getValue($user, 'files', 'quota', 'default');
     if ($userQuota === 'default') {
         $userQuota = OC_AppConfig::getValue('files', 'default_quota', 'none');
     }
     if ($userQuota === 'none') {
         return \OC\Files\SPACE_UNLIMITED;
     } else {
         return OC_Helper::computerFileSize($userQuota);
     }
 }
Exemplo n.º 7
0
 public function tearDown()
 {
     $this->user = null;
     if ($this->storageMock) {
         $this->storageMock->getCache()->clear();
         $this->storageMock = null;
     }
     \OC\Files\Filesystem::tearDown();
     \OC_User::setUserId('');
     \OC_User::deleteUser($this->user);
     \OC_Preferences::deleteUser($this->user);
 }
Exemplo n.º 8
0
 public static function delete($parameters)
 {
     OC_Util::checkLoggedIn();
     $user = OC_User::getUser();
     $app = addslashes(strip_tags($parameters['app']));
     $key = addslashes(strip_tags($parameters['key']));
     if ($key === "" or $app === "") {
         return new OC_OCS_Result(null, 101);
         //key and app are NOT optional here
     }
     if (OC_Preferences::deleteKey($user, $app, $key)) {
         return new OC_OCS_Result(null, 100);
     }
 }
Exemplo n.º 9
0
 public function dropTableEncryption()
 {
     $tableName = $this->tableName;
     if (!\OC_DB::tableExists($tableName)) {
         return;
     }
     $sql = "select `uid`, max(`recovery_enabled`) as `recovery_enabled`, min(`migration_status`) as `migration_status` from `*PREFIX*{$tableName}` group by `uid`";
     $query = \OCP\DB::prepare($sql);
     $result = $query->execute(array())->fetchAll();
     foreach ($result as $row) {
         \OC_Preferences::setValue($row['uid'], 'files_encryption', 'recovery_enabled', $row['recovery_enabled']);
         \OC_Preferences::setValue($row['uid'], 'files_encryption', 'migration_status', $row['migration_status']);
     }
     \OC_DB::dropTable($tableName);
 }
Exemplo n.º 10
0
 /**
  * get the quota for the user
  * @param user
  * @return int
  */
 private function getQuota($user)
 {
     if (in_array($user, $this->userQuota)) {
         return $this->userQuota[$user];
     }
     $userQuota = OC_Preferences::getValue($user, 'files', 'quota', 'default');
     if ($userQuota == 'default') {
         $userQuota = OC_AppConfig::getValue('files', 'default_quota', 'none');
     }
     if ($userQuota == 'none') {
         $this->userQuota[$user] = -1;
     } else {
         $this->userQuota[$user] = OC_Helper::computerFileSize($userQuota);
     }
     return $this->userQuota[$user];
 }
Exemplo n.º 11
0
 /**
  * get the quota for the current user
  * @return int
  */
 private function getQuota()
 {
     if ($this->userQuota != -1) {
         return $this->userQuota;
     }
     $userQuota = OC_Preferences::getValue(OC_User::getUser(), 'files', 'quota', 'default');
     if ($userQuota == 'default') {
         $userQuota = OC_AppConfig::getValue('files', 'default_quota', 'none');
     }
     if ($userQuota == 'none') {
         $this->userQuota = 0;
     } else {
         $this->userQuota = OC_Helper::computerFileSize($userQuota);
     }
     return $this->userQuota;
 }
 /**
  * @brief Set email address
  * @param $uid The username
  */
 private function setEmail($uid)
 {
     if (!$this->db_conn) {
         return false;
     }
     $sql = 'SELECT email FROM auth_user WHERE username = :uid';
     $sth = $this->db->prepare($sql);
     if ($sth->execute(array(':uid' => $uid))) {
         $row = $sth->fetch();
         if ($row) {
             if (OC_Preferences::setValue($uid, 'settings', 'email', $row['email'])) {
                 return true;
             }
         }
     }
     return false;
 }
Exemplo n.º 13
0
 public static function resetPassword($args)
 {
     if (self::checkToken($args['user'], $args['token'])) {
         if (isset($_POST['password'])) {
             if (OC_User::setPassword($args['user'], $_POST['password'])) {
                 OC_Preferences::deleteKey($args['user'], 'owncloud', 'lostpassword');
                 OC_User::unsetMagicInCookie();
                 self::displayResetPasswordPage(true, $args);
             } else {
                 self::displayResetPasswordPage(false, $args);
             }
         } else {
             self::reset($args);
         }
     } else {
         // Someone lost their password
         self::displayLostPasswordPage(false, false);
     }
 }
 /**
  * @brief Send an email while creating and assigning a task
  * @param Title of the task
  * @param Task description
  * @param Project ID to which the task belongs
  * @param To whom the task is assigned
  * @param Deadline for completing the task
  */
 public static function sendTaskCreationMail($title, $desc, $pid, $member, $deadline)
 {
     try {
         $subject = 'You are assigned a task \'' . $title . '\'';
         $message = 'Hello ' . $member . ',';
         $message .= '<br /><p style="text-indent: 50px;" >';
         $message .= 'You are assigned to the task \'' . $title . '\' under the project \'' . OC_Collaboration_Project::getProjectTitle($pid) . '\'.';
         $message .= '<br /><p style="text-align: justify;" ><span style="font-weight: bold;" >';
         $message .= 'Description: ';
         $message .= '</span>' . $desc . '<br /><br /><span style="font-weight: bold;" >';
         $message .= 'Deadline: ';
         $message .= '</span>' . $deadline . '</p><br /><br />';
         $message .= 'For further details, logon to your owncloud account.';
         $message .= '<br /><br />';
         \OC_Mail::send(OC_Preferences::getValue($member, 'settings', 'email'), $member, $subject, $message, OC_Config::getValue('mail_smtpname', ''), 'Owncloud Collaboration App', true);
     } catch (\Exception $e) {
         OC_Log::write('collaboration', __METHOD__ . ', Exception: ' . $e->getMessage(), OCP\Util::DEBUG);
         return false;
     }
 }
Exemplo n.º 15
0
 /**
  * Send a mail to test the settings
  */
 public static function sendTestMail()
 {
     \OC_Util::checkAdminUser();
     \OCP\JSON::callCheck();
     $l = \OC::$server->getL10N('settings');
     $email = \OC_Preferences::getValue(\OC_User::getUser(), 'settings', 'email', '');
     if (!empty($email)) {
         $defaults = new \OC_Defaults();
         try {
             \OC_Mail::send($email, \OC_User::getDisplayName(), $l->t('test email settings'), $l->t('If you received this email, the settings seem to be correct.'), \OCP\Util::getDefaultEmailAddress('no-reply'), $defaults->getName());
         } catch (\Exception $e) {
             $message = $l->t('A problem occurred while sending the e-mail. Please revisit your settings.');
             \OC_JSON::error(array("data" => array("message" => $message)));
             exit;
         }
         \OC_JSON::success(array("data" => array("message" => $l->t("Email sent"))));
     } else {
         $message = $l->t('You need to set your user email before being able to send test emails.');
         \OC_JSON::error(array("data" => array("message" => $message)));
     }
 }
Exemplo n.º 16
0
 public static function loadUserMountPoints($user)
 {
     $user_dir = '/' . $user . '/files';
     $user_root = OC_User::getHome($user);
     $userdirectory = $user_root . '/files';
     if (is_file($user_root . '/mount.php')) {
         $mountConfig = (include $user_root . '/mount.php');
         if (isset($mountConfig['user'][$user])) {
             foreach ($mountConfig['user'][$user] as $mountPoint => $options) {
                 OC_Filesystem::mount($options['class'], $options['options'], $mountPoint);
             }
         }
         $mtime = filemtime($user_root . '/mount.php');
         $previousMTime = OC_Preferences::getValue($user, 'files', 'mountconfigmtime', 0);
         if ($mtime > $previousMTime) {
             //mount config has changed, filecache needs to be updated
             OC_FileCache::triggerUpdate($user);
             OC_Preferences::setValue($user, 'files', 'mountconfigmtime', $mtime);
         }
     }
 }
Exemplo n.º 17
0
 public static function av_scan($path)
 {
     $path = $path[\OC\Files\Filesystem::signal_param_path];
     if ($path != '') {
         $files_view = \OCP\Files::getStorage("files");
         if ($files_view->file_exists($path)) {
             $root = OC_User::getHome(OC_User::getUser()) . '/files';
             $file = $root . $path;
             $result = self::clamav_scan($file);
             switch ($result) {
                 case CLAMAV_SCANRESULT_UNCHECKED:
                     //TODO: Show warning to the user: The file can not be checked
                     break;
                 case CLAMAV_SCANRESULT_INFECTED:
                     //remove file
                     $files_view->unlink($path);
                     OCP\JSON::error(array("data" => array("message" => "Virus detected! Can't upload the file.")));
                     $email = OC_Preferences::getValue(OC_User::getUser(), 'settings', 'email', '');
                     \OCP\Util::writeLog('files_antivirus', 'Email: ' . $email, \OCP\Util::DEBUG);
                     if (!empty($email)) {
                         $tmpl = new OC_Template('files_antivirus', 'notification');
                         $tmpl->assign('file', $path);
                         $tmpl->assign('host', OCP\Util::getServerHost());
                         $tmpl->assign('user', OC_User::getUser());
                         $msg = $tmpl->fetchPage();
                         $from = OCP\Util::getDefaultEmailAddress('security-noreply');
                         OCP\Util::sendMail($email, OC_User::getUser(), 'Malware detected', $msg, $from, 'ownCloud', 1);
                     }
                     exit;
                     break;
                 case CLAMAV_SCANRESULT_CLEAN:
                     //do nothing
                     break;
             }
         }
     }
 }
Exemplo n.º 18
0
 /**
  * updates the timestamp of the most recent login of this user
  */
 public function updateLastLoginTimestamp()
 {
     $this->lastLogin = time();
     \OC_Preferences::setValue($this->uid, 'login', 'lastLogin', $this->lastLogin);
 }
Exemplo n.º 19
0
 /**
  * @brief Erase a file's versions which exceed the set quota
  */
 private static function expire($filename, $versionsSize = null, $offset = 0)
 {
     if (\OCP\Config::getSystemValue('files_versions', Storage::DEFAULTENABLED) == 'true') {
         list($uid, $filename) = self::getUidAndFilename($filename);
         $versionsFileview = new \OC\Files\View('/' . $uid . '/files_versions');
         // get available disk space for user
         $softQuota = true;
         $quota = \OC_Preferences::getValue($uid, 'files', 'quota');
         if ($quota === null || $quota === 'default') {
             $quota = \OC_Appconfig::getValue('files', 'default_quota');
         }
         if ($quota === null || $quota === 'none') {
             $quota = \OC\Files\Filesystem::free_space('/');
             $softQuota = false;
         } else {
             $quota = \OCP\Util::computerFileSize($quota);
         }
         // make sure that we have the current size of the version history
         if ($versionsSize === null) {
             $versionsSize = self::getVersionsSize($uid);
             if ($versionsSize === false || $versionsSize < 0) {
                 $versionsSize = self::calculateSize($uid);
             }
         }
         // calculate available space for version history
         // subtract size of files and current versions size from quota
         if ($softQuota) {
             $files_view = new \OC\Files\View('/' . $uid . '/files');
             $rootInfo = $files_view->getFileInfo('/');
             $free = $quota - $rootInfo['size'];
             // remaining free space for user
             if ($free > 0) {
                 $availableSpace = $free * self::DEFAULTMAXSIZE / 100 - ($versionsSize + $offset);
                 // how much space can be used for versions
             } else {
                 $availableSpace = $free - $versionsSize - $offset;
             }
         } else {
             $availableSpace = $quota - $offset;
         }
         // with the  probability of 0.1% we reduce the number of all versions not only for the current file
         $random = rand(0, 1000);
         if ($random == 0) {
             $allFiles = true;
         } else {
             $allFiles = false;
         }
         $allVersions = Storage::getVersions($uid, $filename);
         $versionsByFile[$filename] = $allVersions;
         $sizeOfDeletedVersions = self::delOldVersions($versionsByFile, $allVersions, $versionsFileview);
         $availableSpace = $availableSpace + $sizeOfDeletedVersions;
         $versionsSize = $versionsSize - $sizeOfDeletedVersions;
         // if still not enough free space we rearrange the versions from all files
         if ($availableSpace <= 0 || $allFiles) {
             $result = Storage::getAllVersions($uid);
             $versionsByFile = $result['by_file'];
             $allVersions = $result['all'];
             $sizeOfDeletedVersions = self::delOldVersions($versionsByFile, $allVersions, $versionsFileview);
             $availableSpace = $availableSpace + $sizeOfDeletedVersions;
             $versionsSize = $versionsSize - $sizeOfDeletedVersions;
         }
         // Check if enough space is available after versions are rearranged.
         // If not we delete the oldest versions until we meet the size limit for versions,
         // but always keep the two latest versions
         $numOfVersions = count($allVersions) - 2;
         $i = 0;
         while ($availableSpace < 0 && $i < $numOfVersions) {
             $version = current($allVersions);
             $versionsFileview->unlink($version['path'] . '.v' . $version['version']);
             $versionsSize -= $version['size'];
             $availableSpace += $version['size'];
             next($allVersions);
             $i++;
         }
         return $versionsSize;
         // finally return the new size of the version history
     }
     return false;
 }
Exemplo n.º 20
0
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library 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 along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
/**
 * This class provides an easy way for storing user preferences.
 */
OC_Preferences::$object = new \OC\Preferences(OC_DB::getConnection());
class OC_Preferences
{
    public static $object;
    /**
     * @brief Get all users using the preferences
     * @return array with user ids
     *
     * This function returns a list of all users that have at least one entry
     * in the preferences table.
     */
    public static function getUsers()
    {
        return self::$object->getUsers();
    }
    /**
Exemplo n.º 21
0
    if (sizeof($users) !== 1) {
        // User not found
        header('HTTP/1.0 404 Not Found');
        exit;
    }
    // Token found login as that user
    \OC_User::setUserId(array_shift($users));
    $forceUserLogout = true;
}
// check if the user has the right permissions.
\OCP\User::checkLoggedIn();
// rss is of content type text/xml
if (isset($_SERVER['HTTP_ACCEPT']) && stristr($_SERVER['HTTP_ACCEPT'], 'application/rss+xml')) {
    header('Content-Type: application/rss+xml');
} else {
    header('Content-Type: text/xml; charset=UTF-8');
}
// generate and show the rss feed
$l = \OCP\Util::getL10N('activity');
$data = new \OCA\Activity\Data(\OC::$server->getActivityManager());
$groupHelper = new \OCA\Activity\GroupHelper(\OC::$server->getActivityManager(), new \OCA\Activity\DataHelper(\OC::$server->getActivityManager(), new \OCA\Activity\ParameterHelper(new \OC\Files\View(''), $l), $l), false);
$tmpl = new \OCP\Template('activity', 'rss');
$tmpl->assign('rssLang', \OC_Preferences::getValue(\OCP\User::getUser(), 'core', 'lang'));
$tmpl->assign('rssLink', \OCP\Util::linkToAbsolute('activity', 'rss.php'));
$tmpl->assign('rssPubDate', date('r'));
$tmpl->assign('user', \OCP\User::getUser());
$tmpl->assign('activities', $data->read($groupHelper, 0, 30, 'all'));
$tmpl->printPage();
if ($forceUserLogout) {
    \OC_User::logout();
}
Exemplo n.º 22
0
 private static function update_mail($uid, $email)
 {
     if ($email != OC_Preferences::getValue($uid, 'settings', 'email', '')) {
         OC_Preferences::setValue($uid, 'settings', 'email', $email);
         OC_Log::write('saml', 'Set email "' . $email . '" for the user: ' . $uid, OC_Log::DEBUG);
     }
 }
Exemplo n.º 23
0
 public function testDuplicateDataMigration()
 {
     // create test table
     OC_DB::createDbFromStructure(__DIR__ . '/encryption_table.xml');
     // in case of duplicate entries we want to preserve 0 on migration status and 1 on recovery
     $data = array(array('user1', 'server-side', 1, 1), array('user1', 'server-side', 1, 0), array('user1', 'server-side', 0, 1), array('user1', 'server-side', 0, 0));
     foreach ($data as $d) {
         OC_DB::executeAudited('INSERT INTO `*PREFIX*encryption_test` values(?, ?, ?, ?)', $d);
     }
     // preform migration
     $migration = new Migration('encryption_test');
     $migration->dropTableEncryption();
     // assert
     $this->assertTableNotExist('encryption_test');
     $rec = \OC_Preferences::getValue('user1', 'files_encryption', 'recovery_enabled');
     $mig = \OC_Preferences::getValue('user1', 'files_encryption', 'migration_status');
     $this->assertEquals(1, $rec);
     $this->assertEquals(0, $mig);
 }
Exemplo n.º 24
0
     // confirm credentials in cookie
     if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username']) && OC_Preferences::getValue($_COOKIE['oc_username'], "login", "token") === $_COOKIE['oc_token']) {
         OC_User::setUserId($_COOKIE['oc_username']);
         OC_Util::redirectToDefaultPage();
     } else {
         OC_User::unsetMagicInCookie();
     }
     // Someone wants to log in :
 } elseif (isset($_POST["user"]) and isset($_POST['password']) and isset($_SESSION['sectoken']) and isset($_POST['sectoken']) and $_SESSION['sectoken'] == $_POST['sectoken']) {
     if (OC_User::login($_POST["user"], $_POST["password"])) {
         if (!empty($_POST["remember_login"])) {
             if (defined("DEBUG") && DEBUG) {
                 OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
             }
             $token = md5($_POST["user"] . time() . $_POST['password']);
             OC_Preferences::setValue($_POST['user'], 'login', 'token', $token);
             OC_User::setMagicInCookie($_POST["user"], $token);
         } else {
             OC_User::unsetMagicInCookie();
         }
         OC_Util::redirectToDefaultPage();
     } else {
         $error = true;
     }
     // The user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
 } elseif (isset($_SERVER["PHP_AUTH_USER"]) && isset($_SERVER["PHP_AUTH_PW"])) {
     if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
         //OC_Log::write('core',"Logged in with HTTP Authentication",OC_Log::DEBUG);
         OC_User::unsetMagicInCookie();
         $_REQUEST['redirect_url'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
         OC_Util::redirectToDefaultPage();
Exemplo n.º 25
0
 /**
  * Tests that the home storage is not wrapped when no quota exists.
  */
 function testHomeStorageWrapperWithQuota()
 {
     $user1 = uniqid();
     \OC_User::createUser($user1, 'test');
     OC_Preferences::setValue($user1, 'files', 'quota', '1024');
     \OC_User::setUserId($user1);
     \OC_Util::setupFS($user1);
     $userMount = \OC\Files\Filesystem::getMountManager()->find('/' . $user1 . '/');
     $this->assertNotNull($userMount);
     $this->assertTrue($userMount->getStorage()->instanceOfStorage('\\OC\\Files\\Storage\\Wrapper\\Quota'));
     // ensure that root wasn't wrapped
     $rootMount = \OC\Files\Filesystem::getMountManager()->find('/');
     $this->assertNotNull($rootMount);
     $this->assertNotInstanceOf('\\OC\\Files\\Storage\\Wrapper\\Quota', $rootMount->getStorage());
     // clean up
     \OC_User::setUserId('');
     \OC_User::deleteUser($user1);
     OC_Preferences::deleteUser($user1);
     \OC_Util::tearDownFS();
 }
Exemplo n.º 26
0
 /**
  * calculate remaining free space for trash bin
  *
  * @param integer $trashbinSize current size of the trash bin
  * @param string $user
  * @return int available free space for trash bin
  */
 private static function calculateFreeSpace($trashbinSize, $user)
 {
     $softQuota = true;
     $quota = \OC_Preferences::getValue($user, 'files', 'quota');
     $view = new \OC\Files\View('/' . $user);
     if ($quota === null || $quota === 'default') {
         $quota = \OC::$server->getAppConfig()->getValue('files', 'default_quota');
     }
     if ($quota === null || $quota === 'none') {
         $quota = \OC\Files\Filesystem::free_space('/');
         $softQuota = false;
     } else {
         $quota = \OCP\Util::computerFileSize($quota);
     }
     // calculate available space for trash bin
     // subtract size of files and current trash bin size from quota
     if ($softQuota) {
         $rootInfo = $view->getFileInfo('/files/', false);
         $free = $quota - $rootInfo['size'];
         // remaining free space for user
         if ($free > 0) {
             $availableSpace = $free * self::DEFAULTMAXSIZE / 100 - $trashbinSize;
             // how much space can be used for versions
         } else {
             $availableSpace = $free - $trashbinSize;
         }
     } else {
         $availableSpace = $quota;
     }
     return $availableSpace;
 }
Exemplo n.º 27
0
 /**
  * perform login using the magic cookie (remember login)
  *
  * @param string $uid the username
  * @param string $currentToken
  * @return bool
  */
 public function loginWithCookie($uid, $currentToken)
 {
     $this->manager->emit('\\OC\\User', 'preRememberedLogin', array($uid));
     $user = $this->manager->get($uid);
     if (is_null($user)) {
         // user does not exist
         return false;
     }
     // get stored tokens
     $tokens = \OC_Preferences::getKeys($uid, 'login_token');
     // test cookies token against stored tokens
     if (!in_array($currentToken, $tokens, true)) {
         return false;
     }
     // replace successfully used token with a new one
     \OC_Preferences::deleteKey($uid, 'login_token', $currentToken);
     $newToken = \OC_Util::generateRandomBytes(32);
     \OC_Preferences::setValue($uid, 'login_token', $newToken, time());
     $this->setMagicInCookie($user->getUID(), $newToken);
     //login
     $this->setUser($user);
     $this->manager->emit('\\OC\\User', 'postRememberedLogin', array($user));
     return true;
 }
Exemplo n.º 28
0
 /**
  * @brief find the best language
  * @param $app Array or string, details below
  * @returns language
  *
  * If $app is an array, ownCloud assumes that these are the available
  * languages. Otherwise ownCloud tries to find the files in the l10n
  * folder.
  *
  * If nothing works it returns 'en'
  */
 public static function findLanguage($app = null)
 {
     if (!is_array($app) && self::$language != '') {
         return self::$language;
     }
     if (OC_User::getUser() && OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang')) {
         $lang = OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang');
         self::$language = $lang;
         if (is_array($app)) {
             $available = $app;
             $lang_exists = array_search($lang, $available) !== false;
         } else {
             $lang_exists = self::languageExists($app, $lang);
         }
         if ($lang_exists) {
             return $lang;
         }
     }
     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
         $accepted_languages = preg_split('/,\\s*/', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
         if (is_array($app)) {
             $available = $app;
         } else {
             $available = self::findAvailableLanguages($app);
         }
         foreach ($accepted_languages as $i) {
             $temp = explode(';', $i);
             $temp[0] = str_replace('-', '_', $temp[0]);
             if (($key = array_search($temp[0], $available)) !== false) {
                 return $available[$key];
             }
             foreach ($available as $l) {
                 if ($temp[0] == substr($l, 0, 2)) {
                     return $l;
                 }
             }
         }
     }
     // Last try: English
     return 'en';
 }
<?php

/**
 * Copyright (c) 2011 Georg Ehrke <ownclouddev at georgswebsite dot de>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */
require_once '../../../lib/base.php';
OC_JSON::checkLoggedIn();
$duration = OC_Preferences::getValue(OC_User::getUser(), 'calendar', 'duration', "60");
OC_JSON::encodedPrint(array("duration" => $duration));
?>
 
Exemplo n.º 30
0
 /**
  * @brief Modifies the given project
  * @param Project ID
  * @param Project title
  * @param Description of the project
  * @param Deadline of the project
  * @param List of members working in the project and their roles
  * @param Member who updated the project
  * @param Whether or not the project has been completed
  * @return int|boolean (Post ID of the post specifying the project updation|false)
  */
 public static function updateProject($pid, $title, $desc, $deadline, $details, $updater, $completed)
 {
     $post_id = NULL;
     try {
         if ($completed && OC_Collaboration_Task::hasPendingTasks($pid)) {
             throw new \Exception('Cannot delete project with pending tasks');
         }
         \OCP\DB::beginTransaction();
         $query = \OCP\DB::prepare('UPDATE `*PREFIX*collaboration_project` SET `title`=?, `description`=?, `last_updated`=CURRENT_TIMESTAMP, `ending_date`=?, `completed`=? WHERE `pid`=?');
         $query->execute(array($title, $desc, OC_Collaboration_Time::convertUITimeToDBTime($deadline . ' 23:59:59'), $completed, $pid));
         $add_member = \OCP\DB::prepare('INSERT INTO `*PREFIX*collaboration_works_on`(`pid`, `member`, `role`) VALUES(?, ?, ?)');
         $cnt = count($details);
         if ($cnt != 0 && isset($details[0]['member'])) {
             foreach ($details as $detail) {
                 $member = strtolower($detail['member']);
                 if (!OC_User::userExists($member)) {
                     OC_User::createUser($member, $member);
                 }
                 $add_member->execute(array($pid, $member, $detail['role']));
                 OC_Preferences::setValue($member, 'settings', 'email', $detail['email']);
                 OC_Preferences::setValue($member, 'collaboration', 'mobile', $detail['mobile']);
             }
         }
         $post_id = OC_Collaboration_Post::createPost('Project Updated', 'Project \'' . $title . '\' has been updated' . '.', $updater, $pid, 'Project Updation', array(), true);
         \OCP\DB::commit();
     } catch (\Exception $e) {
         OC_Log::write('collaboration', __METHOD__ . ', Exception: ' . $e->getMessage(), OCP\Util::DEBUG);
         return false;
     }
     return $post_id;
 }