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

OC_HOOK::connect("OC_FILESYSTEM","post_delete", "OC_SHARE", "deleteItem");
OC_HOOK::connect("OC_FILESYSTEM","post_rename", "OC_SHARE", "renameItem");

/**
 * This class manages shared items within the database. 
 */
class OC_SHARE {
	
	/**
	 * TODO notify user a file is being shared with them?
	 * Share an item, adds an entry into the database
	 * @param string $item
	 * @param user item shared with $uid_shared_with
	 */
	public function __construct($source, $uid_shared_with, $permissions, $public = false) {
		if ($source && OC_FILESYSTEM::file_exists($source) && OC_FILESYSTEM::is_readable($source)) {
			$source = "/".OC_USER::getUser()."/files".$source;
			$uid_owner = OC_USER::getUser();
			if ($public) {
				// TODO create token for public file
				$token = sha1("$uid_owner-$item");
			} else { 
				$query = OC_DB::prepare("INSERT INTO *PREFIX*sharing VALUES(?,?,?,?,?)");
				$target = "/".$uid_shared_with."/files/Share/".basename($source);
				$check = OC_DB::prepare("SELECT target FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with = ?");
				$result = $check->execute(array($target, $uid_shared_with))->fetchAll();
				// Check if target already exists for the user, if it does append a number to the name
				if (count($result) > 0) {
					if ($pos = strrpos($target, ".")) {
						$name = substr($target, 0, $pos);
						$ext = substr($target, $pos);
					} else {
						$name = $target;
						$ext = "";
					}
					$counter = 1;
					while (count($result) > 0) {
						$newTarget = $name."_".$counter.$ext;
						$result = $check->execute(array($newTarget, $uid_shared_with))->fetchAll();
						$counter++;
					}
					$target = $newTarget;
				}
				$query->execute(array($uid_owner, $uid_shared_with, $source, $target, $permissions));
			}
		}
	}
	
	/**
	 * Create a new entry in the database for a file inside a shared folder
	 *
	 * $oldTarget and $newTarget may be the same value. $oldTarget exists in case the file is being moved outside of the folder
	 *
	 * @param $oldTarget The current target location
	 * @param $newTarget The new target location
	 */
	public static function pullOutOfFolder($oldTarget, $newTarget) {
		$folders = self::getParentFolders($oldTarget);
		$source = $folders['source'].substr($oldTarget, strlen($folders['target']));
		$item = self::getItem($folders['target']);
		$query = OC_DB::prepare("INSERT INTO *PREFIX*sharing VALUES(?,?,?,?,?)");
		$query->execute(array($item[0]['uid_owner'], OC_USER::getUser(), $source, $newTarget, $item[0]['is_writeable']));
	}

	/**
	 * Get the item with the specified target location
	 * @param $target The target location of the item
	 * @return An array with the item
	 */
	public static function getItem($target) {
		$query = OC_DB::prepare("SELECT uid_owner, source, is_writeable  FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with = ? LIMIT 1");
		return $query->execute(array($target, OC_USER::getUser()))->fetchAll();
	}
	
	/**
	 * Get all items the current user is sharing
	 * @return An array with all items the user is sharing
	 */
	public static function getMySharedItems() {
		$query = OC_DB::prepare("SELECT uid_shared_with, source, is_writeable FROM *PREFIX*sharing WHERE uid_owner = ?");
		return $query->execute(array(OC_USER::getUser()))->fetchAll();
	}
	
	/**
	 * Get the items within a shared folder that have their own entry for the purpose of name, location, or permissions that differ from the folder itself
	 *
	 * Works for both target and source folders. Can be used for getting all items shared with you e.g. pass '/MTGap/files'
	 *
	 * @param $folder The folder of the items to look for
	 * @return An array with all items in the database that are in the folder
	 */
	public static function getItemsInFolder($folder) {
		// Append '/' in order to filter out the folder itself if not already there
		if (substr($folder, -1) !== "/") {
			$folder .= "/";
		}
		// Remove any duplicate '/'
		$folder = preg_replace('{(/)\1+}', "/", $folder);
		$length = strlen($folder);
		$query = OC_DB::prepare("SELECT uid_owner, source, target FROM *PREFIX*sharing WHERE SUBSTR(source, 1, ?) = ? OR SUBSTR(target, 1, ?) = ? AND uid_shared_with = ?");
		return $query->execute(array($length, $folder, $length, $folder, OC_USER::getUser()))->fetchAll();
	}
	
	/**
	 * Get the source and target parent folders of the specified target location
	 * @param $target The target location of the item
	 * @return An array with the keys 'source' and 'target' with the values of the source and target parent folders
	 */
	public static function getParentFolders($target) {
		// Remove any duplicate or trailing '/'
		$target = rtrim($target, "/");
		$target = preg_replace('{(/)\1+}', "/", $target);
		$query = OC_DB::prepare("SELECT source FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with = ? LIMIT 1");
		// Prevent searching for user directory e.g. '/MTGap/files'
		$userDirectory = substr($target, 0, strpos($target, "files") + 5);
		while ($target != "" && $target != "/" && $target != "." && $target != $userDirectory) {
			// Check if the parent directory of this target location is shared
			$target = dirname($target);
			$result = $query->execute(array($target, OC_USER::getUser()))->fetchAll();
			if (count($result) > 0) {
				break;
			}
		}
		if (count($result) > 0) {
			// Return both the source folder and the target folder
			return array("source" => $result[0]['source'], "target" => $target);
		} else {
			return false;
		}
	}

	/**
	 * Get the source location of the item at the specified target location
	 * @param $target The target location of the item
	 * @return Source location or false if target location is not valid
	 */
	public static function getSource($target) {
		// Remove any duplicate or trailing '/'
		$target = rtrim($target, "/");
		$target = preg_replace('{(/)\1+}', "/", $target);
		$query = OC_DB::prepare("SELECT source FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with = ? LIMIT 1");
		$result = $query->execute(array($target, OC_USER::getUser()))->fetchAll();
		if (count($result) > 0) {
			return $result[0]['source'];
		} else {
			$folders = self::getParentFolders($target);
			if ($folders == false) {
				return false;
			} else {
				return $folders['source'].substr($target, strlen($folders['target']));
			}
		}
	}

	/**
	 * Check if the user has write permission for the item at the specified target location
	 * @param $target The target location of the item
	 * @return True if the user has write permission or false if read only
	 */
	public static function isWriteable($target) {
		$query = OC_DB::prepare("SELECT is_writeable FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with = ? LIMIT 1");
		$result = $query->execute(array($target, OC_USER::getUser()))->fetchAll();
		if (count($result) > 0) {
			return $result[0]['is_writeable'];
		} else {
			// Check if the folder is writeable
			$folders = OC_SHARE::getParentFolders($target);
			$result = $query->execute(array($folders['target'], OC_USER::getUser()))->fetchAll();
			if (count($result) > 0) {
				return $result[0]['is_writeable'];
			} else {
				return false;
			}
		}
	}

	/**
	 * Set the source location to a new value<commit_msg>Add support for sharing files with user groups<commit_after><?php
/**
 * ownCloud
 *
 * @author <NAME>
 * @copyright 2011 <NAME> <EMAIL>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

OC_HOOK::connect("OC_FILESYSTEM","post_delete", "OC_SHARE", "deleteItem");
OC_HOOK::connect("OC_FILESYSTEM","post_rename", "OC_SHARE", "renameItem");

/**
 * This class manages shared items within the database. 
 */
class OC_SHARE {
	
	/**
	 * TODO notify user a file is being shared with them?
	 * Share an item, adds an entry into the database
	 * @param string $item
	 * @param user item shared with $uid_shared_with
	 */
	public function __construct($source, $uid_shared_with, $permissions, $public = false) {
		if ($source && OC_FILESYSTEM::file_exists($source) && OC_FILESYSTEM::is_readable($source)) {
			$source = "/".OC_USER::getUser()."/files".$source;
			$uid_owner = OC_USER::getUser();
			if ($public) {
				// TODO create token for public file
				$token = <PASSWORD>1("$uid_owner-$item");
			} else { 
				$query = OC_DB::prepare("INSERT INTO *PREFIX*sharing VALUES(?,?,?,?,?)");
				$target = "/".$uid_shared_with."/files/Share/".basename($source);
				$check = OC_DB::prepare("SELECT target FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with = ?");
				$result = $check->execute(array($target, $uid_shared_with))->fetchAll();
				// Check if target already exists for the user, if it does append a number to the name
				if (count($result) > 0) {
					if ($pos = strrpos($target, ".")) {
						$name = substr($target, 0, $pos);
						$ext = substr($target, $pos);
					} else {
						$name = $target;
						$ext = "";
					}
					$counter = 1;
					while (count($result) > 0) {
						$newTarget = $name."_".$counter.$ext;
						$result = $check->execute(array($newTarget, $uid_shared_with))->fetchAll();
						$counter++;
					}
					$target = $newTarget;
				}
				$query->execute(array($uid_owner, $uid_shared_with, $source, $target, $permissions));
			}
		}
	}

	/**
	* Get the user and the user's groups and put them into an array
	* @return An array to be used by the IN operator in a query for uid_shared_with
	*/
	private static function getUserAndGroups() {
		$self = OC_USER::getUser();
		$groups = OC_GROUP::getUserGroups($self);
		array_unshift($groups, $self);
		return $groups;
	}

	/**
	* Create a string of ?s based on the specified count
	* @return A string to be placed inside the IN operator in a query for uid_shared_with
	*/
	private static function prepareIN($count) {
		$questionMarks = "?";
		for($i = 1; $i < $count; $i++) {
			$questionMarks .= ",?";
		}
		return $questionMarks;
	}

	/**
	 * Create a new entry in the database for a file inside a shared folder
	 *
	 * $oldTarget and $newTarget may be the same value. $oldTarget exists in case the file is being moved outside of the folder
	 *
	 * @param $oldTarget The current target location
	 * @param $newTarget The new target location
	 */
	public static function pullOutOfFolder($oldTarget, $newTarget) {
		$folders = self::getParentFolders($oldTarget);
		$source = $folders['source'].substr($oldTarget, strlen($folders['target']));
		$item = self::getItem($folders['target']);
		$query = OC_DB::prepare("INSERT INTO *PREFIX*sharing VALUES(?,?,?,?,?)");
		$query->execute(array($item[0]['uid_owner'], OC_USER::getUser(), $source, $newTarget, $item[0]['is_writeable']));
	}

	/**
	 * Get the item with the specified target location
	 * @param $target The target location of the item
	 * @return An array with the item
	 */
	public static function getItem($target) {
		$query = OC_DB::prepare("SELECT uid_owner, source, is_writeable  FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with = ? LIMIT 1");
		return $query->execute(array($target, OC_USER::getUser()))->fetchAll();
	}
	
	/**
	 * Get all items the current user is sharing
	 * @return An array with all items the user is sharing
	 */
	public static function getMySharedItems() {
		$query = OC_DB::prepare("SELECT uid_shared_with, source, is_writeable FROM *PREFIX*sharing WHERE uid_owner = ?");
		return $query->execute(array(OC_USER::getUser()))->fetchAll();
	}
	
	/**
	 * Get the items within a shared folder that have their own entry for the purpose of name, location, or permissions that differ from the folder itself
	 *
	 * Works for both target and source folders. Can be used for getting all items shared with you e.g. pass '/MTGap/files'
	 *
	 * @param $folder The folder of the items to look for
	 * @return An array with all items in the database that are in the folder
	 */
	public static function getItemsInFolder($folder) {
		// Append '/' in order to filter out the folder itself if not already there
		if (substr($folder, -1) !== "/") {
			$folder .= "/";
		}
		// Remove any duplicate '/'
		$folder = preg_replace('{(/)\1+}', "/", $folder);
		$length = strlen($folder);
		$userAndGroups = self::getUserAndGroups();
		$query = OC_DB::prepare("SELECT uid_owner, source, target FROM *PREFIX*sharing WHERE SUBSTR(source, 1, ?) = ? OR SUBSTR(target, 1, ?) = ? AND uid_shared_with IN(".self::prepareIN(count($userAndGroups)).")");
		return $query->execute(array_merge(array($length, $folder, $length, $folder), $userAndGroups))->fetchAll();
	}
	
	/**
	 * Get the source and target parent folders of the specified target location
	 * @param $target The target location of the item
	 * @return An array with the keys 'source' and 'target' with the values of the source and target parent folders
	 */
	public static function getParentFolders($target) {
		// Remove any duplicate or trailing '/'
		$target = rtrim($target, "/");
		$target = preg_replace('{(/)\1+}', "/", $target);
		$userAndGroups = self::getUserAndGroups();
		$query = OC_DB::prepare("SELECT source FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with IN(".self::prepareIN(count($userAndGroups)).") LIMIT 1");
		// Prevent searching for user directory e.g. '/MTGap/files'
		$userDirectory = substr($target, 0, strpos($target, "files") + 5);
		while ($target != "" && $target != "/" && $target != "." && $target != $userDirectory) {
			// Check if the parent directory of this target location is shared
			$target = dirname($target);
			$result = $query->execute(array_merge(array($target), $userAndGroups))->fetchAll();
			if (count($result) > 0) {
				break;
			}
		}
		if (count($result) > 0) {
			// Return both the source folder and the target folder
			return array("source" => $result[0]['source'], "target" => $target);
		} else {
			return false;
		}
	}

	/**
	 * Get the source location of the item at the specified target location
	 * @param $target The target location of the item
	 * @return Source location or false if target location is not valid
	 */
	public static function getSource($target) {
		// Remove any duplicate or trailing '/'
		$target = rtrim($target, "/");
		$target = preg_replace('{(/)\1+}', "/", $target);
		$userAndGroups = self::getUserAndGroups();
		$query = OC_DB::prepare("SELECT source FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with IN(".self::prepareIN(count($userAndGroups)).") LIMIT 1");
		$result = $query->execute(array_merge(array($target), $userAndGroups))->fetchAll();
		if (count($result) > 0) {
			return $result[0]['source'];
		} else {
			$folders = self::getParentFolders($target);
			if ($folders == false) {
				return false;
			} else {
				return $folders['source'].substr($target, strlen($folders['target']));
			}
		}
	}

	/**
	 * Check if the user has write permission for the item at the specified target location
	 * @param $target The target location of the item
	 * @return True if the user has write permission or false if read only
	 */
	public static function isWriteable($target) {
		$userAndGroups = self::getUserAndGroups();
		$query = OC_DB::prepare("SELECT is_writeable FROM *PREFIX*sharing WHERE target = ? AND uid_shared_with IN(".self::prepareIN(count($userAndGroups)).") LIMIT 1");
		$result = $query->execute(array_merge(array($target), $userAndGroups))->fetchAll();
		if (count($result) > 0) {
			return $result[0]['is_writeable'];
		} else {
			// Check if the folder is writeable
			$folders = OC_SHARE::getParentFolders($target);
			$result = $query->execute(array_merge(array($target), $userAndGroups))->fetchAll();
			if (count($result) > 0) {
				return $result[0]['is_writeable'];
			} else {
				return false;
			}
		}
	}

	/**
	 * Set the source location to a new value
{'fraction_non_alphanumeric': 0.1484471683658436, 'fraction_numerical': 0.003948376451175673, 'mean_word_length': 3.992644895557517, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 70, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4205831', 'n_tokens_mistral': 5721, 'n_tokens_neox': 5080, 'n_words': 1694}