/**
  * render_conf_file
  * Write repository and access levels in conf file
  *
  * @return boolean|string
  */
 function render_conf_file()
 {
     $settings = GitoliteAdmin::get_admin_settings();
     $conf_path = $settings['gitoliteadminpath'] . "/gitolite-admin/conf/gitolite.conf";
     $webuser = exec("whoami");
     $conf_file = $conf_path;
     // create access array
     $access_array = array(GITOLITE_READACCESS => 'R', GITOLITE_MANAGEACCESS => 'RW+');
     $fh = fopen($conf_file, 'w');
     if (file_exists($conf_path) && $fh) {
         $repo_table_name = TABLE_PREFIX . 'rt_gitolite_repomaster';
         $access_table_name = TABLE_PREFIX . 'rt_gitolite_access_master';
         $public_key_table_name = TABLE_PREFIX . 'rt_gitolite_user_public_keys';
         $source_table_name = TABLE_PREFIX . 'source_repositories';
         $admin_settings_table_name = TABLE_PREFIX . 'rt_config_settings';
         /** Defalut access to gitolite admin * */
         $get_git_admins = DB::execute("SELECT * FROM " . $admin_settings_table_name);
         fwrite($fh, "repo " . "@all" . "\n");
         fwrite($fh, "RW+" . "\t" . "=" . "\t" . $webuser . "\n");
         fwrite($fh, "repo " . "gitolite-admin" . "\n");
         fwrite($fh, "RW+" . "\t" . "=" . "\t" . $webuser . "\n");
         if ($get_git_admins) {
             $admins_rec = $get_git_admins[0];
             if (is_array($admins_rec)) {
                 $admins = @unserialize($admins_rec['gitoliteadmins']);
                 if ($admins !== false || $admins === 'b:0;') {
                     $admins_array = $admins;
                 } else {
                     $admins_array = array();
                 }
                 if (is_foreachable($admins_array)) {
                     foreach ($admins_array as $keyadmin => $valadmin) {
                         $pubkeys = DB::execute("SELECT * FROM " . $public_key_table_name . " where user_id = '" . $valadmin . "' and is_deleted = '0'");
                         if ($pubkeys) {
                             foreach ($pubkeys as $rowkeys) {
                                 if ($rowkeys['pub_file_name'] != "") {
                                     fwrite($fh, $access_array[GITOLITE_MANAGEACCESS] . "\t" . "=" . "\t" . $rowkeys['pub_file_name'] . "\n");
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $sql = "SELECT a.* ,b.id FROM " . $repo_table_name . " a JOIN " . $source_table_name . " b ON a.repo_fk = b.id  where gitolite_config is null limit 1";
         $result_gitconfig_empty = DB::execute($sql);
         $file_name = "/tmp/gitolite_" . microtime();
         $file_name = str_replace(" ", "-", $file_name);
         $file_name = str_replace(".", "_", $file_name);
         $mysqlACLFlag = true;
         if (!$result_gitconfig_empty) {
             $sql = "SELECT CONCAT('repo ', repo_name),gitolite_config INTO OUTFILE '{$file_name}'\n                        FIELDS ESCAPED BY '' TERMINATED BY '\n' OPTIONALLY ENCLOSED BY ''\n                        LINES TERMINATED BY '\n'  \n                        FROM {$repo_table_name} ";
             try {
                 $result = DB::execute($sql);
             } catch (Exception $e) {
                 $mysqlACLFlag = false;
             }
             if ($mysqlACLFlag && file_exists($file_name)) {
                 $conf_content = file_get_contents($file_name);
                 fwrite($fh, $conf_content);
                 fclose($fh);
                 @unlink($file_name);
                 return true;
             } else {
                 $sql = "SELECT CONCAT('repo ', repo_name) as 'repo_name',gitolite_config FROM {$repo_table_name}";
                 $result = DB::execute($sql);
                 if ($result) {
                     foreach ($result as $row) {
                         $conf_content = "\n" . $row['repo_name'] . "\n" . $row['gitolite_config'];
                         fwrite($fh, $conf_content);
                     }
                 }
                 fclose($fh);
                 return true;
             }
         }
         $result = DB::execute("SELECT a.* ,b.id FROM " . $repo_table_name . " a JOIN " . $source_table_name . " b ON a.repo_fk = b.id");
         try {
             if ($result) {
                 //fetch all gitolite repositories
                 foreach ($result as $row) {
                     $prjobj = new Project($row['project_id']);
                     // get project users
                     $prjusers = $prjobj->users()->getIdNameMap();
                     // get permissions
                     $permissions = DB::execute("SELECT * FROM " . $access_table_name . " where repo_id = '" . $row['repo_id'] . "'");
                     if ($permissions) {
                         // get repository permissions
                         $perm_row = $permissions["0"];
                         $permissions = @unserialize($perm_row['permissions']);
                         if ($permissions !== false || $permissions === 'b:0;') {
                             $permissions_array = $permissions;
                         } else {
                             $permissions_array = array();
                         }
                     } else {
                         $permissions_array = array();
                     }
                     // write repository name in conf file
                     fwrite($fh, "repo " . $row['repo_name'] . "\n");
                     $str_repo_conf = "";
                     if (is_foreachable($prjusers)) {
                         foreach ($prjusers as $keyusers => $valueusers) {
                             $pubkeys = DB::execute("SELECT * FROM " . $public_key_table_name . " where user_id = '" . $keyusers . "' and is_deleted = '0'");
                             if (is_array($pubkeys)) {
                                 foreach ($pubkeys as $rowkeys) {
                                     $access = isset($access_array[$permissions_array[$keyusers]]) ? $access_array[$permissions_array[$keyusers]] : "";
                                     if ($access != "" && $rowkeys['pub_file_name'] != "") {
                                         fwrite($fh, $access . "\t" . "=" . "\t" . $rowkeys['pub_file_name'] . "\n");
                                         $str_repo_conf .= "\t" . $access . "\t" . "=" . "\t" . $rowkeys['pub_file_name'] . "\n";
                                     }
                                 }
                                 // while
                             }
                             // if public keys added
                         }
                         // foreach
                     }
                     // if project user exists
                     $sql = "update " . $repo_table_name . " set gitolite_config='" . $str_repo_conf . "' where repo_id =" . $row['repo_id'];
                     DB::execute($sql);
                 }
                 // while
             }
             // repo exists
         } catch (Exception $e) {
             echo $e;
         }
         return true;
     } else {
         return "can't write file";
     }
 }
 function add_source_gitolite_repository()
 {
     $is_gitolite = GitoliteAdmin::is_gitolite();
     $logged_user = $this->logged_user;
     $user_id = $logged_user->getId();
     $no_key_warning = FALSE;
     $view_url = "";
     if (AngieApplication::isModuleLoaded("source") && $this->getControllerName() == 'ac_gitolite_source') {
         $do_continue = true;
     }
     if ($do_continue) {
         // Add Administrator , Leaders and Project Manager in allowed people list
         //$role = new Roles();
         //$admins = $role::findAdministrators();
         $usrobj = new Users();
         $users_details = $usrobj->findAdministrators();
         if (is_foreachable($users_details)) {
             foreach ($users_details as $key => $value) {
                 // check key exists
                 $user_keys = GitoliteAc::check_keys_added($value->getId());
                 if ($user_keys > 0) {
                     $user_detail_permissions[$value->getId()] = array('readaccess' => 0, 'writeaccess' => 0, 'writeaccessplus' => 1, 'user_keys' => $user_keys);
                     $allowed_users[$value->getId()] = $value->getDisplayName();
                 }
             }
         }
         $this->response->assign(array('curr_users' => $allowed_users, 'user_detail_permissions' => $user_detail_permissions, 'form_action' => Router::assemble('add_source_gitolite_repository'), 'noaccess' => GITOLITE_NOACCESS, 'readaccess' => GITOLITE_READACCESS, 'manageaccess' => GITOLITE_MANAGEACCESS, 'is_gitolite' => $is_gitolite, 'no_key_warning' => $no_key_warning, 'view_url' => $view_url));
     } else {
         $this->response->assign(array('add_error' => TRUE));
     }
     if ($this->request->isSubmitted()) {
         // check for form submission
         try {
             /* Check form with validation error */
             $repository_data = $this->request->post('repository');
             if (!isset($repository_data["repo_notification_setting"])) {
                 $repository_data["repo_notification_setting"] = "no";
             }
             $errors = new ValidationErrors();
             $post_data = $this->request->post();
             $settings = GitoliteAdmin::get_admin_settings();
             $is_remote = !isset($settings["git_server_location"]) || $settings["git_server_location"] != "remote" ? false : true;
             if (!$is_remote) {
                 $sever_user_path = GitoliteAdmin::get_server_user_path();
                 if (!$sever_user_path) {
                     $errors->addError('Repository path on server invalid');
                 }
             }
             $repo_name = trim($repository_data['name']);
             $access = $post_data['access'];
             if ($repo_name == "") {
                 $errors->addError('Please enter repository name', 'repo_name');
             }
             if (!is_array($access) && count($access) == 0) {
                 $errors->addError('Select access levels for user', 'access');
             }
             /* Check for duplications repository name and Key */
             if (!$errors->hasErrors()) {
                 if (!preg_match("/^[A-Za-z0-9-]+\$/", $repo_name)) {
                     $errors->addError('Please enter valid repository name.', 'repo_name');
                 }
                 $dup_cnt = ProjectGitolite::check_source_git_dup($repository_data);
                 if (count($dup_cnt) == 0) {
                     $errors->addError('Problem occured while saving data, please try again.');
                 } elseif (count($dup_cnt) > 0) {
                     if ($dup_cnt[0]['dup_name_cnt'] > 0) {
                         $errors->addError('Repository name already used');
                     }
                 }
             }
             // if errors found throw error exception
             if ($errors->hasErrors()) {
                 throw $errors;
             }
             /** save gitolite details in database * */
             // save reponame
             try {
                 DB::beginWork('Creating a new repository @ ' . __CLASS__);
                 /**
                  * if gitolite is setup on remote, change repo path
                  */
                 if (!$is_remote) {
                     $repo_path = $sever_user_path . "/repositories/" . $repository_data['name'] . ".git";
                 } elseif ($is_remote) {
                     $repo_path = GIT_FILES_PATH . "/" . $repo_name;
                 }
                 if (is_array($post_data)) {
                     $repository_path_url = array('repository_path_url' => $repo_path);
                 }
                 $repository_data = array_merge($repository_data, $repository_path_url);
                 $clone_url = $settings['git_clone_url'] . $repo_name;
                 $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_repo_details($repo_fk, 0, $user_id, $repo_path, $repository_data, $clone_url);
                     if ($repo_id) {
                         $add_access = ProjectGitolite::add_access_levels($repo_id, serialize($post_data['access']), $user_id, 1);
                         if ($add_access) {
                             $res = ProjectGitolite::render_conf_file();
                             $dir = $settings['gitoliteadminpath'] . "gitolite-admin";
                             $command = "cd " . $dir . " && git add * && git commit -am 'render conf file' && git push  || echo 'Not found'";
                             exec($command, $output, $return_var);
                             if ($is_remote) {
                                 $git_server = $settings['gitoliteuser'] . "@" . $settings['gitoliteserveradd'];
                                 //$command = "cd ".$settings['gitoliteadminpath']." && git clone ".$git_server.":".$repo_name;
                                 chdir(GIT_FILES_PATH);
                                 $command = "git clone " . $git_server . ":" . $repo_name;
                                 exec($command, $output, $return_var);
                             }
                         } else {
                             $errors->addError('Error while saving access levels.');
                             throw $errors;
                         }
                     } else {
                         $errors->addError('Error while saving repository.');
                         throw $errors;
                     }
                 } else {
                     $errors->addError('Error while saving repository.');
                     throw $errors;
                 }
                 DB::commit('Repository created @ ' . __CLASS__);
                 $this->response->respondWithData($this->active_repository, array('as' => 'repository'));
             } 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);
         }
     }
 }
 /**
  * Render conf file once mapping is done
  * @return string message
  */
 function render_after_clone_conf()
 {
     $res = ProjectGitolite::render_conf_file();
     $settings = GitoliteAdmin::get_admin_settings();
     $dir = $settings['gitoliteadminpath'] . "gitolite-admin";
     $command = "cd " . $dir . " && git add * && git commit -am 'render conf file' && git push  || echo 'Not found'";
     exec($command, $output, $return_var);
     //print_r($output);
     die("ok");
 }
 /**
  * Check repository access and add repository help on history page
  * @return void
  */
 function history()
 {
     //ProjectGitolite::delete_commits($this->active_repository->getId());
     /*         * $this->wireframe->actions->add('branches', lang('Branches'), '#', array(
               'subitems' => self::ac_gitolite_get_branches(),
               'icon' => AngieApplication::getPreferedInterface() == AngieApplication::INTERFACE_DEFAULT ? AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE) : AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE, AngieApplication::INTERFACE_PHONE),
               'id'=> 'branches_list'
               ));
     
               $this->wireframe->actions->add('tags', lang('Tags'), '#', array(
               'subitems' => self::ac_gitolite_get_tags(),
               'icon' => AngieApplication::getPreferedInterface() == AngieApplication::INTERFACE_DEFAULT ? AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE) : AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE, AngieApplication::INTERFACE_PHONE),
               'id'=> 'tags_list'
               ));
              */
     $repo_id = array_var($_GET, 'project_source_repository_id');
     //project objects id
     $project = $this->active_project;
     $repository = $this->active_repository;
     $repo_details = ProjectGitolite::get_repo_details($repo_id);
     if (is_array($repo_details) && count($repo_details) > 0) {
         //if ( $this->logged_user->isAdministrator () || $this->logged_user->isProjectManager () || $project->isLeader ( $this->logged_user ) ) {
         $this->wireframe->actions->add('manage_access', lang('Manage Access'), Router::assemble('edit_git_repository', array('project_slug' => $project->getSlug(), 'project_source_repository_id' => $repo_id)), array('id' => 'update_access_levels', 'onclick' => new FlyoutFormCallback("access_updated", array('width' => 'narrow')), 'icon' => AngieApplication::getPreferedInterface() == AngieApplication::INTERFACE_DEFAULT ? AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE) : AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE, AngieApplication::INTERFACE_PHONE)));
         //} //if
     }
     /*  Commented FTP section
          $this->wireframe->actions->add('add_ftp', 'FTP Connectiions', Router::assemble('add_ftp_conn',array('project_slug' => $this->active_project->getSlug(),
          'project_source_repository_id' => $repo_id)), array(
          'onclick' => new FlyoutFormCallback('ftps_updated', array('width' => '1100')),
          'icon' => AngieApplication::getPreferedInterface() == AngieApplication::INTERFACE_DEFAULT ? AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE) : AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE, AngieApplication::INTERFACE_PHONE))
          );
         */
     $this->wireframe->actions->add('add_hooks', 'Hooks', Router::assemble('add_hooks_git', array('project_slug' => $this->active_project->getSlug(), 'project_source_repository_id' => $repo_id)), array('onclick' => new FlyoutFormCallback('urls_updated', array('width' => '900')), 'icon' => AngieApplication::getPreferedInterface() == AngieApplication::INTERFACE_DEFAULT ? AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE) : AngieApplication::getImageUrl('icons/16X16-git.png', AC_GITOLITE_MODULE, AngieApplication::INTERFACE_PHONE)));
     $repo_path = $repository->getRepositoryPathUrl();
     $repo_fk = $repository->getId();
     $chk_gitolite = ProjectGitolite::is_gitolite_repo($repo_fk);
     if (is_array($chk_gitolite) && sizeof($chk_gitolite) > 0 && $chk_gitolite['chk_gitolite'] > 0) {
         $settings = GitoliteAdmin::get_admin_settings();
         $clone_url = $settings['git_clone_url'] . $this->active_repository->getName() . ".git";
         $permissions = @unserialize($chk_gitolite['permissions']);
         if ($permissions !== false || $permissions === 'b:0;') {
             $permissions_array = $permissions;
         } else {
             $permissions_array = array();
         }
         if (array_key_exists($this->logged_user->getId(), $permissions_array) && $permissions_array[$this->logged_user->getId()] > 1 || $this->logged_user->isAdministrator() || $this->logged_user->isProjectManager() || $this->active_project->isLeader($this->logged_user)) {
             $body = "<h2>Git Global Setup</h2>";
             $body .= "<code>";
             $body .= "git config --global user.name '" . $this->logged_user->getDisplayName() . "'" . "<br>";
             $body .= "git config --global user.email '" . $this->logged_user->getEmail() . "'" . "<br>";
             $body .= "</code>";
             $body .= "<h2>Create Repository:</h2>";
             $body .= "<code>";
             $body .= "mkdir " . $this->active_repository->getName() . "<br>";
             $body .= "cd " . $this->active_repository->getName() . "<br>";
             $body .= "git init" . "<br>";
             $body .= "touch README" . "<br>";
             $body .= "git add README" . "<br>";
             $body .= "git commit -m 'first commit'" . "<br>";
             $body .= "git remote add origin " . $clone_url . "<br>";
             $body .= "git push -u origin master" . "<br>";
             $body .= "</code>";
             $body .= "<h2>Existing Git Repo?</h2>";
             $body .= "<code>";
             $body .= "cd existing_git_repo" . "<br>";
             $body .= "git remote add origin " . $clone_url . "<br>";
             $body .= "git push -u origin master";
             $body .= "</code>";
             $body_text = $body;
         } else {
             $this->response->forbidden();
         }
     } else {
         $body_text = $repository->getFieldValue("repository_path_url");
     }
     parent::history();
     $this->response->assign(array('body_text' => $body_text, 'repo_path' => $repo_path, 'clone_url' => $clone_url));
 }
 /**
  * Remove a specific publick key
  * @return void
  */
 function remove_key()
 {
     $get_data = $this->request->get();
     if (isset($get_data['key_id'])) {
         $key_id = $get_data['key_id'];
         $filename = GitoliteAc::get_filename($key_id);
         if ($filename != "") {
             $delete_keys = GitoliteAc::remove_keys($key_id);
             if (!$delete_keys) {
                 throw new Exception("Can't delete key");
             } else {
                 $settings = GitoliteAdmin::get_admin_settings();
                 $dirpath = $settings['gitoliteadminpath'] . "gitolite-admin/keydir/";
                 $path = $dirpath . $filename . ".pub";
                 @unlink($path);
                 $active_user = $this->active_user;
                 ProjectGitolite::update_repo_conf_on_public_key($active_user->getId());
                 $command = "cd " . $dirpath . " && git add * && git commit -am 'deleted key {$filename}.pub' && git push  || echo 'Not found'";
                 exec($command, $output);
             }
         }
     }
     echo '<script type="text/javascript">window.location.href = "' . $this->active_user->getViewUrl() . '"</script>';
     die(0);
 }