/**
  * @parra
  *
  */
 public function testPermissionMask()
 {
     $mask = new \AJXP_PermissionMask();
     $mask->updateBranch("/a1/b1/c1", new \AJXP_Permission("r"));
     echo "\n";
     $mask->toStr($mask->getTree(), 1);
     $mask->updateBranch("/a1/b1/c2", new \AJXP_Permission("rw"));
     $mask->updateBranch("/a1/b1/c3", new \AJXP_Permission());
     echo "\n";
     $mask->toStr($mask->getTree(), 1);
     $mask->updateBranch("/a1/b2", new \AJXP_Permission("rw"));
     echo "\n";
     $mask->toStr($mask->getTree(), 1);
     $mask->updateBranch("/a1/b3", new \AJXP_Permission());
     $mask->updateBranch("a2/b1", new \AJXP_Permission());
     $this->assertFalse($mask->match("/", \AJXP_Permission::WRITE));
     $this->assertTrue($mask->match("/", \AJXP_Permission::READ));
     $this->assertTrue($mask->match("/a1/b1/c1", \AJXP_Permission::READ));
     $this->assertTrue($mask->match("/a1/b1", \AJXP_Permission::READ));
     $this->assertFalse($mask->match("/a1/b1", \AJXP_Permission::WRITE));
     $this->assertFalse($mask->match("/a1/b1/c3", \AJXP_Permission::READ));
     $this->assertTrue($mask->match("/a1/b1/c1/d1/e1/f1", \AJXP_Permission::READ));
     $this->assertFalse($mask->match("/a1/b1/c1/d1/e1/f1", \AJXP_Permission::WRITE));
     // This overrides the whole /a1/b1 branch >> do we want that?
     $mask2 = new \AJXP_PermissionMask();
     $mask2->updateBranch("/a1/b1", new \AJXP_Permission("d"));
     //$mask->override($mask2);
     echo "mask 2\n";
     $mask2->toStr($mask2->getTree(), 0);
     echo "mask 1\n";
     $mask->toStr($mask->getTree(), 0);
     echo "Mask 2 override mask 1\n";
     $mask->override($mask2);
     $mask->toStr($mask->getTree(), 0);
     //$this->assertTrue($mask->match("/a1/b1", \AJXP_Permission::WRITE));
     // Todo write more tests
     $mask->updateBranch("/a1/b1/c1", new \AJXP_Permission("w"));
     //$this->assertFalse($mask->match("/a1/b1/c1", \AJXP_Permission::READ));
     $this->assertTrue($mask->match("/a1/b1/c1", \AJXP_Permission::WRITE));
     //
     //
     // $this->assertTrue($mask->match("/a1/b1/c2", \AJXP_Permission::READ));
     //$this->assertTrue($mask->match("/a1/b1/c2", \AJXP_Permission::WRITE));
     //$this->assertTrue($mask->match("/a1", \AJXP_Permission::DENY));
     // Test that a deny is cutting the sub branches
     $mask1 = new \AJXP_PermissionMask();
     $mask1->updateBranch("/a1/b1", new \AJXP_Permission("rw"));
     $mask1->updateBranch("/a1/b2", new \AJXP_Permission("rw"));
     $mask1->updateBranch("/a1/b3/c1", new \AJXP_Permission("rw"));
     $mask1->updateBranch("/a1/b3/c2", new \AJXP_Permission("rw"));
     $mask2 = new \AJXP_PermissionMask();
     $mask2->updateBranch("/a1", new \AJXP_Permission("d"));
     $result = $mask1->override($mask2);
     $this->assertFalse($result->match("/a1", \AJXP_Permission::READ));
     $this->assertFalse($result->match("/a1/b2", \AJXP_Permission::READ));
     $this->assertFalse($result->match("/a1/b3", \AJXP_Permission::READ));
     $this->assertFalse($result->match("/a1/b3/c1", \AJXP_Permission::READ));
     $this->assertFalse($result->match("/a1/any", \AJXP_Permission::READ));
 }
 /**
  * @param Array $httpVars
  * @param Repository $repository
  * @param AbstractAccessDriver $accessDriver
  * @param null $uniqueUser
  * @throws Exception
  * @return int|Repository
  */
 public function createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser = null)
 {
     // ERRORS
     // 100 : missing args
     // 101 : repository label already exists
     // 102 : user already exists
     // 103 : current user is not allowed to share
     // SUCCESS
     // 200
     if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") {
         return 100;
     }
     /*
     // FILE IS ALWAYS THE PARENT FOLDER SO WE NOW CHECK FOLDER_SHARING AT A HIGHER LEVEL
     $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
     $foldersharing = $this->getFilteredOption("ENABLE_FOLDER_SHARING", $this->repository->getId());
     $foldersharingDisabled = isset($foldersharing) && ($foldersharing === false || (is_string($foldersharing) && $foldersharing == "disable"));
     if (is_dir($this->urlBase.$file) && $foldersharingDisabled) {
         return 103;
     }
     */
     $loggedUser = AuthService::getLoggedUser();
     $actRights = $loggedUser->mergedRole->listActionsStatesFor($repository);
     if (isset($actRights["share"]) && $actRights["share"] === false) {
         return 103;
     }
     $users = array();
     $uRights = array();
     $uPasses = array();
     $groups = array();
     $uWatches = array();
     $index = 0;
     $prefix = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId());
     while (isset($httpVars["user_" . $index])) {
         $eType = $httpVars["entry_type_" . $index];
         $uWatch = false;
         $rightString = ($httpVars["right_read_" . $index] == "true" ? "r" : "") . ($httpVars["right_write_" . $index] == "true" ? "w" : "");
         if ($this->watcher !== false) {
             $uWatch = $httpVars["right_watch_" . $index] == "true" ? true : false;
         }
         if (empty($rightString)) {
             $index++;
             continue;
         }
         if ($eType == "user") {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index], AJXP_SANITIZE_EMAILCHARS);
             if (!AuthService::userExists($u) && !isset($httpVars["user_pass_" . $index])) {
                 $index++;
                 continue;
             } else {
                 if (AuthService::userExists($u, "w") && isset($httpVars["user_pass_" . $index])) {
                     throw new Exception("User {$u} already exists, please choose another name.");
                 }
             }
             if (!AuthService::userExists($u, "r") && !empty($prefix) && strpos($u, $prefix) !== 0) {
                 $u = $prefix . $u;
             }
             $users[] = $u;
         } else {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index]);
             if (strpos($u, "/AJXP_TEAM/") === 0) {
                 $confDriver = ConfService::getConfStorageImpl();
                 if (method_exists($confDriver, "teamIdToUsers")) {
                     $teamUsers = $confDriver->teamIdToUsers(str_replace("/AJXP_TEAM/", "", $u));
                     foreach ($teamUsers as $userId) {
                         $users[] = $userId;
                         $uRights[$userId] = $rightString;
                         if ($this->watcher !== false) {
                             $uWatches[$userId] = $uWatch;
                         }
                     }
                 }
                 $index++;
                 continue;
             } else {
                 $groups[] = $u;
             }
         }
         $uRights[$u] = $rightString;
         $uPasses[$u] = isset($httpVars["user_pass_" . $index]) ? $httpVars["user_pass_" . $index] : "";
         if ($this->watcher !== false) {
             $uWatches[$u] = $uWatch;
         }
         $index++;
     }
     $label = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_label"]), AJXP_SANITIZE_HTML);
     $description = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_description"]), AJXP_SANITIZE_HTML);
     if (isset($httpVars["repository_id"])) {
         $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]);
     }
     // CHECK USER & REPO DOES NOT ALREADY EXISTS
     if ($this->getFilteredOption("AVOID_SHARED_FOLDER_SAME_LABEL", $this->repository->getId()) == true) {
         $count = 0;
         $similarLabelRepos = ConfService::listRepositoriesWithCriteria(array("display" => $label), $count);
         if ($count && !isset($editingRepo)) {
             return 101;
         }
         if ($count && isset($editingRepo)) {
             foreach ($similarLabelRepos as $slr) {
                 if ($slr->getUniqueId() != $editingRepo->getUniqueId()) {
                     return 101;
                 }
             }
         }
         /*
         $repos = ConfService::getRepositoriesList();
         foreach ($repos as $obj) {
             if ($obj->getDisplay() == $label && (!isSet($editingRepo) || $editingRepo != $obj)) {
             }
         }
         */
     }
     $confDriver = ConfService::getConfStorageImpl();
     foreach ($users as $userName) {
         if (AuthService::userExists($userName)) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
             if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) {
                 return 102;
             }
         } else {
             if ($httpVars["create_guest_user"] != "true" && !ConfService::getCoreConf("USER_CREATE_USERS", "conf") || AuthService::isReservedUserId($userName)) {
                 return 102;
             }
             if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") {
                 return 100;
             }
         }
     }
     // CREATE SHARED OPTIONS
     $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository);
     $customData = array();
     foreach ($httpVars as $key => $value) {
         if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") {
             $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value;
         }
     }
     if (count($customData)) {
         $options["PLUGINS_DATA"] = $customData;
     }
     if (isset($editingRepo)) {
         $this->getShareStore()->testUserCanEditShare($editingRepo->getOwner());
         $newRepo = $editingRepo;
         $replace = false;
         if ($editingRepo->getDisplay() != $label) {
             $newRepo->setDisplay($label);
             $replace = true;
         }
         if ($editingRepo->getDescription() != $description) {
             $newRepo->setDescription($description);
             $replace = true;
         }
         if ($replace) {
             ConfService::replaceRepository($httpVars["repository_id"], $newRepo);
         }
     } else {
         if ($repository->getOption("META_SOURCES")) {
             $options["META_SOURCES"] = $repository->getOption("META_SOURCES");
             foreach ($options["META_SOURCES"] as $index => &$data) {
                 if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) {
                     $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString();
                 }
                 if ($index == "meta.syncable" && (!isset($data["REPO_SYNCABLE"]) || $data["REPO_SYNCABLE"] === true)) {
                     $data["REQUIRES_INDEXATION"] = true;
                 }
             }
         }
         $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null);
         $gPath = $loggedUser->getGroupPath();
         if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
             $newRepo->setGroupPath($gPath);
         }
         $newRepo->setDescription($description);
         $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
         if (isset($httpVars["filter_nodes"])) {
             $newRepo->setContentFilter(new ContentFilter($httpVars["filter_nodes"]));
         }
         ConfService::addRepository($newRepo);
         if (!isset($httpVars["minisite"])) {
             $this->getShareStore()->storeShare($repository->getId(), array("REPOSITORY" => $newRepo->getUniqueId(), "OWNER_ID" => $loggedUser->getId()), "repository");
         }
     }
     $sel = new UserSelection($this->repository, $httpVars);
     $file = $sel->getUniqueFile();
     $newRepoUniqueId = $newRepo->getUniqueId();
     if (isset($editingRepo)) {
         $currentRights = $this->computeSharedRepositoryAccessRights($httpVars["repository_id"], false, $this->urlBase . $file);
         $originalUsers = array_keys($currentRights["USERS"]);
         $removeUsers = array_diff($originalUsers, $users);
         if (count($removeUsers)) {
             foreach ($removeUsers as $user) {
                 if (AuthService::userExists($user)) {
                     $userObject = $confDriver->createUserObject($user);
                     $userObject->personalRole->setAcl($newRepoUniqueId, "");
                     $userObject->save("superuser");
                 }
                 if ($this->watcher !== false) {
                     $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $user, true);
                 }
             }
         }
         $originalGroups = array_keys($currentRights["GROUPS"]);
         $removeGroups = array_diff($originalGroups, $groups);
         if (count($removeGroups)) {
             foreach ($removeGroups as $groupId) {
                 $role = AuthService::getRole($groupId);
                 if ($role !== false) {
                     $role->setAcl($newRepoUniqueId, "");
                     AuthService::updateRole($role);
                 }
             }
         }
     }
     foreach ($users as $userName) {
         if (AuthService::userExists($userName, "r")) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
         } else {
             if (ConfService::getAuthDriverImpl()->getOptionAsBool("TRANSMIT_CLEAR_PASS")) {
                 $pass = $uPasses[$userName];
             } else {
                 $pass = md5($uPasses[$userName]);
             }
             if (!isset($httpVars["minisite"])) {
                 // This is an explicit user creation - check possible limits
                 AJXP_Controller::applyHook("user.before_create", array($userName, null, false, false));
                 $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, "");
                 if (!empty($limit) && intval($limit) > 0) {
                     $count = count(ConfService::getConfStorageImpl()->getUserChildren($loggedUser->getId()));
                     if ($count >= $limit) {
                         $mess = ConfService::getMessages();
                         throw new Exception($mess['483']);
                     }
                 }
             }
             AuthService::createUser($userName, $pass, false, isset($httpVars["minisite"]));
             $userObject = $confDriver->createUserObject($userName);
             $userObject->personalRole->clearAcls();
             $userObject->setParent($loggedUser->id);
             $userObject->setGroupPath($loggedUser->getGroupPath());
             $userObject->setProfile("shared");
             if (isset($httpVars["minisite"])) {
                 $mess = ConfService::getMessages();
                 $userObject->setHidden(true);
                 $userObject->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", "[" . $mess["share_center.109"] . "] " . AJXP_Utils::sanitize($newRepo->getDisplay(), AJXP_SANITIZE_EMAILCHARS));
             }
             AJXP_Controller::applyHook("user.after_create", array($userObject));
         }
         // CREATE USER WITH NEW REPO RIGHTS
         $userObject->personalRole->setAcl($newRepoUniqueId, $uRights[$userName]);
         // FORK MASK IF THERE IS ANY
         if ($file != "/" && $loggedUser->mergedRole->hasMask($repository->getId())) {
             $parentTree = $loggedUser->mergedRole->getMask($repository->getId())->getTree();
             // Try to find a branch on the current selection
             $parts = explode("/", trim($file, "/"));
             while (($next = array_shift($parts)) !== null) {
                 if (isset($parentTree[$next])) {
                     $parentTree = $parentTree[$next];
                 } else {
                     $parentTree = null;
                     break;
                 }
             }
             if ($parentTree != null) {
                 $newMask = new AJXP_PermissionMask();
                 $newMask->updateTree($parentTree);
             }
             if (isset($newMask)) {
                 $userObject->personalRole->setMask($newRepoUniqueId, $newMask);
             }
         }
         if (isset($httpVars["minisite"])) {
             if (isset($editingRepo)) {
                 try {
                     AuthService::deleteRole("AJXP_SHARED-" . $newRepoUniqueId);
                 } catch (Exception $e) {
                 }
             }
             $newRole = new AJXP_Role("AJXP_SHARED-" . $newRepoUniqueId);
             $r = AuthService::getRole("MINISITE");
             if (is_a($r, "AJXP_Role")) {
                 if ($httpVars["disable_download"]) {
                     $f = AuthService::getRole("MINISITE_NODOWNLOAD");
                     if (is_a($f, "AJXP_Role")) {
                         $r = $f->override($r);
                     }
                 }
                 $allData = $r->getDataArray();
                 $newData = $newRole->getDataArray();
                 if (isset($allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["ACTIONS"][$newRepoUniqueId] = $allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 if (isset($allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["PARAMETERS"][$newRepoUniqueId] = $allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 $newRole->bunchUpdate($newData);
                 AuthService::updateRole($newRole);
                 $userObject->addRole($newRole);
             }
         }
         $userObject->save("superuser");
         if ($this->watcher !== false) {
             // Register a watch on the current folder for shared user
             if ($uWatches[$userName]) {
                 $this->watcher->setWatchOnFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), $userName, MetaWatchRegister::$META_WATCH_USERS_CHANGE, array(AuthService::getLoggedUser()->getId()));
             } else {
                 $this->watcher->removeWatchFromFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), $userName, true);
             }
         }
     }
     if ($this->watcher !== false) {
         // Register a watch on the new repository root for current user
         if ($httpVars["self_watch_folder"] == "true") {
             $this->watcher->setWatchOnFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH);
         } else {
             $this->watcher->removeWatchFromFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), AuthService::getLoggedUser()->getId());
         }
     }
     foreach ($groups as $group) {
         $r = $uRights[$group];
         /*if($group == "AJXP_GRP_/") {
               $group = "ROOT_ROLE";
           }*/
         $grRole = AuthService::getRole($group, true);
         $grRole->setAcl($newRepoUniqueId, $r);
         AuthService::updateRole($grRole);
     }
     if (array_key_exists("minisite", $httpVars) && $httpVars["minisite"] != true) {
         AJXP_Controller::applyHook(isset($editingRepo) ? "node.share.update" : "node.share.create", array('type' => 'repository', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'new_repository' => &$newRepo));
     }
     return $newRepo;
 }
 /**
  * Copy the full tree from the one passed in parameter
  * @param AJXP_PermissionMask $mask
  * @return AJXP_PermissionMask
  */
 function copyMask($mask)
 {
     $this->updateTree($mask->getTree());
 }
 /**
  * @param AbstractAjxpUser $parentUser
  * @param string $parentRepoId
  * @param AJXP_Node $ajxpNode
  * @return AJXP_PermissionMask|null
  */
 public function forkMaskIfAny($parentUser, $parentRepoId, $ajxpNode)
 {
     $file = $ajxpNode->getPath();
     if ($file != "/" && $parentUser->mergedRole->hasMask($parentRepoId)) {
         $parentTree = $parentUser->mergedRole->getMask($parentRepoId)->getTree();
         // Try to find a branch on the current selection
         $parts = explode("/", trim($file, "/"));
         while (($next = array_shift($parts)) !== null) {
             if (is_array($parentTree) && isset($parentTree[$next])) {
                 $parentTree = $parentTree[$next];
             } else {
                 $parentTree = null;
                 break;
             }
         }
         if ($parentTree != null) {
             $newMask = new AJXP_PermissionMask();
             $newMask->updateTree($parentTree);
         }
         if (isset($newMask)) {
             return $newMask;
             //$childUser->personalRole->setMask($childRepoId, $newMask);
         }
     }
     return null;
 }