Example #1
0
 public static function deleteGroup($parameters)
 {
     // Check it exists
     if (!OC_Group::groupExists($parameters['groupid'])) {
         return 101;
     } else {
         if ($parameters['groupid'] == 'admin') {
             // Cannot delete admin group
             return 102;
         } else {
             if (OC_Group::deleteGroup($parameters['groupid'])) {
                 return 100;
             } else {
                 return 103;
             }
         }
     }
 }
 /**
  * @brief Add a user to a group
  * @param $uid Name of the user to add to group
  * @param $gid Name of the group in which add the user
  * @returns true/false
  *
  * Adds a user to a group.
  */
 public static function addToGroup($uid, $gid)
 {
     // Does the user exist?
     if (!OC_User::userExists($uid)) {
         return false;
     }
     // Does the group exist?
     if (!OC_Group::groupExists($gid)) {
         return false;
     }
     // Go go go
     $run = true;
     OC_Hook::emit("OC_Group", "pre_addToGroup", array("run" => &$run, "uid" => $uid, "gid" => $gid));
     if ($run && self::$_backend->addToGroup($uid, $gid)) {
         OC_Hook::emit("OC_Group", "post_addToGroup", array("uid" => $uid, "gid" => $gid));
         return true;
     } else {
         return false;
     }
 }
Example #3
0
OC_JSON::checkSubAdminUser();
OCP\JSON::callCheck();
$success = true;
$username = $_POST["username"];
$group = $_POST["group"];
if ($username == OC_User::getUser() && $group == "admin" && OC_User::isAdminUser($username)) {
    $l = OC_L10N::get('core');
    OC_JSON::error(array('data' => array('message' => $l->t('Admins can\'t remove themself from the admin group'))));
    exit;
}
if (!OC_User::isAdminUser(OC_User::getUser()) && (!OC_SubAdmin::isUserAccessible(OC_User::getUser(), $username) || !OC_SubAdmin::isGroupAccessible(OC_User::getUser(), $group))) {
    $l = OC_L10N::get('core');
    OC_JSON::error(array('data' => array('message' => $l->t('Authentication error'))));
    exit;
}
if (!OC_Group::groupExists($group)) {
    OC_Group::createGroup($group);
}
$l = OC_L10N::get('settings');
$error = $l->t("Unable to add user to group %s", $group);
$action = "add";
// Toggle group
if (OC_Group::inGroup($username, $group)) {
    $action = "remove";
    $error = $l->t("Unable to remove user from group %s", $group);
    $success = OC_Group::removeFromGroup($username, $group);
    $usersInGroup = OC_Group::usersInGroup($group);
    if (count($usersInGroup) == 0) {
        OC_Group::deleteGroup($group);
    }
} else {
Example #4
0
    /**
     * creates a unique name for internal ownCloud use for groups. Don't call it directly.
     * @param string $name the display name of the object
     * @return string with with the name to use in ownCloud or false if unsuccessful.
     *
     * Instead of using this method directly, call
     * createAltInternalOwnCloudName($name, false)
     *
     * Group names are also used as display names, so we do a sequential
     * numbering, e.g. Developers_42 when there are 41 other groups called
     * "Developers"
     */
    private function _createAltInternalOwnCloudNameForGroups($name)
    {
        $query = \OCP\DB::prepare('
			SELECT `owncloud_name`
			FROM `' . $this->getMapTable(false) . '`
			WHERE `owncloud_name` LIKE ?
		');
        $usedNames = array();
        $res = $query->execute(array($name . '_%'));
        while ($row = $res->fetchRow()) {
            $usedNames[] = $row['owncloud_name'];
        }
        if (!$usedNames || count($usedNames) === 0) {
            $lastNo = 1;
            //will become name_2
        } else {
            natsort($usedNames);
            $lastName = array_pop($usedNames);
            $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
        }
        $altName = $name . '_' . strval($lastNo + 1);
        unset($usedNames);
        $attempts = 1;
        while ($attempts < 21) {
            // Check to be really sure it is unique
            // while loop is just a precaution. If a name is not generated within
            // 20 attempts, something else is very wrong. Avoids infinite loop.
            if (!\OC_Group::groupExists($altName)) {
                return $altName;
            }
            $altName = $name . '_' . ($lastNo + $attempts);
            $attempts++;
        }
        return false;
    }
 public function checkPassword($uid, $password)
 {
     if (!$this->db_conn) {
         $this->connectdb();
     }
     if (!$this->db_conn) {
         return false;
     }
     $query = 'SELECT user_login, user_pass FROM ' . self::$params['wordpress_db_prefix'] . 'users WHERE user_login = "******"', '""', $uid) . '"';
     $query .= ' AND user_status = 0';
     $result = $this->wp_instance->db->query($query);
     if ($result && mysqli_num_rows($result) > 0) {
         $row = mysqli_fetch_assoc($result);
         $hash = $row['user_pass'];
         $normalize_path = str_replace('\\', '/', OC_APP::getAppPath('user_wordpress'));
         $path_array = explode('/', $normalize_path);
         array_pop($path_array);
         $app_folder = array_pop($path_array);
         OC::$CLASSPATH['OC_wordpress'] = $app_folder . '/lib/wordpress.class.php';
         require_once $app_folder . '/user_wordpress/class-phpass.php';
         $wp_hasher = new WPPasswordHash(8, TRUE);
         $check = $wp_hasher->CheckPassword($password, $hash);
         if ($check === true) {
             // Make sure the user is in the wordpress_global_group
             if (self::$params['wordpress_global_group'] != '') {
                 if (!OC_Group::groupExists(self::$params['wordpress_global_group'])) {
                     OC_Group::createGroup(self::$params['wordpress_global_group']);
                 }
                 $UserblogsIds = $this->wp_instance->getUserblogsIds($uid);
                 if (empty($UserblogsIds)) {
                     // remove from group if current user has no access to Wordpress blog/site with the same role name.
                     OC_Group::removefromGroup($uid, self::$params['wordpress_global_group']);
                 } else {
                     OC_Group::addToGroup($uid, self::$params['wordpress_global_group']);
                 }
             }
             $this->setUserInfos($uid);
             return $row['user_login'];
         }
     }
     return false;
 }
Example #6
0
 /**
  * @brief Add a user to a group
  * @param string $uid Name of the user to add to group
  * @param string $gid Name of the group in which add the user
  * @return bool
  *
  * Adds a user to a group.
  */
 public static function addToGroup($uid, $gid)
 {
     // Does the group exist?
     if (!OC_Group::groupExists($gid)) {
         return false;
     }
     // Go go go
     $run = true;
     OC_Hook::emit("OC_Group", "pre_addToGroup", array("run" => &$run, "uid" => $uid, "gid" => $gid));
     if ($run) {
         $success = false;
         //add the user to the all backends that have the group
         foreach (self::$_usedBackends as $backend) {
             if (!$backend->implementsActions(OC_GROUP_BACKEND_ADD_TO_GROUP)) {
                 continue;
             }
             if ($backend->groupExists($gid)) {
                 $success |= $backend->addToGroup($uid, $gid);
             }
         }
         if ($success) {
             OC_Hook::emit("OC_User", "post_addToGroup", array("uid" => $uid, "gid" => $gid));
         }
         return $success;
     } else {
         return false;
     }
 }
Example #7
0
 private static function update_groups($uid, $groups, $protectedGroups = array(), $just_created = false)
 {
     if (!$just_created) {
         $old_groups = OC_Group::getUserGroups($uid);
         foreach ($old_groups as $group) {
             if (!in_array($group, $protectedGroups) && !in_array($group, $groups)) {
                 // This does not affect groups from user_group_admin
                 OC_Group::removeFromGroup($uid, $group);
                 OC_Log::write('saml', 'Removed "' . $uid . '" from the group "' . $group . '"', OC_Log::DEBUG);
             }
         }
     }
     foreach ($groups as $group) {
         if (preg_match('/[^a-zA-Z0-9 _\\.@\\-\\/]/', $group)) {
             OC_Log::write('saml', 'Invalid group "' . $group . '", allowed chars "a-zA-Z0-9" and "_.@-/" ', OC_Log::DEBUG);
         } else {
             if (!OC_Group::inGroup($uid, $group)) {
                 if (!OC_Group::groupExists($group)) {
                     if (OCP\App::isEnabled('user_group_admin')) {
                         OC_User_Group_Admin_Util::createHiddenGroup($group);
                     } else {
                         OC_Group::createGroup($group);
                     }
                     OC_Log::write('saml', 'New group created: ' . $group, OC_Log::DEBUG);
                 }
                 if (OCP\App::isEnabled('user_group_admin')) {
                     OC_User_Group_Admin_Util::addToGroup($uid, $group);
                 } else {
                     OC_Group::addToGroup($uid, $group);
                 }
                 OC_Log::write('saml', 'Added "' . $uid . '" to the group "' . $group . '"', OC_Log::DEBUG);
             }
         }
     }
 }
 public function groupExists($group)
 {
     return OC_Group::groupExists($group);
 }
Example #9
0
    exit;
}
if ($idtype == 'event' && !OC_Calendar_App::getEventObject($id)) {
    OCP\JSON::error(array('message' => 'permission denied'));
    exit;
}
$sharewith = $_GET['sharewith'];
$sharetype = strip_tags($_GET['sharetype']);
switch ($sharetype) {
    case 'user':
    case 'group':
    case 'public':
        break;
    default:
        OCP\JSON::error(array('message' => 'unexspected parameter'));
        exit;
}
if ($sharetype == 'user' && !OCP\User::userExists($sharewith)) {
    OCP\JSON::error(array('message' => 'user not found'));
    exit;
} elseif ($sharetype == 'group' && !OC_Group::groupExists($sharewith)) {
    OCP\JSON::error(array('message' => 'group not found'));
    exit;
}
$success = OC_Calendar_Share::unshare(OCP\USER::getUser(), $sharewith, $sharetype, $id, $idtype == 'calendar' ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::EVENT);
if ($success) {
    OCP\JSON::success();
} else {
    OCP\JSON::error(array('message' => 'can not unshare'));
    exit;
}
 /**
  * Generate a string to be used for searching for uid_shared_with that handles both users and groups
  * @param $uid (Optional) The uid to get the user groups for, a gid to get the users in a group, or if not set the current user
  * @return An IN operator as a string
  */
 private static function getUsersAndGroups($uid = null)
 {
     $in = " IN(";
     if (isset($uid) && OC_Group::groupExists($uid)) {
         $users = OC_Group::usersInGroup($uid);
         foreach ($users as $user) {
             // Add a comma only if the the current element isn't the last
             if ($user !== end($users)) {
                 $in .= "'" . $user . "@" . $uid . "', ";
             } else {
                 $in .= "'" . $user . "@" . $uid . "'";
             }
         }
     } else {
         if (isset($uid)) {
             // TODO Check if this is necessary, only constructor needs it as IN. It would be better for other queries to just return =$uid
             $in .= "'" . $uid . "'";
             $groups = OC_Group::getUserGroups($uid);
             foreach ($groups as $group) {
                 $in .= ", '" . $uid . "@" . $group . "'";
             }
         } else {
             $uid = OC_User::getUser();
             $in .= "'" . $uid . "'";
             $groups = OC_Group::getUserGroups($uid);
             foreach ($groups as $group) {
                 $in .= ", '" . $uid . "@" . $group . "'";
             }
         }
     }
     $in .= ", '" . self::PUBLICLINK . "'";
     $in .= ")";
     return $in;
 }
Example #11
0
<?php

/**
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
$l = new OC_l10n('collaboration');
OC::$CLASSPATH['OC_Collaboration_Project'] = 'collaboration/lib/projects.php';
OC::$CLASSPATH['OC_Collaboration_Post'] = 'collaboration/lib/posts.php';
OC::$CLASSPATH['OC_Collaboration_Time'] = 'collaboration/lib/time.php';
OC::$CLASSPATH['OC_Collaboration_Comment'] = 'collaboration/lib/comments.php';
OC::$CLASSPATH['OC_Collaboration_Task'] = 'collaboration/lib/tasks.php';
OC::$CLASSPATH['OC_Collaboration_Mail'] = 'collaboration/lib/mail_templates.php';
OC::$CLASSPATH['OC_Collaboration_Hooks'] = 'collaboration/lib/hooks.php';
OC::$CLASSPATH['OC_Collaboration_Skillset'] = 'collaboration/lib/skillset.php';
OC::$CLASSPATH['OC_Collaboration_Report'] = 'collaboration/lib/reports.php';
OC::$CLASSPATH['OC_Collaboration_Calendar'] = 'collaboration/lib/calendar_support.php';
OC_Hook::connect('OC_User', 'post_deleteUser', 'OC_Collaboration_Hooks', 'notifyUserDeletion');
OC_Hook::connect('OCP\\Share', 'post_shared', 'OC_Collaboration_Hooks', 'notifyFileShare');
$gid = "Collaboration Admin";
if (!OC_Group::groupExists($gid)) {
    OC_Group::createGroup($gid);
}
\OCP\App::addNavigationEntry(array('id' => 'collaboration', 'order' => 0, 'href' => \OCP\Util::linkToRoute('collaboration_route', array('rel_path' => '')), 'icon' => \OCP\Util::imagePath('collaboration', 'collaboration.svg'), 'name' => $l->t('Collaboration')));
Example #12
0
    /**
     * @brief returns an internal ownCloud name for the given LDAP DN
     * @param $dn the dn of the user object
     * @param $ldapname optional, the display name of the object
     * @param $isUser optional, wether it is a user object (otherwise group assumed)
     * @returns string with with the name to use in ownCloud
     *
     * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN
     */
    public function dn2ocname($dn, $ldapname = null, $isUser = true)
    {
        $table = $this->getMapTable($isUser);
        if ($isUser) {
            $fncFindMappedName = 'findMappedUser';
            $nameAttribute = $this->connection->ldapUserDisplayName;
        } else {
            $fncFindMappedName = 'findMappedGroup';
            $nameAttribute = $this->connection->ldapGroupDisplayName;
        }
        //let's try to retrieve the ownCloud name from the mappings table
        $ocname = $this->{$fncFindMappedName}($dn);
        if ($ocname) {
            return $ocname;
        }
        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
        $uuid = $this->getUUID($dn);
        if ($uuid) {
            $query = \OCP\DB::prepare('
				SELECT `owncloud_name`
				FROM `' . $table . '`
				WHERE `directory_uuid` = ?
			');
            $component = $query->execute(array($uuid))->fetchOne();
            if ($component) {
                $query = \OCP\DB::prepare('
					UPDATE `' . $table . '`
					SET `ldap_dn` = ?
					WHERE `directory_uuid` = ?
				');
                $query->execute(array($dn, $uuid));
                return $component;
            }
        }
        if (is_null($ldapname)) {
            $ldapname = $this->readAttribute($dn, $nameAttribute);
            if (!isset($ldapname[0]) && empty($ldapname[0])) {
                \OCP\Util::writeLog('user_ldap', 'No or empty name for ' . $dn . '.', \OCP\Util::INFO);
                return false;
            }
            $ldapname = $ldapname[0];
        }
        $ldapname = $this->sanitizeUsername($ldapname);
        //a new user/group! Then let's try to add it. We're shooting into the blue with the user/group name, assuming that in most cases there will not be a conflict. Otherwise an error will occur and we will continue with our second shot.
        if ($isUser && !\OCP\User::userExists($ldapname) || !$isUser && !\OC_Group::groupExists($ldapname)) {
            if ($this->mapComponent($dn, $ldapname, $isUser)) {
                return $ldapname;
            }
        }
        //doh! There is a conflict. We need to distinguish between users/groups. Adding indexes is an idea, but not much of a help for the user. The DN is ugly, but for now the only reasonable way. But we transform it to a readable format and remove the first part to only give the path where this object is located.
        $oc_name = $this->alternateOwnCloudName($ldapname, $dn);
        if ($isUser && !\OCP\User::userExists($oc_name) || !$isUser && !\OC_Group::groupExists($oc_name)) {
            if ($this->mapComponent($dn, $oc_name, $isUser)) {
                return $oc_name;
            }
        }
        //if everything else did not help..
        \OCP\Util::writeLog('user_ldap', 'Could not create unique ownCloud name for ' . $dn . '.', \OCP\Util::INFO);
        return false;
    }
Example #13
0
 private static function ldap2ownCloudNames($ldapObjects, $isUsers)
 {
     if ($isUsers) {
         $knownObjects = self::mappedUsers();
         $nameAttribute = self::conf('ldapUserDisplayName');
     } else {
         $knownObjects = self::mappedGroups();
         $nameAttribute = self::conf('ldapGroupDisplayName');
     }
     $ownCloudNames = array();
     foreach ($ldapObjects as $ldapObject) {
         $key = self::recursiveArraySearch($knownObjects, $ldapObject['dn']);
         //everything is fine when we know the group
         if ($key !== false) {
             $ownCloudNames[] = $knownObjects[$key]['owncloud_name'];
             continue;
         }
         //we do not take empty usernames
         if (!isset($ldapObject[$nameAttribute]) || empty($ldapObject[$nameAttribute])) {
             OCP\Util::writeLog('user_ldap', 'No or empty name for ' . $ldapObject['dn'] . ', skipping.', OCP\Util::INFO);
             continue;
         }
         //a new group! Then let's try to add it. We're shooting into the blue with the group name, assuming that in most cases there will not be a conflict. But first make sure, that the display name contains only allowed characters.
         $ocname = self::sanitizeUsername($ldapObject[$nameAttribute]);
         if ($isUsers && !\OCP\User::userExists($ocname) || !$isUsers && !\OC_Group::groupExists($ocname)) {
             if (self::mapComponent($ldapObject['dn'], $ocname, $isUsers)) {
                 $ownCloudNames[] = $ocname;
                 continue;
             }
         }
         //doh! There is a conflict. We need to distinguish between groups. Adding indexes is an idea, but not much of a help for the user. The DN is ugly, but for now the only reasonable way. But we transform it to a readable format and remove the first part to only give the path where this entry is located.
         $ocname = self::alternateOwnCloudName($ocname, $ldapObject['dn']);
         if ($isUsers && !\OCP\User::userExists($ocname) || !$isUsers && !\OC_Group::groupExists($ocname)) {
             if (self::mapComponent($ldapObject['dn'], $ocname, $isUsers)) {
                 $ownCloudNames[] = $ocname;
                 continue;
             }
         }
         //if everything else did not help..
         OCP\Util::writeLog('user_ldap', 'Could not create unique ownCloud name for ' . $ldapObject['dn'] . ', skipping.', OCP\Util::INFO);
     }
     return $ownCloudNames;
 }
Example #14
0
 function testMultiBackend()
 {
     $backend1 = new OC_Group_Dummy();
     $backend2 = new OC_Group_Dummy();
     OC_Group::useBackend($backend1);
     OC_Group::useBackend($backend2);
     $group1 = uniqid();
     $group2 = uniqid();
     OC_Group::createGroup($group1);
     //groups should be added to the first registered backend
     $this->assertEqual(array($group1), $backend1->getGroups());
     $this->assertEqual(array(), $backend2->getGroups());
     $this->assertEqual(array($group1), OC_Group::getGroups());
     $this->assertTrue(OC_Group::groupExists($group1));
     $this->assertFalse(OC_Group::groupExists($group2));
     $backend1->createGroup($group2);
     $this->assertEqual(array($group1, $group2), OC_Group::getGroups());
     $this->assertTrue(OC_Group::groupExists($group1));
     $this->assertTrue(OC_Group::groupExists($group2));
     $user1 = uniqid();
     $user2 = uniqid();
     $this->assertFalse(OC_Group::inGroup($user1, $group1));
     $this->assertFalse(OC_Group::inGroup($user2, $group1));
     $this->assertTrue(OC_Group::addToGroup($user1, $group1));
     $this->assertTrue(OC_Group::inGroup($user1, $group1));
     $this->assertFalse(OC_Group::inGroup($user2, $group1));
     $this->assertFalse($backend2->inGroup($user1, $group1));
     $this->assertFalse(OC_Group::addToGroup($user1, $group1));
     $this->assertEqual(array($user1), OC_Group::usersInGroup($group1));
     $this->assertEqual(array($group1), OC_Group::getUserGroups($user1));
     $this->assertEqual(array(), OC_Group::getUserGroups($user2));
     OC_Group::deleteGroup($group1);
     $this->assertEqual(array(), OC_Group::getUserGroups($user1));
     $this->assertEqual(array(), OC_Group::usersInGroup($group1));
     $this->assertFalse(OC_Group::inGroup($user1, $group1));
 }
 private static function updateFolder($uid_shared_with)
 {
     if ($uid_shared_with != self::PUBLICLINK) {
         if (OC_Group::groupExists($uid_shared_with)) {
             $uid_shared_with = OC_Group::usersInGroup($uid_shared_with);
             // Remove the owner from the list of users in the group
             $uid_shared_with = array_diff($uid_shared_with, array(OCP\USER::getUser()));
         } else {
             if ($uid = strstr($uid_shared_with, '@', true)) {
                 $uid_shared_with = array($uid);
             } else {
                 $uid_shared_with = array($uid_shared_with);
             }
         }
         foreach ($uid_shared_with as $uid) {
             $sharedFolder = $uid . '/files/Shared';
             // Update mtime of shared folder to invoke a file cache rescan
             $rootView = new OC_FilesystemView('/');
             $rootView->touch($sharedFolder);
         }
     }
 }
Example #16
0
 public function testMultiBackend()
 {
     $userBackend = new \Test\Util\User\Dummy();
     \OC_User::getManager()->registerBackend($userBackend);
     $backend1 = new OC_Group_Dummy();
     $backend2 = new OC_Group_Dummy();
     OC_Group::useBackend($backend1);
     OC_Group::useBackend($backend2);
     $group1 = $this->getUniqueID();
     $group2 = $this->getUniqueID();
     OC_Group::createGroup($group1);
     //groups should be added to the first registered backend
     $this->assertEquals(array($group1), $backend1->getGroups());
     $this->assertEquals(array(), $backend2->getGroups());
     $this->assertEquals(array($group1), OC_Group::getGroups());
     $this->assertTrue(OC_Group::groupExists($group1));
     $this->assertFalse(OC_Group::groupExists($group2));
     $backend1->createGroup($group2);
     $this->assertEquals(array($group1, $group2), OC_Group::getGroups());
     $this->assertTrue(OC_Group::groupExists($group1));
     $this->assertTrue(OC_Group::groupExists($group2));
     $user1 = $this->getUniqueID();
     $user2 = $this->getUniqueID();
     $userBackend->createUser($user1, '');
     $userBackend->createUser($user2, '');
     $this->assertFalse(OC_Group::inGroup($user1, $group1));
     $this->assertFalse(OC_Group::inGroup($user2, $group1));
     $this->assertTrue(OC_Group::addToGroup($user1, $group1));
     $this->assertTrue(OC_Group::inGroup($user1, $group1));
     $this->assertFalse(OC_Group::inGroup($user2, $group1));
     $this->assertFalse($backend2->inGroup($user1, $group1));
     OC_Group::addToGroup($user1, $group1);
     $this->assertEquals(array($user1), OC_Group::usersInGroup($group1));
     $this->assertEquals(array($group1), OC_Group::getUserGroups($user1));
     $this->assertEquals(array(), OC_Group::getUserGroups($user2));
     OC_Group::deleteGroup($group1);
     $this->assertEquals(array(), OC_Group::getUserGroups($user1));
     $this->assertEquals(array(), OC_Group::usersInGroup($group1));
     $this->assertFalse(OC_Group::inGroup($user1, $group1));
 }
Example #17
0
/**
* Gets an array of groups and will try to add the group to OC and then add the user to the groups.
* 
*/
function update_groups($uid, $groups, $protected_groups = array(), $just_created = false)
{
    if (!$just_created) {
        $old_groups = OC_Group::getUserGroups($uid);
        foreach ($old_groups as $group) {
            if (!in_array($group, $protected_groups) && !in_array($group, $groups)) {
                \OC_Group::removeFromGroup($uid, $group);
                \OCP\Util::writeLog('cas', 'Removed "' . $uid . '" from the group "' . $group . '"', \OCP\Util::DEBUG);
            }
        }
    }
    foreach ($groups as $group) {
        if (preg_match('/[^a-zA-Z0-9 _\\.@\\-]/', $group)) {
            \OCP\Util::writeLog('cas', 'Invalid group "' . $group . '", allowed chars "a-zA-Z0-9" and "_.@-" ', \OCP\Util::DEBUG);
        } else {
            if (!\OC_Group::inGroup($uid, $group)) {
                if (!OC_Group::groupExists($group)) {
                    \OC_Group::createGroup($group);
                    \OCP\Util::writeLog('cas', 'New group created: ' . $group, \OCP\Util::DEBUG);
                }
                \OC_Group::addToGroup($uid, $group);
                \OCP\Util::writeLog('cas', 'Added "' . $uid . '" to the group "' . $group . '"', \OCP\Util::DEBUG);
            }
        }
    }
}
Example #18
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param null $itemSourceName
  * @throws \Exception
  * @internal param \OCP\Item $string type
  * @internal param \OCP\Item $string source
  * @internal param \OCP\SHARE_TYPE_USER $int , SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @internal param \OCP\User $string or group the item is being shared with
  * @internal param \OCP\CRUDS $int permissions
  * @return bool|string Returns true on success or false on failure, Returns token on success for links
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null)
 {
     $uidOwner = \OC_User::getUser();
     $sharingPolicy = \OC_Appconfig::getValue('core', 'shareapi_share_policy', 'global');
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     // verify that the file exists before we try to share it
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         if (!$path) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the file does not exist';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' is the item owner';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' does not exist';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
         if ($sharingPolicy == 'groups_only') {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' is not a member of any groups that ' . $uidOwner . ' is a member of';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because this item is already shared with ' . $shareWith;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because the group ' . $shareWith . ' does not exist';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
             if ($sharingPolicy == 'groups_only' && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because ' . $uidOwner . ' is not a member of the group ' . $shareWith;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing ' . $itemSourceName . ' failed, because this item is already shared with ' . $shareWith;
                     \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                     throw new \Exception($message);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         self::delete($checkExists['id']);
                     }
                     // Generate hash of password - same method as user passwords
                     if (isset($shareWith)) {
                         $forcePortable = CRYPT_BLOWFISH != 1;
                         $hasher = new \PasswordHash(8, $forcePortable);
                         $shareWith = $hasher->HashPassword($shareWith . \OC_Config::getValue('passwordsalt', ''));
                     } else {
                         // reuse the already set password, but only if we change permissions
                         // otherwise the user disabled the password protection
                         if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                             $shareWith = $checkExists['share_with'];
                         }
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing ' . $itemSourceName . ' failed, because sharing with links is not allowed';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
                 return false;
                 // 		} else if ($shareType === self::SHARE_TYPE_CONTACT) {
                 // 			if (!\OC_App::isEnabled('contacts')) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because the contacts app is not enabled';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				return false;
                 // 			}
                 // 			$vcard = \OC_Contacts_App::getContactVCard($shareWith);
                 // 			if (!isset($vcard)) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because the contact does not exist';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				throw new \Exception($message);
                 // 			}
                 // 			$details = \OC_Contacts_VCard::structureContact($vcard);
                 // 			// TODO Add ownCloud user to contacts vcard
                 // 			if (!isset($details['EMAIL'])) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because no email address is associated with the contact';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				throw new \Exception($message);
                 // 			}
                 // 			return self::shareItem($itemType, $itemSource, self::SHARE_TYPE_EMAIL, $details['EMAIL'], $permissions);
             } else {
                 // Future share types need to include their own conditions
                 $message = 'Share type ' . $shareType . ' is not valid for ' . $itemSource;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     }
     // If the item is a folder, scan through the folder looking for equivalent item types
     // 		if ($itemType == 'folder') {
     // 			$parentFolder = self::put('folder', $itemSource, $shareType, $shareWith, $uidOwner, $permissions, true);
     // 			if ($parentFolder && $files = \OC\Files\Filesystem::getDirectoryContent($itemSource)) {
     // 				for ($i = 0; $i < count($files); $i++) {
     // 					$name = substr($files[$i]['name'], strpos($files[$i]['name'], $itemSource) - strlen($itemSource));
     // 					if ($files[$i]['mimetype'] == 'httpd/unix-directory'
     // 						&& $children = \OC\Files\Filesystem::getDirectoryContent($name, '/')
     // 					) {
     // 						// Continue scanning into child folders
     // 						array_push($files, $children);
     // 					} else {
     // 						// Check file extension for an equivalent item type to convert to
     // 						$extension = strtolower(substr($itemSource, strrpos($itemSource, '.') + 1));
     // 						foreach (self::$backends as $type => $backend) {
     // 							if (isset($backend->dependsOn) && $backend->dependsOn == 'file' && isset($backend->supportedFileExtensions) && in_array($extension, $backend->supportedFileExtensions)) {
     // 								$itemType = $type;
     // 								break;
     // 							}
     // 						}
     // 						// Pass on to put() to check if this item should be converted, the item won't be inserted into the database unless it can be converted
     // 						self::put($itemType, $name, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder);
     // 					}
     // 				}
     // 				return true;
     // 			}
     // 			return false;
     // 		} else {
     // Put the item into the database
     return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName);
     // 		}
 }
Example #19
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param string $itemSourceName
  * @param \DateTime $expirationDate
  * @return boolean|string Returns true on success or false on failure, Returns token on success for links
  * @throws \Exception
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null)
 {
     $uidOwner = \OC_User::getUser();
     $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
     $l = \OC_L10N::get('lib');
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     // check if file can be shared
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         // verify that the file exists before we try to share it
         if (!$path) {
             $message = 'Sharing %s failed, because the file does not exist';
             $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         // verify that the user has share permission
         if (!\OC\Files\Filesystem::isSharable($path)) {
             $message = 'You are not allowed to share %s';
             $message_t = $l->t('You are not allowed to share %s', array($itemSourceName));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
     }
     //verify that we don't share a folder which already contains a share mount point
     if ($itemType === 'folder') {
         $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
         $mountManager = \OC\Files\Filesystem::getMountManager();
         $mounts = $mountManager->findIn($path);
         foreach ($mounts as $mount) {
             if ($mount->getStorage()->instanceOfStorage('\\OCA\\Files_Sharing\\ISharedStorage')) {
                 $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     }
     // single file shares should never have delete permissions
     if ($itemType === 'file') {
         $permissions = (int) $permissions & ~\OCP\PERMISSION_DELETE;
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing %s failed, because the user %s is the item owner';
             $message_t = $l->t('Sharing %s failed, because the user %s is the item owner', array($itemSourceName, $shareWith));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing %s failed, because the user %s does not exist';
             $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         if ($shareWithinGroupOnly) {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing %s failed, because the user ' . '%s is not a member of any groups that %s is a member of';
                 $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemSourceName, $shareWith, $uidOwner));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith, $uidOwner), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing %s failed, because this item is already shared with %s';
                 $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing %s failed, because the group %s does not exist';
                 $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
             if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing %s failed, because ' . '%s is not a member of the group %s';
                 $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing %s failed, because this item is already shared with %s';
                     $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                     \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                     throw new \Exception($message_t);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 $updateExistingShare = false;
                 if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     // FIXME Don't delete link if we update it
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         Helper::delete($checkExists['id']);
                         $updateExistingShare = true;
                     }
                     // Generate hash of password - same method as user passwords
                     if (!empty($shareWith)) {
                         $forcePortable = CRYPT_BLOWFISH != 1;
                         $hasher = new \PasswordHash(8, $forcePortable);
                         $shareWith = $hasher->HashPassword($shareWith . \OC_Config::getValue('passwordsalt', ''));
                     } else {
                         // reuse the already set password, but only if we change permissions
                         // otherwise the user disabled the password protection
                         if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                             $shareWith = $checkExists['share_with'];
                         }
                     }
                     if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
                         $message = 'You need to provide a password to create a public link, only protected links are allowed';
                         $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
                         \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                         throw new \Exception($message_t);
                     }
                     if ($updateExistingShare === false && self::isDefaultExpireDateEnabled() && empty($expirationDate)) {
                         $expirationDate = Helper::calcExpireDate();
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName, $expirationDate);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing %s failed, because sharing with links is not allowed';
                 $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
                 throw new \Exception($message_t);
                 return false;
             } else {
                 // Future share types need to include their own conditions
                 $message = 'Share type %s is not valid for %s';
                 $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
                 \OC_Log::write('OCP\\Share', sprintf($message, $shareType, $itemSource), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
     }
     // Put the item into the database
     return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
 }
Example #20
0
 /**
  * creates a unique name for internal ownCloud use for groups. Don't call it directly.
  * @param string $name the display name of the object
  * @return string|false with with the name to use in ownCloud or false if unsuccessful.
  *
  * Instead of using this method directly, call
  * createAltInternalOwnCloudName($name, false)
  *
  * Group names are also used as display names, so we do a sequential
  * numbering, e.g. Developers_42 when there are 41 other groups called
  * "Developers"
  */
 private function _createAltInternalOwnCloudNameForGroups($name)
 {
     $usedNames = $this->groupMapper->getNamesBySearch($name . '_%');
     if (!$usedNames || count($usedNames) === 0) {
         $lastNo = 1;
         //will become name_2
     } else {
         natsort($usedNames);
         $lastName = array_pop($usedNames);
         $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
     }
     $altName = $name . '_' . strval($lastNo + 1);
     unset($usedNames);
     $attempts = 1;
     while ($attempts < 21) {
         // Check to be really sure it is unique
         // while loop is just a precaution. If a name is not generated within
         // 20 attempts, something else is very wrong. Avoids infinite loop.
         if (!\OC_Group::groupExists($altName)) {
             return $altName;
         }
         $altName = $name . '_' . ($lastNo + $attempts);
         $attempts++;
     }
     return false;
 }
Example #21
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param string $itemSourceName
  * @param \DateTime $expirationDate
  * @param bool $passwordChanged
  * @return boolean|string Returns true on success or false on failure, Returns token on success for links
  * @throws \OC\HintException when the share type is remote and the shareWith is invalid
  * @throws \Exception
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null)
 {
     $backend = self::getBackend($itemType);
     $l = \OC::$server->getL10N('lib');
     if ($backend->isShareTypeAllowed($shareType) === false) {
         $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
         $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
         \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
         throw new \Exception($message_t);
     }
     $uidOwner = \OC_User::getUser();
     $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     $itemName = $itemSourceName;
     // check if file can be shared
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         $itemName = $path;
         // verify that the file exists before we try to share it
         if (!$path) {
             $message = 'Sharing %s failed, because the file does not exist';
             $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
         // verify that the user has share permission
         if (!\OC\Files\Filesystem::isSharable($path)) {
             $message = 'You are not allowed to share %s';
             $message_t = $l->t('You are not allowed to share %s', [$path]);
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $path), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
     }
     //verify that we don't share a folder which already contains a share mount point
     if ($itemType === 'folder') {
         $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
         $mountManager = \OC\Files\Filesystem::getMountManager();
         $mounts = $mountManager->findIn($path);
         foreach ($mounts as $mount) {
             if ($mount->getStorage()->instanceOfStorage('\\OCA\\Files_Sharing\\ISharedStorage')) {
                 $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
                 \OCP\Util::writeLog('OCP\\Share', $message, \OCP\Util::DEBUG);
                 throw new \Exception($message);
             }
         }
     }
     // single file shares should never have delete permissions
     if ($itemType === 'file') {
         $permissions = (int) $permissions & ~\OCP\Constants::PERMISSION_DELETE;
     }
     //Validate expirationDate
     if ($expirationDate !== null) {
         try {
             /*
              * Reuse the validateExpireDate.
              * We have to pass time() since the second arg is the time
              * the file was shared, since it is not shared yet we just use
              * the current time.
              */
             $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
         } catch (\Exception $e) {
             throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
         }
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing %s failed, because you can not share with yourself';
             $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing %s failed, because the user %s does not exist';
             $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
         if ($shareWithinGroupOnly) {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing %s failed, because the user ' . '%s is not a member of any groups that %s is a member of';
                 $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing %s failed, because this item is already shared with %s';
                 $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
         }
         if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing %s failed, because this item is already shared with user %s';
                 $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
                 throw new \Exception($message_t);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing %s failed, because the group %s does not exist';
                 $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
             if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing %s failed, because ' . '%s is not a member of the group %s';
                 $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing %s failed, because this item is already shared with %s';
                     $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                     \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                     throw new \Exception($message_t);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 $updateExistingShare = false;
                 if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     // FIXME Don't delete link if we update it
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         Helper::delete($checkExists['id']);
                         $updateExistingShare = true;
                     }
                     if ($passwordChanged === null) {
                         // Generate hash of password - same method as user passwords
                         if (is_string($shareWith) && $shareWith !== '') {
                             self::verifyPassword($shareWith);
                             $shareWith = \OC::$server->getHasher()->hash($shareWith);
                         } else {
                             // reuse the already set password, but only if we change permissions
                             // otherwise the user disabled the password protection
                             if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                                 $shareWith = $checkExists['share_with'];
                             }
                         }
                     } else {
                         if ($passwordChanged === true) {
                             if (is_string($shareWith) && $shareWith !== '') {
                                 self::verifyPassword($shareWith);
                                 $shareWith = \OC::$server->getHasher()->hash($shareWith);
                             }
                         } else {
                             if ($updateExistingShare) {
                                 $shareWith = $checkExists['share_with'];
                             }
                         }
                     }
                     if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
                         $message = 'You need to provide a password to create a public link, only protected links are allowed';
                         $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
                         \OCP\Util::writeLog('OCP\\Share', $message, \OCP\Util::DEBUG);
                         throw new \Exception($message_t);
                     }
                     if ($updateExistingShare === false && self::isDefaultExpireDateEnabled() && empty($expirationDate)) {
                         $expirationDate = Helper::calcExpireDate();
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName, $expirationDate);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing %s failed, because sharing with links is not allowed';
                 $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             } else {
                 if ($shareType === self::SHARE_TYPE_REMOTE) {
                     /*
                      * Check if file is not already shared with the remote user
                      */
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE, $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
                         $message = 'Sharing %s failed, because this item is already shared with %s';
                         $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                         \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                         throw new \Exception($message_t);
                     }
                     $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
                     list($user, $remote) = Helper::splitUserRemote($shareWith);
                     $shareWith = $user . '@' . $remote;
                     $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
                     $send = false;
                     if ($shareId) {
                         $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
                     }
                     if ($send === false) {
                         $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
                         self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
                         $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
                         throw new \Exception($message_t);
                     }
                     return $send;
                 } else {
                     // Future share types need to include their own conditions
                     $message = 'Share type %s is not valid for %s';
                     $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
                     \OCP\Util::writeLog('OCP\\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
                     throw new \Exception($message_t);
                 }
             }
         }
     }
     // Put the item into the database
     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
     return $result ? true : false;
 }
Example #22
0
 $file = $meta;
 if ($file['mimetype'] == 'httpd/unix-directory') {
     $itemType = 'folder';
 } else {
     $itemType = 'file';
 }
 if ($row['permissions'] == 0) {
     $permissions = OCP\PERMISSION_READ | OCP\PERMISSION_SHARE;
 } else {
     $permissions = OCP\PERMISSION_READ | OCP\PERMISSION_UPDATE | OCP\PERMISSION_SHARE;
     if ($itemType == 'folder') {
         $permissions |= OCP\PERMISSION_CREATE;
     }
 }
 $pos = strrpos($row['uid_shared_with'], '@');
 if ($pos !== false && OC_Group::groupExists(substr($row['uid_shared_with'], $pos + 1))) {
     $shareType = OCP\Share::SHARE_TYPE_GROUP;
     $shareWith = substr($row['uid_shared_with'], 0, $pos);
     if (isset($groupShares[$shareWith][$itemSource])) {
         continue;
     } else {
         $groupShares[$shareWith][$itemSource] = true;
     }
 } else {
     if ($row['uid_shared_with'] == 'public') {
         $shareType = OCP\Share::SHARE_TYPE_LINK;
         $shareWith = null;
     } else {
         $shareType = OCP\Share::SHARE_TYPE_USER;
         $shareWith = $row['uid_shared_with'];
     }
Example #23
0
            if (OC_SubAdmin::isGroupAccessible(OC_User::getUser(), $group)) {
                $groups[] = $group;
            }
        }
        if (count($groups) == 0) {
            $groups = OC_SubAdmin::getSubAdminsGroups(OC_User::getUser());
        }
    } else {
        $groups = OC_SubAdmin::getSubAdminsGroups(OC_User::getUser());
    }
}
$username = $_POST["username"];
$password = $_POST["password"];
// Does the group exist?
if (in_array($username, OC_User::getUsers())) {
    OC_JSON::error(array("data" => array("message" => "User already exists")));
    exit;
}
// Return Success story
try {
    OC_User::createUser($username, $password);
    foreach ($groups as $i) {
        if (!OC_Group::groupExists($i)) {
            OC_Group::createGroup($i);
        }
        OC_Group::addToGroup($username, $i);
    }
    OC_JSON::success(array("data" => array("username" => $username, "groups" => implode(", ", OC_Group::getUserGroups($username)))));
} catch (Exception $exception) {
    OC_JSON::error(array("data" => array("message" => $exception->getMessage())));
}
Example #24
0
     $token = OC_Share::getTokenFromSource($path);
     if ($path == $source) {
         $item['privateLink'] = $token;
     } else {
         // If in parent folder, include a path parameter to get direct access to file
         $item['privateLink'] = $token . '&path=' . str_replace('%2F', '/', str_replace('+', '%20', urlencode(substr($source, strlen($path)))));
     }
 } else {
     // Check if uid_shared_with is a group
     $pos = strrpos($uid_shared_with, '@');
     if ($pos !== false) {
         $gid = substr($uid_shared_with, $pos + 1);
     } else {
         $gid = false;
     }
     if ($gid && OC_Group::groupExists($gid)) {
         // Include users in the group so the users can be removed from the list of people to share with
         if ($path == $source) {
             $group = array(array('gid' => $gid, 'permissions' => $rows[$i]['permissions'], 'users' => OC_Group::usersInGroup($gid), 'parentFolder' => false));
         } else {
             $group = array(array('gid' => $gid, 'permissions' => $rows[$i]['permissions'], 'users' => OC_Group::usersInGroup($gid), 'parentFolder' => basename($path)));
         }
         if (!isset($item['groups'])) {
             $item['groups'] = $group;
         } else {
             if (is_array($item['groups'])) {
                 $gidExists = false;
                 $currentGroups = $item['groups'];
                 // Check if the group is already included
                 foreach ($currentGroups as $g) {
                     if ($g['gid'] == $gid) {