/**
  * Index page
  * 
  * @param void
  * @return null
  */
 function index()
 {
     js_assign('invoicing_precision', INVOICE_PRECISION);
     $this->wireframe->addBreadCrumb(lang('Invoicing'), assemble_url('admin'));
     $this->wireframe->addBreadCrumb(lang('Number Generator'), assemble_url('admin_invoicing_number'));
     // prepare javascript variables and counters for preview
     $pattern = Invoices::getInvoiceNumberGeneratorPattern();
     list($total_counter, $year_counter, $month_counter) = Invoices::getDateInvoiceCounters();
     $total_counter++;
     $year_counter++;
     $month_counter++;
     $variable_year = date('Y');
     $variable_month = date('n');
     $variable_month_short = date('M');
     $variable_month_long = date('F');
     js_assign('pattern_variables', array(INVOICE_VARIABLE_CURRENT_YEAR => $variable_year, INVOICE_VARIABLE_CURRENT_MONTH => $variable_month, INVOICE_VARIABLE_CURRENT_MONTH_SHORT => $variable_month_short, INVOICE_VARIABLE_CURRENT_MONTH_LONG => $variable_month_long, INVOICE_NUMBER_COUNTER_TOTAL => $total_counter, INVOICE_NUMBER_COUNTER_YEAR => $year_counter, INVOICE_NUMBER_COUNTER_MONTH => $month_counter));
     $generator_data = $this->request->post('generator');
     if (!is_foreachable($generator_data)) {
         $generator_data = array('pattern' => Invoices::getinvoiceNumberGeneratorPattern());
     }
     // if
     $this->smarty->assign(array('generator_data' => $generator_data));
     if ($this->request->isSubmitted()) {
         $errors = new ValidationErrors();
         $posted_pattern = array_var($generator_data, 'pattern', null);
         if (!trim($posted_pattern)) {
             $errors->addError(lang('Pattern is required'), 'pattern');
         }
         // if
         if (strpos($posted_pattern, INVOICE_NUMBER_COUNTER_TOTAL) === false && strpos($posted_pattern, INVOICE_NUMBER_COUNTER_YEAR) === false && strpos($posted_pattern, INVOICE_NUMBER_COUNTER_MONTH) === false) {
             $errors->addError(lang('One of invoice counters is required (:total, :year, :month)', array('total' => INVOICE_NUMBER_COUNTER_TOTAL, 'year' => INVOICE_NUMBER_COUNTER_YEAR, 'month' => INVOICE_NUMBER_COUNTER_MONTH)), 'pattern');
         }
         // if
         if ($errors->hasErrors()) {
             $this->smarty->assign(array('errors' => $errors));
         } else {
             Invoices::setInvoiceNumberGeneratorPattern($posted_pattern);
             flash_success('Pattern for invoice number generator is saved');
             $this->redirectTo('admin');
         }
         // if
     }
     // if
 }
 /**
  * Edit Project Icon
  *
  * @param void
  * @return null
  */
 function edit_icon()
 {
     if ($this->active_project->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_project->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     if (!extension_loaded('gd')) {
         $message = lang('<b>GD not Installed</b> - GD extension is not installed on your system. You will not be able to upload project icons, company logos and avatars!');
         if ($this->request->isAsyncCall()) {
             echo "<p>{$message}</p>";
             die;
         } else {
             $this->wireframe->addPageMessage($message, PAGE_MESSAGE_ERROR);
         }
         // if
     }
     // if
     if ($this->request->isSubmitted()) {
         if (!isset($_FILES['icon']) || !is_uploaded_file($_FILES['icon']['tmp_name'])) {
             $message = lang('Please select an image');
             if ($this->request->isAsyncCall()) {
                 $this->httpError(HTTP_ERR_OPERATION_FAILED, $message);
             } else {
                 flash_error($message);
                 $this->redirectToUrl($this->active_project->getEditIconUrl());
             }
             // if
         }
         // if
         if (can_resize_images()) {
             $errors = new ValidationErrors();
             do {
                 $from = WORK_PATH . '/' . make_password(10) . '_' . $_FILES['icon']['name'];
             } while (is_file($from));
             if (!move_uploaded_file($_FILES['icon']['tmp_name'], $from)) {
                 $errors->addError(lang("Can't copy image to work path"), 'icon');
             } else {
                 if (FIX_UPLOAD_PERMISSION !== false) {
                     @chmod($from, FIX_UPLOAD_PERMISSION);
                 }
                 // if
                 // small avatar
                 $to = $this->active_project->getIconPath();
                 $small = scale_image($from, $to, 16, 16, IMAGETYPE_GIF);
                 // large avatar
                 $to = $this->active_project->getIconPath(true);
                 $large = scale_image($from, $to, 40, 40, IMAGETYPE_GIF);
                 @unlink($from);
             }
             // if
             if (empty($from)) {
                 $errors->addError('Select icon', 'icon');
             }
             // if
             if ($errors->hasErrors()) {
                 $this->smarty->assign('errors', $errors);
                 $this->render();
             }
             // if
             cache_remove('project_icons');
         }
         // if
     }
     // if
 }
 /**
  * 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);
         }
     }
 }
 /**
  * Reset users password
  *
  * @param void
  * @return null
  */
 function reset_password()
 {
     $user_id = $this->request->getId('user_id');
     $code = trim($this->request->get('code'));
     if (empty($user_id) || empty($code)) {
         $this->httpError(HTTP_ERR_INVALID_PROPERTIES);
     }
     // if
     $user = null;
     if ($user_id) {
         $user = Users::findById($user_id);
     }
     // if
     // Valid user and key
     if (!instance_of($user, 'User')) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if ($user->getPasswordResetKey() != $code) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     // Not expired
     $reset_on = $user->getPasswordResetOn();
     if (instance_of($reset_on, 'DateTimeValue')) {
         if ($reset_on->getTimestamp() + 172800 < time()) {
             $this->httpError(HTTP_ERR_NOT_FOUND);
         }
         // if
     } else {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     $reset_data = $this->request->post('reset');
     $this->smarty->assign(array('reset_data' => $reset_data, 'user' => $user));
     if ($this->request->isSubmitted()) {
         $password = array_var($reset_data, 'password');
         $password_a = array_var($reset_data, 'password_a');
         $errors = new ValidationErrors();
         if (strlen_utf($password) < 3) {
             $errors->addError(lang('Minimal password length is 3 characters'), 'password');
         }
         // if
         if ($password != $password_a) {
             $errors->addError(lang('Passwords do not match'), 'passwords');
         }
         // if
         if ($errors->hasErrors()) {
             $this->smarty->assign('errors', $errors);
             $this->render();
         }
         // if
         $user->setPassword($password);
         $user->setPasswordResetKey(null);
         $user->setPasswordResetOn(null);
         $save = $user->save();
         if ($save && !is_error($save)) {
             $this->authentication->provider->logUserIn($user);
             flash_success('Welcome back :name', array('name' => $user->getDisplayName()));
             $this->redirectTo('dashboard');
         } else {
             $this->smarty->assign('errors', $errors);
         }
         // if
     }
     // if
 }
 function add_ftp_connections()
 {
     /* $cus = new CustomFields();
               //$cus->initForType("Users",2);
               $flds = $cus->getCustomFieldsByType("Users");
     
               //$cus->initForType("Project",1);
               if(is_array($flds) && count($flds) > 0)
               {
               foreach ($flds as $key => $value) {
               $settings["$key"]["label"] = "Comments";
               $settings["$key"]["is_enabled"] = "1";
               $cus->setCustomFieldsByType("Users", $settings);
     
               }
               }
               print_r($flds);
               die(); */
     //$settings["label"];
     //$cus->setCustomFieldsByType("Project", $settings);
     $repo_branches = $this->active_repository;
     $eng = $repo_branches->getEngine($this->active_project->getId());
     //print_r($eng->getBranches);
     $branches_array = $eng->getBranches();
     $repo_branches_str = implode(",", $branches_array);
     $repo_id = array_var($_GET, 'project_source_repository_id');
     //project objects id
     $repo_obj = new ProjectSourceRepository($repo_id);
     $src_repo_id = $repo_obj->getIntegerField1();
     if ($this->request->isSubmitted()) {
         // check for form submission
         $post_data = $this->request->post();
         //print_r($post_data);
         try {
             $errors = new ValidationErrors();
             $ftpdetials = $post_data["ftpdetials"];
             $fld_cnt = count($ftpdetials["ftp_domain"]);
             //print_r($ftpdetials);
             //die();
             $array_urls = array();
             for ($i = 0; $i < $fld_cnt; $i++) {
                 if ($ftpdetials["ftp_domain"][$i] == "" || $ftpdetials["ftp_port"][$i] == "" || $ftpdetials["ftp_username"][$i] == "" || $ftpdetials["ftp_password"][$i] == "" || $ftpdetials["branches"][$i] == "" || $ftpdetials["ftp_dir"][$i] == "") {
                     $errors->addError("Please fill all connection parameters.");
                 } else {
                     $arra_conn[$i] = array("ftp_domain" => $ftpdetials["ftp_domain"][$i], "ftp_port" => $ftpdetials["ftp_port"][$i], "ftp_username" => $ftpdetials["ftp_username"][$i], "ftp_password" => $ftpdetials["ftp_password"][$i], "branches" => $ftpdetials["branches"][$i], "ftp_dir" => $ftpdetials["ftp_dir"][$i]);
                 }
                 /* if(!filter_var($value, FILTER_VALIDATE_URL) && $value != "")
                    {
                    $errors->addError("$value is not a valid URL.");
                    }
                    else
                    {
                    $array_urls[] = $value;
                    } */
             }
             if ($errors->hasErrors()) {
                 throw $errors;
             }
             DB::beginWork('Add FTP Details @ ' . __CLASS__);
             if (is_array($arra_conn) && count($arra_conn) > 0) {
                 $ftp_details_exists = ProjectGitolite::ftp_connections_exists($src_repo_id);
                 if (is_array($ftp_details_exists) && $ftp_details_exists["ftp_cnt"] > 0) {
                     $ftp_table_name = TABLE_PREFIX . "rt_ftp_connections";
                     DB::execute("DELETE FROM {$ftp_table_name} where repo_fk = '" . $src_repo_id . "'");
                 }
                 for ($i = 0; $i < $fld_cnt; $i++) {
                     $ftp_details_add = ProjectGitolite::add_ftp_details($arra_conn[$i], $src_repo_id, $this->logged_user->getId());
                     if (!$ftp_details_add) {
                         $errors->addError('Problem occured while saving data, please try again.');
                         throw $errors;
                     }
                 }
                 DB::commit('FTP details Added @ ' . __CLASS__);
                 $this->response->ok();
             } else {
                 $errors->addError("Error while saving FTP details.");
                 throw $errors;
             }
         } catch (Exception $e) {
             DB::rollback('Failed to add FTP details @ ' . __CLASS__);
             $this->response->exception($e);
         }
     }
     $ftp_details_exists = ProjectGitolite::get_connection_details($src_repo_id);
     $this->response->assign(array('repo_branches_str' => $repo_branches_str, 'branches_array' => $branches_array, 'ftp_test_url' => Router::assemble('test_ftp_conn', array('project_slug' => $this->active_project->getSlug(), 'project_source_repository_id' => $repo_id)), 'form_action' => Router::assemble('add_ftp_conn', array('project_slug' => $this->active_project->getSlug(), 'project_source_repository_id' => $repo_id)), "ftp_details_exists" => $ftp_details_exists));
 }
 /**
  * Mass mailer
  *
  * @param void
  * @return null
  */
 function mass_mailer()
 {
     if (!MASS_MAILER_ENABLED) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $email_data = $this->request->post('email');
     $this->smarty->assign(array('email_data' => $email_data, 'exclude' => array($this->logged_user->getId())));
     if ($this->request->isSubmitted()) {
         $errors = new ValidationErrors();
         $subject = trim(array_var($email_data, 'subject'));
         $body = trim(array_var($email_data, 'body'));
         $recipient_ids = array_var($email_data, 'recipients');
         if (empty($subject)) {
             $errors->addError(lang('Subject is required'), 'subject');
         }
         // if
         if (empty($body)) {
             $errors->addError(lang('Body is required'), 'body');
         }
         // if
         $recipients = array();
         if (is_foreachable($recipient_ids)) {
             $recipients = Users::findByIds(array_unique($recipient_ids));
         }
         // if
         if (!is_foreachable($recipients)) {
             $errors->addError(lang('Please select recipients'), 'recipients');
         }
         // if
         if ($errors->hasErrors()) {
             $this->smarty->assign('errors', $errors);
             $this->render();
         }
         // if
         $mailer =& ApplicationMailer::mailer();
         $message = new Swift_Message($subject, $body, 'text/html', EMAIL_ENCODING, EMAIL_CHARSET);
         $recipients_list = new Swift_RecipientList();
         foreach ($recipients as $recipient) {
             $name = $recipient->getDisplayName();
             $email = $recipient->getEmail();
             if ($name == $email) {
                 $name = '';
             }
             // if
             $recipients_list->add($email, $name);
         }
         // foreach
         $name = $this->logged_user->getDisplayName();
         $email = $this->logged_user->getEmail();
         if ($name == $email) {
             $name = '';
         }
         // if
         if ($mailer->batchSend($message, $recipients_list, new Swift_Address($email, $name))) {
             flash_success('Email has been successfully sent');
         } else {
             flash_error('Failed to send email');
         }
         // if
         $this->redirectTo('admin_tools_mass_mailer');
     }
     // if
 }
 /**
  * Reschedule this milestone
  *
  * @param DateValue $new_start_on
  * @param DateValue $new_due_on
  * @param boolean $reschedule_tasks
  * @return boolean
  */
 function reschedule($new_start_on, $new_due_on, $reschedule_tasks = false)
 {
     $errors = new ValidationErrors();
     if (!instance_of($new_start_on, 'DateValue')) {
         $errors->addError(lang('Start date is not valid'), 'start_on');
     }
     // if
     if (!instance_of($new_due_on, 'DateValue')) {
         $errors->addError(lang('Due date is not valid'), 'start_on');
     }
     // if
     if ($errors->hasErrors()) {
         return $errors;
     }
     // if
     $old_start_on = $this->getStartOn();
     $old_due_on = $this->getDueOn();
     //$this->setStartOn($new_start_on);
     $this->setStartOn(empty($new_start_on->timestamp) ? '' : $new_start_on);
     $this->setDueOn(empty($new_due_on->timestamp) ? '' : $new_due_on);
     $save = $this->save();
     if ($save && !is_error($save)) {
         if ($reschedule_tasks) {
             $diff_days = (int) ceil(($new_due_on->getTimestamp() - $old_due_on->getTimestamp()) / 86400);
             if ($diff_days != 0) {
                 $project_objects_table = TABLE_PREFIX . 'project_objects';
                 $completable_types = get_completable_project_object_types();
                 $rows = db_execute_all("SELECT id FROM {$project_objects_table} WHERE milestone_id = ? AND type IN (?)", $this->getId(), $completable_types);
                 if (is_foreachable($rows)) {
                     $related_object_ids = array();
                     foreach ($rows as $row) {
                         $related_object_ids[] = (int) $row['id'];
                     }
                     // foreach
                     db_execute("UPDATE {$project_objects_table} SET due_on = DATE_ADD(due_on, INTERVAL {$diff_days} DAY) WHERE (id IN (?) OR parent_id IN (?)) AND type IN (?)", $related_object_ids, $related_object_ids, $completable_types);
                 }
                 // if
             }
             // if
         }
         // if
     }
     // if
     return $save;
 }
 /**
  * Show and process add to projects page
  *
  * @param void
  * @return null
  */
 function add_to_projects()
 {
     if ($this->active_user->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->logged_user->isProjectManager()) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $add_to_projects_data = $this->request->post('add_to_projects');
     $this->smarty->assign(array('add_to_projects_data' => $add_to_projects_data, 'exclude_project_ids' => Projects::findProjectIdsByUser($this->active_user)));
     if ($this->request->isSubmitted()) {
         $errors = new ValidationErrors();
         $projects = null;
         if (is_foreachable($add_to_projects_data['projects'])) {
             $projects = Projects::findByIds($add_to_projects_data['projects']);
         }
         // if
         if (!is_foreachable($projects)) {
             $errors->addError(lang('Please select projects'), 'projects');
         }
         // if
         if ($add_to_projects_data['role_id']) {
             $role = Roles::findById($add_to_projects_data['role_id']);
             $permissions = null;
             if (!instance_of($role, 'Role') || !($role->getType() == ROLE_TYPE_PROJECT)) {
                 $errors->addError(lang('Invalid project role'), 'project_permissions');
             }
             // if
         } else {
             $role = null;
             $permissions = array_var($add_to_projects_data, 'permissions');
         }
         // if
         if ($errors->hasErrors()) {
             $this->smarty->assign('errors', $errors);
         } else {
             $added = 0;
             foreach ($projects as $project) {
                 $add = $project->addUser($this->active_user, $role, $permissions);
                 if ($add && !is_error($add)) {
                     $added++;
                 }
                 // if
             }
             // foreach
             if ($added == 1) {
                 flash_success(':name has been added to 1 project', array('name' => $this->active_user->getDisplayName()));
             } else {
                 flash_success(':name has been added to :count projects', array('name' => $this->active_user->getDisplayName(), 'count' => $added));
             }
             // if
             $this->redirectToUrl($this->active_user->getViewUrl());
         }
         // if
     }
     // if
 }
 /**
  * Save company details info
  * 
  * @param void
  * @return void
  */
 function index()
 {
     $brand_path = PUBLIC_PATH . '/brand';
     $default_image_name = 'invoicing_logo.jpg';
     $default_full_image_name = $brand_path . '/' . $default_image_name;
     if (!folder_is_writable($brand_path)) {
         $brand_folder_writable = false;
         $this->wireframe->addPageMessage(lang('Brand folder is not writable (:brand_folder). You will not be able to upload company logo.', array('brand_folder' => $brand_path)), PAGE_MESSAGE_WARNING);
     }
     // if
     $company_data = $this->request->post('company');
     if (!is_foreachable($company_data)) {
         $company_data = array('name' => ConfigOptions::getValue('invoicing_company_name'), 'details' => ConfigOptions::getValue('invoicing_company_details'));
     }
     // if
     if ($this->request->isSubmitted()) {
         $errors = new ValidationErrors();
         db_begin_work();
         $company_name = trim(array_var($company_data, 'name'));
         $company_details = trim(array_var($company_data, 'details'));
         if (!$company_name || !$company_details) {
             if (!$company_name) {
                 $errors->addError(lang('Company name is required'), 'company_name');
             }
             // if
             if (!$company_details) {
                 $errors->addError(lang('Company details are required'), 'company_details');
             }
             // if
         } else {
             // copy and convert logo
             $logo_file = array_var($_FILES, 'company_logo', null);
             if ($logo_file['name']) {
                 $pathinfo = pathinfo($logo_file['name']);
                 do {
                     $new_filename = make_string(30) . '.' . array_var($pathinfo, 'extension');
                     $new_file_full_path = $brand_path . '/' . $new_filename;
                 } while (is_file($new_file_full_path));
                 if (move_uploaded_file($logo_file['tmp_name'], $new_file_full_path)) {
                     if (FIX_UPLOAD_PERMISSION !== false) {
                         @chmod($new_file_full_path, FIX_UPLOAD_PERMISSION);
                     }
                     // if
                     scale_image($new_file_full_path, $new_file_full_path, 600, 150, IMAGETYPE_JPEG, 100);
                 } else {
                     $errors->addError(lang('Could not upload company logo'), 'company_logo');
                 }
                 // if
             }
             // if
             $company_logo_url = get_company_invoicing_logo_url();
             db_commit();
         }
         // if
         if (!$errors->hasErrors()) {
             // set config options
             ConfigOptions::setValue('invoicing_company_name', $company_name);
             ConfigOptions::setValue('invoicing_company_details', $company_details);
             @unlink($default_full_image_name);
             rename($new_file_full_path, $default_full_image_name);
             flash_success('Company identity successfully modified');
             $this->redirectTo('admin_invoicing_company_identity');
             db_commit();
         } else {
             @unlink($new_file_full_path);
             db_rollback();
             $this->smarty->assign('errors', $errors);
         }
         // if
     }
     // if
     $company_logo_url = get_company_invoicing_logo_url();
     $this->smarty->assign(array('company_data' => $company_data, 'company_logo_url' => $company_logo_url));
 }
 /**
  * Render and process forgot password form
  *
  * @param void
  * @return null
  */
 function forgot_password()
 {
     $forgot_password_data = $this->request->post('forgot_password');
     $this->smarty->assign(array("page_title" => lang('Password recovery')));
     $this->smarty->assign('forgot_password_data', $forgot_password_data);
     if ($this->request->isSubmitted()) {
         $errors = new ValidationErrors();
         $email = trim(array_var($forgot_password_data, 'email'));
         if ($email == '') {
             $errors->addError(lang('Email address is required'), 'email');
         } else {
             if (is_valid_email($email)) {
                 $user = Users::findByEmail($email);
                 if (instance_of($user, 'User')) {
                     $user->setPasswordResetKey(make_string(13));
                     $user->setPasswordResetOn(new DateTimeValue());
                     $save = $user->save();
                     if (!$save || is_error($save)) {
                         $errors->addError('Failed to update your user password with reset password data');
                     }
                     // of
                 } else {
                     $errors->addError(lang('There is no user account that matches the e-mail address you entered'), 'email');
                 }
                 // if
             } else {
                 $errors->addError(lang('Invalid email address'), 'email');
             }
             // if
         }
         // if
         if ($errors->hasErrors()) {
             $this->smarty->assign('errors', $errors);
             $this->render();
         }
         // if
         $sent = ApplicationMailer::send(array($user), 'system/forgot_password', array('reset_url' => $user->getResetPasswordUrl()));
         $this->smarty->assign(array('success_message' => lang('We emailed reset password instructions at :email', array('email' => $user->getEmail())), 'forgot_password_data' => null));
     }
     // if
 }
 /**
  * Add new public key of user. Create .pub file gitolite admin directory
  * @return void
  */
 function add_public_keys()
 {
     $active_user = $this->active_user;
     $this->response->assign(array('form_action' => Router::assemble('add_public_keys', array('company_id' => $active_user->getCompanyId(), 'user_id' => $active_user->getId())), 'user_rmail' => $active_user->getEmail()));
     if ($this->request->isSubmitted()) {
         // check for form submission
         $post_data = $this->request->post();
         /* Check form with validation error */
         $errors = new ValidationErrors();
         try {
             $post_data['key_name'] = str_replace(array("\r\n", "\r", "\n"), "", $post_data['key_name']);
             $post_data['public_keys'] = str_replace(array("\r\n", "\r", "\n"), "", $post_data['public_keys']);
             $key_name = trim($post_data['key_name']);
             $public_keys = trim($post_data['public_keys']);
             if ($key_name == "") {
                 $errors->addError('Please enter key name', 'key_name');
             }
             if ($public_keys == "") {
                 $errors->addError('Please enter key', 'public_keys');
             }
             if (!preg_match("/^[A-Za-z0-9-]+\$/", $key_name)) {
                 $errors->addError('Please enter valid key name.', 'public_keys');
             }
             $fetch_actual_key = explode(" ", $public_keys);
             if (!($fetch_actual_key[0] == "ssh-rsa" || $fetch_actual_key[0] == "ssh-dss")) {
                 $errors->addError("Key is invalid. It must begin with 'ssh-rsa' or 'ssh-dss'. Check that you're copying the public half of the key", 'public_keys');
             } else {
                 $tempStr = base64_decode($fetch_actual_key[1], true);
                 if ($tempStr) {
                     if (strpos($tempStr, $fetch_actual_key[0]) === false) {
                         $errors->addError("Key is invalid. Check that you're copying the public half of the key", 'public_keys');
                     }
                 } else {
                     $errors->addError("Key is invalid. Check that you're copying the public half of the key", 'public_keys');
                 }
             }
             $actual_key = $fetch_actual_key[1];
             /* Check for duplications Key name and Key */
             if (!$errors->hasErrors()) {
                 $dup_cnt = GitoliteAc::check_duplication($active_user->getId(), $post_data, $actual_key);
                 if (count($dup_cnt) == 0) {
                     $errors->addError('Problem occured while saving data, please try again.', 'public_keys');
                 } elseif (count($dup_cnt) > 0) {
                     if ($dup_cnt[0]['dup_name_cnt'] > 0) {
                         $errors->addError('You have already added key with same name.');
                     }
                     if ($dup_cnt[1]['dup_name_cnt'] > 0) {
                         $errors->addError('Entered key is already added.');
                     }
                 }
             }
             // if errors found throw error exception
             if ($errors->hasErrors()) {
                 throw $errors;
             }
         } catch (Exception $e) {
             $this->response->exception($e);
         }
         // insert key details in database.
         $pub_file_name = $key_name . "-" . $this->request->get("user_id");
         try {
             DB::beginWork('Adding a new public key @ ' . __CLASS__);
             //print_r($post_data);
             $save_data = GitoliteAc::add_keys($active_user->getId(), $pub_file_name, $post_data);
             if ($save_data) {
                 $file = $pub_file_name . ".pub";
                 $admin_settings = GitoliteAdmin::get_admin_settings();
                 if (!isset($admin_settings['gitoliteadminpath'])) {
                     $this->response->exception("Gitolite admin path not set");
                     die;
                 }
                 $dirpath = $admin_settings['gitoliteadminpath'] . "gitolite-admin/keydir/";
                 $adminrepo = $admin_settings['gitoliteadminpath'] . "gitolite-admin/";
                 $path = $dirpath . $file;
                 $newfh = fopen($path, 'w+');
                 if (!is_writable($path)) {
                     $this->response->exception("Can't write to file public file");
                     die;
                 }
                 $res = fwrite($newfh, $post_data['public_keys']);
                 fclose($fh);
                 ProjectGitolite::update_repo_conf_on_public_key($active_user->getId());
                 $res = ProjectGitolite::render_conf_file();
                 /** Git Push Files * */
                 $command = "cd " . $adminrepo . " && git add * && git commit -am 'added key for user {$file}' && git push";
                 exec($command, $output, $return_var);
                 //cd /var/www/vhosts/web-vision.de/httpdocs/project/work/git/gitolite/gitolite-admin/ && git add * && git commit -am 'added key for user faishal-test-key-147.pub' && git push
                 DB::commit('Key added @ ' . __CLASS__);
                 $show_data['key_name'] = $post_data['key_name'];
                 $show_data['public_key'] = substr($post_data['public_keys'], 0, 25) . "....." . substr($post_data['public_keys'], -30);
                 $show_data['delete_url'] = $this->active_user->getViewUrl() . "/" . "delete-keys" . "/" . $save_data;
                 $this->response->respondWithData($show_data, array('as' => 'settings'));
             }
         } catch (Exception $e) {
             $this->response->exception("Can't save key this time, might be key you are adding is already added");
         }
     }
 }