function phoromatic_webui_right_panel_logged_in($add = null)
{
    $right = null;
    if ($_SESSION['AdminLevel'] == -40) {
        $right .= '<h3>Phoromatic Server</h3><hr /><p><strong>' . date('H:i T - j F Y') . '</p>';
    } else {
        if ($_SESSION['AdminLevel'] > 0) {
            $right .= '<a href="#" onclick="javascript:phoromatic_generate_comparison(\'?result/\');"><div id="phoromatic_result_compare_info_box"></div></a> <a href="#" onclick="javascript:phoromatic_delete_results(\'?results/delete/\'); return false;"><div id="phoromatic_result_delete_box">Delete Selected Results</div></a>';
            if (($bad_systems = phoromatic_server::systems_appearing_down()) != false) {
                $right .= '<ul><li><span class="alert">Systems Needing Attention</span></li>';
                foreach ($bad_systems as $system) {
                    $right .= '<li><a href="?systems/' . $system . '">' . phoromatic_server::system_id_to_name($system) . '</a></li>';
                }
                $right .= '</ul><hr />';
            }
            $right .= $add;
            if ($add == null) {
                $recently_active_systems = phoromatic_server::recently_active_systems($_SESSION['AccountID']);
                if (!empty($recently_active_systems)) {
                    $right .= '<ul><li>Recently Active Systems</li>';
                    foreach ($recently_active_systems as &$row) {
                        $right .= '<li><a href="?systems/' . $row['SystemID'] . '">' . $row['Title'] . '</a></li>';
                    }
                    $right .= '</ul><hr />';
                }
                $right .= '
				<ul>
					<li>Today\'s Scheduled Events</li>';
                $stmt = phoromatic_server::$db->prepare('SELECT Title, ScheduleID, RunAt FROM phoromatic_schedules WHERE AccountID = :account_id AND State >= 1  AND ActiveOn LIKE :active_on ORDER BY RunAt,Title ASC');
                $stmt->bindValue(':account_id', $_SESSION['AccountID']);
                $stmt->bindValue(':active_on', '%' . (date('N') - 1) . '%');
                $result = $stmt->execute();
                $row = $result->fetchArray();
                if ($row == false) {
                    $right .= '</ul><p style="text-align: left; margin: 6px 10px;">No Events Found</p>';
                } else {
                    do {
                        $right .= '<li>' . $row['RunAt'] . ' <a href="?schedules/' . $row['ScheduleID'] . '">' . $row['Title'] . '</a></li>';
                    } while ($row = $result->fetchArray());
                    $right .= '</ul>';
                }
            }
            $system_count = phoromatic_account_system_count();
            $schedule_count = phoromatic_account_schedule_count();
            $stmt = phoromatic_server::$db->prepare('SELECT COUNT(UploadID) AS ResultCount FROM phoromatic_results WHERE AccountID = :account_id');
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $result = $stmt->execute();
            $row = $result->fetchArray();
            $result_count = $row['ResultCount'];
            $stmt = phoromatic_server::$db->prepare('SELECT COUNT(ActivityTime) AS ActivityCount FROM phoromatic_activity_stream WHERE AccountID = :account_id AND ActivityTime LIKE :today_date');
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $stmt->bindValue(':today_date', date('Y-m-d') . '%');
            $result = $stmt->execute();
            $row = $result->fetchArray();
            $activity_count = $row['ActivityCount'];
            $group_name = phoromatic_account_id_to_group_name($_SESSION['AccountID']);
            if ($group_name != null) {
                $group_name = '<strong>' . $group_name . '</strong><br />';
            }
            $right .= '<hr /><p><strong>' . date('H:i T - j F Y') . '</strong><br />' . $group_name . '<a href="?systems">' . $system_count . ' System' . ($system_count == 1 ? '' : 's') . '</a><br /><a href="?schedules">' . $schedule_count . ' Schedule' . ($schedule_count == 1 ? '' : 's') . '</a><br /><a href="?results">' . $result_count . ' Result' . ($result_count == 1 ? '' : 's') . '</a>';
            $right .= ' <a href="/rss.php?user='******'UserID'] . '&amp;v=' . sha1($_SESSION['CreatedOn']) . '"><img src="images/rss.png" /></a>';
            $right .= '<br /><a href="?account_activity">' . $activity_count . ' Activity Events Today</a></p>';
        }
    }
    return $right;
}
    public static function render_page_process($PATH)
    {
        $main = null;
        if (isset($PATH[0])) {
            $upload_ids = explode(',', $PATH[0]);
            foreach ($upload_ids as $i => $upload_id) {
                if (isset($upload_id[5]) && substr($upload_id, 0, 2) == 'S:') {
                    $t = explode(':', $upload_id);
                    $stmt = phoromatic_server::$db->prepare('SELECT UploadID, UploadTime FROM phoromatic_results WHERE AccountID = :account_id AND ScheduleID = :schedule_id ORDER BY UploadTime DESC');
                    $stmt->bindValue(':account_id', $_SESSION['AccountID']);
                    $stmt->bindValue(':schedule_id', $t[1]);
                    $test_result_result = $stmt->execute();
                    $cutoff_time = is_numeric($t[2]) ? strtotime('today -' . $t[2] . ' days') : false;
                    while ($test_result_row = $test_result_result->fetchArray()) {
                        if ($cutoff_time !== false && strtotime($test_result_row['UploadTime']) < $cutoff_time) {
                            break;
                        }
                        $upload_ids[] = $test_result_row['UploadID'];
                    }
                    unset($upload_ids[$i]);
                }
            }
            $upload_ids = array_unique($upload_ids);
            $result_files = array();
            $display_rows = array();
            $system_types = array();
            $schedule_types = array();
            $trigger_types = array();
            $upload_times = array();
            $benchmark_tickets = array();
            $xml_result_hash = array();
            $tickets = array();
            foreach ($upload_ids as $id) {
                $result_share_opt = phoromatic_server::read_setting('force_result_sharing') ? '1 = 1' : 'AccountID = (SELECT AccountID FROM phoromatic_account_settings WHERE LetOtherGroupsViewResults = "1" AND AccountID = phoromatic_results.AccountID)';
                $stmt = phoromatic_server::$db->prepare('SELECT * FROM phoromatic_results WHERE PPRID = :pprid AND (AccountID = :account_id OR ' . $result_share_opt . ') LIMIT 1');
                $stmt->bindValue(':pprid', $id);
                $stmt->bindValue(':account_id', $_SESSION['AccountID']);
                $result = $stmt->execute();
                $row = $result->fetchArray();
                if (false && empty($row)) {
                    // TODO XXX
                    // XXX this code is ultimately dead
                    $stmt = phoromatic_server::$db->prepare('SELECT * FROM phoromatic_results WHERE AccountID = :account_id AND UploadID = :upload_id LIMIT 1');
                    $stmt->bindValue(':account_id', $_SESSION['AccountID']);
                    $stmt->bindValue(':upload_id', $id);
                    $result = $stmt->execute();
                    $row = $result->fetchArray();
                }
                if (empty($row)) {
                    continue;
                }
                $composite_xml = phoromatic_server::phoromatic_account_result_path($row['AccountID'], $row['UploadID']) . 'composite.xml';
                if (!is_file($composite_xml)) {
                    echo 'File Not Found: ' . $composite_xml;
                    return false;
                }
                $display_rows[$composite_xml] = $row;
                pts_arrays::unique_push($benchmark_tickets, $row['BenchmarkTicketID']);
                pts_arrays::unique_push($upload_times, $row['UploadTime']);
                pts_arrays::unique_push($xml_result_hash, $row['XmlUploadHash']);
                pts_arrays::unique_push($system_types, $row['SystemID']);
                pts_arrays::unique_push($schedule_types, $row['ScheduleID']);
                pts_arrays::unique_push($trigger_types, $row['Trigger']);
                pts_arrays::unique_push($tickets, $row['BenchmarkTicketID']);
                // Update view counter
                $stmt_view = phoromatic_server::$db->prepare('UPDATE phoromatic_results SET TimesViewed = (TimesViewed + 1) WHERE AccountID = :account_id AND UploadID = :upload_id');
                $stmt_view->bindValue(':account_id', $_SESSION['AccountID']);
                $stmt_view->bindValue(':upload_id', $row['UploadID']);
                $stmt_view->execute();
            }
            $result_file_title = null;
            if (count($system_types) == 1) {
                $result_file_title = phoromatic_system_id_to_name($system_types[0]) . ' Tests';
            }
            if (!empty($tickets) && $tickets[0] != null) {
                $system_name_format = 'ORIGINAL_DATA';
            } else {
                if (count($trigger_types) == 1 && $trigger_types[0] != null && $benchmark_tickets[0] != null && count($display_rows) > 1) {
                    $system_name_format = 'TRIGGER_AND_SYSTEM';
                } else {
                    if (empty($schedule_types[0])) {
                        $system_name_format = 'ORIGINAL_DATA';
                    } else {
                        if (count($display_rows) == 1) {
                            $system_name_format = 'SYSTEM_NAME';
                        } else {
                            if (count($schedule_types) == 1 && count($system_types) == 1) {
                                $system_name_format = 'TRIGGER';
                                $result_file_title = phoromatic_schedule_id_to_name($schedule_types[0]);
                            } else {
                                if (count($schedule_types) == 1) {
                                    $system_name_format = 'TRIGGER_AND_SYSTEM';
                                } else {
                                    if (false && count($trigger_types) == 1) {
                                        // TODO XXX: this approach yields garbage strings generally without refining the selector
                                        // i.e. first make sure all the schedules match or are comparable
                                        $system_name_format = 'SYSTEM_AND_SCHEDULE';
                                    } else {
                                        $system_name_format = null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (count($schedule_types) == 1 && $schedule_types[0] != 0) {
                self::$schedule_id = $schedule_types[0];
            }
            foreach ($display_rows as $composite_xml => $row) {
                //  $row['SystemID'] . ' ' . $row['ScheduleID'] . ' ' . $row['Trigger']
                switch ($system_name_format) {
                    case 'ORIGINAL_DATA':
                        $system_name = null;
                        break;
                    case 'SYSTEM_NAME':
                        $system_name = phoromatic_system_id_to_name($row['SystemID']);
                        break;
                    case 'TRIGGER':
                        $system_name = $row['Trigger'];
                        break;
                    case 'TRIGGER_AND_SYSTEM':
                        $system_name = phoromatic_system_id_to_name($row['SystemID']) . ': ' . $row['Trigger'];
                        break;
                    case 'SYSTEM_AND_SCHEDULE':
                        $system_name = phoromatic_schedule_id_to_name($row['ScheduleID']) . ': ' . $row['Trigger'];
                        break;
                    default:
                        $system_name = phoromatic_system_id_to_name($row['SystemID']) . ' - ' . phoromatic_schedule_id_to_name($row['ScheduleID']) . ' - ' . $row['Trigger'];
                }
                if ($system_name == null) {
                    $rf = new pts_result_file($composite_xml);
                    $identifiers = $rf->get_system_identifiers();
                    if (count($identifiers) == 1) {
                        $system_name = $identifiers[0];
                    }
                }
                $system_name = str_replace('.SYSTEM', phoromatic_system_id_to_name($row['SystemID']), $system_name);
                $system_name = str_replace('.GROUP', phoromatic_account_id_to_group_name($row['AccountID']), $system_name);
                $system_variables = explode(';', phoromatic_server::system_id_variables($row['SystemID'], $row['AccountID']));
                foreach ($system_variables as $var) {
                    $var = explode('=', $var);
                    if (count($var) == 2) {
                        $system_name = str_replace('.' . $var[0], $var[1], $system_name);
                    }
                }
                $result_files[] = new pts_result_merge_select($composite_xml, null, $system_name);
            }
            $result_file = new pts_result_file(null, true);
            $result_file->set_title('Phoromatic Results');
            if (!empty($result_files)) {
                $attributes = array('new_result_file_title' => $result_file_title);
                if (!empty($result_files)) {
                    $result_file->merge($result_files, $attributes);
                }
            }
            $extra_attributes = array();
            if (isset($_GET['upload_to_openbenchmarking'])) {
                $ob_url = pts_openbenchmarking_client::upload_test_result($result_file, false);
                if ($ob_url) {
                    header('Location: ' . $ob_url);
                }
            }
            $attribute_options = array('normalize_results' => 'normalize_result_buffer', 'sort_by_performance' => 'sort_result_buffer_values', 'sort_by_reverse' => 'reverse_result_buffer', 'sort_by_name' => 'sort_result_buffer', 'condense_comparison' => 'condense_multi_way', 'force_line_graph' => 'force_tracking_line_graph');
            $url_append = null;
            foreach ($attribute_options as $web_var => $attr_var) {
                if (isset($_REQUEST[$web_var])) {
                    $extra_attributes[$attr_var] = true;
                    $url_append .= '&' . $web_var . '=1';
                }
            }
            if (isset($_POST['transpose_comparison'])) {
                $result_file->invert_multi_way_invert();
            }
            $intent = null;
            if (isset($_GET['download']) && $_GET['download'] == 'csv') {
                $result_csv = pts_result_file_output::result_file_to_csv($result_file);
                header('Content-Description: File Transfer');
                header('Content-Type: application/csv');
                header('Content-Disposition: attachment; filename=phoromatic-result.csv');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . strlen($result_csv));
                ob_clean();
                flush();
                echo $result_csv;
                return;
            } else {
                if (isset($_GET['download']) && $_GET['download'] == 'txt') {
                    $result_txt = pts_result_file_output::result_file_to_text($result_file);
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/txt');
                    header('Content-Disposition: attachment; filename=phoromatic-result.txt');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Content-Length: ' . strlen($result_txt));
                    ob_clean();
                    flush();
                    echo $result_txt;
                    return;
                } else {
                    if (isset($_GET['download']) && $_GET['download'] == 'pdf') {
                        ob_start();
                        $_REQUEST['force_format'] = 'PNG';
                        // Force to PNG renderer
                        $_REQUEST['svg_dom_gd_no_interlacing'] = true;
                        // Otherwise FPDF will fail
                        $tdir = pts_client::create_temporary_directory();
                        pts_client::generate_result_file_graphs($result_file, $tdir, $extra_attributes);
                        $pdf = new pts_pdf_template($result_file->get_title(), null);
                        $pdf->AddPage();
                        $pdf->Image(PTS_CORE_STATIC_PATH . 'images/pts-308x160.png', 69, 85, 73, 38);
                        $pdf->Ln(120);
                        $pdf->WriteStatementCenter('www.phoronix-test-suite.com');
                        $pdf->Ln(15);
                        $pdf->WriteBigHeaderCenter($result_file->get_title());
                        $pdf->WriteText($result_file->get_description());
                        $pdf->AddPage();
                        $pdf->Ln(15);
                        $pdf->SetSubject($result_file->get_title() . ' Benchmarks');
                        //$pdf->SetKeywords(implode(', ', $identifiers));
                        $pdf->WriteHeader('Test Systems:');
                        foreach ($result_file->get_systems() as $s) {
                            $pdf->WriteMiniHeader($s->get_identifier());
                            $pdf->WriteText($s->get_hardware());
                            $pdf->WriteText($s->get_software());
                        }
                        $pdf->AddPage();
                        $placement = 1;
                        $results = $result_file->get_result_objects();
                        for ($i = 1; $i <= count($results); $i++) {
                            if (is_file($tdir . 'result-graphs/' . $i . '.png')) {
                                $pdf->Ln(100);
                                $pdf->Image($tdir . 'result-graphs/' . $i . '.png', 50, 40 + ($placement - 1) * 120, 120);
                            }
                            if ($placement == 2) {
                                $placement = 0;
                                if ($i != count($results)) {
                                    $pdf->AddPage();
                                }
                            }
                            $placement++;
                        }
                        ob_get_clean();
                        $pdf->Output('phoromatic.pdf', 'I');
                        //pts_file_io::delete($tdir, null, true);
                        return;
                    } else {
                        if (isset($_GET['download']) && $_GET['download'] == 'xml') {
                            echo $result_file->get_xml();
                            return;
                        }
                    }
                }
            }
            $main .= '<h1>' . $result_file->get_title() . '</h1>';
            $main .= phoromatic_annotate_entry('RESULT', implode(',', $upload_ids), 'TOP');
            if ($result_file->get_system_count() == 1 || ($intent = pts_result_file_analyzer::analyze_result_file_intent($result_file, $intent, true))) {
                $table = new pts_ResultFileCompactSystemsTable($result_file, $intent);
            } else {
                $table = new pts_ResultFileSystemsTable($result_file);
            }
            $main .= '<p style="text-align: center; overflow: auto;" class="result_object">' . pts_render::render_graph_inline_embed($table, $result_file, $extra_attributes) . '</p>';
            $table = new pts_ResultFileTable($result_file, $intent);
            $main .= '<p style="text-align: center; overflow: auto;" class="result_object">' . pts_render::render_graph_inline_embed($table, $result_file, $extra_attributes) . '</p>';
            $main .= '<div id="pts_results_area">';
            foreach ($result_file->get_result_objects(isset($_POST['show_only_changed_results']) ? 'ONLY_CHANGED_RESULTS' : -1) as $i => $result_object) {
                $main .= '<h2><a name="r-' . $i . '"></a><a name="' . $result_object->get_comparison_hash(true, false) . '"></a>' . $result_object->test_profile->get_title() . '</h2>';
                $main .= phoromatic_annotate_entry('RESULT', implode(',', $upload_ids), $result_object->get_comparison_hash(true, false));
                $main .= '<p class="result_object">';
                $main .= pts_render::render_graph_inline_embed($result_object, $result_file, $extra_attributes);
                $main .= '</p>';
            }
            $main .= '</div>';
        } else {
            // No result
        }
        $right = null;
        if (self::$schedule_id && !empty(self::$schedule_id)) {
            $stmt = phoromatic_server::$db->prepare('SELECT * FROM phoromatic_schedules WHERE AccountID = :account_id AND ScheduleID = :schedule_id LIMIT 1');
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $stmt->bindValue(':schedule_id', self::$schedule_id);
            $result = $stmt->execute();
            $row = $result->fetchArray();
            if (!empty($row)) {
                $right .= '<h3><a href="?schedules/' . $row['ScheduleID'] . '">' . $row['Title'] . '</a></h3>';
                if (!empty($row['ActiveOn'])) {
                    $right .= '<p align="center"><strong>' . phoromatic_schedule_activeon_string($row['ActiveOn'], $row['RunAt']) . '</strong></p>';
                }
                $right .= '<p>Compare this result file to the latest results from the past: ';
                $right .= '<select name="view_results_from_past" id="view_results_from_past" onchange="phoromatic_jump_to_results_from(\'' . $row['ScheduleID'] . '\', \'view_results_from_past\', \'' . $PATH[0] . ',\');">';
                $oldest_upload_time = strtotime(phoromatic_oldest_result_for_schedule(self::$schedule_id));
                $opts = array('Week' => 7, 'Three Weeks' => 21, 'Month' => 30, 'Quarter' => 90, 'Six Months' => 180, 'Year' => 365);
                foreach ($opts as $str_name => $time_offset) {
                    if ($oldest_upload_time > time() - 86400 * $time_offset) {
                        break;
                    }
                    $right .= '<option value="' . $time_offset . '">' . $str_name . '</option>';
                }
                $right .= '<option value="all">All Results</option>';
                $right .= '</select>';
                $right .= '</p>';
            }
        }
        if (true) {
            $compare_results = array();
            $hash_matches = 0;
            $ticket_matches = 0;
            $stmt = phoromatic_server::$db->prepare('SELECT * FROM phoromatic_results WHERE AccountID = :account_id AND ComparisonHash = :comparison_hash AND PPRID NOT IN (:pprid) ORDER BY UploadTime DESC LIMIT 12');
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $stmt->bindValue(':comparison_hash', $result_file->get_contained_tests_hash(false));
            $stmt->bindValue(':pprid', implode(',', $upload_ids));
            $result = $stmt->execute();
            while ($row = $result->fetchArray()) {
                $compare_results[$row['PPRID']] = $row;
                $hash_matches++;
            }
            foreach ($benchmark_tickets as $ticket_id) {
                $stmt = phoromatic_server::$db->prepare('SELECT * FROM phoromatic_results WHERE AccountID = :account_id AND BenchmarkTicketID = :ticket_id AND PPRID NOT IN (:pprid) ORDER BY UploadTime DESC LIMIT 12');
                $stmt->bindValue(':account_id', $_SESSION['AccountID']);
                $stmt->bindValue(':ticket_id', $ticket_id);
                $stmt->bindValue(':pprid', implode(',', $upload_ids));
                $result = $stmt->execute();
                while ($row = $result->fetchArray()) {
                    $compare_results[$row['PPRID']] = $row;
                    $ticket_matches++;
                }
            }
            if (!empty($compare_results)) {
                $right .= '<hr /><h3>Compare Results</h3><form name="compare_similar_results" onsubmit="return false;">
						<input type="hidden" value="' . implode(',', $upload_ids) . '" id="compare_similar_results_this" />';
                foreach ($compare_results as &$row) {
                    $right .= '<p><input type="checkbox" value="' . $row['PPRID'] . '" name="compare_results" /> ' . $row['Title'] . '<br /><em>' . phoromatic_system_id_to_name($row['SystemID'], $row['AccountID']) . '</em></p>';
                }
                $right .= '<p><input type="submit" value="Compare Results" id="compare_results_submit" onclick="javascript:phoromatic_do_custom_compare_results(this); return false;" /></p></form>';
                if ($ticket_matches > 3) {
                    $right .= '<p><a href="/results/ticket/' . $ticket_id . '">Find All Matching Results</a>';
                } else {
                    if ($hash_matches > 3) {
                        $right .= '<p><a href="/results/hash/' . $result_file->get_contained_tests_hash(false) . '">Find All Matching Results</a>';
                    }
                }
            }
        }
        if (count($upload_ids) > 1) {
            $checkbox_options = array('normalize_results' => 'Normalize Results', 'sort_by_performance' => 'Sort Results By Performance', 'sort_by_name' => 'Reverse Result By Identifier', 'sort_by_reverse' => 'Reverse Result Order', 'show_only_changed_results' => 'Show Only Results With Result Variation', 'force_line_graph' => 'Force Line Graph');
            if ($result_file->is_multi_way_comparison()) {
                $checkbox_options['condense_comparison'] = 'Condense Comparison';
                $checkbox_options['transpose_comparison'] = 'Transpose Comparison';
            }
            $right .= '<form action="' . $_SERVER['REQUEST_URI'] . '" name="update_result_view" method="post"><hr /><h3>Result Analysis Options</h3><p align="left">' . PHP_EOL;
            foreach ($checkbox_options as $val => $name) {
                $right .= '<input type="checkbox" name="' . $val . '" value="1" ' . (isset($_POST[$val]) ? 'checked="checked" ' : null) . '/> ' . $name . '<br />';
            }
            $right .= '<br /><input type="submit" value="Refresh Results"></p></form>';
        }
        if (self::$schedule_id && !empty(self::$schedule_id) && $system_types[0] && $trigger_types[0]) {
            $stmt = phoromatic_server::$db->prepare('SELECT UserContextStep FROM phoromatic_system_context_logs WHERE AccountID = :account_id AND ScheduleID = :schedule_id AND SystemID = :system_id AND TriggerID = :trigger_id');
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $stmt->bindValue(':system_id', $system_types[0]);
            $stmt->bindValue(':schedule_id', self::$schedule_id);
            $stmt->bindValue(':trigger_id', $trigger_types[0]);
            $result = $stmt->execute();
            if ($row = $result->fetchArray()) {
                $right .= '<hr /><h3>User Context Logs</h3>';
                do {
                    $right .= '<p><a href="?logs/context/' . $system_types[0] . ',' . self::$schedule_id . ',' . base64_encode($trigger_types[0]) . '">' . $row['UserContextStep'] . '</a></p>';
                } while ($row = $result->fetchArray());
            }
        }
        $right .= '<hr /><h3>Result Export</h3>';
        $right .= '<p><a href="/public.php?t=result&ut=' . implode(',', $upload_ids) . $url_append . '">Public Viewer</a></p>';
        $right .= '<p><a href="?' . $_SERVER['QUERY_STRING'] . '/&download=pdf' . $url_append . '">Download As PDF</a></p>';
        $right .= '<p><a href="?' . $_SERVER['QUERY_STRING'] . '/&download=csv">Download As CSV</a></p>';
        $right .= '<p><a href="?' . $_SERVER['QUERY_STRING'] . '/&download=xml">Download As XML</a></p>';
        $right .= '<p><a href="?' . $_SERVER['QUERY_STRING'] . '/&download=txt">Download As TEXT</a></p>';
        $right .= '<p><a href="?' . $_SERVER['QUERY_STRING'] . '/&upload_to_openbenchmarking">Upload To OpenBenchmarking.org</a></p>';
        if (is_file(phoromatic_server::phoromatic_account_result_path($_SESSION['AccountID'], $row['UploadID']) . 'system-logs.zip')) {
            $right .= '<hr /><p><a href="?logs/system/' . $row['UploadID'] . '">View System Logs</a></p>';
        }
        echo phoromatic_webui_header_logged_in();
        echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in($right));
        echo phoromatic_webui_footer();
    }
 public static function render_page_process($PATH)
 {
     echo phoromatic_webui_header_logged_in();
     $main = null;
     if (!PHOROMATIC_USER_IS_VIEWER && isset($PATH[0]) && $PATH[0] == 'delete') {
         $pprids = explode(',', $PATH[1]);
         foreach ($pprids as $pprid) {
             $stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_results WHERE AccountID = :account_id AND PPRID = :pprid');
             $stmt->bindValue(':account_id', $_SESSION['AccountID']);
             $stmt->bindValue(':pprid', $pprid);
             $result = $stmt->execute();
             // TODO XXX fix below
             //$upload_dir = phoromatic_server::phoromatic_account_result_path($_SESSION['AccountID'], $upload_id);
             //pts_file_io::delete($upload_dir);
         }
     }
     if ($main == null) {
         $time_limit = false;
         $time_str = false;
         if (isset($_POST['time'])) {
             $time_str = $_POST['time'];
             $time_limit = strtotime('- ' . $time_str);
         }
         if ($time_limit == false) {
             $time_str = '1 month';
             $time_limit = strtotime('- ' . $time_str);
         }
         $result_limit = isset($_POST['result_limit']) && is_numeric($_POST['result_limit']) && $_POST['result_limit'] > 9 ? $_POST['result_limit'] : 50;
         $main .= '<form action="' . $_SERVER['REQUEST_URI'] . '" method="post"><div style="text-align: left; font-weight: bold;">Show Results For <select id="result_time_limit" name="time">';
         $results_for_length = array('24 hours' => '24 Hours', '3 days' => '3 Days', '1 week' => 'Week', '2 week' => '2 Weeks', '1 month' => 'Month', '2 months' => '2 Months', '3 months' => 'Quarter', '6 months' => '6 Months', '1 year' => 'Year', '2 year' => 'Two Years');
         foreach ($results_for_length as $val => $str) {
             $main .= '<option value="' . $val . '"' . ($time_str == $val ? ' selected="selected"' : null) . '>Past ' . $str . '</option>';
         }
         $main .= '</select> Search For <input type="text" name="search" value="' . (isset($_POST['search']) ? $_POST['search'] : null) . '" /> &nbsp; Limit Results To <select id="result_limit" name="result_limit">';
         for ($i = 25; $i <= 150; $i += 25) {
             $main .= '<option value="' . $i . '"' . ($result_limit == $i ? ' selected="selected"' : null) . '>' . $i . '</option>';
         }
         $main .= '</select> &nbsp; <input type="submit" value="Update" /></div></form>';
         $main .= '<h1>Account Test Results</h1>';
         $main .= '<div class="pts_phoromatic_info_box_area">';
         $search_for = !isset($_POST['search']) || empty($_POST['search']) ? null : 'AND (Title LIKE :search OR Description LIKE :search OR UploadID IN (SELECT UploadID FROM phoromatic_results_systems WHERE AccountID = :account_id AND (Software LIKE :search OR Hardware LIKE :search)))';
         $main .= '<div style="margin: 0 5%;"><ul style="max-height: 100%;"><li><h1>Recent Test Results</h1></li>';
         if (isset($PATH[1]) && $PATH[0] == 'hash') {
             // Find matching comparison hashes
             $stmt = phoromatic_server::$db->prepare('SELECT Title, SystemID, ScheduleID, PPRID, UploadTime, TimesViewed FROM phoromatic_results WHERE AccountID = :account_id ' . $search_for . ' AND ComparisonHash = :comparison_hash ORDER BY UploadTime DESC LIMIT ' . $result_limit);
             $stmt->bindValue(':comparison_hash', $PATH[1]);
         } else {
             if (isset($PATH[1]) && $PATH[0] == 'ticket') {
                 // Find matching ticket results
                 $stmt = phoromatic_server::$db->prepare('SELECT Title, SystemID, ScheduleID, PPRID, UploadTime, TimesViewed FROM phoromatic_results WHERE AccountID = :account_id ' . $search_for . ' AND BenchmarkTicketID = :ticket_id ORDER BY UploadTime DESC LIMIT ' . $result_limit);
                 $stmt->bindValue(':ticket_id', $PATH[1]);
             } else {
                 $stmt = phoromatic_server::$db->prepare('SELECT Title, SystemID, ScheduleID, PPRID, UploadTime, TimesViewed FROM phoromatic_results WHERE AccountID = :account_id ' . $search_for . ' ORDER BY UploadTime DESC LIMIT ' . $result_limit);
             }
         }
         $stmt->bindValue(':account_id', $_SESSION['AccountID']);
         $stmt->bindValue(':search', isset($_POST['search']) ? '%' . $_POST['search'] . '%' : null);
         $test_result_result = $stmt->execute();
         $results = 0;
         while ($test_result_row = $test_result_result->fetchArray()) {
             if (strtotime($test_result_row['UploadTime']) < $time_limit) {
                 break;
             }
             if ($results > 150) {
                 break;
             }
             $main .= '<a onclick=""><li id="result_select_' . $test_result_row['PPRID'] . '"><input type="checkbox" id="result_compare_checkbox_' . $test_result_row['PPRID'] . '" onclick="javascript:phoromatic_checkbox_toggle_result_comparison(\'' . $test_result_row['PPRID'] . '\');" onchange="return false;"></input> <span onclick="javascript:phoromatic_window_redirect(\'?result/' . $test_result_row['PPRID'] . '\');">' . $test_result_row['Title'] . '</span><br /><table><tr><td>' . phoromatic_system_id_to_name($test_result_row['SystemID']) . '</td><td>' . phoromatic_user_friendly_timedate($test_result_row['UploadTime']) . '</td><td>' . $test_result_row['TimesViewed'] . ' Times Viewed</td></table></li></a>';
             $results++;
         }
         if ($results == 0) {
             $main .= '<li class="light" style="text-align: center;">No Results Found</li>';
         } else {
             if ($results > 3) {
                 $main .= '<a onclick=""><li id="global_bottom_totals"><input type="checkbox" id="global_checkbox" onclick="javascript:phoromatic_toggle_checkboxes_on_page(this);" onchange="return false;"></input> <strong>' . $results . ' Results</strong></li></a>';
             }
         }
         $main .= '</ul></div>';
         $main .= '</div>';
         $result_share_opt = phoromatic_server::read_setting('force_result_sharing') ? '1 = 1' : 'AccountID IN (SELECT AccountID FROM phoromatic_account_settings WHERE LetOtherGroupsViewResults = "1")';
         $stmt = phoromatic_server::$db->prepare('SELECT Title, SystemID, ScheduleID, PPRID, UploadTime, TimesViewed, AccountID FROM phoromatic_results WHERE ' . $result_share_opt . ' AND AccountID != :account_id ' . $search_for . ' ORDER BY UploadTime DESC LIMIT ' . $result_limit);
         $stmt->bindValue(':account_id', $_SESSION['AccountID']);
         $stmt->bindValue(':search', isset($_POST['search']) ? '%' . $_POST['search'] . '%' : null);
         $test_result_result = $stmt->execute();
         if (!empty($test_result_result) && ($test_result_row = $test_result_result->fetchArray())) {
             $main .= '<div class="pts_phoromatic_info_box_area">';
             $main .= '<div style="margin: 0 5%;"><ul style="max-height: 100%;"><li><h1>Results Shared By Other Groups</h1></li>';
             $results = 0;
             do {
                 if (strtotime($test_result_row['UploadTime']) < $time_limit) {
                     break;
                 }
                 if ($results > 150) {
                     break;
                 }
                 $main .= '<a onclick=""><li id="result_select_' . $test_result_row['PPRID'] . '"><input type="checkbox" id="result_compare_checkbox_' . $test_result_row['PPRID'] . '" onclick="javascript:phoromatic_checkbox_toggle_result_comparison(\'' . $test_result_row['PPRID'] . '\');" onchange="return false;"></input> <span onclick="javascript:phoromatic_window_redirect(\'?result/' . $test_result_row['PPRID'] . '\');">' . $test_result_row['Title'] . '</span><br /><table><tr><td><strong>' . phoromatic_account_id_to_group_name($test_result_row['AccountID']) . '</strong></td><td>' . phoromatic_system_id_to_name($test_result_row['SystemID'], $test_result_row['AccountID']) . '</td><td>' . phoromatic_user_friendly_timedate($test_result_row['UploadTime']) . '</td><td>' . $test_result_row['TimesViewed'] . ' Times Viewed</td></table></li></a>';
                 $results++;
             } while ($test_result_row = $test_result_result->fetchArray());
             $main .= '</ul></div>';
         }
     }
     echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in());
     echo phoromatic_webui_footer();
 }
    public static function render_page_process($PATH)
    {
        if ($_SESSION['AdminLevel'] != -40) {
            header('Location: /?main');
        }
        if (isset($PATH[0]) && isset($PATH[1])) {
            switch ($PATH[0]) {
                case 'delete':
                    if ($PATH[1] == 'result') {
                        $pprids = explode(',', $PATH[2]);
                        foreach ($pprids as $pprid) {
                            $stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_results WHERE PPRID = :pprid');
                            $stmt->bindValue(':pprid', $pprid);
                            $result = $stmt->execute();
                        }
                        /*						$stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_results_results WHERE AccountID = :account_id AND UploadID = :upload_id');
                        						$stmt->bindValue(':account_id', $PATH[2]);
                        						$stmt->bindValue(':upload_id', $PATH[3]);
                        						$result = $stmt->execute();
                        						$stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_results_systems WHERE AccountID = :account_id AND UploadID = :upload_id');
                        						$stmt->bindValue(':account_id', $PATH[2]);
                        						$stmt->bindValue(':upload_id', $PATH[3]);
                        						$result = $stmt->execute();
                        
                        						$result_dir = phoromatic_server::phoromatic_account_result_path($PATH[2], $PATH[3]);
                        						if(is_dir($result_dir))
                        						{
                        							pts_file_io::delete($result_dir, null, true);
                        						}
                        */
                    } else {
                        if ($PATH[1] == 'schedule') {
                            $stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_schedules WHERE AccountID = :account_id AND ScheduleID = :schedule_id');
                            $stmt->bindValue(':account_id', $PATH[2]);
                            $stmt->bindValue(':schedule_id', $PATH[3]);
                            $result = $stmt->execute();
                        } else {
                            if ($PATH[1] == 'system') {
                                $stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_systems WHERE AccountID = :account_id AND SystemID = :system_id');
                                $stmt->bindValue(':account_id', $PATH[2]);
                                $stmt->bindValue(':system_id', $PATH[3]);
                                $result = $stmt->execute();
                            } else {
                                if ($PATH[1] == 'ticket') {
                                    $stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_benchmark_tickets WHERE AccountID = :account_id AND TicketID = :ticket_id');
                                    $stmt->bindValue(':account_id', $PATH[2]);
                                    $stmt->bindValue(':ticket_id', $PATH[3]);
                                    $result = $stmt->execute();
                                } else {
                                    if ($PATH[1] == 'trigger') {
                                        $stmt = phoromatic_server::$db->prepare('DELETE FROM phoromatic_schedules_triggers WHERE AccountID = :account_id AND ScheduleID = :schedule_id AND Trigger = :trigger');
                                        $stmt->bindValue(':account_id', $PATH[2]);
                                        $stmt->bindValue(':schedule_id', $PATH[3]);
                                        $stmt->bindValue(':trigger', $PATH[4]);
                                        $result = $stmt->execute();
                                        var_dump($result);
                                    }
                                }
                            }
                        }
                    }
                    break;
            }
        }
        $main = '<h1>Phoromatic Server Data</h1>';
        $main .= '<h1>Test Results</h1>';
        $main .= '<a onclick="javascript:phoromatic_generate_comparison(\'public.php?ut=\');"><div id="phoromatic_result_compare_info_box" style="background: #1976d2; border: 1px solid #000;"></div></a> <a onclick="javascript:phoromatic_delete_results(\'?admin_data/delete/result/\'); return false;"><div id="phoromatic_result_delete_box" style="background: #1976d2; border: 1px solid #000;">Delete Selected Results</div></a>';
        $main .= '<div class="pts_phoromatic_info_box_area">';
        $main .= '<div style="height: 500px;"><ul style="max-height: 100%;"><li><h1>Recent Test Results</h1></li>';
        $stmt = phoromatic_server::$db->prepare('SELECT Title, SystemID, ScheduleID, PPRID, UploadTime, TimesViewed, AccountID, UploadID FROM phoromatic_results ORDER BY UploadTime DESC');
        $test_result_result = $stmt->execute();
        $results = 0;
        while ($test_result_row = $test_result_result->fetchArray()) {
            $main .= '<a onclick=""><li id="result_select_' . $test_result_row['PPRID'] . '"><input type="checkbox" id="result_compare_checkbox_' . $test_result_row['PPRID'] . '" onclick="javascript:phoromatic_checkbox_toggle_result_comparison(\'' . $test_result_row['PPRID'] . '\');" onchange="return false;"></input> <span onclick="javascript:phoromatic_window_redirect(\'public.php?ut=' . $test_result_row['PPRID'] . '\');">' . $test_result_row['Title'] . '</span><br /><table><tr><td>' . phoromatic_system_id_to_name($test_result_row['SystemID'], $test_result_row['AccountID']) . '</td><td>' . phoromatic_user_friendly_timedate($test_result_row['UploadTime']) . '</td><td>' . $test_result_row['TimesViewed'] . ' Times Viewed</td></table></li></a>';
            $results++;
        }
        if ($results == 0) {
            $main .= '<li class="light" style="text-align: center;">No Results Found</li>';
        }
        $main .= '</ul></div>';
        $main .= '</div>';
        $main .= '<hr /><h1>Schedules</h1>';
        $main .= '<h2>Active Test Schedules</h2>';
        $main .= '<div class="pts_phoromatic_info_box_area">
				<ul>
					<li><h1>Active Test Schedules</h1></li>';
        $stmt = phoromatic_server::$db->prepare('SELECT Title, ScheduleID, Description, RunTargetSystems, RunTargetGroups, RunAt, ActiveOn, AccountID FROM phoromatic_schedules WHERE State >= 1 ORDER BY Title ASC');
        $result = $stmt->execute();
        $row = $result->fetchArray();
        if ($row == false) {
            $main .= '<li class="light" style="text-align: center;">No Schedules Found</li>';
        } else {
            do {
                $main .= '<a onclick=""><li>' . $row['Title'] . '<br /><table><tr><td>' . phoromatic_account_id_to_group_name($row['AccountID']) . '</td><td>' . pts_strings::plural_handler(count(phoromatic_server::systems_associated_with_schedule($row['AccountID'], $row['ScheduleID'])), 'System') . '</td><td><strong>' . phoromatic_schedule_activeon_string($row['ActiveOn'], $row['RunAt']) . '</strong></td><td><a onclick="return confirm(\'Permanently remove this schedule?\');" href="/?admin_data/delete/schedule/' . $row['AccountID'] . '/' . $row['ScheduleID'] . '">Permanently Remove</a></td></tr></table></li></a>';
            } while ($row = $result->fetchArray());
        }
        $main .= '</ul></div>';
        $main .= '<hr /><h2>Inactive Test Schedules</h2>';
        $main .= '<div class="pts_phoromatic_info_box_area">
				<ul>
					<li><h1>Active Test Schedules</h1></li>';
        $stmt = phoromatic_server::$db->prepare('SELECT Title, ScheduleID, Description, RunTargetSystems, RunTargetGroups, RunAt, ActiveOn, AccountID FROM phoromatic_schedules WHERE State < 1 ORDER BY Title ASC');
        $result = $stmt->execute();
        $row = $result->fetchArray();
        if ($row == false) {
            $main .= '<li class="light" style="text-align: center;">No Schedules Found</li>';
        } else {
            do {
                $main .= '<a onclick=""><li>' . $row['Title'] . '<br /><table><tr><td>' . phoromatic_account_id_to_group_name($row['AccountID']) . '</td><td>' . pts_strings::plural_handler(count(phoromatic_server::systems_associated_with_schedule($row['AccountID'], $row['ScheduleID'])), 'System') . '</td><td><strong>' . phoromatic_schedule_activeon_string($row['ActiveOn'], $row['RunAt']) . '</strong></td><td><a onclick="return confirm(\'Permanently remove this schedule?\');" href="/?admin_data/delete/schedule/' . $row['AccountID'] . '/' . $row['ScheduleID'] . '">Permanently Remove</a></td></tr></table></li></a>';
            } while ($row = $result->fetchArray());
        }
        $main .= '</ul></div>';
        $main .= '<hr /><h2>Schedule Triggers</h2>';
        $main .= '<div class="pts_phoromatic_info_box_area">
				<ul>
					<li><h1>Triggers</h1></li>';
        $stmt = phoromatic_server::$db->prepare('SELECT Trigger, TriggeredOn, AccountID, ScheduleID FROM phoromatic_schedules_triggers ORDER BY TriggeredOn DESC');
        $result = $stmt->execute();
        $row = $result->fetchArray();
        if ($row == false) {
            $main .= '<li class="light" style="text-align: center;">No Triggers Found</li>';
        } else {
            do {
                $main .= '<a onclick=""><li>' . $row['Trigger'] . '<br /><table><tr><td>' . $row['TriggeredOn'] . '</td><td>' . phoromatic_account_id_to_group_name($row['AccountID']) . '</td><td><a onclick="return confirm(\'Permanently remove this trigger?\');" href="/?admin_data/delete/trigger/' . $row['AccountID'] . '/' . $row['ScheduleID'] . '/' . $row['Trigger'] . '">Permanently Remove</a></td></tr></table></li></a>';
            } while ($row = $result->fetchArray());
        }
        $main .= '</ul></div>';
        $main .= '<hr /><h1>Systems</h1>
			<h2>Active Systems</h2>
			<div class="pts_phoromatic_info_box_area">

					<ul>
						<li><h1>Active Systems</h1></li>';
        $stmt = phoromatic_server::$db->prepare('SELECT Title, SystemID, LocalIP, CurrentTask, LastCommunication, EstimatedTimeForTask, TaskPercentComplete, AccountID FROM phoromatic_systems WHERE State >= 0 ORDER BY LastCommunication DESC');
        $result = $stmt->execute();
        $row = $result->fetchArray();
        $active_system_count = 0;
        if ($row == false) {
            $main .= '<li class="light" style="text-align: center;">No Systems Found</li>';
        } else {
            do {
                $main .= '<a onclick=""><li>' . $row['Title'] . '<br /><table><tr><td>' . phoromatic_account_id_to_group_name($row['AccountID']) . '</td><td>' . $row['LocalIP'] . '</td><td><strong>' . $row['CurrentTask'] . '</strong></td><td><strong>Last Communication:</strong> ' . date('j F Y H:i', strtotime($row['LastCommunication'])) . '</td><td><a onclick="return confirm(\'Permanently remove this system?\');" href="/?admin_data/delete/system/' . $row['AccountID'] . '/' . $row['SystemID'] . '">Permanently Remove</a></td></tr></table></li></a>';
                $active_system_count++;
            } while ($row = $result->fetchArray());
        }
        $main .= '</ul></div>';
        $main .= '<h2>Inactive Systems</h2>
			<div class="pts_phoromatic_info_box_area">

					<ul>
						<li><h1>Inactive Systems</h1></li>';
        $stmt = phoromatic_server::$db->prepare('SELECT Title, SystemID, LocalIP, CurrentTask, LastCommunication, EstimatedTimeForTask, TaskPercentComplete, AccountID FROM phoromatic_systems WHERE State < 0 ORDER BY LastCommunication DESC');
        $result = $stmt->execute();
        $row = $result->fetchArray();
        $active_system_count = 0;
        if ($row == false) {
            $main .= '<li class="light" style="text-align: center;">No Systems Found</li>';
        } else {
            do {
                $main .= '<a onclick=""><li>' . $row['Title'] . '<br /><table><tr><td>' . phoromatic_account_id_to_group_name($row['AccountID']) . '</td><td>' . $row['LocalIP'] . '</td><td><strong>' . $row['CurrentTask'] . '</strong></td><td><strong>Last Communication:</strong> ' . date('j F Y H:i', strtotime($row['LastCommunication'])) . '</td><td><a onclick="return confirm(\'Permanently remove this system?\');" href="/?admin_data/delete/system/' . $row['AccountID'] . '/' . $row['SystemID'] . '">Permanently Remove</a></td></tr></table></li></a>';
                $active_system_count++;
            } while ($row = $result->fetchArray());
        }
        $main .= '</ul></div>';
        $stmt = phoromatic_server::$db->prepare('SELECT * FROM phoromatic_benchmark_tickets ORDER BY TicketIssueTime DESC');
        $result = $stmt->execute();
        $main .= '<hr /><h1>Benchmark Tickets</h1>
			<div class="pts_phoromatic_info_box_area"><ul><li><h1>Tickets</h1></li>';
        while ($result && ($row = $result->fetchArray())) {
            $main .= '<a onclick=""><li>' . $row['Title'] . '<br /><table><tr><td><a onclick="return confirm(\'Permanently remove this system?\');" href="/?admin_data/delete/ticket/' . $row['AccountID'] . '/' . $row['TicketID'] . '">Permanently Remove</a></td></tr></table></li></a>';
        }
        $main .= '</ul></div>';
        echo phoromatic_webui_header_logged_in();
        echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in());
        echo phoromatic_webui_footer();
    }
    public static function render_page_process($PATH)
    {
        if ($_SESSION['AdminLevel'] > 3) {
            echo phoromatic_error_page('Unauthorized Access', 'You aren\'t an account administrator!');
            return;
        }
        if (isset($_POST['group_name'])) {
            $stmt = phoromatic_server::$db->prepare('UPDATE phoromatic_accounts SET GroupName = :group_name WHERE AccountID = :account_id');
            $stmt->bindValue(':group_name', $_POST['group_name']);
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $result = $stmt->execute();
        }
        if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['confirm_password']) && isset($_POST['email'])) {
            // REGISTER NEW USER
            if (strlen($_POST['username']) < 4 || strpos($_POST['username'], ' ') !== false) {
                phoromatic_error_page('Oops!', 'Please go back and ensure the supplied username is at least four characters long and contains no spaces.');
                return false;
            }
            if (in_array(strtolower($_POST['username']), array('admin', 'administrator'))) {
                phoromatic_error_page('Oops!', $_POST['username'] . ' is a reserved and common username that may be used for other purposes, please make a different selection.');
                return false;
            }
            if (strlen($_POST['password']) < 6) {
                phoromatic_error_page('Oops!', 'Please go back and ensure the supplied password is at least six characters long.');
                return false;
            }
            if ($_POST['password'] != $_POST['confirm_password']) {
                phoromatic_error_page('Oops!', 'Please go back and ensure the supplied password matches the password confirmation.');
                return false;
            }
            if ($_POST['email'] == null || filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == false) {
                phoromatic_error_page('Oops!', 'Please enter a valid email address.');
                return false;
            }
            $valid_user_name_chars = '1234567890-_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            for ($i = 0; $i < count($_POST['username']); $i++) {
                if (strpos($valid_user_name_chars, substr($_POST['username'], $i, 1)) === false) {
                    phoromatic_error_page('Oops!', 'Please go back and ensure a valid user-name. The character <em>' . substr($_POST['username'], $i, 1) . '</em> is not allowed.');
                    return false;
                }
            }
            $matching_users = phoromatic_server::$db->querySingle('SELECT UserName FROM phoromatic_users WHERE UserName = \'' . SQLite3::escapeString($_POST['username']) . '\'');
            if (!empty($matching_users)) {
                phoromatic_error_page('Oops!', 'The user-name is already taken.');
                return false;
            }
            if (!isset($_POST['admin_level']) || $_POST['admin_level'] == 1 || !is_numeric($_POST['admin_level'])) {
                phoromatic_error_page('Oops!', 'Invalid administration level.');
                return false;
            }
            $stmt = phoromatic_server::$db->prepare('SELECT Salt FROM phoromatic_accounts WHERE AccountID = :account_id');
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $result = $stmt->execute();
            $row = $result->fetchArray();
            $account_salt = $row['Salt'];
            $user_id = pts_strings::random_characters(4, true);
            $salted_password = hash('sha256', $account_salt . $_POST['password']);
            pts_logger::add_to_log($_SERVER['REMOTE_ADDR'] . ' created a new account: ' . $user_id . ' - ' . $_SESSION['AccountID']);
            $stmt = phoromatic_server::$db->prepare('INSERT INTO phoromatic_users (UserID, AccountID, UserName, Email, Password, CreatedOn, LastIP, AdminLevel) VALUES (:user_id, :account_id, :user_name, :email, :password, :current_time, :last_ip, :admin_level)');
            $stmt->bindValue(':user_id', $user_id);
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $stmt->bindValue(':user_name', $_POST['username']);
            $stmt->bindValue(':email', $_POST['email']);
            $stmt->bindValue(':password', $salted_password);
            $stmt->bindValue(':last_ip', $_SERVER['REMOTE_ADDR']);
            $stmt->bindValue(':current_time', phoromatic_server::current_time());
            $stmt->bindValue(':admin_level', $_POST['admin_level']);
            $result = $stmt->execute();
            $stmt = phoromatic_server::$db->prepare('INSERT INTO phoromatic_user_settings (UserID, AccountID) VALUES (:user_id, :account_id)');
            $stmt->bindValue(':user_id', $user_id);
            $stmt->bindValue(':account_id', $_SESSION['AccountID']);
            $result = $stmt->execute();
            phoromatic_add_activity_stream_event('users', $_POST['username'], 'added');
        }
        if ($_SESSION['AdminLevel'] == 1 && isset($_POST['update_user_levels'])) {
            foreach (explode(',', $_POST['update_user_levels']) as $user_id) {
                if (isset($_POST['admin_level_' . $user_id]) && is_numeric($_POST['admin_level_' . $user_id])) {
                    $stmt = phoromatic_server::$db->prepare('UPDATE phoromatic_users SET AdminLevel = :admin_level WHERE AccountID = :account_id AND UserID = :user_id');
                    $stmt->bindValue(':admin_level', $_POST['admin_level_' . $user_id]);
                    $stmt->bindValue(':user_id', $user_id);
                    $stmt->bindValue(':account_id', $_SESSION['AccountID']);
                    $result = $stmt->execute();
                }
            }
        }
        $main = '<h2>Users</h2>
			<p>Users associated with this account. Phoromatic users can be one of several tiers with varying privileges:</p>
			<ol>
				<li><strong>Group Administrator:</strong> The user with full control over the account, the one who originally signed up for the Phoromatic account.</li>
				<li><strong>Administrator:</strong> Additional users created by the group administrator with the same access rights as the group administrator.</li>
				<li><strong>Power Users:</strong> Additional users created by the group administrator with read/write/modify access to all standard Phoromatic functionality, aside from being able to create additional users.</li>
				<li><strong>Viewer:</strong> Additional users created by the group administrator that have access to view data but not to create new schedules, alter system settings, etc.</li>
			</ol>
			<div class="pts_phoromatic_info_box_area">

				<div style="margin: 0 20%;"><form action="' . $_SERVER['REQUEST_URI'] . '" name="edit_user" id="edit_user" method="post">
					<ul>
						<li><h1>All Users</h1></li>';
        $stmt = phoromatic_server::$db->prepare('SELECT * FROM phoromatic_users WHERE AccountID = :account_id ORDER BY UserName ASC');
        $stmt->bindValue(':account_id', $_SESSION['AccountID']);
        $result = $stmt->execute();
        $row = $result->fetchArray();
        $user_ids = array();
        do {
            switch ($row['AdminLevel']) {
                case 1:
                    $level = 'Group Administrator';
                    break;
                case 2:
                    $level = 'Administrator';
                    break;
                case 3:
                    $level = 'Power User';
                    break;
                case 10:
                    $level = 'Viewer';
                    break;
                default:
                    if ($row['AdminLevel'] < 1) {
                        $level = 'Disabled';
                    } else {
                        $level = 'Unknown';
                    }
                    break;
            }
            $main .= '<a href="#"><li>' . $row['UserName'] . '<br /><table><tr><td>';
            if ($row['AdminLevel'] == 1 || $_SESSION['AdminLevel'] != 1) {
                $main .= '<strong>' . $level . '</strong>';
            } else {
                $main .= '<select name="admin_level_' . $row['UserID'] . '">';
                foreach (array($row['AdminLevel'] * -1 => 'Disabled', 2 => 'Administrator', 3 => 'Power User', 10 => 'Viewer') as $level_id => $level_string) {
                    $main .= '<option value="' . $level_id . '"' . ($row['AdminLevel'] == $level_id ? ' selected="selected"' : null) . '>' . $level_string . '</option>';
                }
                $main .= '</select>';
                array_push($user_ids, $row['UserID']);
            }
            $main .= '</td><td>Last Login: '******'LastLogin']) ? 'Never' : date('j F Y H:i', strtotime($row['LastLogin']))) . '</td></tr></table></li></a>';
        } while ($row = $result->fetchArray());
        $main .= '</ul> &nbsp; <input type="hidden" name="update_user_levels" value="' . implode(',', $user_ids) . '" /> <input name="submit" value="Update User Levels" type="submit" /></form>
				</div>
			</div>';
        $main .= '<hr /><form action="' . $_SERVER['REQUEST_URI'] . '" name="add_user" id="add_user" method="post" onsubmit="return validate_new_user();"><h2>Create Additional Account</h2>
			<p>Administrators can create extra accounts to be associated with this account\'s systems, schedules, and test data.</p>
			<h3>User</h3>
			<p><input type="text" name="username" /></p>
			<h3>Password</h3>
			<p><input type="password" name="password" /></p>
			<h3>Confirm Password</h3>
			<p><input type="password" name="confirm_password" /></p>
			<h3>Email</h3>
			<p><input type="text" name="email" /></p>
			<h3>Administration Level</h3>
			<p><select name="admin_level">';
        if ($_SESSION['AdminLevel'] == 1) {
            $main .= '<option value="2">Administrator</option>';
        }
        if ($_SESSION['AdminLevel'] <= 2) {
            $main .= '<option value="3">Power User</option>';
        }
        if ($_SESSION['AdminLevel'] <= 3) {
            $main .= '<option value="10">Viewer</option>';
        }
        $main .= '
			</select></p>
			<p><input name="submit" value="Add User" type="submit" /></p>
			</form>';
        $group_name = phoromatic_account_id_to_group_name($_SESSION['AccountID']);
        $main .= '<hr /><form action="' . $_SERVER['REQUEST_URI'] . '" name="group_name" id="group_name" method="post"><h2>Group Name</h2>
			<p>A group name is an alternative, user-facing name for this set of accounts. The group name feature is primarily useful for being able to better distinguish results between groups when sharing of data within a large organization, etc. The group name is showed next to test results when viewing results from multiple groups/accounts.</p>
			<h3>Group Name</h3>
			<p><input type="text" name="group_name" value="' . $group_name . '" /></p>
			<p><input name="submit" value="Update Group Name" type="submit" /></p>
			</form>';
        echo phoromatic_webui_header_logged_in();
        echo '<div id="pts_phoromatic_main_area">' . $main . '</div>';
        echo phoromatic_webui_footer();
    }