/** * Forward the user to a specified url * * @param string $url The URL to forward to * @param integer $code[optional] HTTP status code * @param integer $method[optional] 2 for meta redirect instead of header */ public function forward($url, $code = 200) { if (TBGContext::getRequest()->isAjaxCall() || TBGContext::getRequest()->getRequestedFormat() == 'json') { $this->getResponse()->ajaxResponseText($code, TBGContext::getMessageAndClear('forward')); } TBGLogging::log("Forwarding to url {$url}"); TBGLogging::log('Triggering header redirect function'); $this->getResponse()->headerRedirect($url, $code); }
public static function add($key, $value) { if (!self::isEnabled()) { TBGLogging::log('Key "' . $key . '" not cached', 'cache'); return false; } apc_store($key, $value); TBGLogging::log('Caching value for key "' . $key . '"', 'cache'); return true; }
/** * Returns the current row * * @return Row */ public function getCurrentRow() { if ($this->int_ptr == 0) { \TBGLogging::log('This is not a valid row'); } if (isset($this->rows[$this->int_ptr - 1])) { return $this->rows[$this->int_ptr - 1]; } return null; }
public function manufacture($classname, $id, $row = null) { // Check that the id is valid if ((int) $id == 0) { throw new Exception('Invalid id'); } // Set up the name for the factory array $factory_array_name = "_{$classname}s"; $item = null; // Set up the manufactured array if it doesn't exist if (!isset($this->{$factory_array_name})) { TBGLogging::log("Setting up manufactured array for {$classname}"); $this->{$factory_array_name} = array(); } // If the current id doesn't exist in the manufactured array, manufacture it if (!array_key_exists($id, $this->{$factory_array_name})) { // Initialize a position for the item in the manufactured array $this->{$factory_array_name}[$id] = null; try { // Check if the class is cacheable as well $cacheable = false; // in_array($classname, array('TBGProject', 'TBGStatus', 'TBGPriority', 'TBGCategory', 'TBGUserstate')); $item = null; // If the class is cacheable, check if it exists in the cache if ($cacheable) { if ($item = TBGCache::get(TBGCache::KEY_TBG_FACTORY . "{$factory_array_name}_{$id}")) { TBGLogging::log("Using cached {$classname} with id {$id}"); } } // If we didn't get an item from the cache, manufacture it if (!$cacheable || !is_object($item)) { $item = new $classname($id, $row); TBGLogging::log("Manufacturing {$classname} with id {$id}"); // Add the item to the cache if it's cacheable if ($cacheable) { TBGCache::add(TBGCache::KEY_TBG_FACTORY . "{$factory_array_name}_{$id}", $item); } } // Add the manufactured item to the manufactured array $this->{$factory_array_name}[$id] = $item; } catch (Exception $e) { throw $e; } } else { TBGLogging::log("Using previously manufactured {$classname} with id {$id}"); } // Return the item at that id in the manufactured array return $this->{$factory_array_name}[$id]; }
public function componentTeamdropdown() { TBGLogging::log('team dropdown component'); $this->rnd_no = rand(); try { $this->team = isset($this->team) ? $this->team : null; if (!$this->team instanceof TBGTeam) { TBGLogging::log('loading team object in dropdown'); $this->team = TBGContext::factory()->TBGTeam($this->team); TBGLogging::log('done (loading team object in dropdown)'); } } catch (Exception $e) { } TBGLogging::log('done (team dropdown component)'); }
/** * Returns a list of changed items with a specified class * * @param string $class The class name * * @return array */ public static function getChangedItems($class) { $retarr = array(); if (isset($_SESSION['changeableitems'][$class]) && is_array($_SESSION['changeableitems'][$class])) { $function = $class . 'Lab'; foreach ($_SESSION['changeableitems'][$class] as $id => $changes) { if ($changes) { try { $retarr[$id] = TBGContext::factory()->{$function}($id); } catch (Exception $e) { TBGLogging::log("Changed item of type {$class}, id {$id} is invalid - unsetting", 'main', TBGLogging::LEVEL_NOTICE); unset($_SESSION['changeableitems'][$class][$id]); } } else { unset($_SESSION['changeableitems'][$class][$id]); } } } return $retarr; }
/** * Populates openid accounts array when needed */ protected function _populateOpenIDAccounts() { if ($this->_openid_accounts === null) { TBGLogging::log('Populating openid accounts'); $this->_openid_accounts = TBGOpenIdAccountsTable::getTable()->getIdentitiesForUserID($this->getID()); TBGLogging::log('...done (Populating user clients)'); } }
public function getUploadStatus($id) { TBGLogging::log('sanitizing id'); // sanitize the ID value $id = preg_replace('/[^a-z0-9]/i', '', $id); if (strlen($id) == 0) { TBGLogging::log('oops, invalid id ' . $id); return; } // ensure the uploaded status data exists in the session if (!array_key_exists($id, $_SESSION['__upload_status'])) { TBGLogging::log('upload with this id ' . $id . ' is not in progress yet'); $_SESSION['__upload_status'][$id] = array('id' => $id, 'finished' => false, 'percent' => 0, 'total' => 0, 'complete' => 0); } // retrieve the data from the session so it can be updated and returned $ret = $_SESSION['__upload_status'][$id]; // if we can't retrieve the status or the upload has finished just return if (!self::CanGetUploadStatus() || $ret['finished']) { TBGLogging::log('upload either finished or we cant track it'); // $ret['finished'] = true; // $ret['percent'] = 100; // $ret['complete'] = 100; return $ret; } // retrieve the upload data from APC $status = apc_fetch('upload_' . $id); // false is returned if the data isn't found if ($status) { $ret['finished'] = (bool) $status['done']; $ret['total'] = $status['total']; $ret['complete'] = $status['current']; if (array_key_exists('file_id', $ret)) { $status['file_id'] = $ret['file_id']; } elseif (array_key_exists('error', $ret)) { $status['failed'] = true; $status['error'] = $ret['error']; } // calculate the completed percentage if ($ret['total'] > 0) { $ret['percent'] = $ret['complete'] / $ret['total'] * 100; } // write the changed data back to the session $_SESSION['__upload_status'][$id] = $ret; } return $ret; }
public function __($text, $replacements = array(), $html_decode = false) { if (isset($this->_strings[$text])) { $retstring = $this->_strings[$text]; } else { $retstring = $text; TBGLogging::log('The text "' . $text . '" does not exist in list of translated strings.', 'i18n'); $this->_missing_strings[$text] = true; } if (!empty($replacements)) { $tmp = array(); foreach ($replacements as $key => $value) { $tmp[$key] = $value; $retstring = str_replace(array_keys($tmp), array_values($tmp), $retstring); } } if ($html_decode) { $retstring = html_entity_decode($retstring); } return $retstring; }
/** * Configure a module * * @param TBGRequest $request The request object */ public function runConfigureModule(TBGRequest $request) { $this->forward403unless($this->access_level == TBGSettings::ACCESS_FULL); try { $module = TBGContext::getModule($request->getParameter('config_module')); if (!$module->isEnabled()) { throw new Exception('disabled'); } elseif (!$module->hasConfigSettings()) { throw new Exception('module not configurable'); } else { if ($request->isMethod(TBGRequest::POST) && $this->access_level == TBGSettings::ACCESS_FULL) { try { $module->postConfigSettings($request); if (!TBGContext::hasMessage('module_message')) { TBGContext::setMessage('module_message', TBGContext::getI18n()->__('Settings saved successfully')); } } catch (Exception $e) { TBGContext::setMessage('module_error', $e->getMessage()); } $this->forward(TBGContext::getRouting()->generate('configure_module', array('config_module' => $request->getParameter('config_module')))); } $this->module = $module; } } catch (Exception $e) { TBGLogging::log('Trying to configure module ' . $request->getParameter('config_module') . " which isn't configurable", 'main', TBGLogging::LEVEL_FATAL); TBGContext::setMessage('module_error', TBGContext::getI18n()->__('The module "%module_name%" is not configurable', array('%module_name%' => $request->getParameter('config_module')))); $this->forward(TBGContext::getRouting()->generate('configure_modules')); } $this->module_message = TBGContext::getMessageAndClear('module_message'); $this->module_error = TBGContext::getMessageAndClear('module_error'); $this->module_error_details = TBGContext::getMessageAndClear('module_error_details'); }
/** * Invoke a trigger * * @param string $module The module for which the trigger is active * @param string $identifier The trigger identifier * @param array $params Parameters to pass to the registered listeners * * @return unknown_type */ protected static function _trigger(TBGEvent $event, $return_when_processed = false) { $module = $event->getModule(); $identifier = $event->getIdentifier(); TBGLogging::log("Triggering {$module} - {$identifier}"); if (isset(self::$_registeredlisteners[$module][$identifier])) { foreach (self::$_registeredlisteners[$module][$identifier] as $trigger) { try { $cb_string = is_array($trigger) ? get_class($trigger[0]) . '::' . $trigger[1] : $trigger; TBGLogging::log('Running callback function ' . $cb_string); $retval = call_user_func($trigger, $event); if ($return_when_processed && $event->isProcessed()) { return true; } TBGLogging::log('done (Running callback function ' . $cb_string . ')'); } catch (Exception $e) { throw $e; } } } TBGLogging::log("done (Triggering {$module} - {$identifier})"); }
public static function loadSettings($uid = 0) { TBGLogging::log("Loading settings"); if (self::$_settings === null || $uid > 0 && !array_key_exists($uid, self::$_loadedsettings)) { TBGLogging::log('Loading settings'); if (self::$_settings === null) { self::$_settings = array(); } TBGLogging::log('Settings not cached or install mode enabled. Retrieving from database'); if ($res = \b2db\Core::getTable('TBGSettingsTable')->getSettingsForScope(TBGContext::getScope()->getID(), $uid)) { $cc = 0; while ($row = $res->getNextRow()) { $cc++; self::$_settings[$row->get(TBGSettingsTable::MODULE)][$row->get(TBGSettingsTable::NAME)][$row->get(TBGSettingsTable::UID)] = $row->get(TBGSettingsTable::VALUE); } if ($cc == 0 && !TBGContext::isInstallmode() && $uid == 0) { TBGLogging::log('There were no settings stored in the database!', 'main', TBGLogging::LEVEL_FATAL); throw new TBGSettingsException('Could not retrieve settings from database (no settings stored)'); } } elseif (!TBGContext::isInstallmode() && $uid == 0) { TBGLogging::log('Settings could not be retrieved from the database!', 'main', TBGLogging::LEVEL_FATAL); throw new TBGSettingsException('Could not retrieve settings from database'); } self::$_loadedsettings[$uid] = true; self::$_timezone = new DateTimeZone(self::getServerTimezoneIdentifier()); TBGLogging::log('Retrieved'); } TBGLogging::log("...done"); }
?> <?php TBGLogging::log('done (rendering header)'); ?> <?php } ?> <div id="content_container"> <?php TBGLogging::log('Rendering content'); ?> <?php echo $content; ?> <?php TBGLogging::log('done (rendering content)'); ?> </div> <?php TBGEvent::createNew('core', 'footer_begin')->trigger(); ?> <?php require THEBUGGENIE_CORE_PATH . 'templates/footer.inc.php'; ?> <?php TBGEvent::createNew('core', 'footer_end')->trigger(); ?> </div> <script type="text/javascript"> document.observe('dom:loaded', function() { var f_init = function() {TBG.initialize({ basepath: '<?php
/** * Generate a url based on a route * * @param string $name The route key * @param array $params key=>value pairs of route parameters * @param boolean $relative Whether to generate an url relative to web root or an absolute * * @return string */ public function generate($name, $params = array(), $relative = true, $querydiv = '/', $divider = '/', $equals = '/') { if (mb_substr($name, 0, 1) == '@') { $name = mb_substr($name, 1); $details = explode('?', $name); $name = array_shift($details); if (count($details)) { $param_details = array_shift($details); $param_details = explode('&', $param_details); foreach ($param_details as $detail) { $param_detail = explode('=', $detail); if (count($param_detail) > 1) { $params[$param_detail[0]] = $param_detail[1]; } } } } if (!isset($this->routes[$name])) { TBGLogging::log("The route '{$name}' does not exist", 'routing', TBGLogging::LEVEL_FATAL); throw new Exception("The route '{$name}' does not exist"); } list($url, $regexp, $names, $names_hash, $action, $module, $defaults, $csrf_enabled) = $this->routes[$name]; $defaults = array('action' => $action, 'module' => $module); // all params must be given foreach ($names as $tmp) { if (!isset($params[$tmp]) && !isset($defaults[$tmp])) { throw new Exception(sprintf('Route named "%s" have a mandatory "%s" parameter', $name, $tmp)); } } $params = self::arrayDeepMerge($defaults, $params); if ($csrf_enabled) { $params['csrf_token'] = TBGContext::generateCSRFtoken(); } // in PHP 5.5, preg_replace with /e modifier is deprecated; preg_replace_callback is recommended $callback = function ($matches) use($params) { return array_key_exists($matches[1], $params) ? urlencode($params[$matches[1]]) : $matches[0]; }; $real_url = preg_replace_callback('/\\:([^\\/]+)/', $callback, $url); // we add all other params if * if (mb_strpos($real_url, '*')) { $tmp = array(); foreach ($params as $key => $value) { if (isset($names_hash[$key]) || isset($defaults[$key])) { continue; } if (is_array($value)) { foreach ($value as $k => $v) { if (is_array($v)) { foreach ($v as $vk => $vv) { if (is_array($vv)) { foreach ($vv as $vvk => $vvv) { $tmp[] = "{$key}[{$k}][{$vk}][{$vvk}]" . $equals . urlencode($vvv); } } else { $tmp[] = "{$key}[{$k}][{$vk}]" . $equals . urlencode($vv); } } } else { $tmp[] = "{$key}[{$k}]" . $equals . urlencode($v); } } } else { $tmp[] = urlencode($key) . $equals . urlencode($value); } } $tmp = implode($divider, $tmp); if (mb_strlen($tmp) > 0) { $tmp = $querydiv . $tmp; } $real_url = preg_replace('/\\/\\*(\\/|$)/', "{$tmp}\$1", $real_url); } // strip off last divider character if (mb_strlen($real_url) > 1) { $real_url = rtrim($real_url, $divider); } if (!$relative) { return TBGContext::getURLhost() . TBGContext::getStrippedTBGPath() . $real_url; } return TBGContext::getStrippedTBGPath() . $real_url; }
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); }
TBGLogging::log('Initializing B2DB'); if (!isset($argc)) { B2DB::setHTMLException(true); } B2DB::initialize(THEBUGGENIE_CORE_PATH . 'b2db_bootstrap.inc.php'); TBGLogging::log('...done (Initializing B2DB)'); if (B2DB::isInitialized()) { TBGLogging::log('Database connection details found, connecting'); B2DB::doConnect(); TBGLogging::log('...done (Database connection details found, connecting)'); TBGLogging::log('Adding core table classpath to autoload path'); TBGContext::addClasspath(THEBUGGENIE_CORE_PATH . 'classes' . DS . 'B2DB' . DS); } } catch (Exception $e) { tbg_exception('Could not load and initiate the B2DB subsystem', $e); } TBGLogging::log('...done'); TBGLogging::log('Initializing context'); TBGContext::initialize(); TBGLogging::log('...done'); //require THEBUGGENIE_CORE_PATH . 'common_functions.inc.php'; require THEBUGGENIE_CORE_PATH . 'geshi/geshi.php'; TBGLogging::log('Caspar framework loaded'); } catch (Exception $e) { if (!isset($argc)) { tbg_exception('Exception caught', $e); exit; } else { throw $e; } }
/** * Perform a permission check on this user * * @param string $permission_type The permission key * @param integer $target_id[optional] a target id if applicable * @param string $module_name[optional] the module for which the permission is valid * @param boolean $explicit[optional] whether to check for an explicit permission and return false if not set * @param boolean $permissive[optional] whether to return false or true when explicit fails * * @return boolean */ public function hasPermission($permission_type, $target_id = 0, $module_name = 'core', $explicit = false, $permissive = false) { TBGLogging::log('Checking permission ' . $permission_type); $group_id = $this->getGroup() instanceof TBGGroup ? $this->getGroup()->getID() : 0; $retval = TBGContext::checkPermission($permission_type, $this->getID(), $group_id, $this->getTeams(), $target_id, $module_name, $explicit, $permissive); TBGLogging::log('...done (Checking permissions ' . $permission_type . ') - return was ' . ($retval ? 'true' : 'false')); return $retval; }
/** * Returns an array of issue types * * @param integer $scope_id The ID number of the scope to load issue types from * @return array */ public static function getAll($scope_id = null) { if (self::$_issuetypes === null) { self::$_issuetypes = array(); $crit = TBGIssueTypesTable::getTable()->getCriteria(); if ($scope_id === null) { $crit->addWhere(TBGIssueTypesTable::SCOPE, TBGContext::getScope()->getID()); } else { $crit->addWhere(TBGIssueTypesTable::SCOPE, $scope_id); } $issuetypes = array(); if ($res = TBGIssueTypesTable::getTable()->doSelect($crit, 'none')) { while ($row = $res->getNextRow()) { $issuetypes[$row->get(TBGIssueTypesTable::ID)] = TBGContext::factory()->TBGIssuetype($res->get(TBGIssueTypesTable::ID), $row); } } else { TBGLogging::log('There are no issue types', 'main', TBGLogging::LEVEL_NOTICE); } self::$_issuetypes = $issuetypes; } return self::$_issuetypes; }
protected function _mail(TBGMimemail $email) { if (!$this->no_dash_f) { $retval = mail($email->getRecipientsAsString(), $email->getSubject(), $email->getBodyAsString(), $email->getHeadersAsString(false, false), '-f' . $email->getFromAddress()); } else { $retval = mail($email->getRecipientsAsString(), $email->getSubject(), $email->getBodyAsString(), $email->getHeadersAsString(false, false)); } if ($retval) { TBGLogging::log("Sending email to {$email->getRecipientsAsString()} accepted for delivery OK"); } else { TBGLogging::log("Sending email to {$email->getRecipientsAsString()} not accepted for delivery", TBGLogging::LEVEL_NOTICE); } return $retval; }
/** * 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; }
/** * 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; }
public static function add($key, $value, $prepend_scope = true) { if (!self::isEnabled()) { return false; } switch (self::$_type) { case self::TYPE_APC: $key = self::getScopedKeyIfAppliccable($key, $prepend_scope); apc_store($key, $value); break; case self::TYPE_FILE: default: self::fileAdd($key, $value, $prepend_scope); } if (self::$_logging) { TBGLogging::log('Caching value for key "' . $key . '"', 'cache'); } return true; }
public function runTransitionIssues(TBGRequest $request) { try { try { $transition = TBGContext::factory()->TBGWorkflowTransition($request['transition_id']); } catch (Exception $e) { $this->getResponse()->setHttpStatus(400); return $this->renderJSON(array('error' => $this->getI18n()->__('This is not a valid transition'))); } $issue_ids = $request['issue_ids']; $status = null; $closed = false; foreach ($issue_ids as $issue_id) { $issue = TBGContext::factory()->TBGIssue($issue_id); if (!$issue->isWorkflowTransitionsAvailable() || !$transition->validateFromRequest($request)) { $this->getResponse()->setHttpStatus(400); return $this->renderJSON(array('error' => TBGContext::getI18n()->__('The transition could not be applied to issue %issue_number because of %errors', array('%issue_number' => $issue->getFormattedIssueNo(), '%errors' => join(', ', $transition->getValidationErrors()))))); } try { $transition->transitionIssueToOutgoingStepFromRequest($issue, $request); } catch (Exception $e) { $this->getResponse()->setHttpStatus(400); TBGLogging::log(TBGLogging::LEVEL_WARNING, 'Transition ' . $transition->getID() . ' failed for issue ' . $issue_id); TBGLogging::log(TBGLogging::LEVEL_WARNING, $e->getMessage()); return $this->renderJSON(array('error' => $this->getI18n()->__('The transition failed because of an error in the workflow. Check your workflow configuration.'))); } if ($status === null) { $status = $issue->getStatus(); } $closed = $issue->isClosed(); } TBGContext::loadLibrary('common'); $options = array('issue_ids' => array_keys($issue_ids), 'last_updated' => tbg_formatTime(time(), 20), 'closed' => $closed); $options['status'] = array('color' => $status->getColor(), 'name' => $status->getName(), 'id' => $status->getID()); if ($request->hasParameter('milestone_id')) { $milestone = new TBGMilestone($request['milestone_id']); $options['milestone_id'] = $milestone->getID(); $options['milestone_name'] = $milestone->getName(); } foreach (array('resolution', 'priority', 'category', 'severity') as $item) { $class = "TBG" . ucfirst($item); if ($request->hasParameter($item . '_id')) { if ($item_id = $request[$item . '_id']) { $itemobject = new $class($item_id); $itemname = $itemobject->getName(); } else { $item_id = 0; $itemname = '-'; } $options[$item] = array('name' => $itemname, 'id' => $item_id); } else { $method = 'get' . ucfirst($item); $itemname = $issue->{$method}() instanceof $class ? $issue->{$method}()->getName() : '-'; $item_id = $issue->{$method}() instanceof $class ? $issue->{$method}()->getID() : 0; $options[$item] = array('name' => $itemname, 'id' => $item_id); } } return $this->renderJSON($options); } catch (Exception $e) { $this->getResponse()->setHttpStatus(400); TBGLogging::log(TBGLogging::LEVEL_WARNING, 'Transition ' . $transition->getID() . ' failed for issue ' . $issue_id); TBGLogging::log(TBGLogging::LEVEL_WARNING, $e->getMessage()); return $this->renderJSON(array('error' => $this->getI18n()->__('An error occured when trying to apply the transition'))); } }
public function doLogin($username, $password, $mode = 1) { $validgroups = $this->getSetting('groups'); $base_dn = $this->getSetting('b_dn'); $dn_attr = $this->escape($this->getSetting('dn_attr')); $username_attr = $this->escape($this->getSetting('u_attr')); $fullname_attr = $this->escape($this->getSetting('f_attr')); $buddyname_attr = $this->escape($this->getSetting('b_attr')); $email_attr = $this->escape($this->getSetting('e_attr')); $groups_members_attr = $this->escape($this->getSetting('g_attr')); $user_class = TBGContext::getModule('auth_ldap')->getSetting('u_type'); $group_class = TBGContext::getModule('auth_ldap')->getSetting('g_type'); $email = null; $integrated_auth = $this->getSetting('integrated_auth'); /* * Do the LDAP check here. * * If a connection error or something, throw an exception and log * * If we can, set $mail and $realname to correct values from LDAP * otherwise don't touch those variables. * * To log do: * TBGLogging::log('error goes here', 'ldap', TBGLogging::LEVEL_FATAL); */ try { /* * First job is to connect to our control user (may be an anonymous bind) * so we can find the user we want to log in as/validate. */ $connection = $this->connect(); $control_user = $this->getSetting('control_user'); $control_password = $this->getSetting('control_pass'); $this->bind($connection, $control_user, $control_password); // Assume bind successful, otherwise we would have had an exception /* * Search for a user with the username specified. We search in the base_dn, so we can * find users in multiple parts of the directory, and only return users of a specific * class (default person). * * We want exactly 1 user to be returned. We get the user's full name, email, cn * and dn. */ $fields = array($fullname_attr, $buddyname_attr, $email_attr, 'cn', $dn_attr); $filter = '(&(objectClass=' . TBGLDAPAuthentication::getModule()->escape($user_class) . ')(' . $username_attr . '=' . $this->escape($username) . '))'; $results = ldap_search($connection, $base_dn, $filter, $fields); if (!$results) { TBGLogging::log('failed to search for user: '******'ldap', TBGLogging::LEVEL_FATAL); throw new Exception(TBGContext::geti18n()->__('Search failed: ') . ldap_error($connection)); } $data = ldap_get_entries($connection, $results); // User does not exist if ($data['count'] == 0) { TBGLogging::log('could not find user ' . $username . ', class ' . $user_class . ', attribute ' . $username_attr, 'ldap', TBGLogging::LEVEL_FATAL); throw new Exception(TBGContext::geti18n()->__('User does not exist in the directory')); } // If we have more than 1 user, something is seriously messed up... if ($data['count'] > 1) { TBGLogging::log('too many users for ' . $username . ', class ' . $user_class . ', attribute ' . $username_attr, 'ldap', TBGLogging::LEVEL_FATAL); throw new Exception(TBGContext::geti18n()->__('This user was found multiple times in the directory, please contact your admimistrator')); } /* * If groups are specified, perform group restriction tests */ if ($validgroups != '') { /* * We will repeat this for every group, but groups are supplied as a comma-separated list */ if (strstr($validgroups, ',')) { $groups = explode(',', $validgroups); } else { $groups = array(); $groups[] = $validgroups; } // Assumed we are initially banned $allowed = false; foreach ($groups as $group) { // No need to carry on looking if we have access if ($allowed == true) { continue; } /* * Find the group we are looking for, we search the entire directory as per users (See that stuff) * We want to find 1 group, if we don't get 1, silently ignore this group. */ $fields2 = array($groups_members_attr); $filter2 = '(&(objectClass=' . TBGLDAPAuthentication::getModule()->escape($group_class) . ')(cn=' . $this->escape($group) . '))'; $results2 = ldap_search($connection, $base_dn, $filter2, $fields2); if (!$results2) { TBGLogging::log('failed to search for user after binding: ' . ldap_error($connection), 'ldap', TBGLogging::LEVEL_FATAL); throw new Exception(TBGContext::geti18n()->__('Search failed ') . ldap_error($connection)); } $data2 = ldap_get_entries($connection, $results2); if ($data2['count'] != 1) { continue; } /* * Look through the group's member list. If we are found, grant access. */ foreach ($data2[0][strtolower($groups_members_attr)] as $member) { $member = preg_replace('/(?<=,) +(?=[a-zA-Z])/', '', $member); $user_dn = preg_replace('/(?<=,) +(?=[a-zA-Z])/', '', $data[0][strtolower($dn_attr)][0]); if (!is_numeric($member) && strtolower($member) == strtolower($user_dn)) { $allowed = true; } } } if ($allowed == false) { throw new Exception(TBGContext::getI18n()->__('You are not a member of a group allowed to log in')); } } /* * Set user's properties. * Realname is obtained from directory, if not found we set it to the username * Email is obtained from directory, if not found we set it to blank */ if (!array_key_exists(strtolower($fullname_attr), $data[0])) { $realname = $username; } else { $realname = $data[0][strtolower($fullname_attr)][0]; } if (!array_key_exists(strtolower($buddyname_attr), $data[0])) { $buddyname = $username; } else { $buddyname = $data[0][strtolower($buddyname_attr)][0]; } if (!array_key_exists(strtolower($email_attr), $data[0])) { $email = ''; } else { $email = $data[0][strtolower($email_attr)][0]; } /* * If we are performing a non integrated authentication login, * now bind to the user and see if the credentials * are valid. We bind using the full DN of the user, so no need for DOMAIN\ stuff * on Windows, and more importantly it fixes other servers. * * If the bind fails (exception), we throw a nicer exception and don't continue. */ if ($mode == 1 && !$integrated_auth) { try { if (!is_array($data[0][strtolower($dn_attr)])) { $dn = $data[0][strtolower($dn_attr)]; } else { $dn = $data[0][strtolower($dn_attr)][0]; } $bind = $this->bind($connection, $this->escape($dn), $password); } catch (Exception $e) { throw new Exception(TBGContext::geti18n()->__('Your password was not accepted by the server')); } } elseif ($mode == 1) { if (!isset($_SERVER[$this->getSetting('integrated_auth_header')]) || $_SERVER[$this->getSetting('integrated_auth_header')] != $username) { throw new Exception(TBGContext::geti18n()->__('HTTP authentication internal error.')); } } } catch (Exception $e) { ldap_unbind($connection); throw $e; } try { /* * Get the user object. If the user exists, update the user's * data from the directory. */ $user = TBGUser::getByUsername($username); if ($user instanceof TBGUser) { $user->setBuddyname($buddyname); $user->setRealname($realname); $user->setPassword($user->getJoinedDate() . $username); // update password $user->setEmail($email); // update email address $user->save(); } else { /* * If not, and we are performing an initial login, create the user object * if we are validating a log in, kick the user out as the session is invalid. */ if ($mode == 1) { // create user $user = new TBGUser(); $user->setUsername($username); $user->setRealname('temporary'); $user->setBuddyname($username); $user->setEmail('temporary'); $user->setEnabled(); $user->setActivated(); $user->setJoined(); $user->setPassword($user->getJoinedDate() . $username); $user->save(); } else { throw new Exception('User does not exist in TBG'); } } } catch (Exception $e) { ldap_unbind($connection); throw $e; } ldap_unbind($connection); /* * Set cookies and return user row for general operations. */ TBGContext::getResponse()->setCookie('tbg3_username', $username); TBGContext::getResponse()->setCookie('tbg3_password', TBGUser::hashPassword($user->getJoinedDate() . $username, $user->getSalt())); return TBGUsersTable::getTable()->getByUsername($username); }
/** * Performs a query, then returns a resultset * * @param string $action[optional] The crud action performed (select, insert, update, delete, create, alter) * * @return Resultset */ public function performQuery($action = '') { try { $values = $this->getCriteria() instanceof Criteria ? $this->getCriteria()->getValues() : array(); \TBGLogging::log('executing PDO query (' . Core::getSQLCount() . ') - ' . ($this->getCriteria() instanceof Criteria ? $this->getCriteria()->action : 'unknown'), 'B2DB'); $time = explode(' ', microtime()); $pretime = $time[1] + $time[0]; $res = $this->statement->execute($values); if (!$res) { $error = $this->statement->errorInfo(); if (Core::isDebugMode()) { $time = explode(' ', microtime()); $posttime = $time[1] + $time[0]; Core::sqlHit($this->printSQL(), implode(', ', $values), $posttime - $pretime); } throw new Exception($error[2], $this->printSQL()); } if (Core::isDebugMode()) { \TBGLogging::log('done', 'B2DB'); } if ($this->getCriteria() instanceof Criteria && $this->getCriteria()->action == 'insert') { if (Core::getDBtype() == 'mysql') { $this->insert_id = Core::getDBLink()->lastInsertId(); } elseif (Core::getDBtype() == 'pgsql') { \TBGLogging::log('sequence: ' . Core::getTablePrefix() . $this->getCriteria()->getTable()->getB2DBName() . '_id_seq', 'b2db'); $this->insert_id = Core::getDBLink()->lastInsertId(Core::getTablePrefix() . $this->getCriteria()->getTable()->getB2DBName() . '_id_seq'); \TBGLogging::log('id is: ' . $this->insert_id, 'b2db'); } } $action = $this->getCriteria() instanceof Criteria ? $this->getCriteria()->action : ''; $retval = new Resultset($this); if (Core::isDebugMode()) { $time = explode(' ', microtime()); $posttime = $time[1] + $time[0]; Core::sqlHit($this->printSQL(), implode(', ', $values), $posttime - $pretime); } if (!$this->getCriteria() || $this->getCriteria()->action != 'select') { $this->statement->closeCursor(); } return $retval; } catch (\Exception $e) { throw $e; } }
public function log($message, $level = 1) { TBGLogging::log($message, $this->getName(), $level); }
protected static function generateDebugInfo() { $tbg_summary = array(); $load_time = self::getLoadtime(); if (\b2db\Core::isInitialized()) { $tbg_summary['db']['queries'] = \b2db\Core::getSQLHits(); $tbg_summary['db']['timing'] = \b2db\Core::getSQLTiming(); } $tbg_summary['load_time'] = $load_time >= 1 ? round($load_time, 2) . 's' : round($load_time * 1000, 1) . 'ms'; $tbg_summary['scope'] = array(); $scope = self::getScope(); $tbg_summary['scope']['id'] = $scope instanceof TBGScope ? $scope->getID() : 'unknown'; $tbg_summary['scope']['hostnames'] = $scope instanceof TBGScope && \b2db\Core::isConnected() ? implode(', ', $scope->getHostnames()) : 'unknown'; $tbg_summary['settings'] = TBGSettings::getAll(); $tbg_summary['memory'] = memory_get_usage(); $tbg_summary['partials'] = self::getVisitedPartials(); if (self::$_i18n instanceof TBGI18n) { foreach (self::getI18n()->getMissingStrings() as $text => $value) { TBGLogging::log('The text "' . $text . '" does not exist in list of translated strings, and was added automatically', 'i18n', TBGLogging::LEVEL_NOTICE); } } $tbg_summary['log'] = TBGLogging::getEntries(); $tbg_summary['routing'] = array('name' => self::getRouting()->getCurrentRouteName(), 'module' => self::getRouting()->getCurrentRouteModule(), 'action' => self::getRouting()->getCurrentRouteAction()); if (isset($_SESSION)) { if (!array_key_exists('___DEBUGINFO___', $_SESSION)) { $_SESSION['___DEBUGINFO___'] = array(); } $_SESSION['___DEBUGINFO___'][self::$debug_id] = $tbg_summary; while (count($_SESSION['___DEBUGINFO___']) > 10) { array_shift($_SESSION['___DEBUGINFO___']); } } }
/** * Import all valid users * * @param TBGRequest $request */ public function runImportUsers(TBGRequest $request) { $validgroups = TBGContext::getModule('auth_ldap')->getSetting('groups'); $base_dn = TBGContext::getModule('auth_ldap')->getSetting('b_dn'); $dn_attr = TBGContext::getModule('auth_ldap')->getSetting('dn_attr'); $username_attr = TBGContext::getModule('auth_ldap')->getSetting('u_attr'); $fullname_attr = TBGContext::getModule('auth_ldap')->getSetting('f_attr'); $buddyname_attr = TBGContext::getModule('auth_ldap')->getSetting('b_attr'); $email_attr = TBGContext::getModule('auth_ldap')->getSetting('e_attr'); $groups_members_attr = TBGContext::getModule('auth_ldap')->getSetting('g_attr'); $user_class = TBGContext::getModule('auth_ldap')->getSetting('u_type'); $group_class = TBGContext::getModule('auth_ldap')->getSetting('g_type'); $users = array(); $importcount = 0; $updatecount = 0; try { /* * Connect and bind to the control user */ $connection = TBGContext::getModule('auth_ldap')->connect(); TBGContext::getModule('auth_ldap')->bind($connection, TBGContext::getModule('auth_ldap')->getSetting('control_user'), TBGContext::getModule('auth_ldap')->getSetting('control_pass')); /* * Get a list of all users of a certain objectClass */ $fields = array($fullname_attr, $buddyname_attr, $username_attr, $email_attr, 'cn', $dn_attr); $filter = '(objectClass=' . TBGLDAPAuthentication::getModule()->escape($user_class) . ')'; $results = ldap_search($connection, $base_dn, $filter, $fields); if (!$results) { TBGLogging::log('failed to search for users: ' . ldap_error($connection), 'ldap', TBGLogging::LEVEL_FATAL); throw new Exception(TBGContext::geti18n()->__('Search failed: ') . ldap_error($connection)); } $data = ldap_get_entries($connection, $results); /* * For every user that exists, process it. */ for ($i = 0; $i != $data['count']; $i++) { $user_dn = $data[$i][strtolower($dn_attr)][0]; /* * If groups are specified, perform group restriction tests */ if ($validgroups != '') { /* * We will repeat this for every group, but groups are supplied as a comma-separated list */ if (strstr($validgroups, ',')) { $groups = explode(',', $validgroups); } else { $groups = array(); $groups[] = $validgroups; } // Assumed we are initially banned $allowed = false; foreach ($groups as $group) { // No need to carry on looking if we have access if ($allowed == true) { continue; } /* * Find the group we are looking for, we search the entire directory * We want to find 1 group, if we don't get 1, silently ignore this group. */ $fields2 = array($groups_members_attr); $filter2 = '(&(cn=' . TBGLDAPAuthentication::getModule()->escape($group) . ')(objectClass=' . TBGLDAPAuthentication::getModule()->escape($group_class) . '))'; $results2 = ldap_search($connection, $base_dn, $filter2, $fields2); if (!$results2) { TBGLogging::log('failed to search for user: '******'ldap', TBGLogging::LEVEL_FATAL); throw new Exception(TBGContext::geti18n()->__('Search failed: ') . ldap_error($connection)); } $data2 = ldap_get_entries($connection, $results2); if ($data2['count'] != 1) { continue; } /* * Look through the group's member list. If we are found, grant access. */ foreach ($data2[0][strtolower($groups_members_attr)] as $member) { $member = preg_replace('/(?<=,) +(?=[a-zA-Z])/', '', $member); $user_dn = preg_replace('/(?<=,) +(?=[a-zA-Z])/', '', $user_dn); if (!is_numeric($member) && strtolower($member) == strtolower($user_dn)) { $allowed = true; } } } if ($allowed == false) { continue; } } $users[$i] = array(); /* * Set user's properties. * Realname is obtained from directory, if not found we set it to the username * Email is obtained from directory, if not found we set it to blank */ if (!array_key_exists(strtolower($fullname_attr), $data[$i])) { $users[$i]['realname'] = $data[$i]['cn'][0]; } else { $users[$i]['realname'] = $data[$i][strtolower($fullname_attr)][0]; } if (!array_key_exists(strtolower($buddyname_attr), $data[$i])) { $users[$i]['buddyname'] = $data[$i]['cn'][0]; } else { $users[$i]['buddyname'] = $data[$i][strtolower($buddyname_attr)][0]; } if (!array_key_exists(strtolower($email_attr), $data[$i])) { $users[$i]['email'] = ''; } else { $users[$i]['email'] = $data[$i][strtolower($email_attr)][0]; } $users[$i]['username'] = $data[$i][strtolower($username_attr)][0]; } } catch (Exception $e) { TBGContext::setMessage('module_error', TBGContext::getI18n()->__('Import failed')); TBGContext::setMessage('module_error_details', $e->getMessage()); $this->forward(TBGContext::getRouting()->generate('configure_module', array('config_module' => 'auth_ldap'))); } /* * For every user that was found, either create a new user object, or update * the existing one. This will update the created and updated counts as appropriate. */ foreach ($users as $ldapuser) { $username = $ldapuser['username']; $email = $ldapuser['email']; $realname = $ldapuser['realname']; $buddyname = $ldapuser['buddyname']; try { $user = TBGUser::getByUsername($username); if ($user instanceof TBGUser) { $user->setRealname($realname); $user->setEmail($email); // update email address $user->save(); $updatecount++; } else { // create user $user = new TBGUser(); $user->setUsername($username); $user->setRealname($realname); $user->setBuddyname($buddyname); $user->setEmail($email); $user->setEnabled(); $user->setActivated(); $user->setPassword($user->getJoinedDate() . $username); $user->setJoined(); $user->save(); $importcount++; } } catch (Exception $e) { ldap_unbind($connection); TBGContext::setMessage('module_error', TBGContext::getI18n()->__('Import failed')); TBGContext::setMessage('module_error_details', $e->getMessage()); $this->forward(TBGContext::getRouting()->generate('configure_module', array('config_module' => 'auth_ldap'))); } } ldap_unbind($connection); TBGContext::setMessage('module_message', TBGContext::getI18n()->__('Import successful! %imp users imported, %upd users updated from LDAP', array('%imp' => $importcount, '%upd' => $updatecount))); $this->forward(TBGContext::getRouting()->generate('configure_module', array('config_module' => 'auth_ldap'))); }
/** * Runs the action for the fourth step of the installation * where it loads fixtures and saves settings for url * * @param TBGRequest $request The request object * * @return null */ public function runInstallStep4(TBGRequest $request) { try { TBGLogging::log('Initializing language support'); TBGContext::reinitializeI18n('en_US'); TBGLogging::log('Loading fixtures for default scope'); $scope = new TBGScope(); $scope->addHostname('*'); $scope->setName('The default scope'); $scope->setEnabled(true); TBGContext::setScope($scope); $scope->save(); TBGLogging::log('Setting up default users and groups'); TBGSettings::saveSetting('language', 'en_US', 'core', 1); $this->htaccess_error = false; $this->htaccess_ok = (bool) $request->getParameter('apache_autosetup'); if ($request->getParameter('apache_autosetup')) { if (!is_writable(THEBUGGENIE_PATH . THEBUGGENIE_PUBLIC_FOLDER_NAME . '/') || file_exists(THEBUGGENIE_PATH . THEBUGGENIE_PUBLIC_FOLDER_NAME . '/.htaccess') && !is_writable(THEBUGGENIE_PATH . THEBUGGENIE_PUBLIC_FOLDER_NAME . '/.htaccess')) { $this->htaccess_error = 'Permission denied when trying to save the [main folder]/' . THEBUGGENIE_PUBLIC_FOLDER_NAME . '/.htaccess'; } else { $content = str_replace('###PUT URL SUBDIRECTORY HERE###', $request->getParameter('url_subdir'), file_get_contents(THEBUGGENIE_CORE_PATH . '/templates/htaccess.template')); file_put_contents(THEBUGGENIE_PATH . THEBUGGENIE_PUBLIC_FOLDER_NAME . '/.htaccess', $content); if (file_get_contents(THEBUGGENIE_PATH . THEBUGGENIE_PUBLIC_FOLDER_NAME . '/.htaccess') != $content) { $this->htaccess_error = true; } } } } catch (Exception $e) { $this->error = $e->getMessage(); throw $e; } }
/** * Launches the MVC framework */ public static function go() { TBGLogging::log('Dispatching'); try { if (($route = self::getRouting()->getRouteFromUrl(self::getRequest()->getParameter('url', null, false))) || self::isInstallmode()) { if (self::isUpgrademode()) { $route = array('module' => 'installation', 'action' => 'upgrade'); } elseif (self::isInstallmode()) { $route = array('module' => 'installation', 'action' => 'installIntro'); } if (self::$_redirect_login) { TBGLogging::log('An error occurred setting up the user object, redirecting to login', 'main', TBGLogging::LEVEL_NOTICE); self::getResponse()->headerRedirect(self::getRouting()->generate('login_redirect'), 403); } if (is_dir(THEBUGGENIE_MODULES_PATH . $route['module'])) { if (!file_exists(THEBUGGENIE_MODULES_PATH . $route['module'] . DS . 'classes' . DS . 'actions.class.php')) { throw new TBGActionNotFoundException('The ' . $route['module'] . ' module is missing the classes/actions.class.php file, containing all the module actions'); } if (!class_exists($route['module'] . 'Actions') && !class_exists($route['module'] . 'ActionComponents')) { self::addClasspath(THEBUGGENIE_MODULES_PATH . $route['module'] . DS . 'classes' . DS); } if (self::performAction($route['module'], $route['action'])) { if (B2DB::isInitialized()) { B2DB::closeDBLink(); } return true; } } else { throw new Exception('Cannot load the ' . $route['module'] . ' module'); return; } } else { require THEBUGGENIE_MODULES_PATH . 'main' . DS . 'classes' . DS . 'actions.class.php'; self::performAction('main', 'notFound'); } } catch (TBGTemplateNotFoundException $e) { B2DB::closeDBLink(); TBGContext::setLoadedAt(); header("HTTP/1.0 404 Not Found", true, 404); tbg_exception($e->getMessage(), $e); } catch (TBGActionNotFoundException $e) { B2DB::closeDBLink(); TBGContext::setLoadedAt(); header("HTTP/1.0 404 Not Found", true, 404); tbg_exception('Module action "' . $route['action'] . '" does not exist for module "' . $route['module'] . '"', $e); } catch (TBGCSRFFailureException $e) { B2DB::closeDBLink(); TBGContext::setLoadedAt(); self::$_response->setHttpStatus(301); $message = $e->getMessage(); if (self::getRequest()->getRequestedFormat() == 'json') { self::$_response->setContentType('application/json'); $message = json_encode(array('message' => $message)); } self::$_response->renderHeaders(); echo $message; } catch (Exception $e) { B2DB::closeDBLink(); TBGContext::setLoadedAt(); header("HTTP/1.0 404 Not Found", true, 404); tbg_exception('An error occured', $e); } }