Ejemplo n.º 1
0
 /**
  * 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);
 }
Ejemplo n.º 2
0
 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;
 }
Ejemplo n.º 3
0
 /**
  * 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;
 }
Ejemplo n.º 4
0
 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)');
 }
Ejemplo n.º 6
0
 /**
  * Send a test email
  *
  * @param TBGRequest $request
  */
 public function runTestEmail(TBGRequest $request)
 {
     if ($email_to = $request->getParameter('test_email_to')) {
         try {
             if (TBGMailing::getModule()->sendTestEmail($email_to)) {
                 TBGContext::setMessage('module_message', TBGContext::getI18n()->__('The email was successfully accepted for delivery'));
             } else {
                 TBGContext::setMessage('module_error', TBGContext::getI18n()->__('The email was not sent'));
                 TBGContext::setMessage('module_error_details', TBGLogging::getMessagesForCategory('mailing', TBGLogging::LEVEL_NOTICE));
             }
         } catch (Exception $e) {
             TBGContext::setMessage('module_error', TBGContext::getI18n()->__('The email was not sent'));
             TBGContext::setMessage('module_error_details', $e->getMessage());
         }
     } else {
         TBGContext::setMessage('module_error', TBGContext::getI18n()->__('Please specify an email address'));
     }
     $this->forward(TBGContext::getRouting()->generate('configure_module', array('config_module' => 'mailing')));
 }
Ejemplo n.º 7
0
 /**
  * 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;
 }
Ejemplo n.º 8
0
 /**
  * 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;
 }
Ejemplo n.º 9
0
/**
 * 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>&nbsp;&nbsp;{$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>&nbsp;&nbsp;{$entry['message']}</div>";
            }
        }
    }
    echo "\n\t\t\t</div>\n\t\t</body>\n\t\t</html>\n\t\t";
    die;
}
Ejemplo n.º 10
0
 /**
  * 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');
 }
Ejemplo n.º 11
0
 /**
  * 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})");
 }
Ejemplo n.º 12
0
				</ul>
			<?php 
}
?>
			<?php 
if (class_exists("TBGContext") && class_exists("TBGLogging") && TBGContext::isDebugMode() && (!isset($exception) || !$exception instanceof TBGComposerException)) {
    ?>
				<h3>Log messages:</h3>
				<?php 
    foreach (TBGLogging::getEntries() as $entry) {
        ?>
					<?php 
        $color = TBGLogging::getCategoryColor($entry['category']);
        ?>
					<?php 
        $lname = TBGLogging::getLevelName($entry['level']);
        ?>
					<div class="log_<?php 
        echo $entry['category'];
        ?>
"><strong><?php 
        echo $lname;
        ?>
</strong> <strong style="color: #<?php 
        echo $color;
        ?>
">[<?php 
        echo $entry['category'];
        ?>
]</strong> <span style="color: #555; font-size: 10px; font-style: italic;"><?php 
        echo $entry['time'];
Ejemplo n.º 13
0
 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");
 }
Ejemplo n.º 14
0
 public function log($message, $level = 1)
 {
     TBGLogging::log($message, $this->getName(), $level);
 }
Ejemplo n.º 15
0
 /**
  * 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;
     }
 }
Ejemplo n.º 16
0
 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;
 }
Ejemplo n.º 17
0
 /**
  * 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;
 }
Ejemplo n.º 18
0
 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);
 }
Ejemplo n.º 19
0
    ?>
				<?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 
Ejemplo n.º 20
0
 /**
  * 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')));
 }
Ejemplo n.º 21
0
 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')));
     }
 }
Ejemplo n.º 22
0
<br>
		<a href="http://www.opensource.org/licenses/mozilla1.1.php"><?php 
echo __('Read the license (MPL 1.1 only)');
?>
</a>
	<?php 
if ($tbg_user->canAccessConfigurationPage()) {
    ?>
        | <b><?php 
    echo link_tag(make_url('configure'), __('Configure %thebuggenie_name', array('%thebuggenie_name' => TBGSettings::getTBGname())));
    ?>
</b>
	<?php 
}
?>
	<?php 
if (TBGContext::isDebugMode() && TBGLogging::isEnabled()) {
    ?>
		<div id="tbg___DEBUGINFO___" style="position: fixed; bottom: 0; left: 0; z-index: 100; display: none; width: 100%;">
		</div>
		<?php 
    echo image_tag('spinning_16.gif', array('style' => 'position: fixed; bottom: 5px; right: 23px;', 'id' => 'tbg___DEBUGINFO___indicator'));
    ?>
		<?php 
    echo image_tag('debug_show.png', array('style' => 'position: fixed; bottom: 5px; right: 3px; cursor: pointer;', 'onclick' => "\$('tbg___DEBUGINFO___').toggle();", 'title' => 'Show debug bar'));
    ?>
	<?php 
}
?>
</footer>
Ejemplo n.º 23
0
 /**
  * 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;
     }
 }
Ejemplo n.º 24
0
 /**
  * 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);
     }
 }
Ejemplo n.º 25
0
 public static function setCLIDebug($value = true)
 {
     self::$_cli_log_to_screen_in_debug_mode = $value;
 }
Ejemplo n.º 26
0
 /**
  * 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)');
     }
 }
Ejemplo n.º 27
0
 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;
 }
Ejemplo n.º 28
0
 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;
 }
Ejemplo n.º 29
0
 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;
 }
Ejemplo n.º 30
0
 /**
  * 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;
 }