public function componentLeftmenu() { $i18n = TBGContext::getI18n(); $config_sections = array(); if (TBGContext::getUser()->getScope()->getID() == 1) { $config_sections[TBGSettings::CONFIGURATION_SECTION_SCOPES] = array('route' => 'configure_scopes', 'description' => $i18n->__('Scopes'), 'icon' => 'scopes', 'module' => 'core'); } $config_sections[TBGSettings::CONFIGURATION_SECTION_SETTINGS] = array('route' => 'configure_settings', 'description' => $i18n->__('Settings'), 'icon' => 'general', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_PERMISSIONS] = array('route' => 'configure_permissions', 'description' => $i18n->__('Permissions'), 'icon' => 'permissions', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_AUTHENTICATION] = array('route' => 'configure_authentication', 'description' => $i18n->__('Authentication'), 'icon' => 'authentication', 'module' => 'core'); if (TBGContext::getScope()->isUploadsEnabled()) { $config_sections[TBGSettings::CONFIGURATION_SECTION_UPLOADS] = array('route' => 'configure_files', 'description' => $i18n->__('Uploads & attachments'), 'icon' => 'files', 'module' => 'core'); } $config_sections[TBGSettings::CONFIGURATION_SECTION_IMPORT] = array('route' => 'configure_import', 'description' => $i18n->__('Import data'), 'icon' => 'import', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_PROJECTS] = array('route' => 'configure_projects', 'description' => $i18n->__('Projects'), 'icon' => 'projects', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_ISSUETYPES] = array('icon' => 'issuetypes', 'description' => $i18n->__('Issue types'), 'route' => 'configure_issuetypes', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_ISSUEFIELDS] = array('icon' => 'resolutiontypes', 'description' => $i18n->__('Issue fields'), 'route' => 'configure_issuefields', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_WORKFLOW] = array('icon' => 'workflow', 'description' => $i18n->__('Workflow'), 'route' => 'configure_workflow', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_USERS] = array('route' => 'configure_users', 'description' => $i18n->__('Users, teams, clients & groups'), 'icon' => 'users', 'module' => 'core'); $config_sections[TBGSettings::CONFIGURATION_SECTION_MODULES][] = array('route' => 'configure_modules', 'description' => $i18n->__('Modules'), 'icon' => 'modules', 'module' => 'core'); foreach (TBGContext::getModules() as $module) { if ($module->hasConfigSettings() && $module->isEnabled()) { $config_sections[TBGSettings::CONFIGURATION_SECTION_MODULES][] = array('route' => array('configure_module', array('config_module' => $module->getName())), 'description' => $module->getConfigTitle(), 'icon' => $module->getName(), 'module' => $module->getName()); } } $breadcrumblinks = array(); foreach ($config_sections as $section) { if (is_array($section) && !array_key_exists('route', $section)) { foreach ($section as $subsection) { $url = is_array($subsection['route']) ? make_url($subsection['route'][0], $subsection['route'][1]) : make_url($subsection['route']); $breadcrumblinks[] = array('url' => $url, 'title' => $subsection['description']); } } else { $breadcrumblinks[] = array('url' => make_url($section['route']), 'title' => $section['description']); } } $this->breadcrumblinks = $breadcrumblinks; $this->config_sections = $config_sections; if ($this->selected_section == TBGSettings::CONFIGURATION_SECTION_MODULES) { if (TBGContext::getRouting()->getCurrentRouteName() == 'configure_modules') { $this->selected_subsection = 'core'; } else { $this->selected_subsection = TBGContext::getRequest()->getParameter('config_module'); } } }
/** * Log a message to the logger * * @param string $message The message to log * @param string $category[optional] The message category (default "main") * @param integer $level[optional] The loglevel */ public static function log($message, $category = 'main', $level = 1) { if (!self::$_logging_enabled) { return false; } if (self::$_loglevel > $level) { return false; } if (self::$_cli_log_to_screen_in_debug_mode && TBGContext::isCLI() && TBGContext::isDebugMode() && class_exists('TBGCliCommand')) { TBGCliCommand::cli_echo(mb_strtoupper(self::getLevelName($level)), 'white', 'bold'); TBGCliCommand::cli_echo(" [{$category}] ", 'green', 'bold'); TBGCliCommand::cli_echo("{$message}\n"); } if (self::$_logonajaxcalls || TBGContext::getRequest()->isAjaxCall()) { if (self::$_logfile !== null) { file_put_contents(self::$_logfile, mb_strtoupper(self::getLevelName($level)) . " [{$category}] {$message}\n", FILE_APPEND); } $time_msg = TBGContext::isDebugMode() ? ($load_time = TBGContext::getLoadtime()) >= 1 ? round($load_time, 2) . ' seconds' : round($load_time * 1000, 3) . ' ms' : ''; self::$_entries[] = array('category' => $category, 'time' => $time_msg, 'message' => $message, 'level' => $level); self::$_categorized_entries[$category][] = array('time' => $time_msg, 'message' => $message, 'level' => $level); } }
public function componentLeftmenu() { $config_sections = TBGSettings::getConfigSections(TBGContext::getI18n()); $breadcrumblinks = array(); foreach ($config_sections as $key => $sections) { foreach ($sections as $section) { if ($key == TBGSettings::CONFIGURATION_SECTION_MODULES) { $url = is_array($section['route']) ? make_url($section['route'][0], $section['route'][1]) : make_url($section['route']); $breadcrumblinks[] = array('url' => $url, 'title' => $section['description']); } else { $breadcrumblinks[] = array('url' => make_url($section['route']), 'title' => $section['description']); } } } $this->breadcrumblinks = $breadcrumblinks; $this->config_sections = $config_sections; if ($this->selected_section == TBGSettings::CONFIGURATION_SECTION_MODULES) { if (TBGContext::getRouting()->getCurrentRouteName() == 'configure_modules') { $this->selected_subsection = 'core'; } else { $this->selected_subsection = TBGContext::getRequest()->getParameter('config_module'); } } }
public function processIncomingEmailCommand($content, TBGIssue $issue, TBGUser $user) { if (!$issue->isWorkflowTransitionsAvailable()) { return false; } $lines = preg_split("/(\r?\n)/", $content); $first_line = array_shift($lines); $commands = explode(" ", trim($first_line)); $command = array_shift($commands); foreach ($issue->getAvailableWorkflowTransitions() as $transition) { if (strpos(str_replace(array(' ', '/'), array('', ''), mb_strtolower($transition->getName())), str_replace(array(' ', '/'), array('', ''), mb_strtolower($command))) !== false) { foreach ($commands as $single_command) { if (mb_strpos($single_command, '=')) { list($key, $val) = explode('=', $single_command); switch ($key) { case 'resolution': if (($resolution = TBGResolution::getResolutionByKeyish($val)) instanceof TBGResolution) { TBGContext::getRequest()->setParameter('resolution_id', $resolution->getID()); } break; case 'status': if (($status = TBGStatus::getStatusByKeyish($val)) instanceof TBGStatus) { TBGContext::getRequest()->setParameter('status_id', $status->getID()); } break; } } } TBGContext::getRequest()->setParameter('comment_body', join("\n", $lines)); return $transition->transitionIssueToOutgoingStepWithoutRequest($issue); } } }
public function runSaveAuthentication(TBGRequest $request) { if (TBGContext::getRequest()->isMethod(TBGRequest::POST)) { $this->forward403unless($this->access_level == TBGSettings::ACCESS_FULL); $settings = array(TBGSettings::SETTING_AUTH_BACKEND, 'register_message', 'forgot_message', 'changepw_message', 'changedetails_message'); foreach ($settings as $setting) { if (TBGContext::getRequest()->getParameter($setting) !== null) { $value = TBGContext::getRequest()->getParameter($setting); TBGSettings::saveSetting($setting, $value); } } } }
public function componentSpecialWhatLinksHere() { $this->linked_article_name = TBGContext::getRequest()->getParameter('linked_article_name'); $this->articles = TBGArticlesTable::getTable()->getAllByLinksToArticleName($this->linked_article_name); }
public function runAddCommitGitorious(TBGRequest $request) { if (!TBGContext::getModule('vcs_integration')->isUsingHTTPMethod()) { echo 'Error: This access method has been disallowed'; exit; } $passkey = TBGContext::getRequest()->getParameter('passkey'); if ($passkey != TBGContext::getModule('vcs_integration')->getSetting('vcs_passkey')) { echo 'Error: Invalid passkey'; exit; } $project = TBGContext::getRequest()->getParameter('project'); $data = TBGContext::getRequest()->getParameter('payload', null, false); if (empty($data) || $data == null) { die('Error: Invalid data'); } if (!function_exists('json_decode')) { die('Error: Gitorious support requires either PHP 5.2.0 or later, or the json PECL module version 1.2.0 or later for prior versions of PHP'); } $entries = json_decode($data); echo $project; $previous = $entries->before; // Parse each commit individually foreach (array_reverse($entries->commits) as $commit) { $email = $commit->author->email; $author = $commit->author->name; $new_rev = $commit->id; $old_rev = $previous; $commit_msg = $commit->message; $time = strtotime($commit->timestamp); //$f_issues = array_unique($f_issues[3]); //$file_lines = preg_split('/[\n\r]+/', $changed); //$files = array(); echo TBGContext::getModule('vcs_integration')->addNewCommit($project, $commit_msg, $old_rev, $previous, $time, "", $author); $previous = $new_rev; exit; } }
/** * Returns the logged in user, or default user if not logged in * * @param TBGRequest $request * @param TBGAction $action * * @return TBGUser */ public static function loginCheck(TBGRequest $request, TBGAction $action) { try { $authentication_method = $action->getAuthenticationMethodForAction(TBGContext::getRouting()->getCurrentRouteAction()); $user = null; $external = false; switch ($authentication_method) { case TBGAction::AUTHENTICATION_METHOD_ELEVATED: case TBGAction::AUTHENTICATION_METHOD_CORE: $username = $request['tbg3_username']; $password = $request['tbg3_password']; if ($authentication_method == TBGAction::AUTHENTICATION_METHOD_ELEVATED) { $elevated_password = $request['tbg3_elevated_password']; } $raw = true; // If no username and password specified, check if we have a session that exists already if ($username === null && $password === null) { if (TBGContext::getRequest()->hasCookie('tbg3_username') && TBGContext::getRequest()->hasCookie('tbg3_password')) { $username = TBGContext::getRequest()->getCookie('tbg3_username'); $password = TBGContext::getRequest()->getCookie('tbg3_password'); $user = TBGUsersTable::getTable()->getByUsername($username); if ($authentication_method == TBGAction::AUTHENTICATION_METHOD_ELEVATED) { $elevated_password = TBGContext::getRequest()->getCookie('tbg3_elevated_password'); if ($user instanceof TBGUser && !$user->hasPasswordHash($password)) { $user = null; } else { if ($user instanceof TBGUser && !$user->hasPasswordHash($elevated_password)) { TBGContext::setUser($user); TBGContext::getRouting()->setCurrentRouteName('elevated_login_page'); throw new TBGElevatedLoginException('reenter'); } } } else { if ($user instanceof TBGUser && !$user->hasPasswordHash($password)) { $user = null; } } $raw = false; if (!$user instanceof TBGUser) { TBGContext::logout(); throw new Exception('No such login'); } } } // If we have authentication details, validate them if (TBGSettings::isUsingExternalAuthenticationBackend() && $username !== null && $password !== null) { $external = true; TBGLogging::log('Authenticating with backend: ' . TBGSettings::getAuthenticationBackend(), 'auth', TBGLogging::LEVEL_INFO); try { $mod = TBGContext::getModule(TBGSettings::getAuthenticationBackend()); if ($mod->getType() !== TBGModule::MODULE_AUTH) { TBGLogging::log('Auth module is not the right type', 'auth', TBGLogging::LEVEL_FATAL); } if (TBGContext::getRequest()->hasCookie('tbg3_username') && TBGContext::getRequest()->hasCookie('tbg3_password')) { $user = $mod->verifyLogin($username, $password); } else { $user = $mod->doLogin($username, $password); } if (!$user instanceof TBGUser) { // Invalid TBGContext::logout(); throw new Exception('No such login'); //TBGContext::getResponse()->headerRedirect(TBGContext::getRouting()->generate('login')); } } catch (Exception $e) { throw $e; } } elseif (TBGSettings::isUsingExternalAuthenticationBackend()) { $external = true; TBGLogging::log('Authenticating without credentials with backend: ' . TBGSettings::getAuthenticationBackend(), 'auth', TBGLogging::LEVEL_INFO); try { $mod = TBGContext::getModule(TBGSettings::getAuthenticationBackend()); if ($mod->getType() !== TBGModule::MODULE_AUTH) { TBGLogging::log('Auth module is not the right type', 'auth', TBGLogging::LEVEL_FATAL); } $user = $mod->doAutoLogin(); if ($user == false) { // Invalid TBGContext::logout(); throw new Exception('No such login'); //TBGContext::getResponse()->headerRedirect(TBGContext::getRouting()->generate('login')); } } catch (Exception $e) { throw $e; } } elseif ($username !== null && $password !== null && !$user instanceof TBGUser) { $external = false; TBGLogging::log('Using internal authentication', 'auth', TBGLogging::LEVEL_INFO); $user = TBGUsersTable::getTable()->getByUsername($username); if (!$user->hasPassword($password)) { $user = null; } if (!$user instanceof TBGUser) { TBGContext::logout(); } } break; case TBGAction::AUTHENTICATION_METHOD_DUMMY: $user = TBGUsersTable::getTable()->getByUserID(TBGSettings::getDefaultUserID()); break; case TBGAction::AUTHENTICATION_METHOD_CLI: $user = TBGUsersTable::getTable()->getByUsername(TBGContext::getCurrentCLIusername()); break; case TBGAction::AUTHENTICATION_METHOD_RSS_KEY: $user = TBGUsersTable::getTable()->getByRssKey($request['rsskey']); break; case TBGAction::AUTHENTICATION_METHOD_APPLICATION_PASSWORD: $user = TBGUsersTable::getTable()->getByUsername($request['api_username']); if (!$user->authenticateApplicationPassword($request['api_token'])) { $user = null; } break; default: if (!TBGSettings::isLoginRequired()) { $user = TBGUsersTable::getTable()->getByUserID(TBGSettings::getDefaultUserID()); } } if ($user instanceof TBGUser) { if (!$user->isActivated()) { throw new Exception('This account has not been activated yet'); } elseif (!$user->isEnabled()) { throw new Exception('This account has been suspended'); } elseif (!$user->isConfirmedMemberOfScope(TBGContext::getScope())) { if (!TBGSettings::isRegistrationAllowed()) { throw new Exception('This account does not have access to this scope'); } } if ($external == false && $authentication_method == TBGAction::AUTHENTICATION_METHOD_CORE) { $password = $user->getHashPassword(); if (!$request->hasCookie('tbg3_username')) { if ($request->getParameter('tbg3_rememberme')) { TBGContext::getResponse()->setCookie('tbg3_username', $user->getUsername()); TBGContext::getResponse()->setCookie('tbg3_password', $user->getPassword()); } else { TBGContext::getResponse()->setSessionCookie('tbg3_username', $user->getUsername()); TBGContext::getResponse()->setSessionCookie('tbg3_password', $user->getPassword()); } } } } elseif (TBGSettings::isLoginRequired()) { throw new Exception('Login required'); } else { throw new Exception('No such login'); } } catch (Exception $e) { throw $e; } return $user; }
public static function getPredefinedFilters($type, TBGSavedSearch $search) { $filters = array(); switch ($type) { case TBGContext::PREDEFINED_SEARCH_PROJECT_OPEN_ISSUES: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); break; case TBGContext::PREDEFINED_SEARCH_PROJECT_OPEN_ISSUES_INCLUDING_SUBPROJECTS: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); $filters['subprojects'] = self::createFilter('subprojects', array('operator' => '=', 'value' => 'all'), $search); break; case TBGContext::PREDEFINED_SEARCH_PROJECT_CLOSED_ISSUES: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'closed'), $search); $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); break; case TBGContext::PREDEFINED_SEARCH_PROJECT_CLOSED_ISSUES_INCLUDING_SUBPROJECTS: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'closed'), $search); $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); $filters['subprojects'] = self::createFilter('subprojects', array('operator' => '=', 'value' => 'all'), $search); break; case TBGContext::PREDEFINED_SEARCH_PROJECT_WISHLIST: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); $types = array(); foreach (TBGContext::getCurrentProject()->getIssuetypeScheme()->getIssuetypes() as $issuetype) { if (in_array($issuetype->getIcon(), array('feature_request', 'enhancement'))) { $types[] = $issuetype->getID(); } } if (count($types)) { $filters['issuetype'] = self::createFilter('issuetype', array('operator' => '=', 'value' => join(',', $types))); } break; case TBGContext::PREDEFINED_SEARCH_PROJECT_REPORTED_LAST_NUMBEROF_TIMEUNITS: $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); $units = TBGContext::getRequest()->getParameter('units'); switch (TBGContext::getRequest()->getParameter('time_unit')) { case 'seconds': $time_unit = NOW - $units; break; case 'minutes': $time_unit = NOW - 60 * $units; break; case 'hours': $time_unit = NOW - 60 * 60 * $units; break; case 'days': $time_unit = NOW - 86400 * $units; break; case 'weeks': $time_unit = NOW - 86400 * 7 * $units; break; case 'months': $time_unit = NOW - 86400 * 30 * $units; break; case 'years': $time_unit = NOW - 86400 * 365 * $units; break; default: $time_unit = NOW - 86400 * 30; } $filters['posted'] = self::createFilter('posted', array('operator' => '>=', 'value' => $time_unit), $search); break; case TBGContext::PREDEFINED_SEARCH_PROJECT_REPORTED_THIS_MONTH: $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); $filters['posted'] = self::createFilter('posted', array('operator' => '>=', 'value' => mktime(date('H'), date('i'), date('s'), date('n'), 1)), $search); break; case TBGContext::PREDEFINED_SEARCH_PROJECT_MILESTONE_TODO: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); $filters['milestone'] = self::createFilter('milestone', array('operator' => '!=', 'value' => 0), $search); break; case TBGContext::PREDEFINED_SEARCH_PROJECT_MOST_VOTED: $filters['project_id'] = self::createFilter('project_id', array('operator' => '=', 'value' => TBGContext::getCurrentProject()->getID()), $search); $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $filters['votes_total'] = self::createFilter('votes_total', array('operator' => '>=', 'value' => '1'), $search); break; case TBGContext::PREDEFINED_SEARCH_MY_REPORTED_ISSUES: $filters['posted_by'] = self::createFilter('posted_by', array('operator' => '=', 'value' => TBGContext::getUser()->getID()), $search); break; case TBGContext::PREDEFINED_SEARCH_MY_ASSIGNED_OPEN_ISSUES: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $filters['assignee_user'] = self::createFilter('assignee_user', array('operator' => '=', 'value' => TBGContext::getUser()->getID()), $search); break; case TBGContext::PREDEFINED_SEARCH_TEAM_ASSIGNED_OPEN_ISSUES: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $teams = array(); foreach (TBGContext::getUser()->getTeams() as $team_id => $team) { $teams[] = $team_id; } $filters['assignee_team'] = self::createFilter('assignee_team', array('operator' => '=', 'value' => join(',', $teams)), $search); break; case TBGContext::PREDEFINED_SEARCH_MY_OWNED_OPEN_ISSUES: $filters['status'] = self::createFilter('status', array('operator' => '=', 'value' => 'open'), $search); $filters['owner_user'] = self::createFilter('owner_user', array('operator' => '=', 'value' => TBGContext::getUser()->getID()), $search); break; } return $filters; }
public function runUpload(TBGRequest $request) { $apc_exists = TBGRequest::CanGetUploadStatus(); if ($apc_exists && !$request['APC_UPLOAD_PROGRESS']) { $request->setParameter('APC_UPLOAD_PROGRESS', $request['upload_id']); } $this->getResponse()->setDecoration(TBGResponse::DECORATE_NONE); $canupload = false; if ($request['mode'] == 'issue') { $issue = TBGContext::factory()->TBGIssue($request['issue_id']); $canupload = (bool) ($issue instanceof TBGIssue && $issue->hasAccess() && $issue->canAttachFiles()); } elseif ($request['mode'] == 'article') { $article = TBGWikiArticle::getByName($request['article_name']); $canupload = (bool) ($article instanceof TBGWikiArticle && $article->canEdit()); } else { $event = TBGEvent::createNew('core', 'upload', $request['mode']); $event->triggerUntilProcessed(); $canupload = $event->isProcessed() ? (bool) $event->getReturnValue() : true; } if ($canupload) { try { $file = TBGContext::getRequest()->handleUpload('uploader_file'); if ($file instanceof TBGFile) { switch ($request['mode']) { case 'issue': if (!$issue instanceof TBGIssue) { break; } $issue->attachFile($file, $request->getRawParameter('comment'), $request['uploader_file_description']); $issue->save(); break; case 'article': if (!$article instanceof TBGWikiArticle) { break; } $article->attachFile($file); break; } if ($apc_exists) { return $this->renderText('ok'); } } $this->error = TBGContext::getI18n()->__('An unhandled error occured with the upload'); } catch (Exception $e) { $this->getResponse()->setHttpStatus(400); $this->error = $e->getMessage(); } } else { // $this->getResponse()->setHttpStatus(401); $this->error = TBGContext::getI18n()->__('You are not allowed to attach files here'); } if (!$apc_exists) { switch ($request['mode']) { case 'issue': if (!$issue instanceof TBGIssue) { break; } $this->forward(TBGContext::getRouting()->generate('viewissue', array('project_key' => $issue->getProject()->getKey(), 'issue_no' => $issue->getFormattedIssueNo()))); break; case 'article': if (!$article instanceof TBGWikiArticle) { break; } $this->forward(TBGContext::getRouting()->generate('publish_article_attachments', array('article_name' => $article->getName()))); break; } } TBGLogging::log('marking upload ' . $request['APC_UPLOAD_PROGRESS'] . ' as completed with error ' . $this->error); $request->markUploadAsFinishedWithError($request['APC_UPLOAD_PROGRESS'], $this->error); return $this->renderText($request['APC_UPLOAD_PROGRESS'] . ': ' . $this->error); }
public static function processCommit(TBGProject $project, $commit_msg, $old_rev, $new_rev, $date = null, $changed, $author, $branch = null) { $output = ''; TBGContext::setCurrentProject($project); if ($project->isArchived()) { return; } try { TBGContext::getI18n(); } catch (Exception $e) { TBGContext::reinitializeI18n(null); } // Is VCS Integration enabled? if (TBGSettings::get('vcs_mode_' . $project->getID(), 'vcs_integration') == TBGVCSIntegration::MODE_DISABLED) { $output .= '[VCS ' . $project->getKey() . '] This project does not use VCS Integration' . "\n"; return $output; } // Parse the commit message, and obtain the issues and transitions for issues. $parsed_commit = TBGIssue::getIssuesFromTextByRegex($commit_msg); $issues = $parsed_commit["issues"]; $transitions = $parsed_commit["transitions"]; // If no issues exist, we may not be able to continue // if (count($issues) == 0) // { // $output .= '[VCS '.$project->getKey().'] This project only accepts commits which affect issues' . "\n"; // return $output; // } // Build list of affected files $file_lines = preg_split('/[\\n\\r]+/', $changed); $files = array(); foreach ($file_lines as $aline) { $action = mb_substr($aline, 0, 1); if ($action == "A" || $action == "U" || $action == "D" || $action == "M") { $theline = trim(mb_substr($aline, 1)); $files[] = array($action, $theline); } } // Find author of commit, fallback is guest /* * Some VCSes use a different format of storing the committer's name. Systems like bzr, git and hg use the format * Joe Bloggs <*****@*****.**>, instead of a classic username. Therefore a user will be found via 4 queries: * a) First we extract the email if there is one, and find a user with that email * b) If one is not found - or if no email was specified, then instead test against the real name (using the name part if there was an email) * c) the username or full name is checked against the friendly name field * d) and if we still havent found one, then we check against the username * e) and if we STILL havent found one, we use the guest user */ if (preg_match("/(?<=<)(.*)(?=>)/", $author, $matches)) { $email = $matches[0]; // a) $user = TBGUsersTable::getTable()->getByEmail($email); if (!$user instanceof TBGUser) { // Not found by email preg_match("/(?<=^)(.*)(?= <)/", $author, $matches); $author = $matches[0]; } } // b) if (!$user instanceof TBGUser) { $user = TBGUsersTable::getTable()->getByRealname($author); } // c) if (!$user instanceof TBGUser) { $user = TBGUsersTable::getTable()->getByBuddyname($author); } // d) if (!$user instanceof TBGUser) { $user = TBGUsersTable::getTable()->getByUsername($author); } // e) if (!$user instanceof TBGUser) { $user = TBGSettings::getDefaultUser(); } TBGContext::setUser($user); TBGSettings::forceSettingsReload(); TBGContext::cacheAllPermissions(); $output .= '[VCS ' . $project->getKey() . '] Commit to be logged by user ' . $user->getName() . "\n"; if ($date == null) { $date = NOW; } // Create the commit data $commit = new TBGVCSIntegrationCommit(); $commit->setAuthor($user); $commit->setDate($date); $commit->setLog($commit_msg); $commit->setPreviousRevision($old_rev); $commit->setRevision($new_rev); $commit->setProject($project); if ($branch !== null) { $data = 'branch:' . $branch; $commit->setMiscData($data); } $commit->save(); $output .= '[VCS ' . $project->getKey() . '] Commit logged with revision ' . $commit->getRevision() . "\n"; // Iterate over affected issues and update them. foreach ($issues as $issue) { $inst = new TBGVCSIntegrationIssueLink(); $inst->setIssue($issue); $inst->setCommit($commit); $inst->save(); // Process all commit-message transitions for an issue. foreach ($transitions[$issue->getFormattedIssueNo()] as $transition) { if (TBGSettings::get('vcs_workflow_' . $project->getID(), 'vcs_integration') == TBGVCSIntegration::WORKFLOW_ENABLED) { TBGContext::setUser($user); TBGSettings::forceSettingsReload(); TBGContext::cacheAllPermissions(); if ($issue->isWorkflowTransitionsAvailable()) { // Go through the list of possible transitions for an issue. Only // process transitions that are applicable to issue's workflow. foreach ($issue->getAvailableWorkflowTransitions() as $possible_transition) { if (mb_strtolower($possible_transition->getName()) == mb_strtolower($transition[0])) { $output .= '[VCS ' . $project->getKey() . '] Running transition ' . $transition[0] . ' on issue ' . $issue->getFormattedIssueNo() . "\n"; // String representation of parameters. Used for log message. $parameters_string = ""; // Iterate over the list of this transition's parameters, and // set them. foreach ($transition[1] as $parameter => $value) { $parameters_string .= "{$parameter}={$value} "; switch ($parameter) { case 'resolution': if (($resolution = TBGResolution::getResolutionByKeyish($value)) instanceof TBGResolution) { TBGContext::getRequest()->setParameter('resolution_id', $resolution->getID()); } break; case 'status': if (($status = TBGStatus::getStatusByKeyish($value)) instanceof TBGStatus) { TBGContext::getRequest()->setParameter('status_id', $status->getID()); } break; } } // Run the transition. $possible_transition->transitionIssueToOutgoingStepWithoutRequest($issue); // Log an informative message about the transition. $output .= '[VCS ' . $project->getKey() . '] Ran transition ' . $possible_transition->getName() . ' with parameters \'' . $parameters_string . '\' on issue ' . $issue->getFormattedIssueNo() . "\n"; } } } } } $issue->addSystemComment(TBGContext::getI18n()->__('This issue has been updated with the latest changes from the code repository.<source>%commit_msg</source>', array('%commit_msg' => $commit_msg)), $user->getID()); $output .= '[VCS ' . $project->getKey() . '] Updated issue ' . $issue->getFormattedIssueNo() . "\n"; } // Create file links foreach ($files as $afile) { // index 0 is action, index 1 is file $inst = new TBGVCSIntegrationFile(); $inst->setAction($afile[0]); $inst->setFile($afile[1]); $inst->setCommit($commit); $inst->save(); $output .= '[VCS ' . $project->getKey() . '] Added with action ' . $afile[0] . ' file ' . $afile[1] . "\n"; } TBGEvent::createNew('vcs_integration', 'new_commit')->trigger(array('commit' => $commit)); return $output; }
/** * Performs an action * * @param string $module Name of the action module * @param string $method Name of the action method to run */ public static function performAction($action, $module, $method) { // Set content variable $content = null; // Set the template to be used when rendering the html (or other) output $templatePath = THEBUGGENIE_MODULES_PATH . $module . DS . 'templates' . DS; $actionClassName = get_class($action); $actionToRunName = 'run' . ucfirst($method); $preActionToRunName = 'pre' . ucfirst($method); // Set up the response object, responsible for controlling any output self::getResponse()->setPage(self::getRouting()->getCurrentRouteName()); self::getResponse()->setTemplate(mb_strtolower($method) . '.' . TBGContext::getRequest()->getRequestedFormat() . '.php'); self::getResponse()->setupResponseContentType(self::getRequest()->getRequestedFormat()); self::setCurrentProject(null); // Run the specified action method set if it exists if (method_exists($action, $actionToRunName)) { // Turning on output buffering ob_start('mb_output_handler'); ob_implicit_flush(0); if (self::getRouting()->isCurrentRouteCSRFenabled()) { // If the csrf check fails, don't proceed if (!self::checkCSRFtoken(true)) { return true; } } if (self::$_debug_mode) { $time = explode(' ', microtime()); $pretime = $time[1] + $time[0]; } if ($content === null) { TBGLogging::log('Running main pre-execute action'); // Running any overridden preExecute() method defined for that module // or the default empty one provided by TBGAction if ($pre_action_retval = $action->preExecute(self::getRequest(), $method)) { $content = ob_get_clean(); TBGLogging::log('preexecute method returned something, skipping further action'); if (self::$_debug_mode) { $visited_templatename = "{$actionClassName}::preExecute()"; } } } if ($content === null) { $action_retval = null; if (self::getResponse()->getHttpStatus() == 200) { // Checking for and running action-specific preExecute() function if // it exists if (method_exists($action, $preActionToRunName)) { TBGLogging::log('Running custom pre-execute action'); $action->{$preActionToRunName}(self::getRequest(), $method); } // Running main route action TBGLogging::log('Running route action ' . $actionToRunName . '()'); if (self::$_debug_mode) { $time = explode(' ', microtime()); $action_pretime = $time[1] + $time[0]; } $action_retval = $action->{$actionToRunName}(self::getRequest()); if (self::$_debug_mode) { $time = explode(' ', microtime()); $action_posttime = $time[1] + $time[0]; TBGContext::visitPartial("{$actionClassName}::{$actionToRunName}", $action_posttime - $action_pretime); } } if (self::getResponse()->getHttpStatus() == 200 && $action_retval) { // If the action returns *any* output, we're done, and collect the // output to a variable to be outputted in context later $content = ob_get_clean(); TBGLogging::log('...done'); } elseif (!$action_retval) { // If the action doesn't return any output (which it usually doesn't) // we continue on to rendering the template file for that specific action TBGLogging::log('...done'); TBGLogging::log('Displaying template'); // Check to see if we have a translated version of the template if ($method != 'notFound' && (!self::isReadySetup() || ($templateName = self::getI18n()->hasTranslatedTemplate(self::getResponse()->getTemplate())) === false)) { // Check to see if any modules provide an alternate template $event = TBGEvent::createNew('core', "TBGContext::performAction::renderTemplate")->triggerUntilProcessed(array('class' => $actionClassName, 'action' => $actionToRunName)); if ($event->isProcessed()) { $templateName = $event->getReturnValue(); } // Check to see if the template has been changed, and whether it's in a // different module, specified by "module/templatename" if (mb_strpos(self::getResponse()->getTemplate(), '/')) { $newPath = explode('/', self::getResponse()->getTemplate()); $templateName = THEBUGGENIE_MODULES_PATH . $newPath[0] . DS . 'templates' . DS . $newPath[1] . '.' . TBGContext::getRequest()->getRequestedFormat() . '.php'; } else { $templateName = $templatePath . self::getResponse()->getTemplate(); } } // Check to see if the template exists and throw an exception otherwise if (!file_exists($templateName)) { TBGLogging::log('The template file for the ' . $method . ' action ("' . self::getResponse()->getTemplate() . '") does not exist', 'core', TBGLogging::LEVEL_FATAL); throw new TBGTemplateNotFoundException('The template file for the ' . $method . ' action ("' . self::getResponse()->getTemplate() . '") does not exist'); } self::loadLibrary('common'); // Present template for current action TBGActionComponent::presentTemplate($templateName, $action->getParameterHolder()); $content = ob_get_clean(); TBGLogging::log('...completed'); } } elseif (self::$_debug_mode) { $time = explode(' ', microtime()); $posttime = $time[1] + $time[0]; TBGContext::visitPartial($visited_templatename, $posttime - $pretime); } if (!isset($tbg_response)) { /** * @global TBGRequest The request object */ $tbg_request = self::getRequest(); /** * @global TBGUser The user object */ $tbg_user = self::getUser(); /** * @global TBGResponse The action object */ $tbg_response = self::getResponse(); // Load the "ui" library, since this is used a lot self::loadLibrary('ui'); } self::loadLibrary('common'); TBGLogging::log('rendering final content'); if (TBGSettings::isMaintenanceModeEnabled() && !mb_strstr(self::getRouting()->getCurrentRouteName(), 'configure')) { if (!file_exists(THEBUGGENIE_CORE_PATH . 'templates/offline.inc.php')) { throw new TBGTemplateNotFoundException('Can not find offline mode template'); } ob_start('mb_output_handler'); ob_implicit_flush(0); require THEBUGGENIE_CORE_PATH . 'templates/offline.inc.php'; $content = ob_get_clean(); } // Render output in correct order self::getResponse()->renderHeaders(); if (self::getResponse()->getDecoration() == TBGResponse::DECORATE_DEFAULT && !self::getRequest()->isAjaxCall()) { ob_start('mb_output_handler'); ob_implicit_flush(0); require THEBUGGENIE_CORE_PATH . 'templates/layout.php'; ob_flush(); } else { // Render header template if any, and store the output in a variable if (!self::getRequest()->isAjaxCall() && self::getResponse()->doDecorateHeader()) { TBGLogging::log('decorating with header'); if (!file_exists(self::getResponse()->getHeaderDecoration())) { throw new TBGTemplateNotFoundException('Can not find header decoration: ' . self::getResponse()->getHeaderDecoration()); } require self::getResponse()->getHeaderDecoration(); } echo $content; TBGLogging::log('...done (rendering content)'); // Render footer template if any if (!self::getRequest()->isAjaxCall() && self::getResponse()->doDecorateFooter()) { TBGLogging::log('decorating with footer'); if (!file_exists(self::getResponse()->getFooterDecoration())) { throw new TBGTemplateNotFoundException('Can not find footer decoration: ' . self::getResponse()->getFooterDecoration()); } require self::getResponse()->getFooterDecoration(); } TBGLogging::log('...done'); } TBGLogging::log('done (rendering final content)'); if (self::isReadySetup() && self::isDebugMode()) { self::getI18n()->addMissingStringsToStringsFile(); } return true; } else { TBGLogging::log("Cannot find the method {$actionToRunName}() in class {$actionClassName}.", 'core', TBGLogging::LEVEL_FATAL); throw new TBGActionNotFoundException("Cannot find the method {$actionToRunName}() in class {$actionClassName}. Make sure the method exists."); } }
public function componentLogin() { $this->selected_tab = isset($this->section) ? $this->section : 'login'; $this->options = $this->getParameterHolder(); try { $this->article = null; $this->article = PublishFactory::articleName('LoginIntro'); } catch (Exception $e) { } if (TBGContext::getRequest()->getParameter('redirect') == true) { $this->mandatory = true; } }
<div class="main_header"> <?php echo $searchtitle; ?> <span class="faded_out"><?php echo __('%number_of% issue(s)', array('%number_of%' => (int) $resultcount)); ?> </span> <div class="search_export_links"> <?php if (TBGContext::getRequest()->hasParameter('quicksearch')) { $searchfor = TBGContext::getRequest()->getParameter('searchfor'); $project_key = TBGContext::getCurrentProject() instanceof TBGProject ? TBGContext::getCurrentProject()->getKey() : 0; echo __('Export results as:') . ' <a href="' . make_url('project_issues', array('project_key' => $project_key, 'quicksearch' => 'true', 'format' => 'csv')) . '?searchfor=' . $searchfor . '"> ' . image_tag('icon_csv.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' CSV</a> <a href="' . make_url('project_issues', array('project_key' => $project_key, 'quicksearch' => 'true', 'format' => 'rss')) . '?searchfor=' . $searchfor . '"> ' . image_tag('icon_rss.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' RSS</a>'; } elseif (TBGContext::getRequest()->hasParameter('predefined_search')) { $searchno = TBGContext::getRequest()->getParameter('predefined_search'); $project_key = TBGContext::getCurrentProject() instanceof TBGProject ? TBGContext::getCurrentProject()->getKey() : 0; $url = TBGContext::getCurrentProject() instanceof TBGProject ? 'project_issues' : 'search'; echo __('Export results as:') . ' <a href="' . make_url($url, array('project_key' => $project_key, 'predefined_search' => $searchno, 'search' => '1', 'format' => 'csv')) . '"> ' . image_tag('icon_csv.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' CSV</a> <a href="' . make_url($url, array('project_key' => $project_key, 'predefined_search' => $searchno, 'search' => '1', 'format' => 'rss')) . '"> ' . image_tag('icon_rss.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' RSS</a>'; } else { /* Produce get parameters for query */ preg_match('/((?<=\\/)issues).+$/i', $_SERVER['QUERY_STRING'], $get); if (!isset($get[0])) { preg_match('/((?<=url=)issues).+$/i', $_SERVER['QUERY_STRING'], $get); } if (isset($get[0])) { if (TBGContext::isProjectContext()) { echo __('Export results as:') . ' <a href="' . make_url('project_issues', array('project_key' => TBGContext::getCurrentProject()->getKey(), 'format' => 'csv')) . '/' . $get[0] . '"> ' . image_tag('icon_csv.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' CSV</a> <a href="' . make_url('project_issues', array('project_key' => TBGContext::getCurrentProject()->getKey(), 'format' => 'rss')) . '?' . $get[0] . '"> ' . image_tag('icon_rss.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' RSS</a>'; } else { echo __('Export results as:') . ' <a href="' . make_url('search', array('format' => 'csv')) . '/' . $get[0] . '"> ' . image_tag('icon_csv.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' CSV</a> <a href="' . make_url('search', array('format' => 'rss')) . '?' . $get[0] . '"> ' . image_tag('icon_rss.png', array('class' => 'image', 'style' => 'vertical-align: top')) . ' RSS</a>'; }
public function componentExtralinks() { switch (true) { case TBGContext::getRequest()->hasParameter('quicksearch'): $searchfor = TBGContext::getRequest()->getParameter('searchfor'); $project_key = TBGContext::getCurrentProject() instanceof TBGProject ? TBGContext::getCurrentProject()->getKey() : 0; $this->csv_url = TBGContext::getRouting()->generate('project_issues', array('project_key' => $project_key, 'quicksearch' => 'true', 'format' => 'csv')) . '?searchfor=' . $searchfor; $this->rss_url = TBGContext::getRouting()->generate('project_issues', array('project_key' => $project_key, 'quicksearch' => 'true', 'format' => 'rss')) . '?searchfor=' . $searchfor; break; case TBGContext::getRequest()->hasParameter('predefined_search'): $searchno = TBGContext::getRequest()->getParameter('predefined_search'); $project_key = TBGContext::getCurrentProject() instanceof TBGProject ? TBGContext::getCurrentProject()->getKey() : 0; $url = TBGContext::getCurrentProject() instanceof TBGProject ? 'project_issues' : 'search'; $this->csv_url = TBGContext::getRouting()->generate($url, array('project_key' => $project_key, 'predefined_search' => $searchno, 'search' => '1', 'format' => 'csv')); $this->rss_url = TBGContext::getRouting()->generate($url, array('project_key' => $project_key, 'predefined_search' => $searchno, 'search' => '1', 'format' => 'rss')); break; default: preg_match('/((?<=\\/)issues).+$/i', TBGContext::getRequest()->getQueryString(), $get); if (!isset($get[0])) { preg_match('/((?<=url=)issues).+$/i', TBGContext::getRequest()->getQueryString(), $get); } if (isset($get[0])) { if (TBGContext::isProjectContext()) { $this->csv_url = TBGContext::getRouting()->generate('project_issues', array('project_key' => TBGContext::getCurrentProject()->getKey(), 'format' => 'csv')) . '/' . $get[0]; $this->rss_url = TBGContext::getRouting()->generate('project_issues', array('project_key' => TBGContext::getCurrentProject()->getKey(), 'format' => 'rss')) . '?' . $get[0]; } else { $this->csv_url = TBGContext::getRouting()->generate('search', array('format' => 'csv')) . '/' . $get[0]; $this->rss_url = TBGContext::getRouting()->generate('search', array('format' => 'rss')) . '?' . $get[0]; } } break; } $i18n = TBGContext::getI18n(); $this->columns = array('title' => $i18n->__('Issue title'), 'issuetype' => $i18n->__('Issue type'), 'assigned_to' => $i18n->__('Assigned to'), 'status' => $i18n->__('Status'), 'resolution' => $i18n->__('Resolution'), 'category' => $i18n->__('Category'), 'severity' => $i18n->__('Severity'), 'percent_complete' => $i18n->__('% completed'), 'reproducability' => $i18n->__('Reproducability'), 'priority' => $i18n->__('Priority'), 'components' => $i18n->__('Component(s)'), 'milestone' => $i18n->__('Milestone'), 'estimated_time' => $i18n->__('Estimate'), 'spent_time' => $i18n->__('Time spent'), 'last_updated' => $i18n->__('Last updated time'), 'comments' => $i18n->__('Number of comments')); }
public function componentReportIssue() { $introarticle = TBGArticlesTable::getTable()->getArticleByName(ucfirst(TBGContext::getCurrentProject()->getKey()) . ':ReportIssueIntro'); $this->introarticle = $introarticle instanceof TBGWikiArticle ? $introarticle : TBGArticlesTable::getTable()->getArticleByName('ReportIssueIntro'); $reporthelparticle = TBGArticlesTable::getTable()->getArticleByName(ucfirst(TBGContext::getCurrentProject()->getKey()) . ':ReportIssueHelp'); $this->reporthelparticle = $reporthelparticle instanceof TBGWikiArticle ? $reporthelparticle : TBGArticlesTable::getTable()->getArticleByName('ReportIssueHelp'); $this->uniqid = TBGContext::getRequest()->getParameter('uniqid', uniqid()); $this->_setupReportIssueProperties(); $dummyissue = new TBGIssue(); $dummyissue->setProject(TBGContext::getCurrentProject()); $this->canupload = TBGSettings::isUploadsEnabled() && $dummyissue->canAttachFiles(); }
/** * Displays a nicely formatted exception message * * @param string $title * @param Exception $exception */ function tbg_exception($title, $exception) { if (TBGContext::getRequest() instanceof TBGRequest && TBGContext::getRequest()->isAjaxCall()) { TBGContext::getResponse()->ajaxResponseText(404, $title); } $ob_status = ob_get_status(); if (!empty($ob_status) && $ob_status['status'] != PHP_OUTPUT_HANDLER_END) { ob_end_clean(); } if (TBGContext::isCLI()) { $trace_elements = null; if ($exception instanceof Exception) { if ($exception instanceof TBGActionNotFoundException) { TBGCliCommand::cli_echo("Could not find the specified action\n", 'white', 'bold'); } elseif ($exception instanceof TBGTemplateNotFoundException) { TBGCliCommand::cli_echo("Could not find the template file for the specified action\n", 'white', 'bold'); } elseif ($exception instanceof B2DBException) { TBGCliCommand::cli_echo("An exception was thrown in the B2DB framework\n", 'white', 'bold'); } else { TBGCliCommand::cli_echo("An unhandled exception occurred:\n", 'white', 'bold'); } echo TBGCliCommand::cli_echo($exception->getMessage(), 'red', 'bold') . "\n"; echo "\n"; TBGCliCommand::cli_echo('Stack trace') . ":\n"; $trace_elements = $exception->getTrace(); } else { if ($exception['code'] == 8) { TBGCliCommand::cli_echo('The following notice has stopped further execution:', 'white', 'bold'); } else { TBGCliCommand::cli_echo('The following error occured:', 'white', 'bold'); } echo "\n"; echo "\n"; TBGCliCommand::cli_echo($title, 'red', 'bold'); echo "\n"; TBGCliCommand::cli_echo("occured in\n"); TBGCliCommand::cli_echo($exception['file'] . ', line ' . $exception['line'], 'blue', 'bold'); echo "\n"; echo "\n"; TBGCliCommand::cli_echo("Backtrace:\n", 'white', 'bold'); $trace_elements = debug_backtrace(); } foreach ($trace_elements as $trace_element) { if (array_key_exists('class', $trace_element)) { TBGCliCommand::cli_echo($trace_element['class'] . $trace_element['type'] . $trace_element['function'] . '()'); } elseif (array_key_exists('function', $trace_element)) { if (in_array($trace_element['function'], array('tbg_error_handler', 'tbg_exception'))) { continue; } TBGCliCommand::cli_echo($trace_element['function'] . '()'); } else { TBGCliCommand::cli_echo('unknown function'); } echo "\n"; if (array_key_exists('file', $trace_element)) { TBGCliCommand::cli_echo($trace_element['file'] . ', line ' . $trace_element['line'], 'blue', 'bold'); } else { TBGCliCommand::cli_echo('unknown file', 'red', 'bold'); } echo "\n"; } if (class_exists('B2DB')) { echo "\n"; TBGCliCommand::cli_echo("SQL queries:\n", 'white', 'bold'); try { $cc = 1; foreach (B2DB::getSQLHits() as $details) { TBGCliCommand::cli_echo("(" . $cc++ . ") ["); $str = $details['time'] >= 1 ? round($details['time'], 2) . ' seconds' : round($details['time'] * 1000, 1) . 'ms'; TBGCliCommand::cli_echo($str); TBGCliCommand::cli_echo("] from "); TBGCliCommand::cli_echo($details['filename'], 'blue'); TBGCliCommand::cli_echo(", line "); TBGCliCommand::cli_echo($details['line'], 'white', 'bold'); TBGCliCommand::cli_echo(":\n"); TBGCliCommand::cli_echo("{$details['sql']}\n"); } echo "\n"; } catch (Exception $e) { TBGCliCommand::cli_echo("Could not generate query list (there may be no database connection)", "red", "bold"); } } echo "\n"; die; } echo "\n\t\t<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n\t\t<html>\n\t\t<head>\n\t\t<style>\n\t\tbody { background-color: #DFDFDF; font-family: \"Droid Sans\", \"Trebuchet MS\", \"Liberation Sans\", \"Nimbus Sans L\", \"Luxi Sans\", Verdana, sans-serif; font-size: 13px; }\n\t\th1 { margin: 5px 0 0 0; font-size: 19px; }\n\t\th2 { margin: 0 0 15px 0; font-size: 16px; }\n\t\th3 { margin: 15px 0 0 0; font-size: 14px; }\n\t\tinput[type=\"text\"], input[type=\"password\"] { float: left; margin-right: 15px; }\n\t\tlabel { float: left; font-weight: bold; margin-right: 5px; display: block; width: 150px; }\n\t\tlabel span { font-weight: normal; color: #888; }\n\t\t.rounded_box {background: transparent; margin:0px;}\n\t\t.rounded_box h4 { margin-bottom: 0px; margin-top: 7px; font-size: 14px; }\n\t\t.xtop, .xbottom {display:block; background:transparent; font-size:1px;}\n\t\t.xb1, .xb2, .xb3, .xb4 {display:block; overflow:hidden;}\n\t\t.xb1, .xb2, .xb3 {height:1px;}\n\t\t.xb2, .xb3, .xb4 {background:#F9F9F9; border-left:1px solid #CCC; border-right:1px solid #CCC;}\n\t\t.xb1 {margin:0 5px; background:#CCC;}\n\t\t.xb2 {margin:0 3px; border-width:0 2px;}\n\t\t.xb3 {margin:0 2px;}\n\t\t.xb4 {height:2px; margin:0 1px;}\n\t\t.xboxcontent {display:block; background:#F9F9F9; border:0 solid #CCC; border-width:0 1px; padding: 0 5px 0 5px;}\n\t\t.xboxcontent table td.description { padding: 3px 3px 3px 0;}\n\t\t.white .xb2, .white .xb3, .white .xb4 { background: #FFF; border-color: #CCC; }\n\t\t.white .xb1 { background: #CCC; }\n\t\t.white .xboxcontent { background: #FFF; border-color: #CCC; }\n\t\tpre { overflow: scroll; padding: 5px; }\n\t\t</style>\n\t\t<!--[if IE]>\n\t\t<style>\n\t\tbody { background-color: #DFDFDF; font-family: sans-serif; font-size: 13px; }\n\t\t</style>\n\t\t<![endif]-->\n\t\t</head>\n\t\t<body>\n\t\t<div class=\"rounded_box white\" style=\"margin: 30px auto 0 auto; width: 700px;\">\n\t\t\t<b class=\"xtop\"><b class=\"xb1\"></b><b class=\"xb2\"></b><b class=\"xb3\"></b><b class=\"xb4\"></b></b>\n\t\t\t<div class=\"xboxcontent\" style=\"vertical-align: middle; padding: 10px 10px 10px 15px;\">\n\t\t\t<img style=\"float: left; margin-right: 10px;\" src=\"" . TBGContext::getTBGPath() . "header.png\"><h1>An error occured in The Bug Genie</h1>"; echo "<h2>{$title}</h2>"; $report_description = null; if ($exception instanceof Exception) { if ($exception instanceof TBGActionNotFoundException) { echo "<h3>Could not find the specified action</h3>"; $report_description = "Could not find the specified action"; } elseif ($exception instanceof TBGTemplateNotFoundException) { echo "<h3>Could not find the template file for the specified action</h3>"; $report_description = "Could not find the template file for the specified action"; } elseif ($exception instanceof B2DBException) { echo "<h3>An exception was thrown in the B2DB framework</h3>"; $report_description = "An exception was thrown in the B2DB framework"; } else { echo "<h3>An unhandled exception occurred:</h3>"; $report_description = "An unhandled exception occurred"; } $report_description .= "\n" . $exception->getMessage(); echo "<i>" . $exception->getMessage() . "</i><br>"; if (class_exists("TBGContext") && TBGContext::isDebugMode()) { echo "<h3>Stack trace:</h3>\n\t\t\t\t\t<ul>"; //echo '<pre>';var_dump($exception->getTrace());die(); foreach ($exception->getTrace() as $trace_element) { echo '<li>'; if (array_key_exists('class', $trace_element)) { echo '<strong>' . $trace_element['class'] . $trace_element['type'] . $trace_element['function'] . '()</strong><br>'; } elseif (array_key_exists('function', $trace_element)) { if (!in_array($trace_element['function'], array('tbg_error_handler', 'tbg_exception'))) { echo '<strong>' . $trace_element['function'] . '()</strong><br>'; } } else { echo '<strong>unknown function</strong><br>'; } if (array_key_exists('file', $trace_element)) { echo '<span style="color: #55F;">' . $trace_element['file'] . '</span>, line ' . $trace_element['line']; } else { echo '<span style="color: #C95;">unknown file</span>'; } echo '</li>'; } echo "</ul>"; } } else { echo '<h3>'; if ($exception['code'] == 8) { echo 'The following notice has stopped further execution:'; $report_description = 'The following notice has stopped further execution: '; } else { echo 'The following error occured:'; $report_description = 'The following error occured: '; } echo '</h3>'; $report_description .= $title; echo "{$title}</i><br>\n\t\t\t\t<h3>Error information:</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>"; echo '<span style="color: #55F;">' . $exception['file'] . '</span>, line ' . $exception['line']; echo "</li>\n\t\t\t\t</ul>"; if (class_exists("TBGContext") && TBGContext::isDebugMode()) { echo "<h3>Backtrace:</h3>\n\t\t\t\t\t<ol>"; foreach (debug_backtrace() as $trace_element) { echo '<li>'; if (array_key_exists('class', $trace_element)) { echo '<strong>' . $trace_element['class'] . $trace_element['type'] . $trace_element['function'] . '()</strong><br>'; } elseif (array_key_exists('function', $trace_element)) { if (in_array($trace_element['function'], array('tbg_error_handler', 'tbg_exception'))) { continue; } echo '<strong>' . $trace_element['function'] . '()</strong><br>'; } else { echo '<strong>unknown function</strong><br>'; } if (array_key_exists('file', $trace_element)) { echo '<span style="color: #55F;">' . $trace_element['file'] . '</span>, line ' . $trace_element['line']; } else { echo '<span style="color: #C95;">unknown file</span>'; } echo '</li>'; } echo "</ol>"; } } if (class_exists("TBGContext") && TBGContext::isDebugMode()) { echo "<h3>Log messages:</h3>"; foreach (TBGLogging::getEntries() as $entry) { $color = TBGLogging::getCategoryColor($entry['category']); $lname = TBGLogging::getLevelName($entry['level']); echo "<div class=\"log_{$entry['category']}\"><strong>{$lname}</strong> <strong style=\"color: #{$color}\">[{$entry['category']}]</strong> <span style=\"color: #555; font-size: 10px; font-style: italic;\">{$entry['time']}</span> {$entry['message']}</div>"; } } if (class_exists("B2DB") && TBGContext::isDebugMode()) { echo "<h3>SQL queries:</h3>"; try { echo "<ol>"; foreach (B2DB::getSQLHits() as $details) { echo "<li>\n\t\t\t\t\t\t\t<b>\n\t\t\t\t\t\t\t<span class=\"faded_out dark small\">["; echo $details['time'] >= 1 ? round($details['time'], 2) . ' seconds' : round($details['time'] * 1000, 1) . 'ms'; echo "]</span> </b> from <b>{$details['filename']}, line {$details['line']}</b>:<br>\n\t\t\t\t\t\t\t<span style=\"font-size: 12px;\">{$details['sql']}</span>\n\t\t\t\t\t\t</li>"; } echo "</ol>"; } catch (Exception $e) { echo '<span style="color: red;">Could not generate query list (there may be no database connection)</span>'; } } echo "</div>\n\t\t\t<b class=\"xbottom\"><b class=\"xb4\"></b><b class=\"xb3\"></b><b class=\"xb2\"></b><b class=\"xb1\"></b></b>\n\t\t</div>"; if (class_exists("TBGContext") && !TBGContext::isDebugMode()) { echo "<div style=\"text-align: left; margin: 35px auto 0 auto; width: 700px; font-size: 13px;\">\n\t\t\t\t<div class=\"rounded_box white\" style=\"margin-bottom: 10px; text-align: right; color: #111;\">\n\t\t\t\t\t<b class=\"xtop\"><b class=\"xb1\"></b><b class=\"xb2\"></b><b class=\"xb3\"></b><b class=\"xb4\"></b></b>\n\t\t\t\t\t<div class=\"xboxcontent\">\n\t\t\t\t\t\t<div style=\"text-align: left;\">\n\t\t\t\t\t\t\t<h2 style=\"padding-top: 10px; margin-bottom: 5px;\">Reporting this issue</h2>\n\t\t\t\t\t\t\tPlease report this error in the bug tracker by pressing the button below. This will file an automatic bug report and open it in a new window.<br><br>\n\t\t\t\t\t\t\tNo login is required - but if you have a username and password entering it below will post the issue with your username, allowing you to follow its progress.\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<br>\n\t\t\t\t\t\t<form action=\"http://thebuggenie.com/thebuggenie/thebuggenie/issues/new/bugreport\" target=\"_new\" method=\"post\">\n\t\t\t\t\t\t\t<label for=\"username\">Username <span>(optional)</span></label>\n\t\t\t\t\t\t\t<input type=\"text\" name=\"tbg3_username\" id=\"username\">\n\t\t\t\t\t\t\t<br style=\"clear: both;\">\n\t\t\t\t\t\t\t<label for=\"password\">Password <span>(optional)</span></label>\n\t\t\t\t\t\t\t<input type=\"password\" name=\"tbg3_password\" id=\"password\">\n\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t<input type=\"hidden\" name=\"category_id\" value=\"34\">\n\t\t\t\t\t\t\t<input type=\"hidden\" name=\"title\" value=\"" . htmlentities($title) . "\">\n\t\t\t\t\t\t\t<input type=\"hidden\" name=\"description\" value=\"" . htmlentities($report_description) . "\n\n\">"; echo "<input type=\"hidden\" name=\"reproduction_steps\" value=\"PHP_SAPI: " . PHP_SAPI . "<br>PHP_VERSION: " . PHP_VERSION . "\n\n'''Backtrace''':<br>"; if ($exception instanceof TBGException) { foreach ($exception->getTrace() as $trace_element) { if (array_key_exists('class', $trace_element)) { echo "'''{$trace_element['class']}{$trace_element['type']}{$trace_element['function']}()'''\n"; } elseif (array_key_exists('function', $trace_element)) { if (in_array($trace_element['function'], array('tbg_error_handler', 'tbg_exception'))) { continue; } echo "'''{$trace_element['function']}()'''\n"; } else { echo "'''unknown function'''\n"; } if (array_key_exists('file', $trace_element)) { echo 'in ' . str_replace(THEBUGGENIE_PATH, '<installpath>/', $trace_element['file']) . ', line ' . $trace_element['line']; } else { echo 'in an unknown file'; } echo "<br>"; } } else { foreach (debug_backtrace() as $trace_element) { if (array_key_exists('class', $trace_element)) { echo "'''{$trace_element['class']}{$trace_element['type']}{$trace_element['function']}()'''\n"; } elseif (array_key_exists('function', $trace_element)) { if (in_array($trace_element['function'], array('tbg_error_handler', 'tbg_exception'))) { continue; } echo "'''{$trace_element['function']}()'''\n"; } else { echo "'''unknown function'''\n"; } if (array_key_exists('file', $trace_element)) { echo 'in ' . str_replace(THEBUGGENIE_PATH, '<installpath>/', $trace_element['file']) . ', line ' . $trace_element['line']; } else { echo 'in an unknown file'; } echo "<br>"; } } echo "\n\n\">"; echo "\t\t\t\t\t\n\t\t\t\t\t\t\t\t<input type=\"submit\" value=\"Submit details for reporting\" style=\"font-size: 16px; font-weight: normal; padding: 5px; margin: 10px 0;\">\n\t\t\t\t\t\t\t\t<div style=\"font-size: 15px; font-weight: bold; padding: 0 5px 10px 0;\">Thank you for helping us improve The Bug Genie!</div>\n\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<b class=\"xbottom\"><b class=\"xb4\"></b><b class=\"xb3\"></b><b class=\"xb2\"></b><b class=\"xb1\"></b></b>\n\t\t\t\t\t</div>"; if (TBGLogging::isEnabled()) { echo "<h3 style=\"margin-top: 50px;\">Log messages (may contain useful information, but will not be submitted):</h3>"; foreach (TBGLogging::getEntries() as $entry) { $color = TBGLogging::getCategoryColor($entry['category']); $lname = TBGLogging::getLevelName($entry['level']); echo "<div class=\"log_{$entry['category']}\"><strong>{$lname}</strong> <strong style=\"color: #{$color}\">[{$entry['category']}]</strong> <span style=\"color: #555; font-size: 10px; font-style: italic;\">{$entry['time']}</span> {$entry['message']}</div>"; } } } echo "\n\t\t\t</div>\n\t\t</body>\n\t\t</html>\n\t\t"; die; }
<?php TBGContext::loadLibrary('ui'); if (TBGContext::getUser()->isGuest() || TBGContext::getRequest()->hasParameter('redirect')) { ?> <script> showFadedBackdrop('<?php echo make_url('get_partial_for_backdrop', array_merge(array('key' => 'login'), $options)); ?> '); </script> <?php } else { ?> <div class="rounded_box green borderless loggedindiv" > <?php echo __('You are already logged in'); ?> </div> <?php }
/** * Returns the current route action * * @return string The current route action */ public function getCurrentRouteAction() { if ($this->current_route_module === null) { $this->getRouteFromUrl(TBGContext::getRequest()->getParameter('url', null, false)); } return $this->current_route_action; }
/** * Present a template * @param string $template_file * @param array $params */ public static function presentTemplate($template_file, $params = array()) { TBGLogging::log("configuring template variables for template {$template_file}"); foreach ($params as $key => $val) { ${$key} = $val; } if (array_key_exists('key', $params)) { $key = $params['key']; } if (array_key_exists('val', $params)) { $val = $params['val']; } /** * @global TBGRequest The request object */ $tbg_request = TBGContext::getRequest(); /** * @global TBGResponse The response object */ $tbg_response = TBGContext::getResponse(); /** * @global TBGRequest The request object */ $tbg_routing = TBGContext::getRouting(); /** * @global TBGUser The user object */ $tbg_user = TBGContext::getUser(); TBGContext::loadLibrary('common'); TBGContext::loadLibrary('ui'); TBGLogging::log('rendering template output'); require $template_file; }
public function componentBuild() { if (!isset($this->build)) { $this->build = new TBGBuild(); $this->build->setProject(TBGContext::getCurrentProject()); $this->build->setName(TBGContext::getI18n()->__('%project_name version 0.0.0', array('%project_name' => $this->project->getName()))); if (TBGContext::getRequest()->getParameter('edition_id') && ($edition = TBGContext::factory()->TBGEdition(TBGContext::getRequest()->getParameter('edition_id')))) { $this->build->setEdition($edition); } } }
protected function _upgradeFrom3dot1() { // Add classpath for existing old tables used for upgrade TBGContext::addAutoloaderClassPath(THEBUGGENIE_MODULES_PATH . 'installation' . DS . 'classes' . DS . 'upgrade_3.1'); TBGContext::addAutoloaderClassPath(THEBUGGENIE_MODULES_PATH . 'mailing' . DS . 'classes' . DS . 'B2DB'); TBGContext::addAutoloaderClassPath(THEBUGGENIE_MODULES_PATH . 'mailing' . DS . 'classes'); TBGContext::addAutoloaderClassPath(THEBUGGENIE_MODULES_PATH . 'publish' . DS . 'classes' . DS . 'B2DB'); TBGContext::addAutoloaderClassPath(THEBUGGENIE_MODULES_PATH . 'publish' . DS . 'classes'); // Create new tables TBGDashboardViewsTable::getTable()->create(); TBGOpenIdAccountsTable::getTable()->create(); TBGProjectAssignedUsersTable::getTable()->create(); TBGProjectAssignedTeamsTable::getTable()->create(); TBGEditionAssignedUsersTable::getTable()->create(); TBGEditionAssignedTeamsTable::getTable()->create(); TBGComponentAssignedUsersTable::getTable()->create(); TBGComponentAssignedTeamsTable::getTable()->create(); TBGRolePermissionsTable::getTable()->create(); TBGUserScopesTable::getTable()->create(); // Upgrade existing tables TBGProjectsTable::getTable()->upgrade(TBGProjectsTable3dot1::getTable()); TBGUsersTable::getTable()->upgrade(TBGUsersTable3dot1::getTable()); TBGIssuesTable::getTable()->upgrade(TBGIssuesTable3dot1::getTable()); TBGIssueTypesTable::getTable()->upgrade(TBGIssueTypesTable3dot1::getTable()); TBGListTypesTable::getTable()->upgrade(TBGListTypesTable3dot1::getTable()); TBGEditionsTable::getTable()->upgrade(TBGEditionsTable3dot1::getTable()); TBGBuildsTable::getTable()->upgrade(TBGBuildsTable3dot1::getTable()); TBGCommentsTable::getTable()->upgrade(TBGCommentsTable3dot1::getTable()); TBGComponentsTable::getTable()->upgrade(TBGComponentsTable3dot1::getTable()); TBGCustomFieldsTable::getTable()->upgrade(TBGCustomFieldsTable3dot1::getTable()); TBGCustomFieldOptionsTable::getTable()->upgrade(TBGCustomFieldOptionsTable3dot1::getTable()); TBGIssueCustomFieldsTable::getTable()->upgrade(TBGIssueCustomFieldsTable3dot1::getTable()); // Create new module tables TBGIncomingEmailAccountTable::getTable()->create(); // Add new indexes TBGArticlesTable::getTable()->createIndexes(); TBGCommentsTable::getTable()->createIndexes(); TBGIssueAffectsBuildTable::getTable()->createIndexes(); TBGIssueAffectsComponentTable::getTable()->createIndexes(); TBGIssueAffectsEditionTable::getTable()->createIndexes(); TBGIssueFieldsTable::getTable()->createIndexes(); TBGIssueFilesTable::getTable()->createIndexes(); TBGIssuesTable::getTable()->createIndexes(); TBGIssuetypeSchemesTable::getTable()->createIndexes(); TBGPermissionsTable::getTable()->createIndexes(); TBGProjectsTable::getTable()->createIndexes(); TBGSettingsTable::getTable()->createIndexes(); TBGTeamMembersTable::getTable()->createIndexes(); TBGUserIssuesTable::getTable()->createIndexes(); TBGUsersTable::getTable()->createIndexes(); TBGUserScopesTable::getTable()->createIndexes(); if (TBGContext::getRequest()->getParameter('fix_my_timestamps', false)) { $this->_fixTimestamps(); } foreach (TBGScope::getAll() as $scope) { TBGRole::loadFixtures($scope); foreach (TBGDatatype::getTypes() as $type => $class) { TBGContext::setPermission('set_datatype_' . $type, 0, 'core', 0, 0, 0, true, $scope->getID()); } TBGContext::setPermission('page_confirm_scope_access', 0, 'core', 0, 0, 0, true, $scope->getID()); if (!TBGSettings::get(TBGSettings::SETTING_DEFAULT_WORKFLOW, 'core', $scope->getID())) { $workflow_id = TBGWorkflowsTable::getTable()->getFirstIdByScope($scope->getID()); if ($workflow_id) { TBGSettings::saveSetting(TBGSettings::SETTING_DEFAULT_WORKFLOW, $workflow_id, 'core', $scope->getID()); } else { TBGWorkflow::loadFixtures($scope); } } if (!TBGSettings::get(TBGSettings::SETTING_DEFAULT_WORKFLOWSCHEME, 'core', $scope->getID())) { $workflow_scheme_id = TBGWorkflowSchemesTable::getTable()->getFirstIdByScope($scope->getID()); if ($workflow_scheme_id) { TBGSettings::saveSetting(TBGSettings::SETTING_DEFAULT_WORKFLOWSCHEME, $workflow_scheme_id, 'core', $scope->getID()); } else { TBGWorkflowScheme::loadFixtures($scope); } } if (!TBGSettings::get(TBGSettings::SETTING_DEFAULT_ISSUETYPESCHEME, 'core', $scope->getID())) { $issuetype_scheme_id = TBGIssuetypeSchemesTable::getTable()->getFirstIdByScope($scope->getID()); if ($issuetype_scheme_id) { TBGSettings::saveSetting(TBGSettings::SETTING_DEFAULT_ISSUETYPESCHEME, $issuetype_scheme_id, 'core', $scope->getID()); } else { TBGIssuetypeScheme::loadFixtures($scope); } } TBGSettings::saveSetting(TBGSettings::SETTING_FAVICON_ID, 0, 'core', $scope->getID()); TBGSettings::saveSetting(TBGSettings::SETTING_FAVICON_TYPE, 0, 'core', $scope->getID()); TBGSettings::saveSetting(TBGSettings::SETTING_HEADER_ICON_ID, 0, 'core', $scope->getID()); TBGSettings::saveSetting(TBGSettings::SETTING_HEADER_ICON_TYPE, 0, 'core', $scope->getID()); } $linkstable = TBGLinksTable::getTable(); $crit = $linkstable->getCriteria(); $crit->addUpdate(TBGLinksTable::URL, 'http://issues.thebuggenie.com'); $crit->addWhere(TBGLinksTable::URL, 'http://thebuggenie.com/thebuggenie'); $crit->addOr(TBGLinksTable::URL, 'http://www.thebuggenie.com/thebuggenie'); $linkstable->doUpdate($crit); $listtypestable = TBGListTypesTable::getTable(); $crit = $listtypestable->getCriteria(); $crit->addUpdate(TBGListTypesTable::ITEMTYPE, 'role'); $crit->addWhere(TBGListTypesTable::ITEMTYPE, 'projectrole'); $listtypestable->doUpdate($crit); $crit = $listtypestable->getCriteria(); $crit->addUpdate(TBGListTypesTable::ITEMTYPE, 'priority'); $crit->addWhere(TBGListTypesTable::ITEMTYPE, 'b2_prioritytypes'); $listtypestable->doUpdate($crit); TBGWorkflowTransitionsTable::getTable()->upgradeFrom3dot1(); TBGSettings::saveSetting(TBGSettings::SETTING_ICONSET, TBGSettings::get(TBGSettings::SETTING_THEME_NAME)); TBGContext::setPermission('readarticle', 0, 'publish', 0, 0, 0, true); foreach (TBGProject::getAll() as $project) { TBGDashboardViewsTable::getTable()->setDefaultViews($project->getID(), TBGDashboardViewsTable::TYPE_PROJECT); if (!$project->getKey()) { $project->setName($project->getName()); } } $this->upgrade_complete = true; }
/** * Forward the user to a different URL * * @param string $url the url to forward to * @param integer $code HTTP status code */ public function headerRedirect($url, $code = 302) { TBGLogging::log('Running header redirect function'); $this->clearHeaders(); $this->setHttpStatus($code); if (TBGContext::getRequest()->isAjaxCall() || TBGContext::getRequest()->getRequestedFormat() == 'json') { $this->renderHeaders(); } else { $this->addHeader("Location: {$url}"); $this->renderHeaders(); } exit; }
/** * Returns the logged in user, or default user if not logged in * * @param string $uname * @param string $upwd * * @return TBGUser */ public static function loginCheck($username = null, $password = null) { try { $row = null; // If no username and password specified, check if we have a session that exists already if ($username === null && $password === null) { if (TBGContext::getRequest()->hasCookie('tbg3_username') && TBGContext::getRequest()->hasCookie('tbg3_password')) { $username = TBGContext::getRequest()->getCookie('tbg3_username'); $password = TBGContext::getRequest()->getCookie('tbg3_password'); $row = TBGUsersTable::getTable()->getByUsernameAndPassword($username, $password); if (!$row) { TBGContext::getResponse()->deleteCookie('tbg3_username'); TBGContext::getResponse()->deleteCookie('tbg3_password'); throw new Exception('No such login'); //TBGContext::getResponse()->headerRedirect(TBGContext::getRouting()->generate('login')); } } } // If we have authentication details, validate them if (TBGSettings::getAuthenticationBackend() !== null && TBGSettings::getAuthenticationBackend() !== 'tbg' && $username !== null && $password !== null) { TBGLogging::log('Authenticating with backend: ' . TBGSettings::getAuthenticationBackend(), 'auth', TBGLogging::LEVEL_INFO); try { $mod = TBGContext::getModule(TBGSettings::getAuthenticationBackend()); if ($mod->getType() !== TBGModule::MODULE_AUTH) { TBGLogging::log('Auth module is not the right type', 'auth', TBGLogging::LEVEL_FATAL); throw new Exception('Invalid module type'); } if (TBGContext::getRequest()->hasCookie('tbg3_username') && TBGContext::getRequest()->hasCookie('tbg3_password')) { $row = $mod->verifyLogin($username, $password); } else { $row = $mod->doLogin($username, $password); } if (!$row) { // Invalid TBGContext::getResponse()->deleteCookie('tbg3_username'); TBGContext::getResponse()->deleteCookie('tbg3_password'); throw new Exception('No such login'); //TBGContext::getResponse()->headerRedirect(TBGContext::getRouting()->generate('login')); } } catch (Exception $e) { throw $e; } } elseif ($username !== null && $password !== null) { TBGLogging::log('Using internal authentication', 'auth', TBGLogging::LEVEL_INFO); // First test a pre-encrypted password $row = TBGUsersTable::getTable()->getByUsernameAndPassword($username, $password); if (!$row) { // Then test an unencrypted password $row = TBGUsersTable::getTable()->getByUsernameAndPassword($username, self::hashPassword($password)); if (!$row) { // This is a legacy account from a 2.1 upgrade - try md5 $row = TBGUsersTable::getTable()->getByUsernameAndPassword($username, md5($password)); if (!$row) { // Invalid TBGContext::getResponse()->deleteCookie('tbg3_username'); TBGContext::getResponse()->deleteCookie('tbg3_password'); throw new Exception('No such login'); //TBGContext::getResponse()->headerRedirect(TBGContext::getRouting()->generate('login')); } else { // convert md5 to new password type $user = new TBGUser($row->get(TBGUsersTable::ID), $row); $user->changePassword($password); $user->save(); unset($user); } } } } elseif (TBGContext::isCLI()) { $row = TBGUsersTable::getTable()->getByUsername(TBGContext::getCurrentCLIusername()); } elseif (!TBGSettings::isLoginRequired()) { $row = TBGUsersTable::getTable()->getByUserID(TBGSettings::getDefaultUserID()); } if ($row) { if (!$row->get(TBGScopesTable::ENABLED)) { throw new Exception('This account belongs to a scope that is not active'); } elseif (!$row->get(TBGUsersTable::ACTIVATED)) { throw new Exception('This account has not been activated yet'); } elseif (!$row->get(TBGUsersTable::ENABLED)) { throw new Exception('This account has been suspended'); } $user = TBGContext::factory()->TBGUser($row->get(TBGUsersTable::ID), $row); } elseif (TBGSettings::isLoginRequired()) { throw new Exception('Login required'); } else { throw new Exception('No such login'); } } catch (Exception $e) { throw $e; } return $user; }
/** * Add a build (AJAX call) * * @param TBGRequest $request The request object */ public function runProjectBuild(TBGRequest $request) { $i18n = TBGContext::getI18n(); if ($this->getUser()->canManageProjectReleases($this->selected_project)) { try { if (TBGContext::getUser()->canManageProjectReleases($this->selected_project)) { if (($b_name = $request['build_name']) && trim($b_name) != '') { $build = new TBGBuild($request['build_id']); $build->setName($b_name); $build->setVersion($request->getParameter('ver_mj', 0), $request->getParameter('ver_mn', 0), $request->getParameter('ver_rev', 0)); $build->setReleased((bool) $request['isreleased']); $build->setLocked((bool) $request['locked']); if ($request['milestone'] && ($milestone = TBGContext::factory()->TBGMilestone($request['milestone']))) { $build->setMilestone($milestone); } else { $build->clearMilestone(); } if ($request['edition'] && ($edition = TBGContext::factory()->TBGEdition($request['edition']))) { $build->setEdition($edition); } else { $build->clearEdition(); } $release_date = null; if ($request['has_release_date']) { $release_date = mktime($request['release_hour'], $request['release_minute'], 1, $request['release_month'], $request['release_day'], $request['release_year']); } $build->setReleaseDate($release_date); switch ($request->getParameter('download', 'leave_file')) { case '0': $build->clearFile(); $build->setFileURL(''); break; case 'upload_file': if ($build->hasFile()) { $build->getFile()->delete(); $build->clearFile(); } $file = TBGContext::getRequest()->handleUpload('upload_file'); $build->setFile($file); $build->setFileURL(''); break; case 'url': $build->clearFile(); $build->setFileURL($request['file_url']); break; } if ($request['edition_id']) { $build->setEdition($edition); } if (!$build->getID()) { $build->setProject($this->selected_project); } $build->save(); } else { throw new Exception($i18n->__('You need to specify a name for the release')); } } else { throw new Exception($i18n->__('You do not have access to this project')); } } catch (Exception $e) { TBGContext::setMessage('build_error', $e->getMessage()); } $this->forward(TBGContext::getRouting()->generate('project_release_center', array('project_key' => $this->selected_project->getKey()))); } return $this->forward403($i18n->__("You don't have access to add releases")); }
public function runAddCommitGitorious(TBGRequest $request) { TBGContext::getResponse()->setContentType('text/plain'); TBGContext::getResponse()->renderHeaders(); $passkey = TBGContext::getRequest()->getParameter('passkey'); $project_id = urldecode(TBGContext::getRequest()->getParameter('project_id')); $project = TBGContext::factory()->TBGProject($project_id); // Validate access if (!$project) { echo 'Error: The project with the ID ' . $project_id . ' does not exist'; exit; } if (TBGSettings::get('access_method_' . $project->getID(), 'vcs_integration') == TBGVCSIntegration::ACCESS_DIRECT) { echo 'Error: This project uses the CLI access method, and so access via HTTP has been disabled'; exit; } if (TBGSettings::get('access_passkey_' . $project->getID(), 'vcs_integration') != $passkey) { echo 'Error: The passkey specified does not match the passkey specified for this project'; exit; } // Validate data $data = html_entity_decode(TBGContext::getRequest()->getParameter('payload', null, false)); if (empty($data) || $data == null) { die('Error: No payload was provided'); } $entries = json_decode($data); if ($entries == null) { die('Error: The payload could not be decoded'); } $entries = json_decode($data); $previous = $entries->before; // Branch is stored in the ref $ref = $entries->ref; $parts = explode('/', $ref); if (count($parts) == 3) { $branch = $parts[2]; } else { $branch = null; } // Parse each commit individually foreach (array_reverse($entries->commits) as $commit) { $email = $commit->author->email; $author = $commit->author->name; $new_rev = $commit->id; $old_rev = $previous; $commit_msg = $commit->message; $time = strtotime($commit->timestamp); // Add commit echo TBGVCSIntegration::processCommit($project, $commit_msg, $old_rev, $previous, $time, "", $author, $branch); $previous = $new_rev; exit; } }
/** * Performs an action * * @param string $action Name of the action * @param string $method Name of the action method to run */ public static function performAction($action, $method) { // Set content variable $content = null; // Set the template to be used when rendering the html (or other) output $templatePath = THEBUGGENIE_MODULES_PATH . $action . DS . 'templates' . DS; // Construct the action class and method name, including any pre- action(s) $actionClassName = $action . 'Actions'; $actionToRunName = 'run' . ucfirst($method); $preActionToRunName = 'pre' . ucfirst($method); // Set up the response object, responsible for controlling any output self::getResponse()->setPage(self::getRouting()->getCurrentRouteName()); self::getResponse()->setTemplate(strtolower($method) . '.' . TBGContext::getRequest()->getRequestedFormat() . '.php'); self::getResponse()->setupResponseContentType(self::getRequest()->getRequestedFormat()); self::setCurrentProject(null); // Set up the action object $actionObject = new $actionClassName(); // Run the specified action method set if it exists if (method_exists($actionObject, $actionToRunName)) { // Turning on output buffering ob_start(); ob_implicit_flush(0); if (self::getRouting()->isCurrentRouteCSRFenabled()) { // If the csrf check fails, don't proceed if (!self::checkCSRFtoken(true)) { return true; } } if (self::$debug_mode) { $time = explode(' ', microtime()); $pretime = $time[1] + $time[0]; } if ($content === null) { TBGLogging::log('Running main pre-execute action'); // Running any overridden preExecute() method defined for that module // or the default empty one provided by TBGAction if ($pre_action_retval = $actionObject->preExecute(self::getRequest(), $method)) { $content = ob_get_clean(); TBGLogging::log('preexecute method returned something, skipping further action'); if (self::$debug_mode) { $visited_templatename = "{$actionClassName}::preExecute()"; } } } if ($content === null) { $action_retval = null; if (self::getResponse()->getHttpStatus() == 200) { // Checking for and running action-specific preExecute() function if // it exists if (method_exists($actionObject, $preActionToRunName)) { TBGLogging::log('Running custom pre-execute action'); $actionObject->{$preActionToRunName}(self::getRequest(), $method); } // Running main route action TBGLogging::log('Running route action ' . $actionToRunName . '()'); if (self::$debug_mode) { $time = explode(' ', microtime()); $action_pretime = $time[1] + $time[0]; } $action_retval = $actionObject->{$actionToRunName}(self::getRequest()); if (self::$debug_mode) { $time = explode(' ', microtime()); $action_posttime = $time[1] + $time[0]; TBGContext::visitPartial("{$actionClassName}::{$actionToRunName}", $action_posttime - $action_pretime); } } if (self::getResponse()->getHttpStatus() == 200 && $action_retval) { // If the action returns *any* output, we're done, and collect the // output to a variable to be outputted in context later $content = ob_get_clean(); TBGLogging::log('...done'); } elseif (!$action_retval) { // If the action doesn't return any output (which it usually doesn't) // we continue on to rendering the template file for that specific action TBGLogging::log('...done'); TBGLogging::log('Displaying template'); // Check to see if we have a translated version of the template if (($templateName = self::getI18n()->hasTranslatedTemplate(self::getResponse()->getTemplate())) === false) { // Check to see if the template has been changed, and whether it's in a // different module, specified by "module/templatename" if (strpos(self::getResponse()->getTemplate(), '/')) { $newPath = explode('/', self::getResponse()->getTemplate()); $templateName = THEBUGGENIE_MODULES_PATH . $newPath[0] . DS . 'templates' . DS . $newPath[1] . '.' . TBGContext::getRequest()->getRequestedFormat() . '.php'; } else { $templateName = $templatePath . self::getResponse()->getTemplate(); } } // Check to see if the template exists and throw an exception otherwise if (!file_exists($templateName)) { TBGLogging::log('The template file for the ' . $method . ' action ("' . self::getResponse()->getTemplate() . '") does not exist', 'core', TBGLogging::LEVEL_FATAL); throw new TBGTemplateNotFoundException('The template file for the ' . $method . ' action ("' . self::getResponse()->getTemplate() . '") does not exist'); } self::loadLibrary('common'); // Present template for current action TBGActionComponent::presentTemplate($templateName, $actionObject->getParameterHolder()); $content = ob_get_clean(); TBGLogging::log('...completed'); } } elseif (self::$debug_mode) { $time = explode(' ', microtime()); $posttime = $time[1] + $time[0]; TBGContext::visitPartial($visited_templatename, $posttime - $pretime); } if (!isset($tbg_response)) { /** * @global TBGRequest The request object */ $tbg_request = self::getRequest(); /** * @global TBGUser The user object */ $tbg_user = self::getUser(); /** * @global TBGResponse The action object */ $tbg_response = self::getResponse(); // Load the "ui" library, since this is used a lot self::loadLibrary('ui'); } self::loadLibrary('common'); // Render header template if any, and store the output in a variable ob_start(); ob_implicit_flush(0); if (!self::getRequest()->isAjaxCall() && self::getResponse()->doDecorateHeader()) { TBGLogging::log('decorating with header'); if (!file_exists(self::getResponse()->getHeaderDecoration())) { throw new TBGTemplateNotFoundException('Can not find header decoration: ' . self::getResponse()->getHeaderDecoration()); } require self::getResponse()->getHeaderDecoration(); $decoration_header = ob_get_clean(); } // Set up the run summary, and store it in a variable ob_start(); ob_implicit_flush(0); $load_time = self::getLoadtime(); if (B2DB::isInitialized()) { $tbg_summary['db_queries'] = B2DB::getSQLHits(); $tbg_summary['db_timing'] = B2DB::getSQLTiming(); } $tbg_summary['load_time'] = $load_time >= 1 ? round($load_time, 2) . ' seconds' : round($load_time * 1000, 1) . 'ms'; $tbg_summary['scope_id'] = self::getScope() instanceof TBGScope ? self::getScope()->getID() : 'unknown'; self::ping(); // Render footer template if any, and store the output in a variable if (!self::getRequest()->isAjaxCall() && self::getResponse()->doDecorateFooter()) { TBGLogging::log('decorating with footer'); require self::getResponse()->getFooterDecoration(); $decoration_footer = ob_get_clean(); } TBGLogging::log('...done'); TBGLogging::log('rendering content'); // Render output in correct order self::getResponse()->renderHeaders(); if (isset($decoration_header)) { echo $decoration_header; } echo $content; if (isset($decoration_footer)) { echo $decoration_footer; } TBGLogging::log('...done (rendering content)'); if (self::isDebugMode()) { self::getI18n()->addMissingStringsToStringsFile(); } return true; } else { TBGLogging::log("Cannot find the method {$actionToRunName}() in class {$actionClassName}.", 'core', TBGLogging::LEVEL_FATAL); throw new TBGActionNotFoundException("Cannot find the method {$actionToRunName}() in class {$actionClassName}. Make sure the method exists."); } }
public function hasTranslatedTemplate($template, $is_component = false) { if (strpos($template, '/')) { $templateinfo = explode('/', $template); $module = $templateinfo[0]; $templatefile = $is_component ? '_' . $templateinfo[1] . '.inc.php' : $templateinfo[1] . '.' . TBGContext::getRequest()->getRequestedFormat() . '.php'; } else { $module = TBGContext::getRouting()->getCurrentRouteModule(); $templatefile = $is_component ? '_' . $template . '.inc.php' : $template . '.' . TBGContext::getRequest()->getRequestedFormat() . '.php'; } if (file_exists(THEBUGGENIE_MODULES_PATH . $module . DS . 'i18n' . DS . $this->_language . DS . 'templates' . DS . $templatefile)) { return THEBUGGENIE_MODULES_PATH . $module . DS . 'i18n' . DS . $this->_language . DS . 'templates' . DS . $templatefile; } elseif (file_exists(THEBUGGENIE_PATH . 'i18n' . DS . $this->getCurrentLanguage() . DS . 'templates' . DS . $module . DS . $templatefile)) { return THEBUGGENIE_PATH . 'i18n' . DS . $this->getCurrentLanguage() . DS . 'templates' . DS . $module . DS . $templatefile; } return false; }
/** * Sets the response to 404 and shows an error, with an optional message * * @param string $message[optional] The message */ public function return404($message = null) { if (TBGContext::getRequest()->isAjaxCall() || TBGContext::getRequest()->getRequestedFormat() == 'json') { $this->getResponse()->ajaxResponseText(404, $message); } $this->message = $message; $this->getResponse()->setHttpStatus(404); $this->getResponse()->setTemplate('main/notfound'); return false; }
/** * Forward the user with HTTP status code 403 and an (optional) message * based on a boolean check * * @param boolean $condition * @param string $message[optional] The message */ public function forward403unless($condition, $message = null) { if (!$condition) { $message = $message === null ? TBGContext::getI18n()->__("You are not allowed to access this page") : htmlentities($message); if (TBGContext::getUser()->isGuest()) { TBGContext::setMessage('login_message_err', $message); TBGContext::setMessage('login_force_redirect', true); TBGContext::setMessage('login_referer', TBGContext::getRouting()->generate(TBGContext::getRouting()->getCurrentRouteName(), TBGContext::getRequest()->getParameters())); $this->forward(TBGContext::getRouting()->generate('login_page'), 403); } else { $this->getResponse()->setHttpStatus(403); $this->getResponse()->setTemplate('main/forbidden', array('message' => $message)); } } }