/**
  * Clone remote repository independent of any project.
  * @throws ValidationErrors
  */
 function clone_source_git_repository()
 {
     $logged_user = $this->logged_user;
     $user_id = $logged_user->getId();
     $web_user = GitoliteAdmin::get_web_user();
     $webuser_pub_key = GitoliteAdmin::get_web_user_key();
     /* echo $webuser_pub_key;
        print_r($webuser_pub_key);
        //die(); */
     $this->response->assign(array('form_action' => Router::assemble('clone_source_git_repository'), 'web_user' => $web_user, 'webuser_pub_key' => $webuser_pub_key));
     if ($this->request->isSubmitted()) {
         // check for form submission
         try {
             $repository_data = $this->request->post('repository');
             $repo_name = trim($repository_data["name"]);
             $repo_url = trim($this->request->post("remoteurl"));
             $errors = new ValidationErrors();
             $post_data = $this->request->post();
             if ($repo_name == "") {
                 $errors->addError('Please enter repository name', 'repo_name');
             }
             if ($repo_url == "") {
                 $errors->addError('Please enter repository URL', 'repo_name');
             }
             $dup_cnt = ProjectGitolite::check_remote_duplication($project_id, $repository_data, $repo_url);
             if (!$errors->hasErrors()) {
                 if (!preg_match("/^[A-Za-z0-9-]+\$/", $repo_name)) {
                     $errors->addError('Please enter valid repository name.', 'repo_name');
                 }
                 /* if(preg_match('|^[a-z]?:@[a-z0-9]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url))
                    {
                    return ;
                    } */
                 if (strstr($repo_url, "http://") || strstr($repo_url, "https://")) {
                     $errors->addError('HTTP url not allowed to add remote repository', 'repo_url');
                 }
                 /* if(!strstr($repo_url,  "git://github.com/"))
                    {
                    $errors->addError('Please enter valid Git URL', 'repo_url');
                    } */
                 if (count($dup_cnt) == 0) {
                     $errors->addError('Problem occured while saving data, please try again.');
                 } elseif (is_array($dup_cnt) && count($dup_cnt) > 0) {
                     if ($dup_cnt[0]['dup_name_cnt'] > 0) {
                         $errors->addError('Repository with same name is already added');
                     }
                     if ($dup_cnt[1]['dup_name_cnt'] > 0) {
                         $errors->addError('Remote URL already cloned under this project.');
                     }
                 }
             }
             if ($errors->hasErrors()) {
                 throw $errors;
             }
             try {
                 DB::beginWork('Creating a new remote repository @ ' . __CLASS__);
                 $actual_git_repo_name = ProjectGitolite::get_actual_repo_name($repo_url);
                 if (!$actual_git_repo_name) {
                     $errors->addError('Invalid Git Repository.');
                     throw $errors;
                 }
                 // clone remote repo
                 // path with folder name which is created as same as repo name to avoid same git repo collision
                 $work_git_path = GIT_FILES_PATH . "/";
                 // path with folder name which is created after repo is cloned
                 $git_ext = strpos($actual_git_repo_name, ".git");
                 if ($git_ext) {
                     $actual_git_repo_name = substr($actual_git_repo_name, 0, -4);
                 }
                 $actual_repo_path = GIT_FILES_PATH . "/" . $repo_name . "/" . $actual_git_repo_name . "/";
                 $folder_append = "";
                 $chk_actual_name_exists_cnt = ProjectGitolite::check_actual_name_count($actual_git_repo_name);
                 if (is_array($chk_actual_name_exists_cnt) && isset($chk_actual_name_exists_cnt["actual_name_cnt"])) {
                     $cnt = $chk_actual_name_exists_cnt["actual_name_cnt"] > 0 ? $chk_actual_name_exists_cnt["actual_name_cnt"] + 1 : "";
                     $folder_append = $cnt != "" ? "-{$cnt}" : "";
                 } else {
                     $folder_append = "-1";
                 }
                 // if git repsitory name is same , we need to change the folder name while cloning the repository
                 $folder_name = $actual_git_repo_name . $folder_append;
                 $actual_repo_path = GIT_FILES_PATH . "/" . $folder_name . "/";
                 $return_status = GitoliteAdmin::clone_remote_repo($repo_url, $work_git_path, $folder_name);
                 if (!$return_status) {
                     $errors->addError('Problem occured while cloning repository.');
                     throw $errors;
                 }
                 $repository_path_url = array('repository_path_url' => $actual_repo_path);
                 //echo $work_git_path;
                 $repository_data = array_merge($repository_data, $repository_path_url);
                 $this->active_repository = new GitRepository();
                 $this->active_repository->setAttributes($repository_data);
                 $this->active_repository->setCreatedBy($this->logged_user);
                 $this->active_repository->save();
                 $repo_fk = $this->active_repository->getId();
                 if ($repo_fk) {
                     $repo_id = ProjectGitolite::add_remote_repo_details($repo_fk, $user_id, $actual_repo_path, $repo_name, $repo_url, $actual_git_repo_name);
                     if ($repo_id) {
                         DB::commit('Repository created @ ' . __CLASS__);
                         //$out = $this->update_remote_repo($repo_fk);
                         $out = GitoliteAdmin::update_remote_repo($repo_fk);
                         $this->response->respondWithData($this->active_repository, array('as' => 'repository'));
                     } else {
                         @ProjectGitolite::remove_directory($work_git_path);
                         $errors->addError('Error while saving repository.');
                         throw $errors;
                     }
                 } else {
                     @ProjectGitolite::remove_directory($work_git_path);
                     $errors->addError('Error while saving repository.');
                     throw $errors;
                 }
             } catch (Exception $e) {
                 DB::rollback('Failed to create a repository @ ' . __CLASS__);
                 $this->response->exception($e);
             }
         } catch (Exception $e) {
             DB::rollback('Failed to create a repository @ ' . __CLASS__);
             $this->response->exception($e);
         }
     }
 }
 /**
  * Get gitolite setup script path.
  *
  * @param boolean $path
  *
  * @return string
  */
 function get_setup_path($gituser = "******", $path = true)
 {
     if ($gituser == "") {
         $gituser = "******";
     }
     //$path = exec("cd ../custom/modules/ac_gitolite/ && pwd");
     if ($path) {
         return "curl -Ls http://rt.cx/gitlab | sudo bash -s <span class='gitolite-user'>" . $gituser . "</span> " . ' ' . GitoliteAdmin::get_web_user() . ' ' . GitoliteAdmin::get_server_name() . ' ' . substr(LICENSE_KEY, 0, 5);
     } else {
         return "curl -Ls http://rt.cx/gitlab | sudo bash -s " . $gituser . ' ' . GitoliteAdmin::get_web_user() . ' ' . GitoliteAdmin::get_server_name() . ' ' . substr(LICENSE_KEY, 0, 5);
     }
 }
 /**
  *  Add new gitolite repository
  * @throws ValidationErrors
  */
 function add_remote_git_repo()
 {
     $project = $this->active_project;
     $project_id = $project->getId();
     $logged_user = $this->logged_user;
     $user_id = $logged_user->getId();
     $web_user = GitoliteAdmin::get_web_user();
     $webuser_pub_key = GitoliteAdmin::get_web_user_key();
     /* echo $webuser_pub_key;
        print_r($webuser_pub_key);
        //die(); */
     $this->response->assign(array('form_action' => Router::assemble('add_remote_git', array('project_slug' => $project->getSlug())), 'web_user' => $web_user, 'webuser_pub_key' => $webuser_pub_key));
     if ($this->request->isSubmitted()) {
         // check for form submission
         try {
             $repository_data = $this->request->post('repository');
             $repo_name = trim($repository_data["name"]);
             $repo_url = trim($this->request->post("remoteurl"));
             $errors = new ValidationErrors();
             $post_data = $this->request->post();
             if ($repo_name == "") {
                 $errors->addError('Please enter repository name', 'repo_name');
             }
             if ($repo_url == "") {
                 $errors->addError('Please enter repository URL', 'repo_name');
             }
             $dup_cnt = ProjectGitolite::check_remote_duplication($project_id, $repository_data, $repo_url);
             /* print_r($dup_cnt);
                die(); */
             if (!$errors->hasErrors()) {
                 if (!preg_match("/^[A-Za-z0-9-]+\$/", $repo_name)) {
                     $errors->addError('Please enter valid repository name.', 'repo_name');
                 }
                 /* if(preg_match('|^[a-z]?:@[a-z0-9]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url))
                    {
                    return ;
                    } */
                 if (strstr($repo_url, "http://") || strstr($repo_url, "https://")) {
                     $errors->addError('HTTP url not allowed to add remote repository', 'repo_url');
                 }
                 /* if(!strstr($repo_url,  "git://github.com/"))
                    {
                    $errors->addError('Please enter valid Git URL', 'repo_url');
                    } */
                 if (count($dup_cnt) == 0) {
                     $errors->addError('Problem occured while saving data, please try again.');
                 } elseif (is_array($dup_cnt) && count($dup_cnt) > 0) {
                     if ($dup_cnt[0]['dup_name_cnt'] > 0) {
                         $errors->addError('Repository with same name is already added');
                     }
                     if ($dup_cnt[1]['dup_name_cnt'] > 0) {
                         $errors->addError('Remote URL already cloned under this project.');
                     }
                 }
             }
             if ($errors->hasErrors()) {
                 throw $errors;
             }
             try {
                 DB::beginWork('Creating a new remote repository @ ' . __CLASS__);
                 $actual_git_repo_name = ProjectGitolite::get_actual_repo_name($repo_url);
                 if (!$actual_git_repo_name) {
                     $errors->addError('Invalid Git Repository.');
                     throw $errors;
                 }
                 // clone remote repo
                 /* echo $actual_git_repo_name;
                    die(); */
                 // path with folder name which is created as same as repo name to avoid same git repo collision
                 $work_git_path = GIT_FILES_PATH . "/";
                 // path with folder name which is created after repo is cloned
                 //
                 //                        /echo $actual_git_repo_name;
                 $git_ext = strpos($actual_git_repo_name, ".git");
                 if ($git_ext) {
                     $actual_git_repo_name = substr($actual_git_repo_name, 0, -4);
                 }
                 $folder_append = "";
                 $chk_actual_name_exists_cnt = ProjectGitolite::check_actual_name_count($actual_git_repo_name);
                 if (is_array($chk_actual_name_exists_cnt) && isset($chk_actual_name_exists_cnt["actual_name_cnt"])) {
                     $cnt = $chk_actual_name_exists_cnt["actual_name_cnt"] > 0 ? $chk_actual_name_exists_cnt["actual_name_cnt"] + 1 : "";
                     $folder_append = $cnt != "" ? "-{$cnt}" : "";
                 } else {
                     $folder_append = "-1";
                 }
                 // if git repsitory name is same , we need to change the folder name while cloning the repository
                 $folder_name = $actual_git_repo_name . $folder_append;
                 $actual_repo_path = GIT_FILES_PATH . "/" . $folder_name . "/";
                 //echo $actual_git_repo_name;
                 $return_status = GitoliteAdmin::clone_remote_repo($repo_url, $work_git_path, $folder_name, $error_message);
                 if (!$return_status) {
                     //$errors->addError('Problem occured while cloning repository.' . $error_message);
                     for ($rCount = 1; count($error_message) > $rCount; $rCount++) {
                         $errors->addError($error_message[$rCount]);
                     }
                     throw $errors;
                 }
                 $repository_path_url = array('repository_path_url' => $actual_repo_path);
                 //echo $work_git_path;
                 $repository_data = array_merge($repository_data, $repository_path_url);
                 /* print_r($repository_data);
                    die(); */
                 $this->active_repository = new GitRepository();
                 $this->active_repository->setAttributes($repository_data);
                 $this->active_repository->setCreatedBy($this->logged_user);
                 $this->active_repository->save();
                 $repo_fk = $this->active_repository->getId();
                 if ($repo_fk) {
                     $clone_url = $repo_url;
                     $body = $clone_url;
                     $this->project_object_repository->setName($this->active_repository->getName());
                     $this->project_object_repository->setBody($body);
                     $this->project_object_repository->setParentId($this->active_repository->getId());
                     $this->project_object_repository->setVisibility($repository_data['visibility']);
                     $this->project_object_repository->setProjectId($this->active_project->getId());
                     $this->project_object_repository->setCreatedBy($this->logged_user);
                     $this->project_object_repository->setState(STATE_VISIBLE);
                     $this->project_object_repository->save();
                     $repo_id = ProjectGitolite::add_remote_repo_details($repo_fk, $user_id, $actual_repo_path, $repo_name, $repo_url, $actual_git_repo_name);
                     if ($repo_id) {
                         ini_set('max_execution_time', 500);
                         $pull_all_branches = ProjectGitolite::pull_branches($actual_repo_path);
                         if (!$pull_all_branches) {
                             @ProjectGitolite::remove_directory($work_git_path);
                             $errors->addError('Error while saving branches.');
                             throw $errors;
                         }
                         //$out = $this->update_remote_repo($repo_fk);
                         /* $branches = $get_branches = exec("cd $actual_repo_path && git branch -a",$output);
                                                       if(is_foreachable($output))
                                                       {
                                                       $array_unique_banch = array();
                                                       foreach ($output as $key => $value)
                                                       {
                                                       $branch_name = substr(strrchr($value, "/"), 1);
                         
                                                       if(!in_array($branch_name, $array_unique_banch))
                                                       {
                                                       exec("cd $actual_repo_path && git checkout -b $branch_name origin/$branch_name && git pull");
                                                       }
                                                       $array_unique_banch[] = $branch_name;
                                                       }
                                                       } */
                         DB::commit('Repository created @ ' . __CLASS__);
                         $out = GitoliteAdmin::update_remote_repo($repo_fk);
                         $this->response->respondWithData($this->project_object_repository);
                     } else {
                         @ProjectGitolite::remove_directory($actual_repo_path);
                         $errors->addError('Error while saving repository');
                         throw $errors;
                     }
                 } else {
                     @ProjectGitolite::remove_directory($actual_repo_path);
                     $errors->addError('Error while saving repository.');
                     throw $errors;
                 }
             } catch (Exception $e) {
                 DB::rollback('Failed to create a repository @ ' . __CLASS__);
                 $this->response->exception($e);
             }
             //$this->response->respondWithData($this->project_object_repository);
             //repo path
             //$repo_path = $sever_user_path."/repositories/".$repository_data['name'].".git";
         } catch (Exception $e) {
             DB::rollback('Failed to create a repository @ ' . __CLASS__);
             $this->response->exception($e);
         }
     }
 }
 /**
  * Parse keydir folder and fetch all keys added on gitolite setup
  * @return array keys
  */
 function parse_user_keys()
 {
     $array_pub_keys = array();
     $web_user = GitoliteAdmin::get_web_user();
     $key_dir_path = GIT_FILES_PATH . "/gitolite/gitolite-admin/keydir/";
     chdir($key_dir_path);
     foreach (glob('*.pub') as $i => $key) {
         //echo $key."<br>";
         $key = preg_replace('/(|@[^.]*)\\.pub$/', '', $key);
         $key_dir_file_path = $key_dir_path . $key . ".pub";
         if (file_exists($key_dir_file_path)) {
             $key_content = file_get_contents($key_dir_file_path);
             $fetch_actual_key = explode(" ", $key_content);
             $actual_key = is_array($fetch_actual_key) && count($fetch_actual_key) > 0 ? $fetch_actual_key[1] : $fetch_actual_key[0];
             $key_exists_details = GitoliteAc::check_key_map_exists($actual_key);
         }
         if (!in_array($key, $array_pub_keys) && $key != "" && !is_array($key_exists_details) && $key != $web_user) {
             $array_pub_keys[] = $key;
         } elseif (is_array($key_exists_details) && count($key_exists_details) > 0) {
             $array_pub_keys[$key_exists_details["key_name"]] = self::$ac_users[$key_exists_details["user_id"]];
         }
     }
     return $array_pub_keys;
 }