From f5c0dbd947d45520550b68dae77a894f871a0758 Mon Sep 17 00:00:00 2001 From: Jakob Sack Date: Wed, 27 Jul 2011 19:07:28 +0200 Subject: Use autoload --- lib/Connector/Sabre/auth.php | 35 ---- lib/Connector/Sabre/directory.php | 131 -------------- lib/Connector/Sabre/file.php | 89 ---------- lib/Connector/Sabre/locks.php | 154 ---------------- lib/Connector/Sabre/node.php | 161 ----------------- lib/Group/backend.php | 96 ---------- lib/Group/database.php | 179 ------------------- lib/User/backend.php | 86 --------- lib/User/database.php | 147 --------------- lib/User/example.php | 97 ---------- lib/base.php | 338 +---------------------------------- lib/connector/sabre/auth.php | 34 ++++ lib/connector/sabre/directory.php | 128 +++++++++++++ lib/connector/sabre/file.php | 87 +++++++++ lib/connector/sabre/locks.php | 152 ++++++++++++++++ lib/connector/sabre/node.php | 158 +++++++++++++++++ lib/database.php | 365 -------------------------------------- lib/db.php | 365 ++++++++++++++++++++++++++++++++++++++ lib/files.php | 3 - lib/group.php | 1 - lib/group/backend.php | 96 ++++++++++ lib/group/database.php | 177 ++++++++++++++++++ lib/hook.php | 69 +++++++ lib/user.php | 1 - lib/user/backend.php | 86 +++++++++ lib/user/database.php | 145 +++++++++++++++ lib/user/example.php | 95 ++++++++++ lib/util.php | 245 +++++++++++++++++++++++++ 28 files changed, 1845 insertions(+), 1875 deletions(-) delete mode 100644 lib/Connector/Sabre/auth.php delete mode 100644 lib/Connector/Sabre/directory.php delete mode 100644 lib/Connector/Sabre/file.php delete mode 100644 lib/Connector/Sabre/locks.php delete mode 100644 lib/Connector/Sabre/node.php delete mode 100644 lib/Group/backend.php delete mode 100644 lib/Group/database.php delete mode 100644 lib/User/backend.php delete mode 100644 lib/User/database.php delete mode 100644 lib/User/example.php create mode 100644 lib/connector/sabre/auth.php create mode 100644 lib/connector/sabre/directory.php create mode 100644 lib/connector/sabre/file.php create mode 100644 lib/connector/sabre/locks.php create mode 100644 lib/connector/sabre/node.php delete mode 100644 lib/database.php create mode 100644 lib/db.php create mode 100644 lib/group/backend.php create mode 100644 lib/group/database.php create mode 100644 lib/hook.php create mode 100644 lib/user/backend.php create mode 100644 lib/user/database.php create mode 100644 lib/user/example.php create mode 100644 lib/util.php (limited to 'lib') diff --git a/lib/Connector/Sabre/auth.php b/lib/Connector/Sabre/auth.php deleted file mode 100644 index cfe7723e761..00000000000 --- a/lib/Connector/Sabre/auth.php +++ /dev/null @@ -1,35 +0,0 @@ -path . '/' . $name; - OC_FILESYSTEM::file_put_contents($newPath,$data); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - $newPath = $this->path . '/' . $name; - OC_FILESYSTEM::mkdir($newPath); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!OC_FILESYSTEM::file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File with name ' . $path . ' could not be located'); - - if (OC_FILESYSTEM::is_dir($path)) { - - return new OC_Connector_Sabre_Directory($path); - - } else { - - return new OC_Connector_Sabre_File($path); - - } - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - $nodes = array(); - // foreach(scandir($this->path) as $node) if($node!='.' && $node!='..') $nodes[] = $this->getChild($node); - if( OC_FILESYSTEM::is_dir($this->path)){ - $dh = OC_FILESYSTEM::opendir($this->path); - while(( $node = readdir($dh)) !== false ){ - if($node!='.' && $node!='..'){ - $nodes[] = $this->getChild($node); - } - } - } - return $nodes; - - } - - /** - * Checks if a child exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - $path = $this->path . '/' . $name; - return OC_FILESYSTEM::file_exists($path); - - } - - /** - * Deletes all files in this directory, and then itself - * - * @return void - */ - public function delete() { - - foreach($this->getChildren() as $child) $child->delete(); - OC_FILESYSTEM::rmdir($this->path); - - } - - /** - * Returns available diskspace information - * - * @return array - */ - public function getQuotaInfo() { - - return array( - OC_FILESYSTEM::filesize('/'), - OC_FILESYSTEM::free_space() - ); - - } - -} - diff --git a/lib/Connector/Sabre/file.php b/lib/Connector/Sabre/file.php deleted file mode 100644 index bb5ab738430..00000000000 --- a/lib/Connector/Sabre/file.php +++ /dev/null @@ -1,89 +0,0 @@ -path,$data); - - } - - /** - * Returns the data - * - * @return string - */ - public function get() { - - return OC_FILESYSTEM::file_get_contents($this->path); - - } - - /** - * Delete the current file - * - * @return void - */ - public function delete() { - - OC_FILESYSTEM::unlink($this->path); - - } - - /** - * Returns the size of the node, in bytes - * - * @return int - */ - public function getSize() { - - return OC_FILESYSTEM::filesize($this->path); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - * - * @return mixed - */ - public function getETag() { - - return null; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - * - * @return mixed - */ - public function getContentType() { - - return OC_FILESYSTEM::getMimeType($this->path); - - } -} - diff --git a/lib/Connector/Sabre/locks.php b/lib/Connector/Sabre/locks.php deleted file mode 100644 index 4f3eb7bbf52..00000000000 --- a/lib/Connector/Sabre/locks.php +++ /dev/null @@ -1,154 +0,0 @@ - ? AND ((uri = ?)'; - $params = array(OC_USER::getUser(),time(),$uri); - - // We need to check locks for every part in the uri. - $uriParts = explode('/',$uri); - - // We already covered the last part of the uri - array_pop($uriParts); - - $currentPath=''; - - foreach($uriParts as $part) { - - if ($currentPath) $currentPath.='/'; - $currentPath.=$part; - - $query.=' OR (depth!=0 AND uri = ?)'; - $params[] = $currentPath; - - } - - if ($returnChildLocks) { - - $query.=' OR (uri LIKE ?)'; - $params[] = $uri . '/%'; - - } - $query.=')'; - - $stmt = OC_DB::prepare($query); - $result = $stmt->execute($params); - - $lockList = array(); - while( $row = $result->fetchRow()){ - - $lockInfo = new Sabre_DAV_Locks_LockInfo(); - $lockInfo->owner = $row['owner']; - $lockInfo->token = $row['token']; - $lockInfo->timeout = $row['timeout']; - $lockInfo->created = $row['created']; - $lockInfo->scope = $row['scope']; - $lockInfo->depth = $row['depth']; - $lockInfo->uri = $row['uri']; - $lockList[] = $lockInfo; - - } - - return $lockList; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 5 minutes - $lockInfo->timeout = 300; - $lockInfo->created = time(); - $lockInfo->uri = $uri; - - $locks = $this->getLocks($uri,false); - $exists = false; - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) $exists = true; - } - - if ($exists) { - $query = OC_DB::prepare( 'UPDATE *PREFIX*locks SET owner = ?, timeout = ?, scope = ?, depth = ?, uri = ?, created = ? WHERE userid = ? AND token = ?' ); - $result = $query->execute( array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,OC_USER::getUser(),$lockInfo->token)); - } else { - $query = OC_DB::prepare( 'INSERT INTO *PREFIX*locks (userid,owner,timeout,scope,depth,uri,created,token) VALUES (?,?,?,?,?,?,?,?)' ); - $result = $query->execute( array(OC_USER::getUser(),$lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); - } - - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $query = OC_DB::prepare( 'DELETE FROM *PREFIX*locks WHERE userid = ? AND uri=? AND token=?' ); - $result = $query->execute( array(OC_USER::getUser(),$uri,$lockInfo->token)); - - return $result->numRows() === 1; - - } - -} - diff --git a/lib/Connector/Sabre/node.php b/lib/Connector/Sabre/node.php deleted file mode 100644 index dc1013dc524..00000000000 --- a/lib/Connector/Sabre/node.php +++ /dev/null @@ -1,161 +0,0 @@ -path = $path; - } - - - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - - list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); - return $name; - - } - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - - $newPath = $parentPath . '/' . $newName; - $oldPath = $this->path; - - OC_FILESYSTEM::rename($this->path,$newPath); - - $this->path = $newPath; - - $query = OC_DB::prepare( 'UPDATE *PREFIX*properties SET propertypath = ? WHERE userid = ? AND propertypath = ?' ); - $query->execute( array( $newPath,OC_USER::getUser(), $oldPath )); - - } - - - - /** - * Returns the last modification time, as a unix timestamp - * - * @return int - */ - public function getLastModified() { - - return OC_FILESYSTEM::filemtime($this->path); - - } - - /** - * Updates properties on this node, - * - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateProperties($properties) { - $existing = $this->getProperties(array()); - foreach($properties as $propertyName => $propertyValue) { - // If it was null, we need to delete the property - if (is_null($propertyValue)) { - if(array_key_exists( $propertyName, $existing )){ - $query = OC_DB::prepare( 'DELETE FROM *PREFIX*properties WHERE userid = ? AND propertypath = ? AND propertyname = ?' ); - $query->execute( array( OC_USER::getUser(), $this->path, $propertyName )); - } - } - else { - if(!array_key_exists( $propertyName, $existing )){ - $query = OC_DB::prepare( 'INSERT INTO *PREFIX*properties (userid,propertypath,propertyname,propertyvalue) VALUES(?,?,?,?)' ); - $query->execute( array( OC_USER::getUser(), $this->path, $propertyName,$propertyValue )); - } - else{ - $query = OC_DB::prepare( 'UPDATE *PREFIX*properties SET propertyvalue = ? WHERE userid = ? AND propertypath = ? AND propertyname = ?' ); - $query->execute( array( $propertyValue,OC_USER::getUser(), $this->path, $propertyName )); - } - } - - } - return true; - } - - /** - * Returns a list of properties for this nodes.; - * - * The properties list is a list of propertynames the client requested, encoded as xmlnamespace#tagName, for example: http://www.example.org/namespace#author - * If the array is empty, all properties should be returned - * - * @param array $properties - * @return void - */ - function getProperties($properties) { - // At least some magic in here :-) - $query = OC_DB::prepare( 'SELECT * FROM *PREFIX*properties WHERE userid = ? AND propertypath = ?' ); - $result = $query->execute( array( OC_USER::getUser(), $this->path )); - - $existing = array(); - while( $row = $result->fetchRow()){ - $existing[$row['propertyname']] = $row['propertyvalue']; - } - - if(count($properties) == 0){ - return $existing; - } - - // if the array was empty, we need to return everything - $props = array(); - foreach($properties as $property) { - if (isset($existing[$property])) $props[$property] = $existing[$property]; - } - return $props; - } -} - diff --git a/lib/Group/backend.php b/lib/Group/backend.php deleted file mode 100644 index 298cced7ff5..00000000000 --- a/lib/Group/backend.php +++ /dev/null @@ -1,96 +0,0 @@ -. -* -*/ - - - -/** - * Abstract base class for user management - */ -abstract class OC_GROUP_BACKEND { - /** - * @brief Try to create a new group - * @param $gid The name of the group to create - * @returns true/false - * - * Trys to create a new group. If the group name already exists, false will - * be returned. - */ - public static function createGroup($gid){} - - /** - * @brief delete a group - * @param $gid gid of the group to delete - * @returns true/false - * - * Deletes a group and removes it from the group_user-table - */ - public static function removeGroup($gid){} - - /** - * @brief is user in group? - * @param $uid uid of the user - * @param $gid gid of the group - * @returns true/false - * - * Checks whether the user is member of a group or not. - */ - public static function inGroup($uid, $gid){} - - /** - * @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){} - - /** - * @brief Removes a user from a group - * @param $uid Name of the user to remove from group - * @param $gid Name of the group from which remove the user - * @returns true/false - * - * removes the user from a group. - */ - public static function removeFromGroup($uid,$gid){} - - /** - * @brief Get all groups a user belongs to - * @param $uid Name of the user - * @returns array with group names - * - * This function fetches all groups a user belongs to. It does not check - * if the user exists at all. - */ - public static function getUserGroups($uid){} - - /** - * @brief get a list of all groups - * @returns array with group names - * - * Returns a list with all groups - */ - public static function getGroups(){} -} diff --git a/lib/Group/database.php b/lib/Group/database.php deleted file mode 100644 index 6e508a4d47c..00000000000 --- a/lib/Group/database.php +++ /dev/null @@ -1,179 +0,0 @@ -. - * - */ -/* - * - * The following SQL statement is just a help for developers and will not be - * executed! - * - * CREATE TABLE `groups` ( - * `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL, - * PRIMARY KEY (`gid`) - * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - * - * CREATE TABLE `group_user` ( - * `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL, - * `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL - * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - * - */ - -require_once( 'Group/backend.php' ); - -/** - * Class for group management in a SQL Database (e.g. MySQL, SQLite) - */ -class OC_GROUP_DATABASE extends OC_GROUP_BACKEND { - static private $userGroupCache=array(); - - /** - * @brief Try to create a new group - * @param $gid The name of the group to create - * @returns true/false - * - * Trys to create a new group. If the group name already exists, false will - * be returned. - */ - public static function createGroup( $gid ){ - // Check for existence - $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*groups` WHERE gid = ?" ); - $result = $query->execute( array( $gid )); - - if( $result->numRows() > 0 ){ - // Can not add an existing group - return false; - } - else{ - // Add group and exit - $query = OC_DB::prepare( "INSERT INTO `*PREFIX*groups` ( `gid` ) VALUES( ? )" ); - $result = $query->execute( array( $gid )); - - return $result ? true : false; - } - } - - /** - * @brief delete a group - * @param $gid gid of the group to delete - * @returns true/false - * - * Deletes a group and removes it from the group_user-table - */ - public static function deleteGroup( $gid ){ - // Delete the group - $query = OC_DB::prepare( "DELETE FROM `*PREFIX*groups` WHERE gid = ?" ); - $result = $query->execute( array( $gid )); - - // Delete the group-user relation - $query = OC_DB::prepare( "DELETE FROM `*PREFIX*group_user` WHERE gid = ?" ); - $result = $query->execute( array( $gid )); - - return true; - } - - /** - * @brief is user in group? - * @param $uid uid of the user - * @param $gid gid of the group - * @returns true/false - * - * Checks whether the user is member of a group or not. - */ - public static function inGroup( $uid, $gid ){ - // check - $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*group_user` WHERE gid = ? AND uid = ?" ); - $result = $query->execute( array( $gid, $uid )); - - return $result->numRows() > 0 ? true : false; - } - - /** - * @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 ){ - // No duplicate entries! - if( !self::inGroup( $uid, $gid )){ - $query = OC_DB::prepare( "INSERT INTO `*PREFIX*group_user` ( `uid`, `gid` ) VALUES( ?, ? )" ); - $result = $query->execute( array( $uid, $gid )); - } - return true; - } - - /** - * @brief Removes a user from a group - * @param $uid Name of the user to remove from group - * @param $gid Name of the group from which remove the user - * @returns true/false - * - * removes the user from a group. - */ - public static function removeFromGroup( $uid, $gid ){ - $query = OC_DB::prepare( "DELETE FROM `*PREFIX*group_user` WHERE `uid` = ? AND `gid` = ?" ); - $result = $query->execute( array( $uid, $gid )); - - return true; - } - - /** - * @brief Get all groups a user belongs to - * @param $uid Name of the user - * @returns array with group names - * - * This function fetches all groups a user belongs to. It does not check - * if the user exists at all. - */ - public static function getUserGroups( $uid ){ - // No magic! - $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*group_user` WHERE uid = ?" ); - $result = $query->execute( array( $uid )); - - $groups = array(); - while( $row = $result->fetchRow()){ - $groups[] = $row["gid"]; - } - - return $groups; - } - - /** - * @brief get a list of all groups - * @returns array with group names - * - * Returns a list with all groups - */ - public static function getGroups(){ - $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*groups`" ); - $result = $query->execute(); - - $groups = array(); - while( $row = $result->fetchRow()){ - $groups[] = $row["gid"]; - } - - return $groups; - } -} diff --git a/lib/User/backend.php b/lib/User/backend.php deleted file mode 100644 index 1797d0c475a..00000000000 --- a/lib/User/backend.php +++ /dev/null @@ -1,86 +0,0 @@ -. - * - */ - -/** - * error code for functions not provided by the user backend - */ -define('OC_USER_BACKEND_NOT_IMPLEMENTED', -501); - -/** - * actions that user backends can define - */ -define('OC_USER_BACKEND_CREATE_USER', 0x000001); -define('OC_USER_BACKEND_DELETE_USER', 0x000010); -define('OC_USER_BACKEND_SET_PASSWORD', 0x000100); -define('OC_USER_BACKEND_CHECK_PASSWORD', 0x001000); -define('OC_USER_BACKEND_GET_USERS', 0x010000); -define('OC_USER_BACKEND_USER_EXISTS', 0x100000); - - -/** - * abstract base class for user management - * subclass this for your own backends and see OC_USER_EXAMPLE for descriptions - */ -abstract class OC_USER_BACKEND { - - protected $possibleActions = array( - OC_USER_BACKEND_CREATE_USER => 'createUser', - OC_USER_BACKEND_DELETE_USER => 'deleteUser', - OC_USER_BACKEND_SET_PASSWORD => 'setPassword', - OC_USER_BACKEND_CHECK_PASSWORD => 'checkPassword', - OC_USER_BACKEND_GET_USERS => 'getUsers', - OC_USER_BACKEND_USER_EXISTS => 'userExists' - ); - - /** - * @brief Get all supported actions - * @returns bitwise-or'ed actions - * - * Returns the supported actions as int to be - * compared with OC_USER_BACKEND_CREATE_USER etc. - */ - public function getSupportedActions(){ - $actions = 0; - foreach($this->possibleActions AS $action => $methodName){ - if(method_exists($this, $methodName)) { - $actions |= $action; - } - } - - return $actions; - } - - /** - * @brief Check if backend implements actions - * @param $actions bitwise-or'ed actions - * @returns boolean - * - * Returns the supported actions as int to be - * compared with OC_USER_BACKEND_CREATE_USER etc. - */ - public function implementsActions($actions){ - return (bool)($this->getSupportedActions() & $actions); - } -} diff --git a/lib/User/database.php b/lib/User/database.php deleted file mode 100644 index 0396ac30958..00000000000 --- a/lib/User/database.php +++ /dev/null @@ -1,147 +0,0 @@ -. - * - */ -/* - * - * The following SQL statement is just a help for developers and will not be - * executed! - * - * CREATE TABLE `users` ( - * `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL, - * `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - * PRIMARY KEY (`uid`) - * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - * - */ - -require_once('User/backend.php'); - -/** - * Class for user management in a SQL Database (e.g. MySQL, SQLite) - */ -class OC_USER_DATABASE extends OC_USER_BACKEND { - static private $userGroupCache=array(); - - /** - * @brief Create a new user - * @param $uid The username of the user to create - * @param $password The password of the new user - * @returns true/false - * - * Creates a new user. Basic checking of username is done in OC_USER - * itself, not in its subclasses. - */ - public function createUser( $uid, $password ){ - if( $this->userExists($uid) ){ - return false; - } - else{ - $query = OC_DB::prepare( "INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )" ); - $result = $query->execute( array( $uid, sha1( $password ))); - - return $result ? true : false; - } - } - - /** - * @brief delete a user - * @param $uid The username of the user to delete - * @returns true/false - * - * Deletes a user - */ - public function deleteUser( $uid ){ - // Delete user-group-relation - $query = OC_DB::prepare( "DELETE FROM `*PREFIX*users` WHERE uid = ?" ); - $result = $query->execute( array( $uid )); - return true; - } - - /** - * @brief Set password - * @param $uid The username - * @param $password The new password - * @returns true/false - * - * Change the password of a user - */ - public function setPassword( $uid, $password ){ - if( $this->userExists($uid) ){ - $query = OC_DB::prepare( "UPDATE *PREFIX*users SET password = ? WHERE uid = ?" ); - $result = $query->execute( array( sha1( $password ), $uid )); - - return true; - } - else{ - return false; - } - } - - /** - * @brief Check if the password is correct - * @param $uid The username - * @param $password The password - * @returns true/false - * - * Check if the password is correct without logging in the user - */ - public function checkPassword( $uid, $password ){ - $query = OC_DB::prepare( "SELECT uid FROM *PREFIX*users WHERE uid = ? AND password = ?" ); - $result = $query->execute( array( $uid, sha1( $password ))); - - if( $result->numRows() > 0 ){ - return true; - } - else{ - return false; - } - } - - /** - * @brief Get a list of all users - * @returns array with all uids - * - * Get a list of all users. - */ - public function getUsers(){ - $query = OC_DB::prepare( "SELECT uid FROM *PREFIX*users" ); - $result = $query->execute(); - - $users=array(); - while( $row = $result->fetchRow()){ - $users[] = $row["uid"]; - } - return $users; - } - - /** - * @brief check if a user exists - * @param string $uid the username - * @return boolean - */ - public function userExists($uid){ - $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*users` WHERE uid = ?" ); - $result = $query->execute( array( $uid )); - - return $result->numRows() > 0; - } -} diff --git a/lib/User/example.php b/lib/User/example.php deleted file mode 100644 index 4abc1b3d49c..00000000000 --- a/lib/User/example.php +++ /dev/null @@ -1,97 +0,0 @@ -. - * - */ - -require_once('User/backend.php'); - -/** - * abstract reference class for user management - * this class should only be used as a reference for method signatures and their descriptions - */ -abstract class OC_USER_EXAMPLE extends OC_USER_BACKEND { - /** - * @brief Create a new user - * @param $uid The username of the user to create - * @param $password The password of the new user - * @returns true/false - * - * Creates a new user. Basic checking of username is done in OC_USER - * itself, not in its subclasses. - */ - public function createUser($uid, $password){ - return OC_USER_BACKEND_NOT_IMPLEMENTED; - } - - /** - * @brief delete a user - * @param $uid The username of the user to delete - * @returns true/false - * - * Deletes a user - */ - public function deleteUser( $uid ){ - return OC_USER_BACKEND_NOT_IMPLEMENTED; - } - - /** - * @brief Set password - * @param $uid The username - * @param $password The new password - * @returns true/false - * - * Change the password of a user - */ - public function setPassword($uid, $password){ - return OC_USER_BACKEND_NOT_IMPLEMENTED; - } - - /** - * @brief Check if the password is correct - * @param $uid The username - * @param $password The password - * @returns true/false - * - * Check if the password is correct without logging in the user - */ - public function checkPassword($uid, $password){ - return OC_USER_BACKEND_NOT_IMPLEMENTED; - } - - /** - * @brief Get a list of all users - * @returns array with all uids - * - * Get a list of all users. - */ - public function getUsers(){ - return OC_USER_BACKEND_NOT_IMPLEMENTED; - } - - /** - * @brief check if a user exists - * @param string $uid the username - * @return boolean - */ - public function userExists($uid){ - return OC_USER_BACKEND_NOT_IMPLEMENTED; - } -} diff --git a/lib/base.php b/lib/base.php index 743ed587922..7c2e7cf88c1 100644 --- a/lib/base.php +++ b/lib/base.php @@ -20,6 +20,14 @@ * */ +// Get rid of this stupid require_once OC_... +function OC_autoload($className) { + if(strpos($className,'OC_')===0) { + require_once strtolower(str_replace('_','/',substr($className,3)) . '.php'); + } +} + +spl_autoload_register('OC_autoload'); // set some stuff //ob_start(); @@ -58,9 +66,6 @@ if( !isset( $RUNTIME_NOAPPS )){ $RUNTIME_NOAPPS = false; } -// Doing the config stuff first -require_once('config.php'); - // TODO: we should get rid of this one, too // WARNING: to make everything even more confusing, DATADIRECTORY is a var that // changes and DATATIRECTORY_ROOT stays the same, but is set by @@ -76,25 +81,6 @@ if( OC_CONFIG::getValue( "forcessl", false )){ } } -// load core libs -require_once('helper.php'); -require_once('database.php'); -require_once('app.php'); -require_once('appconfig.php'); -require_once('files.php'); -require_once('filesystem.php'); -require_once('filestorage.php'); -require_once('l10n.php'); -require_once('preferences.php'); -require_once('log.php'); -require_once('user.php'); -require_once('group.php'); -require_once('ocs.php'); -require_once('ocsclient.php'); -require_once('connect.php'); -require_once('remotestorage.php'); -require_once('search.php'); - $error=(count(OC_UTIL::checkServer())>0); OC_USER::useBackend( OC_CONFIG::getValue( "userbackend", "database" )); @@ -117,313 +103,5 @@ if(!$error and !$RUNTIME_NOAPPS ){ OC_APP::loadApps(); } -/** - * Class for utility functions - * - */ -class OC_UTIL { - public static $scripts=array(); - public static $styles=array(); - public static $headers=array(); - private static $fsSetup=false; - - // Can be set up - public static function setupFS( $user = "", $root = "files" ){// configure the initial filesystem based on the configuration - if(self::$fsSetup){//setting up the filesystem twice can only lead to trouble - return false; - } - - // Global Variables - global $SERVERROOT; - global $CONFIG_DATADIRECTORY; - - $CONFIG_DATADIRECTORY_ROOT = OC_CONFIG::getValue( "datadirectory", "$SERVERROOT/data" ); - $CONFIG_BACKUPDIRECTORY = OC_CONFIG::getValue( "backupdirectory", "$SERVERROOT/backup" ); - - // Create root dir - if(!is_dir($CONFIG_DATADIRECTORY_ROOT)){ - @mkdir($CONFIG_DATADIRECTORY_ROOT) or die("Can't create data directory ($CONFIG_DATADIRECTORY_ROOT), you can usually fix this by setting the owner of '$SERVERROOT' to the user that the web server uses (www-data for debian/ubuntu)"); - } - - // 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(); - } - - if( $user != "" ){ //if we aren't logged in, there is no use to set up the filesystem - //first set up the local "root" storage and the backupstorage if needed - $rootStorage=OC_FILESYSTEM::createStorage('local',array('datadir'=>$CONFIG_DATADIRECTORY_ROOT)); -// if( OC_CONFIG::getValue( "enablebackup", false )){ -// // This creates the Directorys recursively -// if(!is_dir( "$CONFIG_BACKUPDIRECTORY/$user/$root" )){ -// mkdir( "$CONFIG_BACKUPDIRECTORY/$user/$root", 0755, true ); -// } -// $backupStorage=OC_FILESYSTEM::createStorage('local',array('datadir'=>$CONFIG_BACKUPDIRECTORY)); -// $backup=new OC_FILEOBSERVER_BACKUP(array('storage'=>$backupStorage)); -// $rootStorage->addObserver($backup); -// } - OC_FILESYSTEM::mount($rootStorage,'/'); - - $CONFIG_DATADIRECTORY = "$CONFIG_DATADIRECTORY_ROOT/$user/$root"; - if( !is_dir( $CONFIG_DATADIRECTORY )){ - mkdir( $CONFIG_DATADIRECTORY, 0755, true ); - } - -// TODO: find a cool way for doing this -// //set up the other storages according to the system settings -// foreach($CONFIG_FILESYSTEM as $storageConfig){ -// if(OC_FILESYSTEM::hasStorageType($storageConfig['type'])){ -// $arguments=$storageConfig; -// unset($arguments['type']); -// unset($arguments['mountpoint']); -// $storage=OC_FILESYSTEM::createStorage($storageConfig['type'],$arguments); -// if($storage){ -// OC_FILESYSTEM::mount($storage,$storageConfig['mountpoint']); -// } -// } -// } - - //jail the user into his "home" directory - OC_FILESYSTEM::chroot("/$user/$root"); - self::$fsSetup=true; - } - } - - public static function tearDownFS(){ - OC_FILESYSTEM::tearDown(); - self::$fsSetup=false; - } - - /** - * get the current installed version of ownCloud - * @return array - */ - public static function getVersion(){ - return array(1,60,0); - } - - /** - * add a javascript file - * - * @param url $url - */ - public static function addScript( $application, $file = null ){ - if( is_null( $file )){ - $file = $application; - $application = ""; - } - if( !empty( $application )){ - self::$scripts[] = "$application/js/$file"; - }else{ - self::$scripts[] = "js/$file"; - } - } - - /** - * add a css file - * - * @param url $url - */ - public static function addStyle( $application, $file = null ){ - if( is_null( $file )){ - $file = $application; - $application = ""; - } - if( !empty( $application )){ - self::$styles[] = "$application/css/$file"; - }else{ - self::$styles[] = "css/$file"; - } - } - - /** - * @brief Add a custom element to the header - * @param string tag tag name of the element - * @param array $attributes array of attrobutes for the element - * @param string $text the text content for the element - */ - public static function addHeader( $tag, $attributes, $text=''){ - self::$headers[]=array('tag'=>$tag,'attributes'=>$attributes,'text'=>$text); - } - - /** - * formats a timestamp in the "right" way - * - * @param int timestamp $timestamp - * @param bool dateOnly option to ommit time from the result - */ - public static function formatDate( $timestamp,$dateOnly=false){ - if(isset($_SESSION['timezone'])){//adjust to clients timezone if we know it - $systemTimeZone = intval(exec('date +%z')); - $systemTimeZone=(round($systemTimeZone/100,0)*60)+($systemTimeZone%100); - $clientTimeZone=$_SESSION['timezone']*60; - $offset=$clientTimeZone-$systemTimeZone; - $timestamp=$timestamp+$offset*60; - } - $timeformat=$dateOnly?'F j, Y':'F j, Y, H:i'; - return date($timeformat,$timestamp); - } - - /** - * Shows a pagenavi widget where you can jump to different pages. - * - * @param int $pagecount - * @param int $page - * @param string $url - * @return OC_TEMPLATE - */ - public static function getPageNavi($pagecount,$page,$url) { - - $pagelinkcount=8; - if ($pagecount>1) { - $pagestart=$page-$pagelinkcount; - if($pagestart<0) $pagestart=0; - $pagestop=$page+$pagelinkcount; - if($pagestop>$pagecount) $pagestop=$pagecount; - - $tmpl = new OC_TEMPLATE( '', 'part.pagenavi', '' ); - $tmpl->assign('page',$page); - $tmpl->assign('pagecount',$pagecount); - $tmpl->assign('pagestart',$pagestart); - $tmpl->assign('pagestop',$pagestop); - $tmpl->assign('url',$url); - return $tmpl; - } - } - - - - /** - * check if the current server configuration is suitable for ownCloud - * @return array arrays with error messages and hints - */ - public static function checkServer(){ - global $SERVERROOT; - global $CONFIG_DATADIRECTORY; - - $CONFIG_DATADIRECTORY_ROOT = OC_CONFIG::getValue( "datadirectory", "$SERVERROOT/data" );; - $CONFIG_BACKUPDIRECTORY = OC_CONFIG::getValue( "backupdirectory", "$SERVERROOT/backup" ); - $CONFIG_INSTALLED = OC_CONFIG::getValue( "installed", false ); - $errors=array(); - - //check for database drivers - if(!is_callable('sqlite_open') and !is_callable('mysql_connect')){ - $errors[]=array('error'=>'No database drivers (sqlite or mysql) installed.
','hint'=>'');//TODO: sane hint - } - $CONFIG_DBTYPE = OC_CONFIG::getValue( "dbtype", "sqlite" ); - $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" ); - - //try to get the username the httpd server runs on, used in hints - $stat=stat($_SERVER['DOCUMENT_ROOT']); - if(is_callable('posix_getpwuid')){ - $serverUser=posix_getpwuid($stat['uid']); - $serverUser='\''.$serverUser['name'].'\''; - }else{ - $serverUser='\'www-data\' for ubuntu/debian';//TODO: try to detect the distro and give a guess based on that - } - - //common hint for all file permissons error messages - $permissionsHint="Permissions can usually be fixed by setting the owner of the file or directory to the user the web server runs as ($serverUser)"; - - //check for correct file permissions - if(!stristr(PHP_OS, 'WIN')){ - $prems=substr(decoct(fileperms($CONFIG_DATADIRECTORY_ROOT)),-3); - if(substr($prems,-1)!='0'){ - OC_HELPER::chmodr($CONFIG_DATADIRECTORY_ROOT,0770); - clearstatcache(); - $prems=substr(decoct(fileperms($CONFIG_DATADIRECTORY_ROOT)),-3); - if(substr($prems,2,1)!='0'){ - $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY_ROOT.') is readable from the web
','hint'=>$permissionsHint); - } - } - if( OC_CONFIG::getValue( "enablebackup", false )){ - $prems=substr(decoct(fileperms($CONFIG_BACKUPDIRECTORY)),-3); - if(substr($prems,-1)!='0'){ - OC_HELPER::chmodr($CONFIG_BACKUPDIRECTORY,0770); - clearstatcache(); - $prems=substr(decoct(fileperms($CONFIG_BACKUPDIRECTORY)),-3); - if(substr($prems,2,1)!='0'){ - $errors[]=array('error'=>'Data directory ('.$CONFIG_BACKUPDIRECTORY.') is readable from the web
','hint'=>$permissionsHint); - } - } - } - }else{ - //TODO: premisions checks for windows hosts - } - if(is_dir($CONFIG_DATADIRECTORY_ROOT) and !is_writable($CONFIG_DATADIRECTORY_ROOT)){ - $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY_ROOT.') not writable by ownCloud
','hint'=>$permissionsHint); - } - - //TODO: check for php modules - - return $errors; - } -} - -/** - * This class manages the hooks. It basically provides two functions: adding - * slots and emitting signals. - */ -class OC_HOOK{ - static private $registered = array(); - - /** - * @brief connects a function to a hook - * @param $signalclass class name of emitter - * @param $signalname name of signal - * @param $slotclass class name of slot - * @param $slotname name of slot - * @returns true/false - * - * This function makes it very easy to connect to use hooks. - * - * TODO: write example - */ - static public function connect( $signalclass, $signalname, $slotclass, $slotname ){ - // Cerate the data structure - if( !array_key_exists( $signalclass, self::$registered )){ - self::$registered[$signalclass] = array(); - } - if( !array_key_exists( $signalname, self::$registered[$signalclass] )){ - self::$registered[$signalclass][$signalname] = array(); - } - - // register hook - self::$registered[$signalclass][$signalname][] = array( - "class" => $slotclass, - "name" => $slotname ); - // No chance for failure ;-) - return true; - } - - /** - * @brief emitts a signal - * @param $signalclass class name of emitter - * @param $signalname name of signal - * @param $params defautl: array() array with additional data - * @returns true if slots exists or false if not - * - * Emits a signal. To get data from the slot use references! - * - * TODO: write example - */ - static public function emit( $signalclass, $signalname, $params = array()){ - // Return false if there are no slots - if( !array_key_exists( $signalclass, self::$registered )){ - return false; - } - if( !array_key_exists( $signalname, self::$registered[$signalclass] )){ - return false; - } - - // Call all slots - foreach( self::$registered[$signalclass][$signalname] as $i ){ - call_user_func( array( $i["class"], $i["name"] ), $params ); - } - - // return true - return true; - } -} ?> diff --git a/lib/connector/sabre/auth.php b/lib/connector/sabre/auth.php new file mode 100644 index 00000000000..4e974ad821d --- /dev/null +++ b/lib/connector/sabre/auth.php @@ -0,0 +1,34 @@ +path . '/' . $name; + OC_FILESYSTEM::file_put_contents($newPath,$data); + + } + + /** + * Creates a new subdirectory + * + * @param string $name + * @return void + */ + public function createDirectory($name) { + + $newPath = $this->path . '/' . $name; + OC_FILESYSTEM::mkdir($newPath); + + } + + /** + * Returns a specific child node, referenced by its name + * + * @param string $name + * @throws Sabre_DAV_Exception_FileNotFound + * @return Sabre_DAV_INode + */ + public function getChild($name) { + + $path = $this->path . '/' . $name; + + if (!OC_FILESYSTEM::file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File with name ' . $path . ' could not be located'); + + if (OC_FILESYSTEM::is_dir($path)) { + + return new OC_Connector_Sabre_Directory($path); + + } else { + + return new OC_Connector_Sabre_File($path); + + } + + } + + /** + * Returns an array with all the child nodes + * + * @return Sabre_DAV_INode[] + */ + public function getChildren() { + + $nodes = array(); + // foreach(scandir($this->path) as $node) if($node!='.' && $node!='..') $nodes[] = $this->getChild($node); + if( OC_FILESYSTEM::is_dir($this->path)){ + $dh = OC_FILESYSTEM::opendir($this->path); + while(( $node = readdir($dh)) !== false ){ + if($node!='.' && $node!='..'){ + $nodes[] = $this->getChild($node); + } + } + } + return $nodes; + + } + + /** + * Checks if a child exists. + * + * @param string $name + * @return bool + */ + public function childExists($name) { + + $path = $this->path . '/' . $name; + return OC_FILESYSTEM::file_exists($path); + + } + + /** + * Deletes all files in this directory, and then itself + * + * @return void + */ + public function delete() { + + foreach($this->getChildren() as $child) $child->delete(); + OC_FILESYSTEM::rmdir($this->path); + + } + + /** + * Returns available diskspace information + * + * @return array + */ + public function getQuotaInfo() { + + return array( + OC_FILESYSTEM::filesize('/'), + OC_FILESYSTEM::free_space() + ); + + } + +} + diff --git a/lib/connector/sabre/file.php b/lib/connector/sabre/file.php new file mode 100644 index 00000000000..fb4e559aa50 --- /dev/null +++ b/lib/connector/sabre/file.php @@ -0,0 +1,87 @@ +path,$data); + + } + + /** + * Returns the data + * + * @return string + */ + public function get() { + + return OC_FILESYSTEM::file_get_contents($this->path); + + } + + /** + * Delete the current file + * + * @return void + */ + public function delete() { + + OC_FILESYSTEM::unlink($this->path); + + } + + /** + * Returns the size of the node, in bytes + * + * @return int + */ + public function getSize() { + + return OC_FILESYSTEM::filesize($this->path); + + } + + /** + * Returns the ETag for a file + * + * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. + * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. + * + * Return null if the ETag can not effectively be determined + * + * @return mixed + */ + public function getETag() { + + return null; + + } + + /** + * Returns the mime-type for a file + * + * If null is returned, we'll assume application/octet-stream + * + * @return mixed + */ + public function getContentType() { + + return OC_FILESYSTEM::getMimeType($this->path); + + } +} + diff --git a/lib/connector/sabre/locks.php b/lib/connector/sabre/locks.php new file mode 100644 index 00000000000..88bab509898 --- /dev/null +++ b/lib/connector/sabre/locks.php @@ -0,0 +1,152 @@ + ? AND ((uri = ?)'; + $params = array(OC_USER::getUser(),time(),$uri); + + // We need to check locks for every part in the uri. + $uriParts = explode('/',$uri); + + // We already covered the last part of the uri + array_pop($uriParts); + + $currentPath=''; + + foreach($uriParts as $part) { + + if ($currentPath) $currentPath.='/'; + $currentPath.=$part; + + $query.=' OR (depth!=0 AND uri = ?)'; + $params[] = $currentPath; + + } + + if ($returnChildLocks) { + + $query.=' OR (uri LIKE ?)'; + $params[] = $uri . '/%'; + + } + $query.=')'; + + $stmt = OC_DB::prepare($query); + $result = $stmt->execute($params); + + $lockList = array(); + while( $row = $result->fetchRow()){ + + $lockInfo = new Sabre_DAV_Locks_LockInfo(); + $lockInfo->owner = $row['owner']; + $lockInfo->token = $row['token']; + $lockInfo->timeout = $row['timeout']; + $lockInfo->created = $row['created']; + $lockInfo->scope = $row['scope']; + $lockInfo->depth = $row['depth']; + $lockInfo->uri = $row['uri']; + $lockList[] = $lockInfo; + + } + + return $lockList; + + } + + /** + * Locks a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + // We're making the lock timeout 5 minutes + $lockInfo->timeout = 300; + $lockInfo->created = time(); + $lockInfo->uri = $uri; + + $locks = $this->getLocks($uri,false); + $exists = false; + foreach($locks as $k=>$lock) { + if ($lock->token == $lockInfo->token) $exists = true; + } + + if ($exists) { + $query = OC_DB::prepare( 'UPDATE *PREFIX*locks SET owner = ?, timeout = ?, scope = ?, depth = ?, uri = ?, created = ? WHERE userid = ? AND token = ?' ); + $result = $query->execute( array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,OC_USER::getUser(),$lockInfo->token)); + } else { + $query = OC_DB::prepare( 'INSERT INTO *PREFIX*locks (userid,owner,timeout,scope,depth,uri,created,token) VALUES (?,?,?,?,?,?,?,?)' ); + $result = $query->execute( array(OC_USER::getUser(),$lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); + } + + return true; + + } + + /** + * Removes a lock from a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + $query = OC_DB::prepare( 'DELETE FROM *PREFIX*locks WHERE userid = ? AND uri=? AND token=?' ); + $result = $query->execute( array(OC_USER::getUser(),$uri,$lockInfo->token)); + + return $result->numRows() === 1; + + } + +} + diff --git a/lib/connector/sabre/node.php b/lib/connector/sabre/node.php new file mode 100644 index 00000000000..03d5e90012e --- /dev/null +++ b/lib/connector/sabre/node.php @@ -0,0 +1,158 @@ +path = $path; + } + + + + /** + * Returns the name of the node + * + * @return string + */ + public function getName() { + + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); + return $name; + + } + + /** + * Renames the node + * + * @param string $name The new name + * @return void + */ + public function setName($name) { + + list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); + list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); + + $newPath = $parentPath . '/' . $newName; + $oldPath = $this->path; + + OC_FILESYSTEM::rename($this->path,$newPath); + + $this->path = $newPath; + + $query = OC_DB::prepare( 'UPDATE *PREFIX*properties SET propertypath = ? WHERE userid = ? AND propertypath = ?' ); + $query->execute( array( $newPath,OC_USER::getUser(), $oldPath )); + + } + + + + /** + * Returns the last modification time, as a unix timestamp + * + * @return int + */ + public function getLastModified() { + + return OC_FILESYSTEM::filemtime($this->path); + + } + + /** + * Updates properties on this node, + * + * @param array $mutations + * @see Sabre_DAV_IProperties::updateProperties + * @return bool|array + */ + public function updateProperties($properties) { + $existing = $this->getProperties(array()); + foreach($properties as $propertyName => $propertyValue) { + // If it was null, we need to delete the property + if (is_null($propertyValue)) { + if(array_key_exists( $propertyName, $existing )){ + $query = OC_DB::prepare( 'DELETE FROM *PREFIX*properties WHERE userid = ? AND propertypath = ? AND propertyname = ?' ); + $query->execute( array( OC_USER::getUser(), $this->path, $propertyName )); + } + } + else { + if(!array_key_exists( $propertyName, $existing )){ + $query = OC_DB::prepare( 'INSERT INTO *PREFIX*properties (userid,propertypath,propertyname,propertyvalue) VALUES(?,?,?,?)' ); + $query->execute( array( OC_USER::getUser(), $this->path, $propertyName,$propertyValue )); + } + else{ + $query = OC_DB::prepare( 'UPDATE *PREFIX*properties SET propertyvalue = ? WHERE userid = ? AND propertypath = ? AND propertyname = ?' ); + $query->execute( array( $propertyValue,OC_USER::getUser(), $this->path, $propertyName )); + } + } + + } + return true; + } + + /** + * Returns a list of properties for this nodes.; + * + * The properties list is a list of propertynames the client requested, encoded as xmlnamespace#tagName, for example: http://www.example.org/namespace#author + * If the array is empty, all properties should be returned + * + * @param array $properties + * @return void + */ + function getProperties($properties) { + // At least some magic in here :-) + $query = OC_DB::prepare( 'SELECT * FROM *PREFIX*properties WHERE userid = ? AND propertypath = ?' ); + $result = $query->execute( array( OC_USER::getUser(), $this->path )); + + $existing = array(); + while( $row = $result->fetchRow()){ + $existing[$row['propertyname']] = $row['propertyvalue']; + } + + if(count($properties) == 0){ + return $existing; + } + + // if the array was empty, we need to return everything + $props = array(); + foreach($properties as $property) { + if (isset($existing[$property])) $props[$property] = $existing[$property]; + } + return $props; + } +} + diff --git a/lib/database.php b/lib/database.php deleted file mode 100644 index 8d7c76756c1..00000000000 --- a/lib/database.php +++ /dev/null @@ -1,365 +0,0 @@ -. - * - */ - -/** - * This class manages the access to the database. It basically is a wrapper for - * MDB2 with some adaptions. - */ -class OC_DB { - static private $DBConnection=false; - static private $schema=false; - static private $affected=0; - static private $result=false; - - /** - * @brief connects to the database - * @returns true if connection can be established or nothing (die()) - * - * Connects to the database as specified in config.php - */ - static public function connect(){ - // The global data we need - $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" );; - $CONFIG_DBHOST = OC_CONFIG::getValue( "dbhost", "" );; - $CONFIG_DBUSER = OC_CONFIG::getValue( "dbuser", "" );; - $CONFIG_DBPASSWORD = OC_CONFIG::getValue( "dbpassword", "" );; - $CONFIG_DBTYPE = OC_CONFIG::getValue( "dbtype", "sqlite" );; - global $SERVERROOT; - $datadir=OC_CONFIG::getValue( "datadirectory", "$SERVERROOT/data" ); - - // do nothing if the connection already has been established - if(!self::$DBConnection){ - // Require MDB2.php (not required in the head of the file so we only load it when needed) - require_once('MDB2.php'); - - // Prepare options array - $options = array( - 'portability' => MDB2_PORTABILITY_ALL, - 'log_line_break' => '
', - 'idxname_format' => '%s', - 'debug' => true, - 'quote_identifier' => true ); - - // Add the dsn according to the database type - if( $CONFIG_DBTYPE == 'sqlite' or $CONFIG_DBTYPE == 'sqlite3' ){ - // sqlite - $dsn = array( - 'phptype' => $CONFIG_DBTYPE, - 'database' => "$datadir/$CONFIG_DBNAME.db", - 'mode' => '0644' ); - } - elseif( $CONFIG_DBTYPE == 'mysql' ){ - // MySQL - $dsn = array( - 'phptype' => 'mysql', - 'username' => $CONFIG_DBUSER, - 'password' => $CONFIG_DBPASSWORD, - 'hostspec' => $CONFIG_DBHOST, - 'database' => $CONFIG_DBNAME ); - } - elseif( $CONFIG_DBTYPE == 'pgsql' ){ - // PostgreSQL - $dsn = array( - 'phptype' => 'pgsql', - 'username' => $CONFIG_DBUSER, - 'password' => $CONFIG_DBPASSWORD, - 'hostspec' => $CONFIG_DBHOST, - 'database' => $CONFIG_DBNAME ); - } - - // Try to establish connection - self::$DBConnection = MDB2::factory( $dsn, $options ); - - // Die if we could not connect - if( PEAR::isError( self::$DBConnection )){ - echo( 'can not connect to database, using '.$CONFIG_DBTYPE.'. ('.self::$DBConnection->getUserInfo().')'); - $error = self::$DBConnection->getMessage(); - error_log( $error); - error_log( self::$DBConnection->getUserInfo()); - die( $error ); - } - - // We always, really always want associative arrays - self::$DBConnection->setFetchMode(MDB2_FETCHMODE_ASSOC); - - //we need to function module for query pre-procesing - self::$DBConnection->loadModule('Function'); - } - - // we are done. great! - return true; - } - - /** - * @brief SQL query - * @param $query Query string - * @returns result as MDB2_Result - * - * SQL query via MDB2 query() - */ - static public function query( $query ){ - // Optimize the query - $query = self::processQuery( $query ); - - self::connect(); - //fix differences between sql versions - - // return the result - $result = self::$DBConnection->exec( $query ); - - // Die if we have an error (error means: bad query, not 0 results!) - if( PEAR::isError($result)) { - $entry = 'DB Error: "'.$result->getMessage().'"
'; - $entry .= 'Offending command was: '.$cmd.'
'; - error_log( $entry ); - die( $entry ); - } - - return $result; - } - - /** - * @brief Prepare a SQL query - * @param $query Query string - * @returns prepared SQL query - * - * SQL query via MDB2 prepare(), needs to be execute()'d! - */ - static public function prepare( $query ){ - // Optimize the query - $query = self::processQuery( $query ); - - self::connect(); - // return the result - $result = self::$DBConnection->prepare( $query ); - - // Die if we have an error (error means: bad query, not 0 results!) - if( PEAR::isError($result)) { - $entry = 'DB Error: "'.$result->getMessage().'"
'; - $entry .= 'Offending command was: '.$query.'
'; - error_log( $entry ); - die( $entry ); - } - - return $result; - } - - /** - * @brief gets last value of autoincrement - * @returns id - * - * MDB2 lastInsertID() - * - * Call this method right after the insert command or other functions may - * cause trouble! - */ - public static function insertid(){ - self::connect(); - return self::$DBConnection->lastInsertID(); - } - - /** - * @brief Disconnect - * @returns true/false - * - * This is good bye, good bye, yeah! - */ - public static function disconnect(){ - // Cut connection if required - if(self::$DBConnection){ - self::$DBConnection->disconnect(); - self::$DBConnection=false; - } - - return true; - } - - /** - * @brief Escapes bad characters - * @param $string string with dangerous characters - * @returns escaped string - * - * MDB2 escape() - */ - public static function escape( $string ){ - self::connect(); - return self::$DBConnection->escape( $string ); - } - - /** - * @brief saves database scheme to xml file - * @param $file name of file - * @returns true/false - * - * TODO: write more documentation - */ - public static function getDbStructure( $file ){ - self::connectScheme(); - - // write the scheme - $definition = self::$schema->getDefinitionFromDatabase(); - $dump_options = array( - 'output_mode' => 'file', - 'output' => $file, - 'end_of_line' => "\n" - ); - self::$schema->dumpDatabase( $definition, $dump_options, MDB2_SCHEMA_DUMP_STRUCTURE ); - - return true; - } - - /** - * @brief Creates tables from XML file - * @param $file file to read structure from - * @returns true/false - * - * TODO: write more documentation - */ - public static function createDbFromStructure( $file ){ - $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" ); - $CONFIG_DBTABLEPREFIX = OC_CONFIG::getValue( "dbtableprefix", "oc_" ); - - self::connectScheme(); - - // read file - $content = file_get_contents( $file ); - - // Make changes and save them to a temporary file - $file2 = tempnam( sys_get_temp_dir(), 'oc_db_scheme_' ); - $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content ); - $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content ); - file_put_contents( $file2, $content ); - - // Try to create tables - $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); - - // Delete our temporary file - unlink( $file2 ); - - // Die in case something went wrong - if( $definition instanceof MDB2_Schema_Error ){ - die( $definition->getMessage().': '.$definition->getUserInfo()); - } -// if(OC_CONFIG::getValue('dbtype','sqlite')=='sqlite'){ -// $definition['overwrite']=true;//always overwrite for sqlite -// } - $ret=self::$schema->createDatabase( $definition ); - - // Die in case something went wrong - if( $ret instanceof MDB2_Error ){ - die ($ret->getMessage() . ': ' . $ret->getUserInfo()); - } - - return true; - } - - /** - * @brief connects to a MDB2 database scheme - * @returns true/false - * - * Connects to a MDB2 database scheme - */ - private static function connectScheme(){ - // We need a database connection - self::connect(); - - // Connect if this did not happen before - if(!self::$schema){ - require_once('MDB2/Schema.php'); - self::$schema=MDB2_Schema::factory(self::$DBConnection); - } - - return true; - } - - /** - * @brief does minor chages to query - * @param $query Query string - * @returns corrected query string - * - * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX - * and replaces the ` woth ' or " according to the database driver. - */ - private static function processQuery( $query ){ - self::connect(); - // We need Database type and table prefix - $CONFIG_DBTYPE = OC_CONFIG::getValue( "dbtype", "sqlite" ); - $CONFIG_DBTABLEPREFIX = OC_CONFIG::getValue( "dbtableprefix", "oc_" ); - - // differences is getting the current timestamp - $query = str_replace( 'NOW()', self::$DBConnection->now(), $query ); - $query = str_replace( 'now()', self::$DBConnection->now(), $query ); - - // differences in escaping of table names (` for mysql) - // Problem: what if there is a ` in the value we want to insert? - if( $CONFIG_DBTYPE == 'sqlite' ){ - $query = str_replace( '`', '\'', $query ); - } - elseif( $CONFIG_DBTYPE == 'pgsql' ){ - $query = str_replace( '`', '"', $query ); - } - - // replace table name prefix - $query = str_replace( '*PREFIX*', $CONFIG_DBTABLEPREFIX, $query ); - - return $query; - } - - /** - * @brief drop a table - * @param string $tableNamme the table to drop - */ - public static function dropTable($tableName){ - self::connect(); - self::$DBConnection->loadModule('Manager'); - self::$DBConnection->dropTable($tableName); - } - - /** - * remove all tables defined in a database structure xml file - * @param string $file the xml file describing the tables - */ - public static function removeDBStructure($file){ - $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" ); - $CONFIG_DBTABLEPREFIX = OC_CONFIG::getValue( "dbtableprefix", "oc_" ); - self::connectScheme(); - - // read file - $content = file_get_contents( $file ); - - // Make changes and save them to a temporary file - $file2 = tempnam( sys_get_temp_dir(), 'oc_db_scheme_' ); - $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content ); - $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content ); - file_put_contents( $file2, $content ); - - // get the tables - $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); - - // Delete our temporary file - unlink( $file2 ); - foreach($definition['tables'] as $name=>$table){ - self::dropTable($name); - } - } -} -?> \ No newline at end of file diff --git a/lib/db.php b/lib/db.php new file mode 100644 index 00000000000..8d7c76756c1 --- /dev/null +++ b/lib/db.php @@ -0,0 +1,365 @@ +. + * + */ + +/** + * This class manages the access to the database. It basically is a wrapper for + * MDB2 with some adaptions. + */ +class OC_DB { + static private $DBConnection=false; + static private $schema=false; + static private $affected=0; + static private $result=false; + + /** + * @brief connects to the database + * @returns true if connection can be established or nothing (die()) + * + * Connects to the database as specified in config.php + */ + static public function connect(){ + // The global data we need + $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" );; + $CONFIG_DBHOST = OC_CONFIG::getValue( "dbhost", "" );; + $CONFIG_DBUSER = OC_CONFIG::getValue( "dbuser", "" );; + $CONFIG_DBPASSWORD = OC_CONFIG::getValue( "dbpassword", "" );; + $CONFIG_DBTYPE = OC_CONFIG::getValue( "dbtype", "sqlite" );; + global $SERVERROOT; + $datadir=OC_CONFIG::getValue( "datadirectory", "$SERVERROOT/data" ); + + // do nothing if the connection already has been established + if(!self::$DBConnection){ + // Require MDB2.php (not required in the head of the file so we only load it when needed) + require_once('MDB2.php'); + + // Prepare options array + $options = array( + 'portability' => MDB2_PORTABILITY_ALL, + 'log_line_break' => '
', + 'idxname_format' => '%s', + 'debug' => true, + 'quote_identifier' => true ); + + // Add the dsn according to the database type + if( $CONFIG_DBTYPE == 'sqlite' or $CONFIG_DBTYPE == 'sqlite3' ){ + // sqlite + $dsn = array( + 'phptype' => $CONFIG_DBTYPE, + 'database' => "$datadir/$CONFIG_DBNAME.db", + 'mode' => '0644' ); + } + elseif( $CONFIG_DBTYPE == 'mysql' ){ + // MySQL + $dsn = array( + 'phptype' => 'mysql', + 'username' => $CONFIG_DBUSER, + 'password' => $CONFIG_DBPASSWORD, + 'hostspec' => $CONFIG_DBHOST, + 'database' => $CONFIG_DBNAME ); + } + elseif( $CONFIG_DBTYPE == 'pgsql' ){ + // PostgreSQL + $dsn = array( + 'phptype' => 'pgsql', + 'username' => $CONFIG_DBUSER, + 'password' => $CONFIG_DBPASSWORD, + 'hostspec' => $CONFIG_DBHOST, + 'database' => $CONFIG_DBNAME ); + } + + // Try to establish connection + self::$DBConnection = MDB2::factory( $dsn, $options ); + + // Die if we could not connect + if( PEAR::isError( self::$DBConnection )){ + echo( 'can not connect to database, using '.$CONFIG_DBTYPE.'. ('.self::$DBConnection->getUserInfo().')'); + $error = self::$DBConnection->getMessage(); + error_log( $error); + error_log( self::$DBConnection->getUserInfo()); + die( $error ); + } + + // We always, really always want associative arrays + self::$DBConnection->setFetchMode(MDB2_FETCHMODE_ASSOC); + + //we need to function module for query pre-procesing + self::$DBConnection->loadModule('Function'); + } + + // we are done. great! + return true; + } + + /** + * @brief SQL query + * @param $query Query string + * @returns result as MDB2_Result + * + * SQL query via MDB2 query() + */ + static public function query( $query ){ + // Optimize the query + $query = self::processQuery( $query ); + + self::connect(); + //fix differences between sql versions + + // return the result + $result = self::$DBConnection->exec( $query ); + + // Die if we have an error (error means: bad query, not 0 results!) + if( PEAR::isError($result)) { + $entry = 'DB Error: "'.$result->getMessage().'"
'; + $entry .= 'Offending command was: '.$cmd.'
'; + error_log( $entry ); + die( $entry ); + } + + return $result; + } + + /** + * @brief Prepare a SQL query + * @param $query Query string + * @returns prepared SQL query + * + * SQL query via MDB2 prepare(), needs to be execute()'d! + */ + static public function prepare( $query ){ + // Optimize the query + $query = self::processQuery( $query ); + + self::connect(); + // return the result + $result = self::$DBConnection->prepare( $query ); + + // Die if we have an error (error means: bad query, not 0 results!) + if( PEAR::isError($result)) { + $entry = 'DB Error: "'.$result->getMessage().'"
'; + $entry .= 'Offending command was: '.$query.'
'; + error_log( $entry ); + die( $entry ); + } + + return $result; + } + + /** + * @brief gets last value of autoincrement + * @returns id + * + * MDB2 lastInsertID() + * + * Call this method right after the insert command or other functions may + * cause trouble! + */ + public static function insertid(){ + self::connect(); + return self::$DBConnection->lastInsertID(); + } + + /** + * @brief Disconnect + * @returns true/false + * + * This is good bye, good bye, yeah! + */ + public static function disconnect(){ + // Cut connection if required + if(self::$DBConnection){ + self::$DBConnection->disconnect(); + self::$DBConnection=false; + } + + return true; + } + + /** + * @brief Escapes bad characters + * @param $string string with dangerous characters + * @returns escaped string + * + * MDB2 escape() + */ + public static function escape( $string ){ + self::connect(); + return self::$DBConnection->escape( $string ); + } + + /** + * @brief saves database scheme to xml file + * @param $file name of file + * @returns true/false + * + * TODO: write more documentation + */ + public static function getDbStructure( $file ){ + self::connectScheme(); + + // write the scheme + $definition = self::$schema->getDefinitionFromDatabase(); + $dump_options = array( + 'output_mode' => 'file', + 'output' => $file, + 'end_of_line' => "\n" + ); + self::$schema->dumpDatabase( $definition, $dump_options, MDB2_SCHEMA_DUMP_STRUCTURE ); + + return true; + } + + /** + * @brief Creates tables from XML file + * @param $file file to read structure from + * @returns true/false + * + * TODO: write more documentation + */ + public static function createDbFromStructure( $file ){ + $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" ); + $CONFIG_DBTABLEPREFIX = OC_CONFIG::getValue( "dbtableprefix", "oc_" ); + + self::connectScheme(); + + // read file + $content = file_get_contents( $file ); + + // Make changes and save them to a temporary file + $file2 = tempnam( sys_get_temp_dir(), 'oc_db_scheme_' ); + $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content ); + $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content ); + file_put_contents( $file2, $content ); + + // Try to create tables + $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); + + // Delete our temporary file + unlink( $file2 ); + + // Die in case something went wrong + if( $definition instanceof MDB2_Schema_Error ){ + die( $definition->getMessage().': '.$definition->getUserInfo()); + } +// if(OC_CONFIG::getValue('dbtype','sqlite')=='sqlite'){ +// $definition['overwrite']=true;//always overwrite for sqlite +// } + $ret=self::$schema->createDatabase( $definition ); + + // Die in case something went wrong + if( $ret instanceof MDB2_Error ){ + die ($ret->getMessage() . ': ' . $ret->getUserInfo()); + } + + return true; + } + + /** + * @brief connects to a MDB2 database scheme + * @returns true/false + * + * Connects to a MDB2 database scheme + */ + private static function connectScheme(){ + // We need a database connection + self::connect(); + + // Connect if this did not happen before + if(!self::$schema){ + require_once('MDB2/Schema.php'); + self::$schema=MDB2_Schema::factory(self::$DBConnection); + } + + return true; + } + + /** + * @brief does minor chages to query + * @param $query Query string + * @returns corrected query string + * + * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX + * and replaces the ` woth ' or " according to the database driver. + */ + private static function processQuery( $query ){ + self::connect(); + // We need Database type and table prefix + $CONFIG_DBTYPE = OC_CONFIG::getValue( "dbtype", "sqlite" ); + $CONFIG_DBTABLEPREFIX = OC_CONFIG::getValue( "dbtableprefix", "oc_" ); + + // differences is getting the current timestamp + $query = str_replace( 'NOW()', self::$DBConnection->now(), $query ); + $query = str_replace( 'now()', self::$DBConnection->now(), $query ); + + // differences in escaping of table names (` for mysql) + // Problem: what if there is a ` in the value we want to insert? + if( $CONFIG_DBTYPE == 'sqlite' ){ + $query = str_replace( '`', '\'', $query ); + } + elseif( $CONFIG_DBTYPE == 'pgsql' ){ + $query = str_replace( '`', '"', $query ); + } + + // replace table name prefix + $query = str_replace( '*PREFIX*', $CONFIG_DBTABLEPREFIX, $query ); + + return $query; + } + + /** + * @brief drop a table + * @param string $tableNamme the table to drop + */ + public static function dropTable($tableName){ + self::connect(); + self::$DBConnection->loadModule('Manager'); + self::$DBConnection->dropTable($tableName); + } + + /** + * remove all tables defined in a database structure xml file + * @param string $file the xml file describing the tables + */ + public static function removeDBStructure($file){ + $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" ); + $CONFIG_DBTABLEPREFIX = OC_CONFIG::getValue( "dbtableprefix", "oc_" ); + self::connectScheme(); + + // read file + $content = file_get_contents( $file ); + + // Make changes and save them to a temporary file + $file2 = tempnam( sys_get_temp_dir(), 'oc_db_scheme_' ); + $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content ); + $content = str_replace( '*dbprefix*', $CONFIG_DBTABLEPREFIX, $content ); + file_put_contents( $file2, $content ); + + // get the tables + $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); + + // Delete our temporary file + unlink( $file2 ); + foreach($definition['tables'] as $name=>$table){ + self::dropTable($name); + } + } +} +?> \ No newline at end of file diff --git a/lib/files.php b/lib/files.php index d8133667954..d24eb282c45 100644 --- a/lib/files.php +++ b/lib/files.php @@ -21,9 +21,6 @@ * */ -require_once("log.php"); - - /** * Class for fileserver access * diff --git a/lib/group.php b/lib/group.php index 6510838ccfc..71caaee6132 100644 --- a/lib/group.php +++ b/lib/group.php @@ -78,7 +78,6 @@ class OC_GROUP { case 'database': case 'mysql': case 'sqlite': - require_once('Group/database.php'); self::$_backend = new OC_GROUP_DATABASE(); break; default: diff --git a/lib/group/backend.php b/lib/group/backend.php new file mode 100644 index 00000000000..298cced7ff5 --- /dev/null +++ b/lib/group/backend.php @@ -0,0 +1,96 @@ +. +* +*/ + + + +/** + * Abstract base class for user management + */ +abstract class OC_GROUP_BACKEND { + /** + * @brief Try to create a new group + * @param $gid The name of the group to create + * @returns true/false + * + * Trys to create a new group. If the group name already exists, false will + * be returned. + */ + public static function createGroup($gid){} + + /** + * @brief delete a group + * @param $gid gid of the group to delete + * @returns true/false + * + * Deletes a group and removes it from the group_user-table + */ + public static function removeGroup($gid){} + + /** + * @brief is user in group? + * @param $uid uid of the user + * @param $gid gid of the group + * @returns true/false + * + * Checks whether the user is member of a group or not. + */ + public static function inGroup($uid, $gid){} + + /** + * @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){} + + /** + * @brief Removes a user from a group + * @param $uid Name of the user to remove from group + * @param $gid Name of the group from which remove the user + * @returns true/false + * + * removes the user from a group. + */ + public static function removeFromGroup($uid,$gid){} + + /** + * @brief Get all groups a user belongs to + * @param $uid Name of the user + * @returns array with group names + * + * This function fetches all groups a user belongs to. It does not check + * if the user exists at all. + */ + public static function getUserGroups($uid){} + + /** + * @brief get a list of all groups + * @returns array with group names + * + * Returns a list with all groups + */ + public static function getGroups(){} +} diff --git a/lib/group/database.php b/lib/group/database.php new file mode 100644 index 00000000000..8c04ca5d36b --- /dev/null +++ b/lib/group/database.php @@ -0,0 +1,177 @@ +. + * + */ +/* + * + * The following SQL statement is just a help for developers and will not be + * executed! + * + * CREATE TABLE `groups` ( + * `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL, + * PRIMARY KEY (`gid`) + * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + * + * CREATE TABLE `group_user` ( + * `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL, + * `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL + * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + * + */ + +/** + * Class for group management in a SQL Database (e.g. MySQL, SQLite) + */ +class OC_GROUP_DATABASE extends OC_GROUP_BACKEND { + static private $userGroupCache=array(); + + /** + * @brief Try to create a new group + * @param $gid The name of the group to create + * @returns true/false + * + * Trys to create a new group. If the group name already exists, false will + * be returned. + */ + public static function createGroup( $gid ){ + // Check for existence + $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*groups` WHERE gid = ?" ); + $result = $query->execute( array( $gid )); + + if( $result->numRows() > 0 ){ + // Can not add an existing group + return false; + } + else{ + // Add group and exit + $query = OC_DB::prepare( "INSERT INTO `*PREFIX*groups` ( `gid` ) VALUES( ? )" ); + $result = $query->execute( array( $gid )); + + return $result ? true : false; + } + } + + /** + * @brief delete a group + * @param $gid gid of the group to delete + * @returns true/false + * + * Deletes a group and removes it from the group_user-table + */ + public static function deleteGroup( $gid ){ + // Delete the group + $query = OC_DB::prepare( "DELETE FROM `*PREFIX*groups` WHERE gid = ?" ); + $result = $query->execute( array( $gid )); + + // Delete the group-user relation + $query = OC_DB::prepare( "DELETE FROM `*PREFIX*group_user` WHERE gid = ?" ); + $result = $query->execute( array( $gid )); + + return true; + } + + /** + * @brief is user in group? + * @param $uid uid of the user + * @param $gid gid of the group + * @returns true/false + * + * Checks whether the user is member of a group or not. + */ + public static function inGroup( $uid, $gid ){ + // check + $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*group_user` WHERE gid = ? AND uid = ?" ); + $result = $query->execute( array( $gid, $uid )); + + return $result->numRows() > 0 ? true : false; + } + + /** + * @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 ){ + // No duplicate entries! + if( !self::inGroup( $uid, $gid )){ + $query = OC_DB::prepare( "INSERT INTO `*PREFIX*group_user` ( `uid`, `gid` ) VALUES( ?, ? )" ); + $result = $query->execute( array( $uid, $gid )); + } + return true; + } + + /** + * @brief Removes a user from a group + * @param $uid Name of the user to remove from group + * @param $gid Name of the group from which remove the user + * @returns true/false + * + * removes the user from a group. + */ + public static function removeFromGroup( $uid, $gid ){ + $query = OC_DB::prepare( "DELETE FROM `*PREFIX*group_user` WHERE `uid` = ? AND `gid` = ?" ); + $result = $query->execute( array( $uid, $gid )); + + return true; + } + + /** + * @brief Get all groups a user belongs to + * @param $uid Name of the user + * @returns array with group names + * + * This function fetches all groups a user belongs to. It does not check + * if the user exists at all. + */ + public static function getUserGroups( $uid ){ + // No magic! + $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*group_user` WHERE uid = ?" ); + $result = $query->execute( array( $uid )); + + $groups = array(); + while( $row = $result->fetchRow()){ + $groups[] = $row["gid"]; + } + + return $groups; + } + + /** + * @brief get a list of all groups + * @returns array with group names + * + * Returns a list with all groups + */ + public static function getGroups(){ + $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*groups`" ); + $result = $query->execute(); + + $groups = array(); + while( $row = $result->fetchRow()){ + $groups[] = $row["gid"]; + } + + return $groups; + } +} diff --git a/lib/hook.php b/lib/hook.php new file mode 100644 index 00000000000..08b6d5e8b6b --- /dev/null +++ b/lib/hook.php @@ -0,0 +1,69 @@ + $slotclass, + "name" => $slotname ); + + // No chance for failure ;-) + return true; + } + + /** + * @brief emitts a signal + * @param $signalclass class name of emitter + * @param $signalname name of signal + * @param $params defautl: array() array with additional data + * @returns true if slots exists or false if not + * + * Emits a signal. To get data from the slot use references! + * + * TODO: write example + */ + static public function emit( $signalclass, $signalname, $params = array()){ + // Return false if there are no slots + if( !array_key_exists( $signalclass, self::$registered )){ + return false; + } + if( !array_key_exists( $signalname, self::$registered[$signalclass] )){ + return false; + } + + // Call all slots + foreach( self::$registered[$signalclass][$signalname] as $i ){ + call_user_func( array( $i["class"], $i["name"] ), $params ); + } + + // return true + return true; + } +} + diff --git a/lib/user.php b/lib/user.php index a64ce05f2c9..b93e2133352 100644 --- a/lib/user.php +++ b/lib/user.php @@ -95,7 +95,6 @@ class OC_USER { case 'database': case 'mysql': case 'sqlite': - require_once('User/database.php'); self::$_usedBackends[$backend] = new OC_USER_DATABASE(); break; default: diff --git a/lib/user/backend.php b/lib/user/backend.php new file mode 100644 index 00000000000..1797d0c475a --- /dev/null +++ b/lib/user/backend.php @@ -0,0 +1,86 @@ +. + * + */ + +/** + * error code for functions not provided by the user backend + */ +define('OC_USER_BACKEND_NOT_IMPLEMENTED', -501); + +/** + * actions that user backends can define + */ +define('OC_USER_BACKEND_CREATE_USER', 0x000001); +define('OC_USER_BACKEND_DELETE_USER', 0x000010); +define('OC_USER_BACKEND_SET_PASSWORD', 0x000100); +define('OC_USER_BACKEND_CHECK_PASSWORD', 0x001000); +define('OC_USER_BACKEND_GET_USERS', 0x010000); +define('OC_USER_BACKEND_USER_EXISTS', 0x100000); + + +/** + * abstract base class for user management + * subclass this for your own backends and see OC_USER_EXAMPLE for descriptions + */ +abstract class OC_USER_BACKEND { + + protected $possibleActions = array( + OC_USER_BACKEND_CREATE_USER => 'createUser', + OC_USER_BACKEND_DELETE_USER => 'deleteUser', + OC_USER_BACKEND_SET_PASSWORD => 'setPassword', + OC_USER_BACKEND_CHECK_PASSWORD => 'checkPassword', + OC_USER_BACKEND_GET_USERS => 'getUsers', + OC_USER_BACKEND_USER_EXISTS => 'userExists' + ); + + /** + * @brief Get all supported actions + * @returns bitwise-or'ed actions + * + * Returns the supported actions as int to be + * compared with OC_USER_BACKEND_CREATE_USER etc. + */ + public function getSupportedActions(){ + $actions = 0; + foreach($this->possibleActions AS $action => $methodName){ + if(method_exists($this, $methodName)) { + $actions |= $action; + } + } + + return $actions; + } + + /** + * @brief Check if backend implements actions + * @param $actions bitwise-or'ed actions + * @returns boolean + * + * Returns the supported actions as int to be + * compared with OC_USER_BACKEND_CREATE_USER etc. + */ + public function implementsActions($actions){ + return (bool)($this->getSupportedActions() & $actions); + } +} diff --git a/lib/user/database.php b/lib/user/database.php new file mode 100644 index 00000000000..ace3c897703 --- /dev/null +++ b/lib/user/database.php @@ -0,0 +1,145 @@ +. + * + */ +/* + * + * The following SQL statement is just a help for developers and will not be + * executed! + * + * CREATE TABLE `users` ( + * `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL, + * `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + * PRIMARY KEY (`uid`) + * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + * + */ + +/** + * Class for user management in a SQL Database (e.g. MySQL, SQLite) + */ +class OC_USER_DATABASE extends OC_USER_BACKEND { + static private $userGroupCache=array(); + + /** + * @brief Create a new user + * @param $uid The username of the user to create + * @param $password The password of the new user + * @returns true/false + * + * Creates a new user. Basic checking of username is done in OC_USER + * itself, not in its subclasses. + */ + public function createUser( $uid, $password ){ + if( $this->userExists($uid) ){ + return false; + } + else{ + $query = OC_DB::prepare( "INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )" ); + $result = $query->execute( array( $uid, sha1( $password ))); + + return $result ? true : false; + } + } + + /** + * @brief delete a user + * @param $uid The username of the user to delete + * @returns true/false + * + * Deletes a user + */ + public function deleteUser( $uid ){ + // Delete user-group-relation + $query = OC_DB::prepare( "DELETE FROM `*PREFIX*users` WHERE uid = ?" ); + $result = $query->execute( array( $uid )); + return true; + } + + /** + * @brief Set password + * @param $uid The username + * @param $password The new password + * @returns true/false + * + * Change the password of a user + */ + public function setPassword( $uid, $password ){ + if( $this->userExists($uid) ){ + $query = OC_DB::prepare( "UPDATE *PREFIX*users SET password = ? WHERE uid = ?" ); + $result = $query->execute( array( sha1( $password ), $uid )); + + return true; + } + else{ + return false; + } + } + + /** + * @brief Check if the password is correct + * @param $uid The username + * @param $password The password + * @returns true/false + * + * Check if the password is correct without logging in the user + */ + public function checkPassword( $uid, $password ){ + $query = OC_DB::prepare( "SELECT uid FROM *PREFIX*users WHERE uid = ? AND password = ?" ); + $result = $query->execute( array( $uid, sha1( $password ))); + + if( $result->numRows() > 0 ){ + return true; + } + else{ + return false; + } + } + + /** + * @brief Get a list of all users + * @returns array with all uids + * + * Get a list of all users. + */ + public function getUsers(){ + $query = OC_DB::prepare( "SELECT uid FROM *PREFIX*users" ); + $result = $query->execute(); + + $users=array(); + while( $row = $result->fetchRow()){ + $users[] = $row["uid"]; + } + return $users; + } + + /** + * @brief check if a user exists + * @param string $uid the username + * @return boolean + */ + public function userExists($uid){ + $query = OC_DB::prepare( "SELECT * FROM `*PREFIX*users` WHERE uid = ?" ); + $result = $query->execute( array( $uid )); + + return $result->numRows() > 0; + } +} diff --git a/lib/user/example.php b/lib/user/example.php new file mode 100644 index 00000000000..069f14492a4 --- /dev/null +++ b/lib/user/example.php @@ -0,0 +1,95 @@ +. + * + */ + +/** + * abstract reference class for user management + * this class should only be used as a reference for method signatures and their descriptions + */ +abstract class OC_USER_EXAMPLE extends OC_USER_BACKEND { + /** + * @brief Create a new user + * @param $uid The username of the user to create + * @param $password The password of the new user + * @returns true/false + * + * Creates a new user. Basic checking of username is done in OC_USER + * itself, not in its subclasses. + */ + public function createUser($uid, $password){ + return OC_USER_BACKEND_NOT_IMPLEMENTED; + } + + /** + * @brief delete a user + * @param $uid The username of the user to delete + * @returns true/false + * + * Deletes a user + */ + public function deleteUser( $uid ){ + return OC_USER_BACKEND_NOT_IMPLEMENTED; + } + + /** + * @brief Set password + * @param $uid The username + * @param $password The new password + * @returns true/false + * + * Change the password of a user + */ + public function setPassword($uid, $password){ + return OC_USER_BACKEND_NOT_IMPLEMENTED; + } + + /** + * @brief Check if the password is correct + * @param $uid The username + * @param $password The password + * @returns true/false + * + * Check if the password is correct without logging in the user + */ + public function checkPassword($uid, $password){ + return OC_USER_BACKEND_NOT_IMPLEMENTED; + } + + /** + * @brief Get a list of all users + * @returns array with all uids + * + * Get a list of all users. + */ + public function getUsers(){ + return OC_USER_BACKEND_NOT_IMPLEMENTED; + } + + /** + * @brief check if a user exists + * @param string $uid the username + * @return boolean + */ + public function userExists($uid){ + return OC_USER_BACKEND_NOT_IMPLEMENTED; + } +} diff --git a/lib/util.php b/lib/util.php new file mode 100644 index 00000000000..8beb4a884bc --- /dev/null +++ b/lib/util.php @@ -0,0 +1,245 @@ +$CONFIG_DATADIRECTORY_ROOT)); +// if( OC_CONFIG::getValue( "enablebackup", false )){ +// // This creates the Directorys recursively +// if(!is_dir( "$CONFIG_BACKUPDIRECTORY/$user/$root" )){ +// mkdir( "$CONFIG_BACKUPDIRECTORY/$user/$root", 0755, true ); +// } +// $backupStorage=OC_FILESYSTEM::createStorage('local',array('datadir'=>$CONFIG_BACKUPDIRECTORY)); +// $backup=new OC_FILEOBSERVER_BACKUP(array('storage'=>$backupStorage)); +// $rootStorage->addObserver($backup); +// } + OC_FILESYSTEM::mount($rootStorage,'/'); + + $CONFIG_DATADIRECTORY = "$CONFIG_DATADIRECTORY_ROOT/$user/$root"; + if( !is_dir( $CONFIG_DATADIRECTORY )){ + mkdir( $CONFIG_DATADIRECTORY, 0755, true ); + } + +// TODO: find a cool way for doing this +// //set up the other storages according to the system settings +// foreach($CONFIG_FILESYSTEM as $storageConfig){ +// if(OC_FILESYSTEM::hasStorageType($storageConfig['type'])){ +// $arguments=$storageConfig; +// unset($arguments['type']); +// unset($arguments['mountpoint']); +// $storage=OC_FILESYSTEM::createStorage($storageConfig['type'],$arguments); +// if($storage){ +// OC_FILESYSTEM::mount($storage,$storageConfig['mountpoint']); +// } +// } +// } + + //jail the user into his "home" directory + OC_FILESYSTEM::chroot("/$user/$root"); + self::$fsSetup=true; + } + } + + public static function tearDownFS(){ + OC_FILESYSTEM::tearDown(); + self::$fsSetup=false; + } + + /** + * get the current installed version of ownCloud + * @return array + */ + public static function getVersion(){ + return array(1,60,0); + } + + /** + * add a javascript file + * + * @param url $url + */ + public static function addScript( $application, $file = null ){ + if( is_null( $file )){ + $file = $application; + $application = ""; + } + if( !empty( $application )){ + self::$scripts[] = "$application/js/$file"; + }else{ + self::$scripts[] = "js/$file"; + } + } + + /** + * add a css file + * + * @param url $url + */ + public static function addStyle( $application, $file = null ){ + if( is_null( $file )){ + $file = $application; + $application = ""; + } + if( !empty( $application )){ + self::$styles[] = "$application/css/$file"; + }else{ + self::$styles[] = "css/$file"; + } + } + + /** + * @brief Add a custom element to the header + * @param string tag tag name of the element + * @param array $attributes array of attrobutes for the element + * @param string $text the text content for the element + */ + public static function addHeader( $tag, $attributes, $text=''){ + self::$headers[]=array('tag'=>$tag,'attributes'=>$attributes,'text'=>$text); + } + + /** + * formats a timestamp in the "right" way + * + * @param int timestamp $timestamp + * @param bool dateOnly option to ommit time from the result + */ + public static function formatDate( $timestamp,$dateOnly=false){ + if(isset($_SESSION['timezone'])){//adjust to clients timezone if we know it + $systemTimeZone = intval(exec('date +%z')); + $systemTimeZone=(round($systemTimeZone/100,0)*60)+($systemTimeZone%100); + $clientTimeZone=$_SESSION['timezone']*60; + $offset=$clientTimeZone-$systemTimeZone; + $timestamp=$timestamp+$offset*60; + } + $timeformat=$dateOnly?'F j, Y':'F j, Y, H:i'; + return date($timeformat,$timestamp); + } + + /** + * Shows a pagenavi widget where you can jump to different pages. + * + * @param int $pagecount + * @param int $page + * @param string $url + * @return OC_TEMPLATE + */ + public static function getPageNavi($pagecount,$page,$url) { + + $pagelinkcount=8; + if ($pagecount>1) { + $pagestart=$page-$pagelinkcount; + if($pagestart<0) $pagestart=0; + $pagestop=$page+$pagelinkcount; + if($pagestop>$pagecount) $pagestop=$pagecount; + + $tmpl = new OC_TEMPLATE( '', 'part.pagenavi', '' ); + $tmpl->assign('page',$page); + $tmpl->assign('pagecount',$pagecount); + $tmpl->assign('pagestart',$pagestart); + $tmpl->assign('pagestop',$pagestop); + $tmpl->assign('url',$url); + return $tmpl; + } + } + + + + /** + * check if the current server configuration is suitable for ownCloud + * @return array arrays with error messages and hints + */ + public static function checkServer(){ + global $SERVERROOT; + global $CONFIG_DATADIRECTORY; + + $CONFIG_DATADIRECTORY_ROOT = OC_CONFIG::getValue( "datadirectory", "$SERVERROOT/data" );; + $CONFIG_BACKUPDIRECTORY = OC_CONFIG::getValue( "backupdirectory", "$SERVERROOT/backup" ); + $CONFIG_INSTALLED = OC_CONFIG::getValue( "installed", false ); + $errors=array(); + + //check for database drivers + if(!is_callable('sqlite_open') and !is_callable('mysql_connect')){ + $errors[]=array('error'=>'No database drivers (sqlite or mysql) installed.
','hint'=>'');//TODO: sane hint + } + $CONFIG_DBTYPE = OC_CONFIG::getValue( "dbtype", "sqlite" ); + $CONFIG_DBNAME = OC_CONFIG::getValue( "dbname", "owncloud" ); + + //try to get the username the httpd server runs on, used in hints + $stat=stat($_SERVER['DOCUMENT_ROOT']); + if(is_callable('posix_getpwuid')){ + $serverUser=posix_getpwuid($stat['uid']); + $serverUser='\''.$serverUser['name'].'\''; + }else{ + $serverUser='\'www-data\' for ubuntu/debian';//TODO: try to detect the distro and give a guess based on that + } + + //common hint for all file permissons error messages + $permissionsHint="Permissions can usually be fixed by setting the owner of the file or directory to the user the web server runs as ($serverUser)"; + + //check for correct file permissions + if(!stristr(PHP_OS, 'WIN')){ + $prems=substr(decoct(fileperms($CONFIG_DATADIRECTORY_ROOT)),-3); + if(substr($prems,-1)!='0'){ + OC_HELPER::chmodr($CONFIG_DATADIRECTORY_ROOT,0770); + clearstatcache(); + $prems=substr(decoct(fileperms($CONFIG_DATADIRECTORY_ROOT)),-3); + if(substr($prems,2,1)!='0'){ + $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY_ROOT.') is readable from the web
','hint'=>$permissionsHint); + } + } + if( OC_CONFIG::getValue( "enablebackup", false )){ + $prems=substr(decoct(fileperms($CONFIG_BACKUPDIRECTORY)),-3); + if(substr($prems,-1)!='0'){ + OC_HELPER::chmodr($CONFIG_BACKUPDIRECTORY,0770); + clearstatcache(); + $prems=substr(decoct(fileperms($CONFIG_BACKUPDIRECTORY)),-3); + if(substr($prems,2,1)!='0'){ + $errors[]=array('error'=>'Data directory ('.$CONFIG_BACKUPDIRECTORY.') is readable from the web
','hint'=>$permissionsHint); + } + } + } + }else{ + //TODO: premisions checks for windows hosts + } + if(is_dir($CONFIG_DATADIRECTORY_ROOT) and !is_writable($CONFIG_DATADIRECTORY_ROOT)){ + $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY_ROOT.') not writable by ownCloud
','hint'=>$permissionsHint); + } + + //TODO: check for php modules + + return $errors; + } +} + -- cgit v1.2.3