Exemplo n.º 1
1
/**
 * Process the query
 * @param $user the user to look for
 * @param $password the user password
 * @param $id the id in the hatting table
 */
function processLoad($user, $password, $id)
{
    // Connect to the database
    $pdo = pdo_connect();
    getUser($pdo, $user, $password);
    $idQ = $pdo->quote($id);
    $query = "SELECT name, uri, type, x, y, rotation, scale, color, feather from hatting where id={$idQ}";
    $rows = $pdo->query($query);
    if ($row = $rows->fetch()) {
        // We found the record in the database
        echo "<hatter status=\"yes\">";
        $uri = $row['uri'];
        $x = $row['x'];
        $y = $row['y'];
        $angle = $row['rotation'];
        $scale = $row['scale'];
        $color = $row['color'];
        $hat = $row['type'];
        $feather = $row['feather'] == 1 ? "yes" : "no";
        echo "<hatting uri=\"{$uri}\" x=\"{$x}\" y=\"{$y}\" angle=\"{$angle}\" scale=\"{$scale}\" color=\"{$color}\" type=\"{$hat}\" feather=\"{$feather}\" />\r\n";
        echo "</hatter>";
        exit;
    }
    echo '<hatter status="no" msg="image" />';
}
Exemplo n.º 2
0
function saveMedia($bin_name, $base_imgpath)
{
    $folder_path = $base_imgpath . '/' . $bin_name . '/';
    try {
        $dbh = pdo_connect();
        $sql = 'SELECT COUNT(DISTINCT `id`) FROM `' . $bin_name . '_media`';
        $rec = $dbh->prepare($sql);
        $rec->execute();
        $row = $rec->fetch(PDO::FETCH_NUM);
        echo 'This bin: ' . $bin_name . ' has ' . $row[0] . ' media files.' . PHP_EOL;
        $sql = 'SELECT DISTINCT `id`, `media_url_https` FROM `' . $bin_name . '_media`';
        $rec2 = $dbh->prepare($sql);
        $rec2->execute();
        $i = 1;
        while ($row = $rec2->fetch(PDO::FETCH_ASSOC)) {
            echo $i . '. ';
            saveMedia2File($folder_path, $row['media_url_https'], $row['id']);
            $i++;
        }
        unset($dbh);
    } catch (PDOException $e) {
        $errorMessage = $e->getCode() . ': ' . $e->getMessage();
        return $errorMessage;
    }
}
Exemplo n.º 3
0
function get_related_dates($projectname, $basedate)
{
    include "cdash/config.php";
    require_once "cdash/pdo.php";
    $dates = array();
    $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
    pdo_select_db("{$CDASH_DB_NAME}", $db);
    $dbQuery = pdo_query("SELECT nightlytime FROM project WHERE name='{$projectname}'");
    if (pdo_num_rows($dbQuery) > 0) {
        $project = pdo_fetch_array($dbQuery);
        $nightlytime = $project['nightlytime'];
        //echo "query result nightlytime: " . $nightlytime . "<br/>";
    } else {
        $nightlytime = "00:00:00";
        //echo "default nightlytime: " . $nightlytime . "<br/>";
    }
    if (!isset($basedate) || strlen($basedate) == 0) {
        $basedate = gmdate(FMT_DATE);
    }
    // Convert the nightly time into GMT
    $nightlytime = gmdate(FMT_TIME, strtotime($nightlytime));
    $nightlyhour = time2hour($nightlytime);
    $nightlyminute = time2minute($nightlytime);
    $nightlysecond = time2second($nightlytime);
    $basemonth = date2month($basedate);
    $baseday = date2day($basedate);
    $baseyear = date2year($basedate);
    $dates['nightly+2'] = gmmktime($nightlyhour, $nightlyminute, $nightlysecond, $basemonth, $baseday + 2, $baseyear);
    $dates['nightly+1'] = gmmktime($nightlyhour, $nightlyminute, $nightlysecond, $basemonth, $baseday + 1, $baseyear);
    $dates['nightly-0'] = gmmktime($nightlyhour, $nightlyminute, $nightlysecond, $basemonth, $baseday, $baseyear);
    $dates['nightly-1'] = gmmktime($nightlyhour, $nightlyminute, $nightlysecond, $basemonth, $baseday - 1, $baseyear);
    $dates['nightly-2'] = gmmktime($nightlyhour, $nightlyminute, $nightlysecond, $basemonth, $baseday - 2, $baseyear);
    // Snapshot of "now"
    //
    $currentgmtime = time();
    $currentgmdate = gmdate(FMT_DATE, $currentgmtime);
    // Find the most recently past nightly time:
    //
    $todaymonth = date2month($currentgmdate);
    $todayday = date2day($currentgmdate);
    $todayyear = date2year($currentgmdate);
    $currentnightly = gmmktime($nightlyhour, $nightlyminute, $nightlysecond, $todaymonth, $todayday, $todayyear);
    while ($currentnightly > $currentgmtime) {
        $todayday = $todayday - 1;
        $currentnightly = gmmktime($nightlyhour, $nightlyminute, $nightlysecond, $todaymonth, $todayday, $todayyear);
    }
    $dates['now'] = $currentgmtime;
    $dates['most-recent-nightly'] = $currentnightly;
    $dates['today_utc'] = $currentgmdate;
    $dates['basedate'] = gmdate(FMT_DATE, $dates['nightly-0']);
    // CDash equivalent of DART1's "last rollup time"
    if ($dates['basedate'] === $dates['today_utc']) {
        // If it's today, it's now:
        $dates['last-rollup-time'] = $dates['now'];
    } else {
        // If it's not today, it's the nightly time on the basedate:
        $dates['last-rollup-time'] = $dates['nightly-0'];
    }
    return $dates;
}
Exemplo n.º 4
0
/**
 * Process the XML query
 * @param $xmltext the provided XML
 */
function processXml($xmltext)
{
    // Load the XML
    $xml = new XMLReader();
    if (!$xml->XML($xmltext)) {
        echo '<hatter status="no" msg="invalid XML" />';
        exit;
    }
    // Connect to the database
    $pdo = pdo_connect();
    // Read to the start tag
    while ($xml->read()) {
        if ($xml->nodeType == XMLReader::ELEMENT && $xml->name == "hatter") {
            // We have the hatter tag
            $magic = $xml->getAttribute("magic");
            if ($magic != "NechAtHa6RuzeR8x") {
                echo '<hatter status="no" msg="magic" />';
                exit;
            }
            $user = $xml->getAttribute("user");
            $password = $xml->getAttribute("pw");
            $userid = getUser($pdo, $user, $password);
            // Read to the hatting tag
            while ($xml->read()) {
                if ($xml->nodeType == XMLReader::ELEMENT && $xml->name == "hatting") {
                    $name = $xml->getAttribute("name");
                    $uri = $xml->getAttribute("uri");
                    $x = $xml->getAttribute("x");
                    $y = $xml->getAttribute("y");
                    $angle = $xml->getAttribute("angle");
                    $scale = $xml->getAttribute("scale");
                    $color = $xml->getAttribute("color");
                    $hat = $xml->getAttribute("hat");
                    $feather = $xml->getAttribute("feather") == "yes" ? 1 : 0;
                    $nameQ = $pdo->quote($name);
                    $uriQ = $pdo->quote($uri);
                    // Checks
                    if (!is_numeric($x) || !is_numeric($y) || !is_numeric($angle) || !is_numeric($scale) || !is_numeric($color) || !is_numeric($hat)) {
                        echo '<hatter status="no" msg="invalid" />';
                        exit;
                    }
                    $query = <<<QUERY
REPLACE INTO hatting(name, userid, uri, type, x, y, rotation, scale, color, feather)
VALUES({$nameQ}, '{$userid}', {$uriQ}, {$hat}, {$x}, {$y}, {$angle}, {$scale}, {$color}, {$feather})
QUERY;
                    if (!$pdo->query($query)) {
                        echo '<hatter status="no" msg="insertfail">' . $query . '</hatter>';
                        exit;
                    }
                    echo '<hatter status="yes"/>';
                    exit;
                }
            }
        }
    }
    echo '<hatter save="no" msg="invalid XML" />';
}
Exemplo n.º 5
0
function pdo_select_db($database, $link_identifier = null)
{
    global $CDASH_DB_HOST, $CDASH_DB_LOGIN, $CDASH_DB_PASS, $cdash_database_connection;
    if (!is_null($link_identifier) and $link_identifier instanceof CDash\Database and $cdash_database_connection->getDatabaseName() === $database) {
        $cdash_database_connection = $link_identifier;
    } else {
        $cdash_database_connection = pdo_connect($CDASH_DB_HOST, $CDASH_DB_LOGIN, $CDASH_DB_PASS, $database);
    }
    return true;
}
Exemplo n.º 6
0
/**
 * Ask the database for the user ID. If the user exists, the password
 * must match.
 * @param $pdo PHP Data Object
 * @param $user The user name
 * @param $password Password
 * @return id if successful or exits if not
 */
function updateroomstatus($stat, $email, $roomNum, $location)
{
    // Connect to the database
    $pdo = pdo_connect();
    $sql = <<<SQL
        UPDATE conferenceRooms
        SET status=?,roomEmail=?
        WHERE confRm=?
SQL;
    $statement = $pdo->prepare($sql);
    $statement->execute(array($stat, $email, $roomNum, $location));
}
Exemplo n.º 7
0
/** */
function get_link_identifier($link_identifier = NULL)
{
    global $CDASH_DB_TYPE;
    global $last_link;
    if (isset($link_identifier)) {
        return $link_identifier;
    }
    if (isset($last_link)) {
        return $last_link;
    }
    $last_link = pdo_connect();
    return $last_link;
}
Exemplo n.º 8
0
/**
 * Process the query
 * @param $user the user to look for
 * @param $password the user password
 * @param $id the id in the hatting table
 */
function processDelete($user, $password, $id)
{
    // Connect to the database
    $pdo = pdo_connect();
    $idQ = $pdo->quote($id);
    getUser($pdo, $user, $password);
    $query = "DELETE from hatting where id={$idQ}";
    if (!$pdo->query($query)) {
        echo '<hatter status="no" msg="deletefail">' . $query . '</hatter>';
        exit;
    }
    echo '<hatter status="yes"/>';
    $pdo = null;
}
Exemplo n.º 9
0
/**
 * Process the query
 * @param $user the user to look for
 * @param $password the user password
 */
function process($user, $password)
{
    // Connect to the database
    $pdo = pdo_connect();
    $userid = getUser($pdo, $user, $password);
    $query = "select id, name from hatting where userid='{$userid}'";
    $rows = $pdo->query($query);
    echo "<hatter status=\"yes\">";
    foreach ($rows as $row) {
        $id = $row['id'];
        $name = $row['name'];
        echo "<hatting id=\"{$id}\" name=\"{$name}\" />\r\n";
    }
    echo "</hatter>";
}
Exemplo n.º 10
0
/**
 * Process the query
 * @param $user the user to look for
 * @param $password the user password
 * @param $id the id in the hatting table
 */
function processLoad()
{
    $pdo = pdo_connect();
    $query = "SELECT * from conferenceRooms";
    $statement = $pdo->prepare($query);
    $statement->execute();
    $activities = $statement->fetchAll();
    $x = 0;
    foreach ($activities as $row) {
        $result[$x] = array($row['location'], $row['confRm'], $row['capacity'], $row['polycomExt'], $row['avResources'], $row['ownership'], $row['notes'], $row['status'], $row['floor'], $row['roomEmail']);
        $x = $x + 1;
    }
    echo json_encode($result);
    // echo json_encode($result);
    exit;
}
Exemplo n.º 11
0
function insertroom($location, $room, $floor, $status, $email, $owner, $resources, $capacity)
{
    $poly = "";
    $note = "";
    $sql = <<<SQL
INSERT INTO conferenceRooms(location,confRm,capacity,polycomExt,avResources,ownership,notes,status,floor,roomEmail)
VALUES (?,?,?,?,?,?,?,?,?,?)
SQL;
    $pdo = pdo_connect();
    $statement = $pdo->prepare($sql);
    if ($statement->execute(array($location, $room, $capacity, $poly, $resources, $owner, $note, $status, $floor, $email))) {
        return true;
    } else {
        return false;
    }
}
Exemplo n.º 12
0
function get_dashboard_JSON($projectname, $date, &$response)
{
    include "cdash/config.php";
    require_once "cdash/pdo.php";
    $projectid = get_project_id($projectname);
    if ($projectid == -1) {
        return;
    }
    $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
    if (!$db) {
        echo "Error connecting to CDash database server<br>\n";
        exit(0);
    }
    if (!pdo_select_db("{$CDASH_DB_NAME}", $db)) {
        echo "Error selecting CDash database<br>\n";
        exit(0);
    }
    $project = pdo_query("SELECT * FROM project WHERE id='{$projectid}'");
    if (pdo_num_rows($project) > 0) {
        $project_array = pdo_fetch_array($project);
    } else {
        $project_array = array();
        $project_array["cvsurl"] = "unknown";
        $project_array["bugtrackerurl"] = "unknown";
        $project_array["documentationurl"] = "unknown";
        $project_array["homeurl"] = "unknown";
        $project_array["googletracker"] = "unknown";
        $project_array["name"] = $projectname;
        $project_array["nightlytime"] = "00:00:00";
    }
    list($previousdate, $currentstarttime, $nextdate) = get_dates($date, $project_array["nightlytime"]);
    $response['datetime'] = date("l, F d Y H:i:s", time());
    $response['date'] = $date;
    $response['unixtimestamp'] = $currentstarttime;
    $response['startdate'] = date("l, F d Y H:i:s", $currentstarttime);
    $response['svn'] = make_cdash_url(htmlentities($project_array["cvsurl"]));
    $response['bugtracker'] = make_cdash_url(htmlentities($project_array["bugtrackerurl"]));
    $response['googletracker'] = htmlentities($project_array["googletracker"]);
    $response['documentation'] = make_cdash_url(htmlentities($project_array["documentationurl"]));
    $response['projectid'] = $projectid;
    $response['projectname'] = $project_array["name"];
    $response['projectname_encoded'] = urlencode($project_array["name"]);
    $response['projectpublic'] = $project_array["public"];
    $response['previousdate'] = $previousdate;
    $response['nextdate'] = $nextdate;
    $response['logoid'] = getLogoID($projectid);
    if (empty($project_array["homeurl"])) {
        $response['home'] = "index.php?project=" . urlencode($project_array["name"]);
    } else {
        $response['home'] = make_cdash_url(htmlentities($project_array["homeurl"]));
    }
    if ($CDASH_USE_LOCAL_DIRECTORY && file_exists("local/models/proProject.php")) {
        include_once "local/models/proProject.php";
        $pro = new proProject();
        $pro->ProjectId = $projectid;
        $response['proedition'] = $pro->GetEdition(1);
    }
    $userid = 0;
    if (isset($_SESSION['cdash'])) {
        $userid = $_SESSION['cdash']['loginid'];
        // Is the user super administrator
        $userquery = pdo_query("SELECT admin FROM " . qid('user') . " WHERE id='{$userid}'");
        $user_array = pdo_fetch_array($userquery);
        $response['admin'] = $user_array[0];
        // Is the user administrator of the project
        $userquery = pdo_query("SELECT role FROM user2project WHERE userid=" . qnum($userid) . " AND projectid=" . qnum($projectid));
        $user_array = pdo_fetch_array($userquery);
        $response['projectrole'] = $user_array[0];
    }
    $response['userid'] = $userid;
}
Exemplo n.º 13
0
function deleteGame($username, $title)
{
    $data = array();
    $connection = pdo_connect();
    if (doesTitleExist($username, $title)) {
        $query = <<<SQL
DELETE
FROM SAVEGAMES
WHERE Username = ? AND Title = ?
SQL;
        $statement = $connection->prepare($query);
        $result = $statement->execute(array($username, $title));
        if ($result == true) {
            $data['delete'] = true;
        } else {
            $data['delete'] = false;
            $data['error'] = "Couldn't delete";
        }
    } else {
        $data['delete'] = false;
        $data['error'] = "Title not valid";
    }
    echo json_encode($data);
}
Exemplo n.º 14
0
function echo_main_dashboard_JSON($project_instance, $date)
{
    $start = microtime_float();
    $noforcelogin = 1;
    include_once dirname(dirname(dirname(__DIR__))) . '/config/config.php';
    require_once 'include/pdo.php';
    include 'public/login.php';
    include_once 'models/banner.php';
    include_once 'models/build.php';
    include_once 'models/subproject.php';
    $response = array();
    $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
    if (!$db) {
        $response['error'] = 'Error connecting to CDash database server';
        echo json_encode($response);
        return;
    }
    if (!pdo_select_db("{$CDASH_DB_NAME}", $db)) {
        $response['error'] = 'Error selecting CDash database';
        echo json_encode($response);
        return;
    }
    $projectid = $project_instance->Id;
    $project = pdo_query("SELECT * FROM project WHERE id='{$projectid}'");
    if (pdo_num_rows($project) > 0) {
        $project_array = pdo_fetch_array($project);
        $projectname = $project_array['name'];
        if (isset($project_array['testingdataurl']) && $project_array['testingdataurl'] != '') {
            $testingdataurl = make_cdash_url(htmlentities($project_array['testingdataurl']));
        }
    } else {
        $response['error'] = "This project doesn't exist. Maybe the URL you are trying to access is wrong.";
        echo json_encode($response);
        return;
    }
    if (!checkUserPolicy(@$_SESSION['cdash']['loginid'], $project_array['id'], 1)) {
        $response['requirelogin'] = 1;
        echo json_encode($response);
        return;
    }
    $response = begin_JSON_response();
    $response['title'] = "CDash - {$projectname}";
    $response['feed'] = $CDASH_ENABLE_FEED;
    $response['showcalendar'] = 1;
    $Banner = new Banner();
    $Banner->SetProjectId(0);
    $text = $Banner->GetText();
    $banners = array();
    if ($text !== false) {
        $banners[] = $text;
    }
    $Banner->SetProjectId($projectid);
    $text = $Banner->GetText();
    if ($text !== false) {
        $banners[] = $text;
    }
    $response['banners'] = $banners;
    $site_response = array();
    // If parentid is set we need to lookup the date for this build
    // because it is not specified as a query string parameter.
    if (isset($_GET['parentid'])) {
        $parentid = pdo_real_escape_numeric($_GET['parentid']);
        $parent_build = new Build();
        $parent_build->Id = $parentid;
        $date = $parent_build->GetDate();
        $response['parentid'] = $parentid;
    } else {
        $response['parentid'] = -1;
    }
    list($previousdate, $currentstarttime, $nextdate) = get_dates($date, $project_array['nightlytime']);
    // Main dashboard section
    get_dashboard_JSON($projectname, $date, $response);
    $response['displaylabels'] = $project_array['displaylabels'];
    $page_id = 'index.php';
    $response['childview'] = 0;
    if ($CDASH_USE_LOCAL_DIRECTORY && file_exists('local/models/proProject.php')) {
        include_once 'local/models/proProject.php';
        $pro = new proProject();
        $pro->ProjectId = $projectid;
        $response['proedition'] = $pro->GetEdition(1);
    }
    if ($currentstarttime > time() && !isset($_GET['parentid'])) {
        $response['error'] = 'CDash cannot predict the future (yet)';
        echo json_encode($response);
        return;
    }
    // Menu definition
    $response['menu'] = array();
    $beginning_timestamp = $currentstarttime;
    $end_timestamp = $currentstarttime + 3600 * 24;
    $beginning_UTCDate = gmdate(FMT_DATETIME, $beginning_timestamp);
    $end_UTCDate = gmdate(FMT_DATETIME, $end_timestamp);
    if ($project_instance->GetNumberOfSubProjects($end_UTCDate) > 0) {
        $response['menu']['subprojects'] = 1;
    }
    if (isset($_GET['parentid'])) {
        $page_id = 'indexchildren.php';
        $response['childview'] = 1;
        // When a parentid is specified, we should link to the next build,
        // not the next day.
        $previous_buildid = $parent_build->GetPreviousBuildId();
        $current_buildid = $parent_build->GetCurrentBuildId();
        $next_buildid = $parent_build->GetNextBuildId();
        $base_url = 'index.php?project=' . urlencode($projectname);
        if ($previous_buildid > 0) {
            $response['menu']['previous'] = "{$base_url}&parentid={$previous_buildid}";
        } else {
            $response['menu']['noprevious'] = '1';
        }
        $response['menu']['current'] = "{$base_url}&parentid={$current_buildid}";
        if ($next_buildid > 0) {
            $response['menu']['next'] = "{$base_url}&parentid={$next_buildid}";
        } else {
            $response['menu']['nonext'] = '1';
        }
    } elseif (!has_next_date($date, $currentstarttime)) {
        $response['menu']['nonext'] = 1;
    }
    // Check if a SubProject parameter was specified.
    $subproject_name = @$_GET['subproject'];
    $subprojectid = false;
    if ($subproject_name) {
        $SubProject = new SubProject();
        $subproject_name = htmlspecialchars(pdo_real_escape_string($subproject_name));
        $SubProject->SetName($subproject_name);
        $SubProject->SetProjectId($projectid);
        $subprojectid = $SubProject->GetId();
        if ($subprojectid) {
            // Add an extra URL argument for the menu
            $response['extraurl'] = '&subproject=' . urlencode($subproject_name);
            $response['subprojectname'] = $subproject_name;
            $subproject_response = array();
            $subproject_response['name'] = $SubProject->GetName();
            $dependencies = $SubProject->GetDependencies();
            if ($dependencies) {
                $dependencies_response = array();
                foreach ($dependencies as $dependency) {
                    $dependency_response = array();
                    $DependProject = new SubProject();
                    $DependProject->SetId($dependency);
                    $dependency_response['name'] = $DependProject->GetName();
                    $dependency_response['name_encoded'] = urlencode($DependProject->GetName());
                    $dependency_response['nbuilderror'] = $DependProject->GetNumberOfErrorBuilds($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['nbuildwarning'] = $DependProject->GetNumberOfWarningBuilds($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['nbuildpass'] = $DependProject->GetNumberOfPassingBuilds($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['nconfigureerror'] = $DependProject->GetNumberOfErrorConfigures($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['nconfigurewarning'] = $DependProject->GetNumberOfWarningConfigures($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['nconfigurepass'] = $DependProject->GetNumberOfPassingConfigures($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['ntestpass'] = $DependProject->GetNumberOfPassingTests($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['ntestfail'] = $DependProject->GetNumberOfFailingTests($beginning_UTCDate, $end_UTCDate);
                    $dependency_response['ntestnotrun'] = $DependProject->GetNumberOfNotRunTests($beginning_UTCDate, $end_UTCDate);
                    if (strlen($DependProject->GetLastSubmission()) == 0) {
                        $dependency_response['lastsubmission'] = 'NA';
                    } else {
                        $dependency_response['lastsubmission'] = $DependProject->GetLastSubmission();
                    }
                    $dependencies_response[] = $dependency_response;
                }
                $subproject_response['dependencies'] = $dependencies_response;
            }
            $response['subproject'] = $subproject_response;
        } else {
            add_log("SubProject '{$subproject_name}' does not exist", __FILE__ . ':' . __LINE__ . ' - ' . __FUNCTION__, LOG_WARNING);
        }
    }
    if (isset($testingdataurl)) {
        $response['testingdataurl'] = $testingdataurl;
    }
    // updates
    $updates_response = array();
    $gmdate = gmdate(FMT_DATE, $currentstarttime);
    $updates_response['url'] = 'viewChanges.php?project=' . urlencode($projectname) . '&amp;date=' . $gmdate;
    $dailyupdate = pdo_query("SELECT count(ds.dailyupdateid),count(distinct ds.author)\n            FROM dailyupdate AS d LEFT JOIN dailyupdatefile AS ds ON (ds.dailyupdateid = d.id)\n            WHERE d.date='{$gmdate}' and d.projectid='{$projectid}' GROUP BY ds.dailyupdateid");
    if (pdo_num_rows($dailyupdate) > 0) {
        $dailupdate_array = pdo_fetch_array($dailyupdate);
        $updates_response['nchanges'] = $dailupdate_array[0];
        $updates_response['nauthors'] = $dailupdate_array[1];
    } else {
        $updates_response['nchanges'] = -1;
    }
    $updates_response['timestamp'] = date('l, F d Y - H:i T', $currentstarttime);
    $response['updates'] = $updates_response;
    // This array is used to track if expected builds are found or not.
    $received_builds = array();
    // Get info about our buildgroups.
    $buildgroups_response = array();
    $buildgroup_result = pdo_query("SELECT bg.id, bg.name, bgp.position FROM buildgroup AS bg\n            LEFT JOIN buildgroupposition AS bgp ON (bgp.buildgroupid=bg.id)\n            WHERE bg.projectid={$projectid} AND bg.starttime < '{$beginning_UTCDate}' AND\n            (bg.endtime > '{$beginning_UTCDate}' OR\n             bg.endtime='1980-01-01 00:00:00')");
    while ($buildgroup_array = pdo_fetch_array($buildgroup_result)) {
        $buildgroup_response = array();
        $groupname = $buildgroup_array['name'];
        $buildgroup_response['id'] = $buildgroup_array['id'];
        $buildgroup_response['name'] = $groupname;
        $buildgroup_response['linkname'] = str_replace(' ', '_', $groupname);
        $buildgroup_response['position'] = $buildgroup_array['position'];
        $buildgroup_response['numupdatedfiles'] = 0;
        $buildgroup_response['numupdateerror'] = 0;
        $buildgroup_response['numupdatewarning'] = 0;
        $buildgroup_response['updateduration'] = 0;
        $buildgroup_response['configureduration'] = 0;
        $buildgroup_response['numconfigureerror'] = 0;
        $buildgroup_response['numconfigurewarning'] = 0;
        $buildgroup_response['numbuilderror'] = 0;
        $buildgroup_response['numbuildwarning'] = 0;
        $buildgroup_response['numtestnotrun'] = 0;
        $buildgroup_response['numtestfail'] = 0;
        $buildgroup_response['numtestpass'] = 0;
        $buildgroup_response['testduration'] = 0;
        $buildgroup_response['hasupdatedata'] = false;
        $buildgroup_response['hasconfiguredata'] = false;
        $buildgroup_response['hascompilationdata'] = false;
        $buildgroup_response['hastestdata'] = false;
        $buildgroup_response['hasnormalbuilds'] = false;
        $buildgroup_response['hasparentbuilds'] = false;
        $buildgroup_response['builds'] = array();
        $received_builds[$groupname] = array();
        $buildgroups_response[] = $buildgroup_response;
    }
    // Filters:
    //
    $filterdata = get_filterdata_from_request($page_id);
    $filter_sql = $filterdata['sql'];
    $limit_sql = '';
    if ($filterdata['limit'] > 0) {
        $limit_sql = ' LIMIT ' . $filterdata['limit'];
    }
    unset($filterdata['xml']);
    $response['filterdata'] = $filterdata;
    $response['filterurl'] = get_filterurl();
    // Check if we should be excluding some SubProjects from our
    // build results.
    $include_subprojects = false;
    $exclude_subprojects = false;
    $included_subprojects = array();
    $excluded_subprojects = array();
    $selected_subprojects = '';
    $num_selected_subprojects = 0;
    $filter_on_labels = false;
    $share_label_filters = false;
    foreach ($filterdata['filters'] as $filter) {
        if ($filter['field'] == 'subprojects') {
            if ($filter['compare'] == 92) {
                $excluded_subprojects[] = $filter['value'];
            } elseif ($filter['compare'] == 93) {
                $included_subprojects[] = $filter['value'];
            }
        } elseif ($filter['field'] == 'label') {
            $filter_on_labels = true;
        }
    }
    if ($filter_on_labels && $project_instance->ShareLabelFilters) {
        $share_label_filters = true;
        $response['sharelabelfilters'] = true;
        $label_ids_array = get_label_ids_from_filterdata($filterdata);
        $label_ids = '(' . implode(', ', $label_ids_array) . ')';
    }
    // Include takes precedence over exclude.
    if (!empty($included_subprojects)) {
        $num_selected_subprojects = count($included_subprojects);
        $selected_subprojects = implode("','", $included_subprojects);
        $selected_subprojects = "('" . $selected_subprojects . "')";
        $include_subprojects = true;
    } elseif (!empty($excluded_subprojects)) {
        $num_selected_subprojects = count($excluded_subprojects);
        $selected_subprojects = implode("','", $excluded_subprojects);
        $selected_subprojects = "('" . $selected_subprojects . "')";
        $exclude_subprojects = true;
    }
    // add a request for the subproject
    $subprojectsql = '';
    if ($subproject_name && is_numeric($subprojectid)) {
        $subprojectsql = ' AND sp2b.subprojectid=' . $subprojectid;
    }
    // Use this as the default date clause, but if $filterdata has a date clause,
    // then cancel this one out:
    //
    $date_clause = "AND b.starttime<'{$end_UTCDate}' AND b.starttime>='{$beginning_UTCDate}' ";
    if ($filterdata['hasdateclause']) {
        $date_clause = '';
    }
    $parent_clause = '';
    if (isset($_GET['parentid'])) {
        // If we have a parentid, then we should only show children of that build.
        // Date becomes irrelevant in this case.
        $parent_clause = 'AND (b.parentid = ' . qnum($_GET['parentid']) . ') ';
        $date_clause = '';
    } elseif (empty($subprojectsql)) {
        // Only show builds that are not children.
        $parent_clause = 'AND (b.parentid = -1 OR b.parentid = 0) ';
    }
    $build_rows = array();
    // If the user is logged in we display if the build has some changes for him
    $userupdatesql = '';
    if (isset($_SESSION['cdash']) && array_key_exists('loginid', $_SESSION['cdash'])) {
        $userupdatesql = "(SELECT count(updatefile.updateid) FROM updatefile,build2update,user2project,\n            user2repository\n                WHERE build2update.buildid=b.id\n                AND build2update.updateid=updatefile.updateid\n                AND user2project.projectid=b.projectid\n                AND user2project.userid='" . $_SESSION['cdash']['loginid'] . "'\n                AND user2repository.userid=user2project.userid\n                AND (user2repository.projectid=0 OR user2repository.projectid=b.projectid)\n                AND user2repository.credential=updatefile.author) AS userupdates,";
    }
    $sql = get_index_query();
    $sql .= "WHERE b.projectid='{$projectid}' AND g.type='Daily'\n        {$parent_clause} {$date_clause} {$subprojectsql} {$filter_sql} {$limit_sql}";
    // We shouldn't get any builds for group that have been deleted (otherwise something is wrong)
    $builds = pdo_query($sql);
    // Log any errors
    $pdo_error = pdo_error();
    if (strlen($pdo_error) > 0) {
        add_log('SQL error: ' . $pdo_error, 'Index.php', LOG_ERR);
    }
    // Gather up results from this query.
    $build_data = array();
    while ($build_row = pdo_fetch_array($builds)) {
        $build_data[] = $build_row;
    }
    $dynamic_builds = array();
    if (empty($filter_sql)) {
        $dynamic_builds = get_dynamic_builds($projectid, $end_UTCDate);
        $build_data = array_merge($build_data, $dynamic_builds);
    }
    // Check if we need to summarize coverage by subproject groups.
    // This happens when we have subprojects and we're looking at the children
    // of a specific build.
    $coverage_groups = array();
    if (isset($_GET['parentid']) && $_GET['parentid'] > 0 && $project_instance->GetNumberOfSubProjects($end_UTCDate) > 0) {
        $groups = $project_instance->GetSubProjectGroups();
        foreach ($groups as $group) {
            // Keep track of coverage info on a per-group basis.
            $groupId = $group->GetId();
            $coverage_groups[$groupId] = array();
            $coverageThreshold = $group->GetCoverageThreshold();
            $coverage_groups[$groupId]['thresholdgreen'] = $coverageThreshold;
            $coverage_groups[$groupId]['thresholdyellow'] = $coverageThreshold * 0.7;
            $coverage_groups[$groupId]['label'] = $group->GetName();
            $coverage_groups[$groupId]['loctested'] = 0;
            $coverage_groups[$groupId]['locuntested'] = 0;
            $coverage_groups[$groupId]['position'] = $group->GetPosition();
            $coverage_groups[$groupId]['coverages'] = array();
        }
        if (count($groups) > 1) {
            // Add a Total group too.
            $coverage_groups[0] = array();
            $coverageThreshold = $project_array['coveragethreshold'];
            $coverage_groups[0]['thresholdgreen'] = $coverageThreshold;
            $coverage_groups[0]['thresholdyellow'] = $coverageThreshold * 0.7;
            $coverage_groups[0]['label'] = 'Total';
            $coverage_groups[0]['loctested'] = 0;
            $coverage_groups[0]['locuntested'] = 0;
            $coverage_groups[0]['position'] = 0;
        }
    }
    // Fetch all the rows of builds into a php array.
    // Compute additional fields for each row that we'll need to generate the xml.
    //
    $build_rows = array();
    foreach ($build_data as $build_row) {
        // Fields that come from the initial query:
        //  id
        //  sitename
        //  stamp
        //  name
        //  siteid
        //  type
        //  generator
        //  starttime
        //  endtime
        //  submittime
        //  groupname
        //  position
        //  groupid
        //  countupdatefiles
        //  updatestatus
        //  countupdatewarnings
        //  countbuildwarnings
        //  countbuilderrors
        //  countbuilderrordiff
        //  countbuildwarningdiff
        //  configureduration
        //  countconfigureerrors
        //  countconfigurewarnings
        //  countconfigurewarningdiff
        //  counttestsnotrun
        //  counttestsnotrundiff
        //  counttestsfailed
        //  counttestsfaileddiff
        //  counttestspassed
        //  counttestspasseddiff
        //  countteststimestatusfailed
        //  countteststimestatusfaileddiff
        //  testduration
        //
        // Fields that we add within this loop:
        //  maxstarttime
        //  buildids (array of buildids for summary rows)
        //  countbuildnotes (added by users)
        //  labels
        //  updateduration
        //  countupdateerrors
        //  test
        //
        $buildid = $build_row['id'];
        $groupid = $build_row['groupid'];
        $siteid = $build_row['siteid'];
        $parentid = $build_row['parentid'];
        $build_row['buildids'][] = $buildid;
        $build_row['maxstarttime'] = $build_row['starttime'];
        // Updates
        if (!empty($build_row['updatestarttime'])) {
            $build_row['updateduration'] = round((strtotime($build_row['updateendtime']) - strtotime($build_row['updatestarttime'])) / 60, 1);
        } else {
            $build_row['updateduration'] = 0;
        }
        if (strlen($build_row['updatestatus']) > 0 && $build_row['updatestatus'] != '0') {
            $build_row['countupdateerrors'] = 1;
        } else {
            $build_row['countupdateerrors'] = 0;
        }
        // Error/Warnings differences
        if (empty($build_row['countbuilderrordiffp'])) {
            $build_row['countbuilderrordiffp'] = 0;
        }
        if (empty($build_row['countbuilderrordiffn'])) {
            $build_row['countbuilderrordiffn'] = 0;
        }
        if (empty($build_row['countbuildwarningdiffp'])) {
            $build_row['countbuildwarningdiffp'] = 0;
        }
        if (empty($build_row['countbuildwarningdiffn'])) {
            $build_row['countbuildwarningdiffn'] = 0;
        }
        $build_row['hasconfigure'] = 0;
        if ($build_row['countconfigureerrors'] != -1 || $build_row['countconfigurewarnings'] != -1) {
            $build_row['hasconfigure'] = 1;
        }
        if ($build_row['countconfigureerrors'] < 0) {
            $build_row['countconfigureerrors'] = 0;
        }
        if ($build_row['countconfigurewarnings'] < 0) {
            $build_row['countconfigurewarnings'] = 0;
        }
        if (empty($build_row['countconfigurewarningdiff'])) {
            $build_row['countconfigurewarningdiff'] = 0;
        }
        $build_row['hastest'] = 0;
        if ($build_row['counttestsfailed'] != -1) {
            $build_row['hastest'] = 1;
        }
        if (empty($build_row['testduration'])) {
            $time_array = pdo_fetch_array(pdo_query("SELECT SUM(time) FROM build2test WHERE buildid='{$buildid}'"));
            $build_row['testduration'] = round($time_array[0], 1);
        } else {
            $build_row['testduration'] = round($build_row['testduration'], 1);
        }
        $build_rows[] = $build_row;
    }
    // Generate the JSON response from the rows of builds.
    $response['coverages'] = array();
    $response['dynamicanalyses'] = array();
    $num_nightly_coverages_builds = 0;
    $show_aggregate = false;
    $response['comparecoverage'] = 0;
    foreach ($build_rows as $build_array) {
        $groupid = $build_array['groupid'];
        // Find the buildgroup array for this build.
        $i = -1;
        for ($j = 0; $j < count($buildgroups_response); $j++) {
            if ($buildgroups_response[$j]['id'] == $groupid) {
                $i = $j;
                break;
            }
        }
        if ($i == -1) {
            add_log("BuildGroup '{$groupid}' not found for build #" . $build_array['id'], __FILE__ . ':' . __LINE__ . ' - ' . __FUNCTION__, LOG_WARNING);
            continue;
        }
        $groupname = $buildgroups_response[$i]['name'];
        $build_response = array();
        $received_builds[$groupname][] = $build_array['sitename'] . '_' . $build_array['name'];
        $buildid = $build_array['id'];
        $siteid = $build_array['siteid'];
        $countChildrenResult = pdo_single_row_query('SELECT count(id) AS numchildren
                FROM build WHERE parentid=' . qnum($buildid));
        $numchildren = $countChildrenResult['numchildren'];
        $build_response['numchildren'] = $numchildren;
        $child_builds_hyperlink = '';
        $selected_configure_errors = 0;
        $selected_configure_warnings = 0;
        $selected_configure_duration = 0;
        $selected_build_errors = 0;
        $selected_build_warnings = 0;
        $selected_build_duration = 0;
        $selected_tests_not_run = 0;
        $selected_tests_failed = 0;
        $selected_tests_passed = 0;
        $selected_test_duration = 0;
        if ($numchildren > 0) {
            $child_builds_hyperlink = get_child_builds_hyperlink($build_array['id'], $filterdata);
            $build_response['multiplebuildshyperlink'] = $child_builds_hyperlink;
            $buildgroups_response[$i]['hasparentbuilds'] = true;
            // Compute selected (excluded or included) SubProject results.
            if ($selected_subprojects) {
                $select_query = "\n                    SELECT configureerrors, configurewarnings, configureduration,\n                           builderrors, buildwarnings, buildduration,\n                           b.starttime, b.endtime, testnotrun, testfailed, testpassed,\n                           btt.time AS testduration, sb.name\n                    FROM build AS b\n                    INNER JOIN subproject2build AS sb2b ON (b.id = sb2b.buildid)\n                    INNER JOIN subproject AS sb ON (sb2b.subprojectid = sb.id)\n                    LEFT JOIN buildtesttime AS btt ON (b.id=btt.buildid)\n                    WHERE b.parentid={$buildid}\n                    AND sb.name IN {$selected_subprojects}";
                $select_results = pdo_query($select_query);
                while ($select_array = pdo_fetch_array($select_results)) {
                    $selected_configure_errors += max(0, $select_array['configureerrors']);
                    $selected_configure_warnings += max(0, $select_array['configurewarnings']);
                    $selected_configure_duration += max(0, $select_array['configureduration']);
                    $selected_build_errors += max(0, $select_array['builderrors']);
                    $selected_build_warnings += max(0, $select_array['buildwarnings']);
                    $selected_build_duration += max(0, $select_array['buildduration']);
                    $selected_tests_not_run += max(0, $select_array['testnotrun']);
                    $selected_tests_failed += max(0, $select_array['testfailed']);
                    $selected_tests_passed += max(0, $select_array['testpassed']);
                    $selected_test_duration += max(0, $select_array['testduration']);
                }
            }
        } else {
            $buildgroups_response[$i]['hasnormalbuilds'] = true;
        }
        if (strtolower($build_array['type']) == 'continuous') {
            $buildgroups_response[$i]['sorttype'] = 'time';
        }
        // Attempt to determine the platform based on the OSName and the buildname
        $buildplatform = '';
        if (strtolower(substr($build_array['osname'], 0, 7)) == 'windows') {
            $buildplatform = 'windows';
        } elseif (strtolower(substr($build_array['osname'], 0, 8)) == 'mac os x') {
            $buildplatform = 'mac';
        } elseif (strtolower(substr($build_array['osname'], 0, 5)) == 'linux' || strtolower(substr($build_array['osname'], 0, 3)) == 'aix') {
            $buildplatform = 'linux';
        } elseif (strtolower(substr($build_array['osname'], 0, 7)) == 'freebsd') {
            $buildplatform = 'freebsd';
        } elseif (strtolower(substr($build_array['osname'], 0, 3)) == 'gnu') {
            $buildplatform = 'gnu';
        }
        // Add link based on changeid if appropriate.
        $changelink = null;
        $changeicon = null;
        if ($build_array['changeid'] && $project_instance->CvsViewerType === 'github') {
            $changelink = $project_instance->CvsUrl . '/pull/' . $build_array['changeid'];
            $changeicon = 'img/Octocat.png';
        }
        if (isset($_GET['parentid'])) {
            if (empty($site_response)) {
                $site_response['site'] = $build_array['sitename'];
                $site_response['siteoutoforder'] = $build_array['siteoutoforder'];
                $site_response['siteid'] = $siteid;
                $site_response['buildname'] = $build_array['name'];
                $site_response['buildplatform'] = $buildplatform;
                $site_response['generator'] = $build_array['generator'];
                if (!is_null($changelink)) {
                    $site_response['changelink'] = $changelink;
                    $site_response['changeicon'] = $changeicon;
                }
            }
        } else {
            $build_response['site'] = $build_array['sitename'];
            $build_response['siteoutoforder'] = $build_array['siteoutoforder'];
            $build_response['siteid'] = $siteid;
            $build_response['buildname'] = $build_array['name'];
            $build_response['buildplatform'] = $buildplatform;
            if (!is_null($changelink)) {
                $build_response['changelink'] = $changelink;
                $build_response['changeicon'] = $changeicon;
            }
        }
        if (isset($build_array['userupdates'])) {
            $build_response['userupdates'] = $build_array['userupdates'];
        }
        $build_response['id'] = $build_array['id'];
        $build_response['done'] = $build_array['done'];
        $build_response['uploadfilecount'] = $build_array['builduploadfiles'];
        $build_response['buildnotes'] = $build_array['countbuildnotes'];
        $build_response['notes'] = $build_array['countnotes'];
        // Figure out how many labels to report for this build.
        if (!array_key_exists('numlabels', $build_array) || $build_array['numlabels'] == 0) {
            $num_labels = 0;
        } else {
            $num_labels = $build_array['numlabels'];
        }
        $label_query = 'SELECT l.text FROM label AS l
            INNER JOIN label2build AS l2b ON (l.id=l2b.labelid)
            INNER JOIN build AS b ON (l2b.buildid=b.id)
            WHERE b.id=' . qnum($buildid);
        $build_labels = array();
        if ($num_selected_subprojects > 0) {
            // Special handling for whitelisting/blacklisting SubProjects.
            if ($include_subprojects) {
                $num_labels = 0;
            }
            $labels_result = pdo_query($label_query);
            while ($label_row = pdo_fetch_array($labels_result)) {
                // Whitelist case
                if ($include_subprojects && in_array($label_row['text'], $included_subprojects)) {
                    $num_labels++;
                    $build_labels[] = $label_row['text'];
                }
                // Blacklist case
                if ($exclude_subprojects) {
                    if (in_array($label_row['text'], $excluded_subprojects)) {
                        $num_labels--;
                    } else {
                        $build_labels[] = $label_row['text'];
                    }
                }
            }
            if ($num_labels === 0) {
                // Skip this build entirely if none of its SubProjects
                // survived filtering.
                continue;
            }
        }
        // Assign a label to this build based on how many labels it has.
        if ($num_labels == 0) {
            $build_label = '(none)';
        } elseif ($num_labels == 1) {
            // Exactly one label for this build
            if (!empty($build_labels)) {
                // If we're whitelisting or blacklisting we've already figured
                // out what this label is.
                $build_label = $build_labels[0];
            } else {
                // Otherwise we look it up here.
                $label_result = pdo_single_row_query($label_query);
                $build_label = $label_result['text'];
            }
        } else {
            // More than one label, just report the number.
            $build_label = "({$num_labels} labels)";
        }
        $build_response['label'] = $build_label;
        // Calculate this build's total duration.
        $duration = strtotime($build_array['endtime']) - strtotime($build_array['starttime']);
        $build_response['time'] = time_difference($duration, true);
        $build_response['timefull'] = $duration;
        $update_response = array();
        $countupdatefiles = $build_array['countupdatefiles'];
        $update_response['files'] = $countupdatefiles;
        $buildgroups_response[$i]['numupdatedfiles'] += $countupdatefiles;
        $build_response['hasupdate'] = false;
        if (!empty($build_array['updatestarttime'])) {
            $build_response['hasupdate'] = true;
            if ($build_array['countupdateerrors'] > 0) {
                $update_response['errors'] = 1;
                $buildgroups_response[$i]['numupdateerror'] += 1;
            } else {
                $update_response['errors'] = 0;
                if ($build_array['countupdatewarnings'] > 0) {
                    $update_response['warning'] = 1;
                    $buildgroups_response[$i]['numupdatewarning'] += 1;
                }
            }
            $duration = $build_array['updateduration'];
            $update_response['time'] = time_difference($duration * 60.0, true);
            $update_response['timefull'] = $duration;
            $buildgroups_response[$i]['updateduration'] += $duration;
            $buildgroups_response[$i]['hasupdatedata'] = true;
            $build_response['update'] = $update_response;
        }
        $compilation_response = array();
        if ($build_array['countbuilderrors'] >= 0) {
            if ($include_subprojects) {
                $nerrors = $selected_build_errors;
                $nwarnings = $selected_build_warnings;
                $buildduration = $selected_build_duration;
            } else {
                $nerrors = $build_array['countbuilderrors'] - $selected_build_errors;
                $nwarnings = $build_array['countbuildwarnings'] - $selected_build_warnings;
                $buildduration = $build_array['buildduration'] - $selected_build_duration;
            }
            $compilation_response['error'] = $nerrors;
            $buildgroups_response[$i]['numbuilderror'] += $nerrors;
            $compilation_response['warning'] = $nwarnings;
            $buildgroups_response[$i]['numbuildwarning'] += $nwarnings;
            $compilation_response['time'] = time_difference($buildduration, true);
            $compilation_response['timefull'] = $buildduration;
            if (!$include_subprojects && !$exclude_subprojects) {
                // Don't show diff when filtering by SubProject.
                $compilation_response['nerrordiffp'] = $build_array['countbuilderrordiffp'];
                $compilation_response['nerrordiffn'] = $build_array['countbuilderrordiffn'];
                $compilation_response['nwarningdiffp'] = $build_array['countbuildwarningdiffp'];
                $compilation_response['nwarningdiffn'] = $build_array['countbuildwarningdiffn'];
            }
        }
        $build_response['hascompilation'] = false;
        if (!empty($compilation_response)) {
            $build_response['hascompilation'] = true;
            $build_response['compilation'] = $compilation_response;
            $buildgroups_response[$i]['hascompilationdata'] = true;
        }
        $build_response['hasconfigure'] = false;
        if ($build_array['hasconfigure'] != 0) {
            $build_response['hasconfigure'] = true;
            $configure_response = array();
            if ($include_subprojects) {
                $nconfigureerrors = $selected_configure_errors;
                $nconfigurewarnings = $selected_configure_warnings;
                $configureduration = $selected_configure_duration;
            } else {
                $nconfigureerrors = $build_array['countconfigureerrors'] - $selected_configure_errors;
                $nconfigurewarnings = $build_array['countconfigurewarnings'] - $selected_configure_warnings;
                $configureduration = $build_array['configureduration'] - $selected_configure_duration;
            }
            $configure_response['error'] = $nconfigureerrors;
            $buildgroups_response[$i]['numconfigureerror'] += $nconfigureerrors;
            $configure_response['warning'] = $nconfigurewarnings;
            $buildgroups_response[$i]['numconfigurewarning'] += $nconfigurewarnings;
            if (!$include_subprojects && !$exclude_subprojects) {
                $configure_response['warningdiff'] = $build_array['countconfigurewarningdiff'];
            }
            $configure_response['time'] = time_difference($configureduration, true);
            $configure_response['timefull'] = $configureduration;
            $build_response['configure'] = $configure_response;
            $buildgroups_response[$i]['hasconfiguredata'] = true;
            $buildgroups_response[$i]['configureduration'] += $configureduration;
        }
        $build_response['hastest'] = false;
        if ($build_array['hastest'] != 0) {
            $build_response['hastest'] = true;
            $buildgroups_response[$i]['hastestdata'] = true;
            $test_response = array();
            if ($include_subprojects) {
                $nnotrun = $selected_tests_not_run;
                $nfail = $selected_tests_failed;
                $npass = $selected_tests_passed;
                $testduration = $selected_test_duration;
            } else {
                $nnotrun = $build_array['counttestsnotrun'] - $selected_tests_not_run;
                $nfail = $build_array['counttestsfailed'] - $selected_tests_failed;
                $npass = $build_array['counttestspassed'] - $selected_tests_passed;
                $testduration = $build_array['testduration'] - $selected_test_duration;
            }
            if (!$include_subprojects && !$exclude_subprojects) {
                $test_response['nnotrundiffp'] = $build_array['counttestsnotrundiffp'];
                $test_response['nnotrundiffn'] = $build_array['counttestsnotrundiffn'];
                $test_response['nfaildiffp'] = $build_array['counttestsfaileddiffp'];
                $test_response['nfaildiffn'] = $build_array['counttestsfaileddiffn'];
                $test_response['npassdiffp'] = $build_array['counttestspasseddiffp'];
                $test_response['npassdiffn'] = $build_array['counttestspasseddiffn'];
            }
            if ($project_array['showtesttime'] == 1) {
                $test_response['timestatus'] = $build_array['countteststimestatusfailed'];
                $test_response['ntimediffp'] = $build_array['countteststimestatusfaileddiffp'];
                $test_response['ntimediffn'] = $build_array['countteststimestatusfaileddiffn'];
            }
            if ($share_label_filters) {
                $label_query_base = "SELECT b2t.status, b2t.newstatus\n                    FROM build2test AS b2t\n                    INNER JOIN label2test AS l2t ON\n                    (l2t.testid=b2t.testid AND l2t.buildid=b2t.buildid)\n                    WHERE b2t.buildid = '{$buildid}' AND\n                    l2t.labelid IN {$label_ids}";
                $label_filter_query = $label_query_base . $limit_sql;
                $labels_result = pdo_query($label_filter_query);
                $nnotrun = 0;
                $nfail = 0;
                $npass = 0;
                $test_response['nfaildiffp'] = 0;
                $test_response['nfaildiffn'] = 0;
                $test_response['npassdiffp'] = 0;
                $test_response['npassdiffn'] = 0;
                $test_response['nnotrundiffp'] = 0;
                $test_response['nnotrundiffn'] = 0;
                while ($label_row = pdo_fetch_array($labels_result)) {
                    switch ($label_row['status']) {
                        case 'passed':
                            $npass++;
                            if ($label_row['newstatus'] == 1) {
                                $test_response['npassdiffp']++;
                            }
                            break;
                        case 'failed':
                            $nfail++;
                            if ($label_row['newstatus'] == 1) {
                                $test_response['nfaildiffp']++;
                            }
                            break;
                        case 'notrun':
                            $nnotrun++;
                            if ($label_row['newstatus'] == 1) {
                                $test_response['nnotrundiffp']++;
                            }
                            break;
                    }
                }
            }
            $test_response['notrun'] = $nnotrun;
            $test_response['fail'] = $nfail;
            $test_response['pass'] = $npass;
            $buildgroups_response[$i]['numtestnotrun'] += $nnotrun;
            $buildgroups_response[$i]['numtestfail'] += $nfail;
            $buildgroups_response[$i]['numtestpass'] += $npass;
            $test_response['time'] = time_difference($testduration, true);
            $test_response['timefull'] = $testduration;
            $buildgroups_response[$i]['testduration'] += $testduration;
            $build_response['test'] = $test_response;
        }
        $starttimestamp = strtotime($build_array['starttime'] . ' UTC');
        $submittimestamp = strtotime($build_array['submittime'] . ' UTC');
        // Use the default timezone.
        $build_response['builddatefull'] = $starttimestamp;
        // If the data is more than 24h old then we switch from an elapsed to a normal representation
        if (time() - $starttimestamp < 86400) {
            $build_response['builddate'] = date(FMT_DATETIMEDISPLAY, $starttimestamp);
            $build_response['builddateelapsed'] = time_difference(time() - $starttimestamp, false, 'ago');
        } else {
            $build_response['builddateelapsed'] = date(FMT_DATETIMEDISPLAY, $starttimestamp);
            $build_response['builddate'] = time_difference(time() - $starttimestamp, false, 'ago');
        }
        $build_response['submitdate'] = date(FMT_DATETIMEDISPLAY, $submittimestamp);
        // Generate a string summarizing this build's timing.
        $timesummary = $build_response['builddate'];
        if ($build_response['hasupdate'] && array_key_exists('time', $build_response['update'])) {
            $timesummary .= ', Update time: ' . $build_response['update']['time'];
        }
        if ($build_response['hasconfigure'] && array_key_exists('time', $build_response['configure'])) {
            $timesummary .= ', Configure time: ' . $build_response['configure']['time'];
        }
        if ($build_response['hascompilation'] && array_key_exists('time', $build_response['compilation'])) {
            $timesummary .= ', Build time: ' . $build_response['compilation']['time'];
        }
        if ($build_response['hastest'] && array_key_exists('time', $build_response['test'])) {
            $timesummary .= ', Test time: ' . $build_response['test']['time'];
        }
        $timesummary .= ', Total time: ' . $build_response['time'];
        $build_response['timesummary'] = $timesummary;
        if ($include_subprojects || $exclude_subprojects) {
            // Check if this build should be filtered out now that its
            // numbers have been updated by the SubProject include/exclude
            // filter.
            if (!build_survives_filter($build_response, $filterdata)) {
                continue;
            }
        }
        if ($build_array['name'] != 'Aggregate Coverage') {
            $buildgroups_response[$i]['builds'][] = $build_response;
        }
        // Coverage
        //
        // Determine if this is a parent build with no actual coverage of its own.
        $linkToChildCoverage = false;
        if ($numchildren > 0) {
            $countChildrenResult = pdo_single_row_query('SELECT count(fileid) AS nfiles FROM coverage
                    WHERE buildid=' . qnum($buildid));
            if ($countChildrenResult['nfiles'] == 0) {
                $linkToChildCoverage = true;
            }
        }
        $coverageIsGrouped = false;
        $loctested = $build_array['loctested'];
        $locuntested = $build_array['locuntested'];
        if ($loctested + $locuntested > 0) {
            $coverage_response = array();
            $coverage_response['buildid'] = $build_array['id'];
            if ($linkToChildCoverage) {
                $coverage_response['childlink'] = "{$child_builds_hyperlink}##Coverage";
            }
            if ($build_array['type'] === 'Nightly' && $build_array['name'] !== 'Aggregate Coverage') {
                $num_nightly_coverages_builds++;
                if ($num_nightly_coverages_builds > 1) {
                    $show_aggregate = true;
                    if ($linkToChildCoverage) {
                        $response['comparecoverage'] = 1;
                    }
                }
            }
            $percent = round(compute_percentcoverage($loctested, $locuntested), 2);
            if ($build_array['subprojectgroup']) {
                $groupId = $build_array['subprojectgroup'];
                if (array_key_exists($groupId, $coverage_groups)) {
                    $coverageIsGrouped = true;
                    $coverageThreshold = $coverage_groups[$groupId]['thresholdgreen'];
                    $coverage_groups[$groupId]['loctested'] += $loctested;
                    $coverage_groups[$groupId]['locuntested'] += $locuntested;
                    if (count($coverage_groups) > 1) {
                        // Add to Total.
                        $coverage_groups[0]['loctested'] += $loctested;
                        $coverage_groups[0]['locuntested'] += $locuntested;
                    }
                }
            }
            $coverage_response['percentage'] = $percent;
            $coverage_response['locuntested'] = intval($locuntested);
            $coverage_response['loctested'] = intval($loctested);
            // Compute the diff
            if (!empty($build_array['loctesteddiff'])) {
                $loctesteddiff = $build_array['loctesteddiff'];
                $locuntesteddiff = $build_array['locuntesteddiff'];
                @($previouspercent = round(($loctested - $loctesteddiff) / ($loctested - $loctesteddiff + $locuntested - $locuntesteddiff) * 100, 2));
                $percentdiff = round($percent - $previouspercent, 2);
                $coverage_response['percentagediff'] = $percentdiff;
                $coverage_response['locuntesteddiff'] = $locuntesteddiff;
                $coverage_response['loctesteddiff'] = $loctesteddiff;
            }
            $starttimestamp = strtotime($build_array['starttime'] . ' UTC');
            $coverage_response['datefull'] = $starttimestamp;
            // If the data is more than 24h old then we switch from an elapsed to a normal representation
            if (time() - $starttimestamp < 86400) {
                $coverage_response['date'] = date(FMT_DATETIMEDISPLAY, $starttimestamp);
                $coverage_response['dateelapsed'] = time_difference(time() - $starttimestamp, false, 'ago');
            } else {
                $coverage_response['dateelapsed'] = date(FMT_DATETIMEDISPLAY, $starttimestamp);
                $coverage_response['date'] = time_difference(time() - $starttimestamp, false, 'ago');
            }
            // Are there labels for this build?
            //
            $coverage_response['label'] = $build_label;
            if ($coverageIsGrouped) {
                $coverage_groups[$groupId]['coverages'][] = $coverage_response;
            } else {
                $coverage_response['site'] = $build_array['sitename'];
                $coverage_response['buildname'] = $build_array['name'];
                $response['coverages'][] = $coverage_response;
            }
        }
        if (!$coverageIsGrouped) {
            $coverageThreshold = $project_array['coveragethreshold'];
            $response['thresholdgreen'] = $coverageThreshold;
            $response['thresholdyellow'] = $coverageThreshold * 0.7;
        }
        // Dynamic Analysis
        //
        if (!empty($build_array['checker'])) {
            // Determine if this is a parent build with no dynamic analysis
            // of its own.
            $linkToChildren = false;
            if ($numchildren > 0) {
                $countChildrenResult = pdo_single_row_query('SELECT count(id) AS num FROM dynamicanalysis
                        WHERE buildid=' . qnum($build_array['id']));
                if ($countChildrenResult['num'] == 0) {
                    $linkToChildren = true;
                }
            }
            $DA_response = array();
            $DA_response['site'] = $build_array['sitename'];
            $DA_response['buildname'] = $build_array['name'];
            $DA_response['buildid'] = $build_array['id'];
            $DA_response['checker'] = $build_array['checker'];
            $DA_response['defectcount'] = $build_array['numdefects'];
            $starttimestamp = strtotime($build_array['starttime'] . ' UTC');
            $DA_response['datefull'] = $starttimestamp;
            if ($linkToChildren) {
                $DA_response['childlink'] = "{$child_builds_hyperlink}##DynamicAnalysis";
            }
            // If the data is more than 24h old then we switch from an elapsed to a normal representation
            if (time() - $starttimestamp < 86400) {
                $DA_response['date'] = date(FMT_DATETIMEDISPLAY, $starttimestamp);
                $DA_response['dateelapsed'] = time_difference(time() - $starttimestamp, false, 'ago');
            } else {
                $DA_response['dateelapsed'] = date(FMT_DATETIMEDISPLAY, $starttimestamp);
                $DA_response['date'] = time_difference(time() - $starttimestamp, false, 'ago');
            }
            // Are there labels for this build?
            //
            $DA_response['label'] = $build_label;
            $response['dynamicanalyses'][] = $DA_response;
        }
    }
    // Put some finishing touches on our buildgroups now that we're done
    // iterating over all the builds.
    $addExpected = empty($filter_sql) && pdo_num_rows($builds) + count($dynamic_builds) > 0;
    for ($i = 0; $i < count($buildgroups_response); $i++) {
        $buildgroups_response[$i]['testduration'] = time_difference($buildgroups_response[$i]['testduration'], true);
        $num_expected_builds = 0;
        if (!$filter_sql) {
            $groupname = $buildgroups_response[$i]['name'];
            $expected_builds = add_expected_builds($buildgroups_response[$i]['id'], $currentstarttime, $received_builds[$groupname]);
            if (is_array($expected_builds)) {
                $num_expected_builds = count($expected_builds);
                $buildgroups_response[$i]['builds'] = array_merge($buildgroups_response[$i]['builds'], $expected_builds);
            }
        }
        // Show how many builds this group has.
        $num_builds = count($buildgroups_response[$i]['builds']);
        $num_builds_label = '';
        if ($num_expected_builds > 0) {
            $num_actual_builds = $num_builds - $num_expected_builds;
            $num_builds_label = "{$num_actual_builds} of {$num_builds} builds";
        } else {
            if ($num_builds === 1) {
                $num_builds_label = '1 build';
            } else {
                $num_builds_label = "{$num_builds} builds";
            }
        }
        $buildgroups_response[$i]['numbuildslabel'] = $num_builds_label;
    }
    // Create a separate "all buildgroups" section of our response.
    // This is used to allow project admins to move builds between groups.
    $response['all_buildgroups'] = array();
    foreach ($buildgroups_response as $group) {
        $response['all_buildgroups'][] = array('id' => $group['id'], 'name' => $group['name']);
    }
    // At this point it is safe to remove any empty buildgroups from our response.
    function is_buildgroup_nonempty($group)
    {
        return !empty($group['builds']);
    }
    $buildgroups_response = array_filter($buildgroups_response, 'is_buildgroup_nonempty');
    // Report buildgroups as a list, not an associative array.
    // Otherwise any missing buildgroups will cause our view to
    // not honor the order specified by the project admins.
    $buildgroups_response = array_values($buildgroups_response);
    // Remove Aggregate Coverage if it should not be displayed.
    if (!$show_aggregate) {
        for ($i = 0; $i < count($response['coverages']); $i++) {
            if ($response['coverages'][$i]['buildname'] === 'Aggregate Coverage') {
                unset($response['coverages'][$i]);
            }
        }
        $response['coverages'] = array_values($response['coverages']);
    }
    if ($response['childview'] == 1) {
        // Report number of children.
        if (!empty($buildgroups_response)) {
            $numchildren = count($buildgroups_response[0]['builds']);
        } else {
            $row = pdo_single_row_query('SELECT count(id) AS numchildren
                    FROM build WHERE parentid=' . qnum($parentid));
            $numchildren = $row['numchildren'];
        }
        $response['numchildren'] = $numchildren;
    }
    // Generate coverage by group here.
    if (!empty($coverage_groups)) {
        $response['coveragegroups'] = array();
        foreach ($coverage_groups as $groupid => $group) {
            $loctested = $group['loctested'];
            $locuntested = $group['locuntested'];
            if ($loctested == 0 && $locuntested == 0) {
                continue;
            }
            $percentage = round($loctested / ($loctested + $locuntested) * 100, 2);
            $group['percentage'] = $percentage;
            $group['id'] = $groupid;
            $response['coveragegroups'][] = $group;
        }
    }
    $response['buildgroups'] = $buildgroups_response;
    $response['enableTestTiming'] = $project_array['showtesttime'];
    $end = microtime_float();
    $response['generationtime'] = round($end - $start, 3);
    if (!empty($site_response)) {
        $response = array_merge($response, $site_response);
    }
    echo json_encode(cast_data_for_JSON($response));
}
Exemplo n.º 15
0
<?php

include_once "pdo_mysql.php";
$username = "******";
$password = "";
$host = "localhost";
$database = "vaproject";
$server = pdo_connect($host, $username, $password);
$connection = pdo_select_db($database, $server);
$datasets = ["fri", "sat", "sun"];
$datasetsLabels = ["Friday", "Saturday", "Sunday"];
$whichDay = htmlspecialchars($_GET["day"]);
$whichDay = array_search($whichDay, array_values($datasetsLabels));
$inputDay = $datasets[$whichDay];
$whichPlace = htmlspecialchars($_GET["place"]);
$whatTime = (int) htmlspecialchars($_GET["time"]);
$position = htmlspecialchars($_GET["position"]);
$firstquery = pdo_query("select * from places where name = '" . $whichPlace . "'");
$firstresult = pdo_fetch_assoc($firstquery);
$xposition = $firstresult["x"];
$yposition = $firstresult["y"];
$selectedCategory = $firstresult["category"];
if (!strcasecmp($position, "after")) {
    $myquery = "Select move.name, count(*) as number, move.category, move.x, move.y from movement_combined move, \n        (select id,min(timestamp) as timestamp from movement_combined where id in (select distinct(id) from movement_combined \n        where name = '" . $whichPlace . "' and HOUR(timestamp) = " . $whatTime . " and day = '" . $inputDay . "') and day = '" . $inputDay . "' and \n        HOUR(timestamp) = " . ($whatTime + 1) . " group by id) as temp where temp.timestamp = move.timestamp and temp.id = move.id \n        group by move.name order by number DESC limit 5";
} else {
    $myquery = "Select move.name, count(*) as number, move.category, move.x, move.y from movement_combined move, \n        (select id,max(timestamp) as timestamp from movement_combined where id in (select distinct(id) from movement_combined \n        where name = '" . $whichPlace . "' and HOUR(timestamp) = " . $whatTime . " and day = '" . $inputDay . "') and day = '" . $inputDay . "' and \n        HOUR(timestamp) = " . ($whatTime - 1) . " group by id) as temp where temp.timestamp = move.timestamp and temp.id = move.id \n        group by move.name order by number DESC limit 5";
}
$query = pdo_query($myquery);
if (!$query) {
    echo pdo_error();
    die;
Exemplo n.º 16
0
/**
 * Authentication function
 * This is called on every page load where common.php is selected, as well as when
 * submitting the login form.
 **/
function auth($SessionCachePolicy = 'private_no_expire')
{
    include dirname(__DIR__) . '/config/config.php';
    $loginid = 1231564132;
    if (isset($CDASH_EXTERNAL_AUTH) && $CDASH_EXTERNAL_AUTH && isset($_SERVER['REMOTE_USER'])) {
        $login = $_SERVER['REMOTE_USER'];
        return authenticate($login, null, $SessionCachePolicy, 0);
        // we don't remember
    }
    if (@$_GET['logout']) {
        // user requested logout
        session_name('CDash');
        session_cache_limiter('nocache');
        @session_start();
        unset($_SESSION['cdash']);
        session_destroy();
        // Remove the cookie if we have one
        $cookienames = array('CDash', str_replace('.', '_', 'CDash-' . $_SERVER['SERVER_NAME']));
        // php doesn't like dot in cookie names
        foreach ($cookienames as $cookiename) {
            if (isset($_COOKIE[$cookiename])) {
                $cookievalue = $_COOKIE[$cookiename];
                $cookieuseridkey = substr($cookievalue, 0, strlen($cookievalue) - 33);
                $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
                pdo_select_db("{$CDASH_DB_NAME}", $db);
                pdo_query('UPDATE ' . qid('user') . " SET cookiekey='' WHERE id=" . qnum($cookieuseridkey));
                setcookie('CDash-' . $_SERVER['SERVER_NAME'], '', time() - 3600);
            }
        }
        echo "<script language=\"javascript\">window.location='index.php'</script>";
        return 0;
    }
    if (isset($_POST['sent'])) {
        // arrive from login form
        @($login = $_POST['login']);
        if ($login != null) {
            $login = htmlspecialchars(pdo_real_escape_string($login));
        }
        @($passwd = $_POST['passwd']);
        if ($passwd != null) {
            $passwd = htmlspecialchars(pdo_real_escape_string($passwd));
        }
        return authenticate($login, $passwd, $SessionCachePolicy, isset($_POST['rememberme']));
    } else {
        // arrive from session var
        $cookiename = str_replace('.', '_', 'CDash-' . $_SERVER['SERVER_NAME']);
        // php doesn't like dot in cookie names
        if (isset($_COOKIE[$cookiename])) {
            $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
            pdo_select_db("{$CDASH_DB_NAME}", $db);
            $cookievalue = $_COOKIE[$cookiename];
            $cookiekey = substr($cookievalue, strlen($cookievalue) - 33);
            if (strlen($cookiekey) < 1) {
                return false;
            }
            $cookieuseridkey = substr($cookievalue, 0, strlen($cookievalue) - 33);
            $sql = 'SELECT email,password,id FROM ' . qid('user') . "\n                WHERE cookiekey='" . pdo_real_escape_string($cookiekey) . "'";
            if (!empty($cookieuseridkey)) {
                $sql .= " AND id='" . pdo_real_escape_string($cookieuseridkey) . "'";
            }
            $result = pdo_query("{$sql}");
            if (pdo_num_rows($result) == 1) {
                $user_array = pdo_fetch_array($result);
                session_name('CDash');
                session_cache_limiter($SessionCachePolicy);
                session_set_cookie_params($CDASH_COOKIE_EXPIRATION_TIME);
                @ini_set('session.gc_maxlifetime', $CDASH_COOKIE_EXPIRATION_TIME + 600);
                session_start();
                $sessionArray = array('login' => $user_array['email'], 'passwd' => $user_array['password'], 'ID' => session_id(), 'valid' => 1, 'loginid' => $user_array['id']);
                $_SESSION['cdash'] = $sessionArray;
                return true;
            }
        }
        // Return early if a session has already been started.
        if (session_status() != PHP_SESSION_NONE) {
            return;
        }
        session_name('CDash');
        session_cache_limiter($SessionCachePolicy);
        session_set_cookie_params($CDASH_COOKIE_EXPIRATION_TIME);
        @ini_set('session.gc_maxlifetime', $CDASH_COOKIE_EXPIRATION_TIME + 600);
        session_start();
        $email = @$_SESSION['cdash']['login'];
        if (!empty($email)) {
            $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
            pdo_select_db("{$CDASH_DB_NAME}", $db);
            $sql = 'SELECT id,password FROM ' . qid('user') . " WHERE email='" . pdo_real_escape_string($email) . "'";
            $result = pdo_query("{$sql}");
            if (pdo_num_rows($result) == 0) {
                pdo_free_result($result);
                $loginerror = 'Wrong email or password.';
                return false;
            }
            $user_array = pdo_fetch_array($result);
            if ($user_array['password'] == $_SESSION['cdash']['passwd']) {
                return true;
            }
            $loginerror = 'Wrong email or password.';
            return false;
        }
    }
}
Exemplo n.º 17
0
<?php

// ini_set("display_errors", On);
// error_reporting(E_ALL);
require_once $_SERVER['DOCUMENT_ROOT'] . '/function/function.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/function/CFstatus.php';
session_start();
$pdo = pdo_connect();
$mail = $_SESSION['MAIL'];
$sql = "SELECT * FROM User WHERE `mail` = '{$mail}' AND `invalid` = 0 LIMIT 1;";
$user = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
if (isset($_SESSION["MAIL"]) && $_SESSION["MAIL"] != null && md5($user['password']) === $_SESSION["PASS"]) {
} else {
    $pdo = null;
    session_delete();
    header("Location: login.php");
    exit;
}
?>
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>提出状況 - C Factory</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/paper/bootstrap.min.css" rel="stylesheet">
<link href="/css/style.css" rel="stylesheet">
</head>
Exemplo n.º 18
0
    die;
}
include_once "../../config.php";
include "../../common/functions.php";
include "../common/functions.php";
// make sure only one controller script is running
$thislockfp = script_lock('controller');
if (!is_resource($thislockfp)) {
    logit("controller.log", "controller.php already running, skipping this check");
    exit;
}
if (dbserver_has_utf8mb4_support() == false) {
    logit("controller.log", "DMI-TCAT requires at least MySQL version 5.5.3 - please upgrade your server");
    exit;
}
$dbh = pdo_connect();
$roles = unserialize(CAPTUREROLES);
// first gather all instructions sent by the webinterface to the controller (ie. the instruction queue)
$commands = array();
foreach ($roles as $role) {
    $commands[$role] = array();
}
if (array_key_exists('track', $commands) && geobinsActive() && geophp_sane()) {
    $geoActive = true;
} else {
    $geoActive = false;
}
$rec = $dbh->prepare("SHOW TABLES LIKE 'tcat_controller_tasklist'");
if ($rec->execute() && $rec->rowCount() > 0) {
    $sql = "select task, instruction from tcat_controller_tasklist order by id asc lock in share mode";
    foreach ($dbh->query($sql) as $row) {
Exemplo n.º 19
0
/** Authentication function */
function auth($SessionCachePolicy = 'private_no_expire')
{
    include "cdash/config.php";
    $loginid = 1231564132;
    if (isset($CDASH_EXTERNAL_AUTH) && $CDASH_EXTERNAL_AUTH && isset($_SERVER['REMOTE_USER'])) {
        $login = $_SERVER['REMOTE_USER'];
        return authenticate($login, NULL, $SessionCachePolicy, 0);
        // we don't remember
    }
    if (@$_GET["logout"]) {
        // user requested logout
        session_name("CDash");
        session_cache_limiter('nocache');
        @session_start();
        unset($_SESSION['cdash']);
        session_destroy();
        // Remove the cookie if we have one
        $cookienames = array("CDash", str_replace('.', '_', "CDash-" . $_SERVER['SERVER_NAME']));
        // php doesn't like dot in cookie names
        foreach ($cookienames as $cookiename) {
            if (isset($_COOKIE[$cookiename])) {
                $cookievalue = $_COOKIE[$cookiename];
                $cookieuseridkey = substr($cookievalue, 0, strlen($cookievalue) - 33);
                $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
                pdo_select_db("{$CDASH_DB_NAME}", $db);
                pdo_query("UPDATE " . qid("user") . " SET cookiekey='' WHERE id=" . qnum($cookieuseridkey));
                setcookie("CDash-" . $_SERVER['SERVER_NAME'], "", time() - 3600);
            }
        }
        echo "<script language=\"javascript\">window.location='index.php'</script>";
        return 0;
    }
    if (isset($_POST["sent"])) {
        @($login = $_POST["login"]);
        if ($login != NULL) {
            $login = htmlspecialchars(pdo_real_escape_string($login));
        }
        @($passwd = $_POST["passwd"]);
        if ($passwd != NULL) {
            $passwd = htmlspecialchars(pdo_real_escape_string($passwd));
        }
        @($rememberme = $_POST["rememberme"]);
        if ($rememberme != NULL) {
            $rememberme = pdo_real_escape_numeric($rememberme);
        }
        return authenticate($login, $passwd, $SessionCachePolicy, $rememberme);
    } else {
        // arrive from session var
        $cookiename = str_replace('.', '_', "CDash-" . $_SERVER['SERVER_NAME']);
        // php doesn't like dot in cookie names
        if (isset($_COOKIE[$cookiename])) {
            $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
            pdo_select_db("{$CDASH_DB_NAME}", $db);
            $cookievalue = $_COOKIE[$cookiename];
            $cookiekey = substr($cookievalue, strlen($cookievalue) - 33);
            $cookieuseridkey = substr($cookievalue, 0, strlen($cookievalue) - 33);
            $sql = "SELECT email,password,id FROM " . qid("user") . "\n         WHERE cookiekey='" . pdo_real_escape_string($cookiekey) . "'";
            if (!empty($cookieuseridkey)) {
                $sql .= " AND id='" . pdo_real_escape_string($cookieuseridkey) . "'";
            }
            $result = pdo_query("{$sql}");
            if (pdo_num_rows($result) == 1) {
                $user_array = pdo_fetch_array($result);
                session_name("CDash");
                session_cache_limiter($SessionCachePolicy);
                session_set_cookie_params($CDASH_COOKIE_EXPIRATION_TIME);
                @ini_set('session.gc_maxlifetime', $CDASH_COOKIE_EXPIRATION_TIME + 600);
                session_start();
                $sessionArray = array("login" => $user_array['email'], "passwd" => $user_array['password'], "ID" => session_id(), "valid" => 1, "loginid" => $user_array['id']);
                $_SESSION['cdash'] = $sessionArray;
                return true;
            }
        }
        session_name("CDash");
        session_cache_limiter($SessionCachePolicy);
        session_set_cookie_params($CDASH_COOKIE_EXPIRATION_TIME);
        @ini_set('session.gc_maxlifetime', $CDASH_COOKIE_EXPIRATION_TIME + 600);
        session_start();
        $email = @$_SESSION['cdash']["login"];
        if (!empty($email)) {
            $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
            pdo_select_db("{$CDASH_DB_NAME}", $db);
            $sql = "SELECT id,password FROM " . qid("user") . " WHERE email='" . pdo_real_escape_string($email) . "'";
            $result = pdo_query("{$sql}");
            if (pdo_num_rows($result) == 0) {
                pdo_free_result($result);
                $loginerror = "Wrong email or password.";
                return false;
            }
            $user_array = pdo_fetch_array($result);
            if ($user_array["password"] == $_SESSION['cdash']["passwd"]) {
                return true;
            }
            $loginerror = "Wrong email or password.";
            return false;
        }
    }
}
Exemplo n.º 20
0

    <div id="navi">
        <ul>
            <li><a href="list.php">杂烩</a></li>
            <li><a href="list.php?type=4">NBA战报</a></li>
            <li><a href="#">c</a></li>
            <li><a href="#">d</a></li>
            <li><a href="#">e</a></li>
        </ul>
    </div>

    <div id="list">
        <div id="list_display">
            <?php 
$pdo_connect = pdo_connect();
if (isset($_GET["type"]) && !empty($_GET["type"])) {
    $result = get_query_result_for_list($pdo_connect, 1, $_GET["type"]);
} else {
    $result = get_query_result_for_list($pdo_connect);
}
$html = get_html_from_result_for_list($result);
echo $html;
?>
        </div>
        <div id="list_bottom">
            <div id="page_num">1</div>
            <div id="change_page_btn">
                <span id="pre_btn"><a href="#" title="上一页">Prev</a></span>
                <span id="next_btn"><a href="#" title="下一页">Next</a></span>
            </div>
Exemplo n.º 21
0
function get_all_datasets()
{
    global $dataset;
    $dbh = pdo_connect();
    $rec = $dbh->prepare("SELECT id, querybin, type, active, comments FROM tcat_query_bins WHERE access = " . TCAT_QUERYBIN_ACCESS_OK . " OR access = " . TCAT_QUERYBIN_ACCESS_READONLY . " ORDER BY LOWER(querybin)");
    $datasets = array();
    try {
        if ($rec->execute() && $rec->rowCount() > 0) {
            while ($res = $rec->fetch()) {
                $row = array();
                $row['bin'] = $res['querybin'];
                $row['type'] = $res['type'];
                $row['active'] = $res['active'];
                $row['comments'] = $res['comments'];
                $rec2 = $dbh->prepare("SELECT count(t.id) AS notweets, MAX(t.created_at) AS max  FROM " . $res['querybin'] . "_tweets t ");
                if ($rec2->execute() && $rec2->rowCount() > 0) {
                    $res2 = $rec2->fetch();
                    $row['notweets'] = $res2['notweets'];
                    $row['maxtime'] = $res2['max'];
                }
                $rec3 = $dbh->prepare("SELECT starttime AS min FROM tcat_query_bins b, tcat_query_bins_periods bp WHERE b.querybin = '" . $res['querybin'] . "' AND b.id = bp.querybin_id");
                if ($rec3->execute() && $rec3->rowCount() > 0) {
                    $res3 = $rec3->fetch();
                    $row['mintime'] = $res3['min'];
                }
                $row['keywords'] = "";
                if ($dataset == $row['bin']) {
                    $rec2 = $dbh->prepare("SELECT distinct(p.phrase) FROM tcat_query_bins_phrases bp, tcat_query_phrases p WHERE bp.querybin_id = " . $res['id'] . " AND bp.phrase_id = p.id ORDER BY LOWER(p.phrase)");
                    if ($rec2->execute() && $rec2->rowCount() > 0) {
                        $res2 = $rec2->fetchAll(PDO::FETCH_COLUMN);
                        $row['keywords'] = implode(", ", $res2);
                    } elseif (in_array($row['type'], array("follow", "timeline"))) {
                        $rec2 = $dbh->prepare("SELECT distinct(t.from_user_name) FROM tcat_query_bins_users bu, " . $res['querybin'] . "_tweets t WHERE bu.querybin_id = " . $res['id'] . " AND bu.user_id = t.from_user_id ORDER BY LOWER(t.from_user_name)");
                        if ($rec2->execute() && $rec2->rowCount() > 0) {
                            $res2 = $rec2->fetchAll(PDO::FETCH_COLUMN);
                            $row['keywords'] = implode(", ", $res2);
                        }
                    }
                }
                $datasets[$row['bin']] = $row;
            }
        }
    } catch (PDOException $e) {
        if ($e->errorInfo[0] == '42S02') {
            // Base table or view not found
            // Tables not yet created: just return empty $datasets
        } else {
            throw $e;
        }
    }
    return $datasets;
}
Exemplo n.º 22
0
function tweet_purge($query_bin, $dt_start, $dt_end)
{
    // Create WHERE clause to restrict to requested timestamp range
    $time_condition = created_at_condition($dt_start, $dt_end);
    if (isset($time_condition)) {
        $where = 'WHERE ' . $time_condition;
    } else {
        $where = '';
    }
    // Query database
    $result = [];
    $dbh = pdo_connect();
    $bin_name = $query_bin['bin'];
    // Tables without a 'created_at' column
    foreach (["media", "places", "withheld"] as $tbl) {
        $table_name = $bin_name . '_' . $tbl;
        if ($where !== '') {
            // Must join with *_tweets to get 'created_at' timestamp
            $sql = "DELETE FROM `{$table_name}`" . " USING `{$table_name}` INNER JOIN `{$bin_name}_tweets`" . " ON `{$bin_name}_tweets`.id=`{$table_name}`.tweet_id" . " {$where}";
        } else {
            $sql = "DELETE FROM `{$table_name}`";
            // time irrelvant: del all
        }
        $rec = $dbh->prepare($sql);
        $rec->execute();
        $result[$tbl] = $rec->rowCount();
    }
    // Tables with a 'created_at' column
    foreach (["tweets", "hashtags", "mentions", "urls"] as $tbl) {
        $table_name = $bin_name . '_' . $tbl;
        $sql = "DELETE FROM `{$table_name}` {$where}";
        $rec = $dbh->prepare($sql);
        $rec->execute();
        $result[$tbl] = $rec->rowCount();
    }
    return $result;
}
Exemplo n.º 23
0
function echo_subprojects_dashboard_JSON($project_instance, $date)
{
    $start = microtime_float();
    $noforcelogin = 1;
    include_once dirname(dirname(dirname(__DIR__))) . '/config/config.php';
    require_once 'include/pdo.php';
    include 'public/login.php';
    include_once 'models/banner.php';
    include_once 'models/subproject.php';
    $response = array();
    $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
    if (!$db) {
        $response['error'] = 'Error connecting to CDash database server';
        echo json_encode($response);
        return;
    }
    if (!pdo_select_db("{$CDASH_DB_NAME}", $db)) {
        $response['error'] = 'Error selecting CDash database';
        echo json_encode($response);
        return;
    }
    $Project = $project_instance;
    $projectid = $project_instance->Id;
    if (!checkUserPolicy(@$_SESSION['cdash']['loginid'], $projectid, 1)) {
        $response['requirelogin'] = 1;
        echo json_encode($response);
        return;
    }
    $response = begin_JSON_response();
    $response['title'] = 'CDash - ' . $Project->Name;
    $response['showcalendar'] = 1;
    $banners = array();
    $Banner = new Banner();
    $Banner->SetProjectId(0);
    $text = $Banner->GetText();
    if ($text !== false) {
        $banners[] = $text;
    }
    $Banner->SetProjectId($projectid);
    $text = $Banner->GetText();
    if ($text !== false) {
        $banners[] = $text;
    }
    $response['banners'] = $banners;
    global $CDASH_SHOW_LAST_SUBMISSION;
    if ($CDASH_SHOW_LAST_SUBMISSION) {
        $response['showlastsubmission'] = 1;
    }
    list($previousdate, $currentstarttime, $nextdate) = get_dates($date, $Project->NightlyTime);
    // Main dashboard section
    get_dashboard_JSON($Project->GetName(), $date, $response);
    $projectname_encoded = urlencode($Project->Name);
    if ($currentstarttime > time()) {
        $response['error'] = 'CDash cannot predict the future (yet)';
        echo json_encode($response);
        return;
    }
    $linkparams = 'project=' . urlencode($Project->Name);
    if (!empty($date)) {
        $linkparams .= "&date={$date}";
    }
    $response['linkparams'] = $linkparams;
    // Menu definition
    $menu_response = array();
    $menu_response['subprojects'] = 1;
    $menu_response['previous'] = "viewSubProjects.php?project={$projectname_encoded}&date={$previousdate}";
    $menu_response['current'] = "viewSubProjects.php?project={$projectname_encoded}";
    if (!has_next_date($date, $currentstarttime)) {
        $menu_response['nonext'] = 1;
    } else {
        $menu_response['next'] = "viewSubProjects.php?project={$projectname_encoded}&date={$nextdate}";
    }
    $response['menu'] = $menu_response;
    $beginning_timestamp = $currentstarttime;
    $end_timestamp = $currentstarttime + 3600 * 24;
    $beginning_UTCDate = gmdate(FMT_DATETIME, $beginning_timestamp);
    $end_UTCDate = gmdate(FMT_DATETIME, $end_timestamp);
    // Get some information about the project
    $project_response = array();
    $project_response['nbuilderror'] = $Project->GetNumberOfErrorBuilds($beginning_UTCDate, $end_UTCDate, true);
    $project_response['nbuildwarning'] = $Project->GetNumberOfWarningBuilds($beginning_UTCDate, $end_UTCDate, true);
    $project_response['nbuildpass'] = $Project->GetNumberOfPassingBuilds($beginning_UTCDate, $end_UTCDate, true);
    $project_response['nconfigureerror'] = $Project->GetNumberOfErrorConfigures($beginning_UTCDate, $end_UTCDate, true);
    $project_response['nconfigurewarning'] = $Project->GetNumberOfWarningConfigures($beginning_UTCDate, $end_UTCDate, true);
    $project_response['nconfigurepass'] = $Project->GetNumberOfPassingConfigures($beginning_UTCDate, $end_UTCDate, true);
    $project_response['ntestpass'] = $Project->GetNumberOfPassingTests($beginning_UTCDate, $end_UTCDate, true);
    $project_response['ntestfail'] = $Project->GetNumberOfFailingTests($beginning_UTCDate, $end_UTCDate, true);
    $project_response['ntestnotrun'] = $Project->GetNumberOfNotRunTests($beginning_UTCDate, $end_UTCDate, true);
    if (strlen($Project->GetLastSubmission()) == 0) {
        $project_response['lastsubmission'] = 'NA';
    } else {
        $project_response['lastsubmission'] = $Project->GetLastSubmission();
    }
    $response['project'] = $project_response;
    // Look for the subproject
    $row = 0;
    $subprojectids = $Project->GetSubProjects();
    $subprojProp = array();
    foreach ($subprojectids as $subprojectid) {
        $SubProject = new SubProject();
        $SubProject->SetId($subprojectid);
        $subprojProp[$subprojectid] = array('name' => $SubProject->GetName());
    }
    $testSubProj = new SubProject();
    $result = $testSubProj->GetNumberOfErrorBuilds($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nbuilderror'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfWarningBuilds($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nbuildwarning'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfPassingBuilds($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nbuildpass'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfErrorConfigures($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nconfigureerror'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfWarningConfigures($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nconfigurewarning'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfPassingConfigures($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nconfigurepass'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfPassingTests($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['ntestpass'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfFailingTests($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['ntestfail'] = intval($row[1]);
        }
    }
    $result = $testSubProj->GetNumberOfNotRunTests($beginning_UTCDate, $end_UTCDate, true);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['ntestnotrun'] = intval($row[1]);
        }
    }
    $reportArray = array('nbuilderror', 'nbuildwarning', 'nbuildpass', 'nconfigureerror', 'nconfigurewarning', 'nconfigurepass', 'ntestpass', 'ntestfail', 'ntestnotrun');
    $subprojects_response = array();
    foreach ($subprojectids as $subprojectid) {
        $SubProject = new SubProject();
        $SubProject->SetId($subprojectid);
        $subproject_response = array();
        $subproject_response['name'] = $SubProject->GetName();
        $subproject_response['name_encoded'] = urlencode($SubProject->GetName());
        foreach ($reportArray as $reportnum) {
            $reportval = array_key_exists($reportnum, $subprojProp[$subprojectid]) ? $subprojProp[$subprojectid][$reportnum] : 0;
            $subproject_response[$reportnum] = $reportval;
        }
        if (strlen($SubProject->GetLastSubmission()) == 0) {
            $subproject_response['lastsubmission'] = 'NA';
        } else {
            $subproject_response['lastsubmission'] = $SubProject->GetLastSubmission();
        }
        $subprojects_response[] = $subproject_response;
    }
    $response['subprojects'] = $subprojects_response;
    $end = microtime_float();
    $response['generationtime'] = round($end - $start, 3);
    echo json_encode(cast_data_for_JSON($response));
}
Exemplo n.º 24
0
function binsToDb($stuff, $type)
{
    $dbh = pdo_connect();
    foreach ($stuff as $binname => $queries) {
        $binname = trim($binname);
        $rec2 = $dbh->prepare("SELECT id FROM tcat_query_bins WHERE querybin = '{$binname}'");
        if ($rec2->execute() && $rec2->rowCount() > 0) {
            // check whether the table has already been imported
            print "{$binname} already exists in the query manager, skipping it's import" . PHP_EOL;
            continue;
        }
        // select start and end of dataset
        $sql = "SELECT min(created_at) AS min, max(created_at) AS max FROM " . $binname . "_tweets";
        $rec = $dbh->prepare($sql);
        if (!$rec->execute() || !$rec->rowCount()) {
            die("could not find " . $binname . "_tweets" . PHP_EOL);
        }
        $res = $rec->fetch();
        $starttime = $res['min'];
        $endtime = $res['max'];
        $active = 0;
        if (strtotime($endtime) > strtotime(strftime("%Y-%m-%d 00:00:00", date('U')))) {
            // see whether it is still active
            $endtime = "0000:00:00 00:00:00";
            $active = 1;
        }
        $querybin_id = queryManagerCreateBin($binname, $type, $starttime, $endtime, $active);
        $queries = explode(",", $queries);
        // insert phrases
        if ($type == 'track') {
            queryManagerInsertPhrases($querybin_id, $queries, $starttime, $endtime);
        }
        // insert users
        if ($type == 'follow') {
            queryManagerInsertUsers($querybin_id, $queries, $starttime, $endtime);
        }
    }
    $dbh = false;
}
Exemplo n.º 25
0
<?php

session_start();
include_once "pdo_mysql.php";
if (isset($_POST['submit_signup'])) {
    $username = '******';
    $password = '******';
    $host = 'dbserver.engr.scu.edu';
    $database = 'sdb_pnguyen';
    if (!($server = pdo_connect("{$host}", $username, $password))) {
        die('Error connecting to ' . $host . '.' . pdo_error());
    }
    if (!($conn = pdo_select_db($database, $server))) {
        die('Error selecting ' . $database . '.' . pdo_error());
    }
    $user = $_POST['name'];
    if ($_POST['password'] == $_POST['password2']) {
        $password = $_POST['password'];
        $email = $_POST['email'];
        $NewRequestQuery = "INSERT INTO `enqueue_login` (`user`, `email`, `password`, `isInstructor`) VALUES ('{$user}', '{$email}', '{$password}', '0')";
        pdo_query($NewRequestQuery);
        echo "Success! Redirecting to home...";
        header("refresh:3; url= landing_page.php");
    } else {
        echo "Your passwords did not match! Redirecting to signup...";
        header("refresh:3; url=signup.php");
    }
}
Exemplo n.º 26
0
 function mysql_connect($hostname = NULL, $username = NULL, $password = NULL, $new = NULL, $flags = NULL)
 {
     return pdo_connect(func_get_args());
 }
Exemplo n.º 27
0
 function insertDB()
 {
     // insert all Tweets into the database and empty the queue
     $dbh = pdo_connect();
     // make a list of all bins in the queue and count the number of placeholders needed per insert query
     $binlist = array();
     foreach ($this->queue as $obj) {
         $bin_name = $obj['bin_name'];
         if (isset($binlist[$bin_name])) {
             $binlist[$bin_name]['tweets']++;
             $binlist[$bin_name]['hashtags'] += count($obj['tweet']->hashtags);
             $binlist[$bin_name]['urls'] += count($obj['tweet']->urls);
             $binlist[$bin_name]['mentions'] += count($obj['tweet']->user_mentions);
             $binlist[$bin_name]['withheld'] += count($obj['tweet']->withheld_in_countries);
             $binlist[$bin_name]['places'] += count($obj['tweet']->places);
             $binlist[$bin_name]['media'] += count($obj['tweet']->media);
             continue;
         }
         if (!$this->hasCached($bin_name)) {
             $this->cacheBin($bin_name);
         }
         $binlist[$bin_name] = array('tweets' => 1, 'hashtags' => count($obj['tweet']->hashtags), 'urls' => count($obj['tweet']->urls), 'mentions' => count($obj['tweet']->user_mentions), 'withheld' => count($obj['tweet']->withheld_in_countries), 'places' => count($obj['tweet']->places), 'media' => count($obj['tweet']->media));
     }
     // process the queue bin by bin
     foreach ($binlist as $bin_name => $counts) {
         // first prepare the multiple insert statements for tweets, mentions, hashtags, urls, withheld, places
         $statement = array();
         $extensions = array('tweets', 'mentions', 'hashtags', 'urls', 'withheld', 'places', 'media');
         foreach ($extensions as $ext) {
             $statement[$ext] = $this->headMultiInsert($bin_name, $ext, $counts[$ext]);
         }
         $tweeti = 1;
         $tweetq = $dbh->prepare($statement['tweets']);
         $hashtagsi = 1;
         $hashtagsq = $dbh->prepare($statement['hashtags']);
         $urlsi = 1;
         $urlsq = $dbh->prepare($statement['urls']);
         $mentionsi = 1;
         $mentionsq = $dbh->prepare($statement['mentions']);
         $withheldi = 1;
         $withheldq = $dbh->prepare($statement['withheld']);
         $placesi = 1;
         $placesq = $dbh->prepare($statement['places']);
         $mediai = 1;
         $mediaq = $dbh->prepare($statement['media']);
         // go now and iterate the queue item by item
         foreach ($this->queue as $obj) {
             if ($obj['bin_name'] !== $bin_name) {
                 continue;
             }
             $t = $obj['tweet'];
             // read the tweets table structure from cache
             $fields = $this->binColumnsCache[$bin_name]['tweets'];
             foreach ($fields as $f) {
                 $tweetq->bindParam($tweeti++, $t->{$f});
             }
             // and the other tables
             if ($t->hashtags) {
                 $fields = $this->binColumnsCache[$bin_name]['hashtags'];
                 foreach ($t->hashtags as $hashtag) {
                     foreach ($fields as $f) {
                         if ($f == 'id') {
                             continue;
                         }
                         $hashtagsq->bindParam($hashtagsi++, $hashtag->{$f});
                     }
                 }
             }
             if ($t->user_mentions) {
                 $fields = $this->binColumnsCache[$bin_name]['mentions'];
                 foreach ($t->user_mentions as $mention) {
                     foreach ($fields as $f) {
                         if ($f == 'id') {
                             continue;
                         }
                         $mentionsq->bindParam($mentionsi++, $mention->{$f});
                     }
                 }
             }
             if ($t->urls) {
                 $fields = $this->binColumnsCache[$bin_name]['urls'];
                 foreach ($t->urls as $url) {
                     foreach ($fields as $f) {
                         if ($f == 'id') {
                             continue;
                         }
                         $urlsq->bindParam($urlsi++, $url->{$f});
                     }
                 }
             }
             if ($statement['withheld'] !== '') {
                 if ($t->withheld_in_countries && !empty($t->withheld_in_countries) && !empty($this->binColumnsCache[$bin_name]['withheld'])) {
                     $fields = $this->binColumnsCache[$bin_name]['withheld'];
                     foreach ($t->withheld_in_countries as $withheld) {
                         foreach ($fields as $f) {
                             if ($f == 'id') {
                                 continue;
                             }
                             $withheldq->bindParam($withheldi++, $withheld->{$f});
                         }
                     }
                 }
             }
             if ($statement['places'] !== '') {
                 if ($t->places && !empty($t->places) && !empty($this->binColumnsCache[$bin_name]['places'])) {
                     $fields = $this->binColumnsCache[$bin_name]['places'];
                     foreach ($t->places as $place) {
                         foreach ($fields as $f) {
                             $placesq->bindParam($placesi++, $place->{$f});
                         }
                     }
                 }
             }
             if ($statement['media'] !== '') {
                 if ($t->media && !empty($t->media) && !empty($this->binColumnsCache[$bin_name]['media'])) {
                     $fields = $this->binColumnsCache[$bin_name]['media'];
                     foreach ($t->media as $media) {
                         foreach ($fields as $f) {
                             $mediaq->bindParam($mediai++, $media->{$f});
                         }
                     }
                 }
             }
         }
         // finaly insert the tweets and other data
         if ($statement['tweets'] !== '') {
             try {
                 $tweetq->execute();
             } catch (PDOException $e) {
                 $this->reportPDOError($e, $bin_name . '_tweets');
             }
         }
         if ($statement['hashtags'] !== '') {
             try {
                 $hashtagsq->execute();
             } catch (PDOException $e) {
                 $this->reportPDOError($e, $bin_name . '_hashtags');
             }
         }
         if ($statement['urls'] !== '') {
             try {
                 $urlsq->execute();
             } catch (PDOException $e) {
                 $this->reportPDOError($e, $bin_name . '_urls');
             }
         }
         if ($statement['mentions'] !== '') {
             try {
                 $mentionsq->execute();
             } catch (PDOException $e) {
                 $this->reportPDOError($e, $bin_name . '_mentions');
             }
         }
         if ($statement['withheld'] !== '') {
             try {
                 $withheldq->execute();
             } catch (PDOException $e) {
                 $this->reportPDOError($e, $bin_name . '_withheld');
             }
         }
         if ($statement['places'] !== '') {
             try {
                 $placesq->execute();
             } catch (PDOException $e) {
                 $this->reportPDOError($e, $bin_name . '_places');
             }
         }
         if ($statement['media'] !== '') {
             try {
                 $mediaq->execute();
             } catch (PDOException $e) {
                 $this->reportPDOError($e, $bin_name . '_media');
             }
         }
         if (defined('CAPTURE') && database_activity($dbh)) {
             $pid = getmypid();
             file_put_contents(BASE_FILE . "proc/" . CAPTURE . ".procinfo", $pid . "|" . time());
         }
     }
     $dbh = null;
     $this->queue = array();
 }
Exemplo n.º 28
0
/** Add daily changes if necessary */
function addDailyChanges($projectid)
{
    include "cdash/config.php";
    include_once "cdash/common.php";
    include_once "cdash/sendemail.php";
    $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
    pdo_select_db("{$CDASH_DB_NAME}", $db);
    $project_array = pdo_fetch_array(pdo_query("SELECT nightlytime,name,autoremovetimeframe,autoremovemaxbuilds,emailadministrator\n                                              FROM project WHERE id='{$projectid}'"));
    $date = "";
    // now
    list($previousdate, $currentstarttime, $nextdate) = get_dates($date, $project_array["nightlytime"]);
    $date = gmdate(FMT_DATE, $currentstarttime);
    // Check if we already have it somwhere
    $query = pdo_query("SELECT id FROM dailyupdate WHERE projectid='{$projectid}' AND date='{$date}'");
    if (pdo_num_rows($query) == 0) {
        $cvsauthors = array();
        pdo_query("INSERT INTO dailyupdate (projectid,date,command,type,status)\n               VALUES ({$projectid},'{$date}','NA','NA','0')");
        $updateid = pdo_insert_id("dailyupdate");
        $dates = get_related_dates($project_array["nightlytime"], $date);
        $commits = get_repository_commits($projectid, $dates);
        // Insert the commits
        foreach ($commits as $commit) {
            $filename = $commit['directory'] . "/" . $commit['filename'];
            $checkindate = $commit['time'];
            $author = addslashes($commit['author']);
            $email = '';
            if (isset($commit['email'])) {
                $email = addslashes($commit['email']);
            }
            $log = addslashes($commit['comment']);
            $revision = $commit['revision'];
            $priorrevision = $commit['priorrevision'];
            // Check if we have a robot file for this build
            $robot = pdo_query("SELECT authorregex FROM projectrobot\n                  WHERE projectid=" . qnum($projectid) . " AND robotname='" . $author . "'");
            if (pdo_num_rows($robot) > 0) {
                $robot_array = pdo_fetch_array($robot);
                $regex = $robot_array['authorregex'];
                preg_match($regex, $commit['comment'], $matches);
                if (isset($matches[1])) {
                    $author = addslashes($matches[1]);
                }
            }
            if (!in_array(stripslashes($author), $cvsauthors)) {
                $cvsauthors[] = stripslashes($author);
            }
            pdo_query("INSERT INTO dailyupdatefile (dailyupdateid,filename,checkindate,author,email,log,revision,priorrevision)\n                   VALUES ({$updateid},'{$filename}','{$checkindate}','{$author}','{$email}','{$log}','{$revision}','{$priorrevision}')");
            add_last_sql_error("addDailyChanges", $projectid);
        }
        // end foreach commit
        // If the project has the option to send an email to the author
        if ($project_array['emailadministrator']) {
            sendEmailUnregisteredUsers($projectid, $cvsauthors);
        }
        // Send an email if some expected builds have not been submitting
        sendEmailExpectedBuilds($projectid, $currentstarttime);
        // cleanBuildEmail
        cleanBuildEmail();
        cleanUserTemp();
        // If the status of daily update is set to 2 that means we should send an email
        $query = pdo_query("SELECT status FROM dailyupdate WHERE projectid='{$projectid}' AND date='{$date}'");
        $dailyupdate_array = pdo_fetch_array($query);
        $dailyupdate_status = $dailyupdate_array["status"];
        if ($dailyupdate_status == 2) {
            // Find the groupid
            $group_query = pdo_query("SELECT buildid,groupid FROM summaryemail WHERE date='{$date}'");
            while ($group_array = pdo_fetch_array($group_query)) {
                $groupid = $group_array["groupid"];
                $buildid = $group_array["buildid"];
                // Find if the build has any errors
                $builderror = pdo_query("SELECT count(buildid) FROM builderror WHERE buildid='{$buildid}' AND type='0'");
                $builderror_array = pdo_fetch_array($builderror);
                $nbuilderrors = $builderror_array[0];
                // Find if the build has any warnings
                $buildwarning = pdo_query("SELECT count(buildid) FROM builderror WHERE buildid='{$buildid}' AND type='1'");
                $buildwarning_array = pdo_fetch_array($buildwarning);
                $nbuildwarnings = $buildwarning_array[0];
                // Find if the build has any test failings
                if ($project_emailtesttimingchanged) {
                    $sql = "SELECT count(testid) FROM build2test WHERE buildid='{$buildid}' AND (status='failed' OR timestatus>" . qnum($project_testtimemaxstatus) . ")";
                } else {
                    $sql = "SELECT count(testid) FROM build2test WHERE buildid='{$buildid}' AND status='failed'";
                }
                $nfail_array = pdo_fetch_array(pdo_query($sql));
                $nfailingtests = $nfail_array[0];
                sendsummaryemail($projectid, $groupid, $nbuildwarnings, $nbuilderrors, $nfailingtests);
            }
        }
        pdo_query("UPDATE dailyupdate SET status='1' WHERE projectid='{$projectid}' AND date='{$date}'");
        // Remove the old logs
        include_once "models/errorlog.php";
        $ErrorLog = new ErrorLog();
        $ErrorLog->Clean(10);
        // 10 days
        // Clean the backup directory
        clean_backup_directory();
        // Remove the first builds of the project
        include_once "cdash/autoremove.php";
        removeFirstBuilds($projectid, $project_array["autoremovetimeframe"], $project_array["autoremovemaxbuilds"]);
        removeBuildsGroupwise($projectid, $project_array["autoremovemaxbuilds"]);
    }
}
Exemplo n.º 29
0
=========================================================================*/
// To be able to access files in this CDash installation regardless
// of getcwd() value:
//
$cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__)));
set_include_path($cdashpath . PATH_SEPARATOR . get_include_path());
require_once "cdash/config.php";
require_once "cdash/pdo.php";
require_once "cdash/common.php";
$buildid = pdo_real_escape_numeric($_GET["buildid"]);
if (!isset($buildid) || !is_numeric($buildid)) {
    echo "Not a valid buildid!";
    return;
}
$db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
pdo_select_db("{$CDASH_DB_NAME}", $db);
// Find the project variables
$build = pdo_query("SELECT name,type,siteid,projectid,starttime FROM build WHERE id='{$buildid}'");
$build_array = pdo_fetch_array($build);
$buildtype = $build_array["type"];
$buildname = $build_array["name"];
$siteid = $build_array["siteid"];
$starttime = $build_array["starttime"];
$projectid = $build_array["projectid"];
// Find the other builds
$previousbuilds = pdo_query("SELECT b.id,b.starttime,bu.nfiles FROM build as b,build2update AS b2u, buildupdate as bu\n                             WHERE b2u.updateid=bu.id AND b2u.buildid=b.id\n                               AND b.siteid='{$siteid}' AND b.type='{$buildtype}' AND b.name='{$buildname}'\n                               AND b.projectid='{$projectid}' AND b.starttime<='{$starttime}' ORDER BY b.starttime ASC");
?>


<br>
Exemplo n.º 30
0
/** Generate the subprojects dashboard */
function generate_subprojects_dashboard_XML($project_instance, $date)
{
    $start = microtime_float();
    $noforcelogin = 1;
    include_once "cdash/config.php";
    require_once "cdash/pdo.php";
    include 'login.php';
    include_once "models/banner.php";
    include_once "models/subproject.php";
    $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
    if (!$db) {
        echo "Error connecting to CDash database server<br>\n";
        return;
    }
    if (!pdo_select_db("{$CDASH_DB_NAME}", $db)) {
        echo "Error selecting CDash database<br>\n";
        return;
    }
    $Project = $project_instance;
    $projectid = $project_instance->Id;
    $homeurl = make_cdash_url(htmlentities($Project->HomeUrl));
    checkUserPolicy(@$_SESSION['cdash']['loginid'], $projectid);
    $xml = begin_XML_for_XSLT();
    $xml .= "<title>CDash - " . $Project->Name . "</title>";
    $Banner = new Banner();
    $Banner->SetProjectId(0);
    $text = $Banner->GetText();
    if ($text !== false) {
        $xml .= "<banner>";
        $xml .= add_XML_value("text", $text);
        $xml .= "</banner>";
    }
    $Banner->SetProjectId($projectid);
    $text = $Banner->GetText();
    if ($text !== false) {
        $xml .= "<banner>";
        $xml .= add_XML_value("text", $text);
        $xml .= "</banner>";
    }
    global $CDASH_SHOW_LAST_SUBMISSION;
    if ($CDASH_SHOW_LAST_SUBMISSION) {
        $xml .= "<showlastsubmission>1</showlastsubmission>";
    }
    list($previousdate, $currentstarttime, $nextdate) = get_dates($date, $Project->NightlyTime);
    $svnurl = make_cdash_url(htmlentities($Project->CvsUrl));
    $homeurl = make_cdash_url(htmlentities($Project->HomeUrl));
    $bugurl = make_cdash_url(htmlentities($Project->BugTrackerUrl));
    $googletracker = htmlentities($Project->GoogleTracker);
    $docurl = make_cdash_url(htmlentities($Project->DocumentationUrl));
    // Main dashboard section
    $xml .= "<dashboard>\n  <datetime>" . date("l, F d Y H:i:s T", time()) . "</datetime>\n  <date>" . $date . "</date>\n  <unixtimestamp>" . $currentstarttime . "</unixtimestamp>\n  <svn>" . $svnurl . "</svn>\n  <bugtracker>" . $bugurl . "</bugtracker>\n  <googletracker>" . $googletracker . "</googletracker>\n  <documentation>" . $docurl . "</documentation>\n  <logoid>" . $Project->getLogoID() . "</logoid>\n  <projectid>" . $projectid . "</projectid>\n  <projectname>" . $Project->Name . "</projectname>\n  <projectname_encoded>" . urlencode($Project->Name) . "</projectname_encoded>\n  <previousdate>" . $previousdate . "</previousdate>\n  <projectpublic>" . $Project->Public . "</projectpublic>\n  <nextdate>" . $nextdate . "</nextdate>";
    if (empty($Project->HomeUrl)) {
        $xml .= "<home>index.php?project=" . urlencode($Project->Name) . "</home>";
    } else {
        $xml .= "<home>" . $homeurl . "</home>";
    }
    if ($CDASH_USE_LOCAL_DIRECTORY && file_exists("local/models/proProject.php")) {
        include_once "local/models/proProject.php";
        $pro = new proProject();
        $pro->ProjectId = $projectid;
        $xml .= "<proedition>" . $pro->GetEdition(1) . "</proedition>";
    }
    if ($currentstarttime > time()) {
        $xml .= "<future>1</future>";
    } else {
        $xml .= "<future>0</future>";
    }
    $xml .= "</dashboard>";
    // Menu definition
    $xml .= "<menu>";
    if (!has_next_date($date, $currentstarttime)) {
        $xml .= add_XML_value("nonext", "1");
    }
    $xml .= "</menu>";
    $beginning_timestamp = $currentstarttime;
    $end_timestamp = $currentstarttime + 3600 * 24;
    $beginning_UTCDate = gmdate(FMT_DATETIME, $beginning_timestamp);
    $end_UTCDate = gmdate(FMT_DATETIME, $end_timestamp);
    // User
    if (isset($_SESSION['cdash'])) {
        $xml .= "<user>";
        $userid = $_SESSION['cdash']['loginid'];
        $user2project = pdo_query("SELECT role FROM user2project WHERE userid='{$userid}' and projectid='{$projectid}'");
        $user2project_array = pdo_fetch_array($user2project);
        $user = pdo_query("SELECT admin FROM " . qid("user") . "  WHERE id='{$userid}'");
        $user_array = pdo_fetch_array($user);
        $xml .= add_XML_value("id", $userid);
        $isadmin = 0;
        if ($user2project_array["role"] > 1 || $user_array["admin"]) {
            $isadmin = 1;
        }
        $xml .= add_XML_value("admin", $isadmin);
        $xml .= add_XML_value("projectrole", $user2project_array['role']);
        $xml .= "</user>";
    }
    // Get some information about the project
    $xml .= "<project>";
    $xml .= add_XML_value("nbuilderror", $Project->GetNumberOfErrorBuilds($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("nbuildwarning", $Project->GetNumberOfWarningBuilds($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("nbuildpass", $Project->GetNumberOfPassingBuilds($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("nconfigureerror", $Project->GetNumberOfErrorConfigures($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("nconfigurewarning", $Project->GetNumberOfWarningConfigures($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("nconfigurepass", $Project->GetNumberOfPassingConfigures($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("ntestpass", $Project->GetNumberOfPassingTests($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("ntestfail", $Project->GetNumberOfFailingTests($beginning_UTCDate, $end_UTCDate, true));
    $xml .= add_XML_value("ntestnotrun", $Project->GetNumberOfNotRunTests($beginning_UTCDate, $end_UTCDate, true));
    if (strlen($Project->GetLastSubmission()) == 0) {
        $xml .= add_XML_value("lastsubmission", "NA");
    } else {
        $xml .= add_XML_value("lastsubmission", $Project->GetLastSubmission());
    }
    $xml .= "</project>";
    // Look for the subproject
    $row = 0;
    $subprojectids = $Project->GetSubProjects();
    $subprojProp = array();
    foreach ($subprojectids as $subprojectid) {
        $SubProject = new SubProject();
        $SubProject->SetId($subprojectid);
        $subprojProp[$subprojectid] = array('name' => $SubProject->GetName());
    }
    $testSubProj = new SubProject();
    $result = $testSubProj->GetNumberOfErrorBuilds($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nbuilderror'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfWarningBuilds($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nbuildwarning'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfPassingBuilds($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nbuildpass'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfErrorConfigures($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nconfigureerror'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfWarningConfigures($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nconfigurewarning'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfPassingConfigures($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['nconfigurepass'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfPassingTests($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['ntestpass'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfFailingTests($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['ntestfail'] = $row[1];
        }
    }
    $result = $testSubProj->GetNumberOfNotRunTests($beginning_UTCDate, $end_UTCDate, True);
    if ($result) {
        foreach ($result as $row) {
            $subprojProp[$row['subprojectid']]['ntestnotrun'] = $row[1];
        }
    }
    $reportArray = array('nbuilderror', 'nbuildwarning', 'nbuildpass', 'nconfigureerror', 'nconfigurewarning', 'nconfigurepass', 'ntestpass', 'ntestfail', 'ntestnotrun');
    foreach ($subprojectids as $subprojectid) {
        $SubProject = new SubProject();
        $SubProject->SetId($subprojectid);
        $xml .= "<subproject>";
        $xml .= add_XML_value("name", $SubProject->GetName());
        $xml .= add_XML_value("name_encoded", urlencode($SubProject->GetName()));
        foreach ($reportArray as $reportnum) {
            $reportval = array_key_exists($reportnum, $subprojProp[$subprojectid]) ? $subprojProp[$subprojectid][$reportnum] : 0;
            $xml .= add_XML_value($reportnum, $reportval);
        }
        if (strlen($SubProject->GetLastSubmission()) == 0) {
            $xml .= add_XML_value("lastsubmission", "NA");
        } else {
            $xml .= add_XML_value("lastsubmission", $SubProject->GetLastSubmission());
        }
        $xml .= "</subproject>";
        if ($row == 1) {
            $row = 0;
        } else {
            $row = 1;
        }
    }
    // end for each subproject
    $end = microtime_float();
    $xml .= "<generationtime>" . round($end - $start, 3) . "</generationtime>";
    $xml .= "</cdash>";
    return $xml;
}