Example #1
0
 /** Return the coverage per directory with the number of lines
  * covered and not covered */
 private function CoveragePerDirectory()
 {
     include_once '../cdash/common.php';
     if (!isset($this->Parameters['project'])) {
         echo "Project not set";
         return;
     }
     $projectid = get_project_id($this->Parameters['project']);
     if (!is_numeric($projectid) || $projectid <= 0) {
         echo "Project not found";
         return;
     }
     // Select the last build that has coverage from the project
     $query = pdo_query("SELECT buildid FROM coveragesummary,build WHERE build.id=coveragesummary.buildid\n                              AND build.projectid='{$projectid}' ORDER BY buildid DESC LIMIT 1");
     echo pdo_error();
     if (pdo_num_rows($query) == 0) {
         echo "No coverage entries found for this project";
         return;
     }
     $query_array = pdo_fetch_array($query);
     $buildid = $query_array['buildid'];
     // Find the coverage files
     $query = pdo_query("SELECT cf.fullpath,c.loctested,c.locuntested FROM coverage as c,coveragefile as cf\n                 WHERE c.fileid=cf.id AND c.buildid='" . $buildid . "' ORDER BY cf.fullpath ASC");
     echo pdo_error();
     $coveragearray = array();
     while ($query_array = pdo_fetch_array($query)) {
         $fullpath = $query_array['fullpath'];
         $paths = explode('/', $fullpath);
         $current = array();
         for ($i = 1; $i < count($paths) - 1; $i++) {
             if ($i == 1) {
                 if (!isset($coveragearray[$paths[$i]])) {
                     $coveragearray[$paths[$i]] = array();
                 }
                 $current =& $coveragearray[$paths[$i]];
             } else {
                 if ($i == count($paths) - 2) {
                     if (isset($current[$paths[$i]])) {
                         $v = $current[$paths[$i]]['locuntested'];
                         $current[$paths[$i]]['locuntested'] = (int) $v + $query_array['locuntested'];
                         $v = $current[$paths[$i]]['loctested'];
                         $current[$paths[$i]]['loctested'] = (int) $v + $query_array['loctested'];
                     } else {
                         @($current[$paths[$i]]['locuntested'] = $query_array['locuntested']);
                         @($current[$paths[$i]]['loctested'] = $query_array['loctested']);
                     }
                     unset($current);
                 } else {
                     $current[$paths[$i]] = array();
                     $current[$paths[$i]]['locuntested'] = 0;
                     $current[$paths[$i]]['loctested'] = 0;
                     $current =& $current[$paths[$i]];
                 }
             }
         }
     }
     return $coveragearray;
 }
Example #2
0
 /** List Defects */
 private function ListDefects()
 {
     include_once 'cdash/common.php';
     if (!isset($this->Parameters['project'])) {
         echo "Project not set";
         return;
     }
     $projectid = get_project_id($this->Parameters['project']);
     if (!is_numeric($projectid) || $projectid <= 0) {
         echo "Project not found";
         return;
     }
     // We need multiple queries (4 to be exact)
     // First for the build failures
     $users = array();
     $query = pdo_query("SELECT SUM(errors) AS nerrors,SUM(nfiles) AS nfiles,author FROM(\n            SELECT b.id,bed.difference_positive AS errors,u.author,\n            COUNT(u.author) AS nfiles, COUNT(DISTINCT u.author) AS dauthor\n            FROM build2group AS b2g, buildgroup AS bg,updatefile AS u,build2update AS b2u, builderrordiff AS bed, build AS b\n            WHERE b.projectid=" . $projectid . " AND u.updateid=b2u.updateid AND b2u.buildid=b.id AND b2g.buildid=b.id AND b2g.groupid=bg.id AND bg.name!='Experimental'\n            AND bed.buildid=b.id AND bed.difference_positive>0 AND bed.difference_negative!=bed.difference_positive\n            AND b.starttime<NOW()\n            GROUP BY b.id,bed.difference_positive,u.author HAVING COUNT(DISTINCT u.author)=1) AS q GROUP BY author");
     echo pdo_error();
     while ($query_array = pdo_fetch_array($query)) {
         $users[$query_array['author']]['builderrors'] = $query_array['nerrors'];
         $users[$query_array['author']]['builderrorsfiles'] = $query_array['nfiles'];
     }
     // Then for the build fixes
     $query = pdo_query("SELECT SUM(fixes) AS nfixes,SUM(nfiles) AS nfiles,author FROM(\n            SELECT b.id,bed.difference_positive AS errors,bed.difference_negative AS fixes,u.author,\n            COUNT(u.author) AS nfiles, COUNT(DISTINCT u.author) AS dauthor\n            FROM build2group AS b2g, buildgroup AS bg,updatefile AS u,build2update AS b2u, builderrordiff AS bed, build AS b\n            WHERE b.projectid=" . $projectid . " AND u.updateid=b2u.updateid AND b2u.buildid=b.id AND b2g.buildid=b.id AND b2g.groupid=bg.id AND bg.name!='Experimental'\n            AND bed.buildid=b.id AND bed.difference_negative>0 AND bed.difference_positive<bed.difference_negative\n            AND b.starttime<NOW()\n            GROUP BY b.id,bed.difference_positive,bed.difference_negative,u.author HAVING COUNT(DISTINCT u.author)=1) AS q GROUP BY author");
     echo pdo_error();
     while ($query_array = pdo_fetch_array($query)) {
         $users[$query_array['author']]['buildfixes'] = $query_array['nfixes'];
         $users[$query_array['author']]['buildfixesfiles'] = $query_array['nfiles'];
     }
     // Then for the test failures
     $query = pdo_query("SELECT SUM(testerrors) AS ntesterrors,SUM(nfiles) AS nfiles,author FROM(SELECT b.id, td.difference_positive AS testerrors,\n              u.author,COUNT(u.author) AS nfiles, COUNT(DISTINCT u.author) AS dauthor\n              FROM build2group AS b2g, buildgroup AS bg,updatefile AS u, build2update AS b2u, build AS b, testdiff AS td\n              WHERE b.projectid=" . $projectid . " AND u.updateid=b2u.updateid AND b2u.buildid=b.id AND b2g.buildid=b.id AND b2g.groupid=bg.id AND bg.name!='Experimental'\n              AND td.buildid=b.id AND td.difference_positive>0 AND td.type=1\n              AND b.starttime<NOW()\n              GROUP BY b.id,td.difference_positive,u.author HAVING COUNT(DISTINCT u.author)=1) AS q GROUP BY author");
     echo pdo_error();
     while ($query_array = pdo_fetch_array($query)) {
         $users[$query_array['author']]['testerrors'] = $query_array['ntesterrors'];
         $users[$query_array['author']]['testerrorsfiles'] = $query_array['nfiles'];
     }
     // Then for the test fixes
     $query = pdo_query("SELECT SUM(testfixes) AS ntestfixes,SUM(nfiles) AS nfiles,author FROM(SELECT b.id, td.difference_positive AS testfixes,\n              u.author,COUNT(u.author) AS nfiles, COUNT(DISTINCT u.author) AS dauthor\n              FROM build2group AS b2g, buildgroup AS bg,updatefile AS u, build2update AS b2u, build AS b, testdiff AS td\n              WHERE b.projectid=" . $projectid . " AND u.updateid=b2u.updateid AND b2u.buildid=b.id AND b2g.buildid=b.id AND b2g.groupid=bg.id AND bg.name!='Experimental'\n              AND td.buildid=b.id AND td.difference_positive>0 AND td.type=2 AND td.difference_negative=0\n              AND b.starttime<NOW()\n              GROUP BY b.id,td.difference_positive,u.author HAVING COUNT(DISTINCT u.author)=1) AS q GROUP BY author");
     echo pdo_error();
     while ($query_array = pdo_fetch_array($query)) {
         $users[$query_array['author']]['testfixes'] = $query_array['ntestfixes'];
         $users[$query_array['author']]['testfixesfiles'] = $query_array['nfiles'];
     }
     // Another select for neutral
     $query = pdo_query("SELECT b.id, bed.difference_positive AS errors,\n          u.author AS author,count(*) AS nfiles\n         FROM build2group AS b2g, buildgroup AS bg,updatefile AS u, build2update AS b2u, build AS b\n         LEFT JOIN builderrordiff AS bed ON (bed.buildid=b.id AND difference_positive!=difference_negative)\n         LEFT JOIN testdiff AS t ON (t.buildid=b.id)\n         WHERE b.projectid=" . $projectid . " AND u.updateid=b2u.updateid AND b2u.buildid=b.id AND b2g.buildid=b.id AND b2g.groupid=bg.id AND bg.name!='Experimental'\n         AND bed.difference_positive IS NULL\n         AND t.difference_positive IS NULL\n         AND b.starttime<NOW() GROUP BY u.author,b.id,bed.difference_positive");
     echo pdo_error();
     while ($query_array = pdo_fetch_array($query)) {
         $users[$query_array['author']]['neutralfiles'] = $query_array['nfiles'];
     }
     return $users;
 }
Example #3
0
function get_dynamic_builds($projectid, $end_UTCDate)
{
    $builds = array();
    // Get the build rules for each dynamic group belonging to this project.
    $rules = pdo_query("\n    SELECT b2gr.buildname, b2gr.siteid, b2gr.parentgroupid, bg.id, bg.name,\n           bg.type, gp.position\n    FROM build2grouprule AS b2gr\n    LEFT JOIN buildgroup AS bg ON (bg.id = b2gr.groupid)\n    LEFT JOIN buildgroupposition AS gp ON (gp.buildgroupid=bg.id)\n    WHERE bg.projectid='{$projectid}' AND bg.endtime='1980-01-01 00:00:00' AND\n          bg.type != 'Daily'");
    if (!$rules) {
        echo pdo_error();
        return;
    }
    while ($rule = pdo_fetch_array($rules)) {
        $buildgroup_name = $rule['name'];
        $buildgroup_id = $rule['id'];
        $buildgroup_position = $rule['position'];
        if ($rule['type'] == 'Latest') {
            // optional fields: parentgroupid, site, and build name match.
            // Use these to construct a WHERE clause for our query.
            $where = '';
            $whereClauses = array();
            if (!empty($rule['parentgroupid'])) {
                $whereClauses[] = "b2g.groupid='" . $rule['parentgroupid'] . "'";
            }
            if (!empty($rule['siteid'])) {
                $whereClauses[] = "s.id='" . $rule['siteid'] . "'";
            }
            if (!empty($rule['buildname'])) {
                $whereClauses[] = "b.name LIKE '" . $rule['buildname'] . "'";
            }
            if (!empty($whereClauses)) {
                $where = 'WHERE ' . implode($whereClauses, ' AND ');
                $where .= " AND b.starttime<'{$end_UTCDate}'";
            }
            // We only want the most recent build.
            $order = 'ORDER BY b.submittime DESC LIMIT 1';
            $sql = get_index_query();
            $sql .= "{$where} {$order}";
            $build = pdo_single_row_query($sql);
            if (empty($build)) {
                continue;
            }
            $build['groupname'] = $buildgroup_name;
            $build['groupid'] = $buildgroup_id;
            $build['position'] = $buildgroup_position;
            $builds[] = $build;
        }
    }
    return $builds;
}
Example #4
0
function get_dynamic_builds($projectid)
{
    $builds = array();
    // Get the build rules for each dynamic group belonging to this project.
    $rules = pdo_query("\n    SELECT b2gr.buildname, b2gr.siteid, b2gr.parentgroupid, bg.id, bg.name,\n           bg.type, gp.position\n    FROM build2grouprule AS b2gr\n    LEFT JOIN buildgroup AS bg ON (bg.id = b2gr.groupid)\n    LEFT JOIN buildgroupposition AS gp ON (gp.buildgroupid=bg.id)\n    WHERE bg.projectid='{$projectid}' AND bg.endtime='1980-01-01 00:00:00' AND\n          bg.type != 'Daily'");
    if (!$rules) {
        echo pdo_error();
        return;
    }
    while ($rule = pdo_fetch_array($rules)) {
        $buildgroup_name = $rule['name'];
        $buildgroup_id = $rule['id'];
        $buildgroup_position = $rule['position'];
        if ($rule['type'] == 'Latest') {
            // optional fields: parentgroupid, site, and build name match.
            // Use these to construct a WHERE clause for our query.
            $where = "";
            $whereClauses = array();
            if (!empty($rule['parentgroupid'])) {
                $whereClauses[] = "b2g.groupid='" . $rule['parentgroupid'] . "'";
            }
            if (!empty($rule['siteid'])) {
                $whereClauses[] = "s.id='" . $rule['siteid'] . "'";
            }
            if (!empty($rule['buildname'])) {
                $whereClauses[] = "b.name LIKE '" . $rule['buildname'] . "'";
            }
            if (!empty($whereClauses)) {
                $where = "WHERE " . implode($whereClauses, " AND ");
            }
            // We only want the most recent build.
            $order = "ORDER BY b.submittime DESC LIMIT 1";
            // Copied from index.php.
            $sql = "SELECT b.id,b.siteid,b.parentid,\n              bu.status AS updatestatus,\n              i.osname AS osname,\n              bu.starttime AS updatestarttime,\n              bu.endtime AS updateendtime,\n              bu.nfiles AS countupdatefiles,\n              bu.warnings AS countupdatewarnings,\n              c.status AS configurestatus,\n              c.starttime AS configurestarttime,\n              c.endtime AS configureendtime,\n              be_diff.difference_positive AS countbuilderrordiffp,\n              be_diff.difference_negative AS countbuilderrordiffn,\n              bw_diff.difference_positive AS countbuildwarningdiffp,\n              bw_diff.difference_negative AS countbuildwarningdiffn,\n              ce_diff.difference AS countconfigurewarningdiff,\n              btt.time AS testsduration,\n              tnotrun_diff.difference_positive AS counttestsnotrundiffp,\n              tnotrun_diff.difference_negative AS counttestsnotrundiffn,\n              tfailed_diff.difference_positive AS counttestsfaileddiffp,\n              tfailed_diff.difference_negative AS counttestsfaileddiffn,\n              tpassed_diff.difference_positive AS counttestspasseddiffp,\n              tpassed_diff.difference_negative AS counttestspasseddiffn,\n              tstatusfailed_diff.difference_positive AS countteststimestatusfaileddiffp,\n              tstatusfailed_diff.difference_negative AS countteststimestatusfaileddiffn,\n              (SELECT count(buildid) FROM build2note WHERE buildid=b.id)  AS countnotes,\n              (SELECT count(buildid) FROM buildnote WHERE buildid=b.id) AS countbuildnotes,\n              s.name AS sitename,\n              s.outoforder AS siteoutoforder,\n              b.stamp,b.name,b.type,b.generator,b.starttime,b.endtime,b.submittime,\n              b.configureerrors AS countconfigureerrors,\n              b.configurewarnings AS countconfigurewarnings,\n              b.builderrors AS countbuilderrors,\n              b.buildwarnings AS countbuildwarnings,\n              b.testnotrun AS counttestsnotrun,\n              b.testfailed AS counttestsfailed,\n              b.testpassed AS counttestspassed,\n              b.testtimestatusfailed AS countteststimestatusfailed,\n              sp.id AS subprojectid,\n              sp.groupid AS subprojectgroup,\n              (SELECT count(buildid) FROM errorlog WHERE buildid=b.id) AS nerrorlog,\n              (SELECT count(buildid) FROM build2uploadfile WHERE buildid=b.id) AS builduploadfiles\n              FROM build AS b\n              LEFT JOIN build2group AS b2g ON (b2g.buildid=b.id)\n              LEFT JOIN buildgroup AS g ON (g.id=b2g.groupid)\n              LEFT JOIN site AS s ON (s.id=b.siteid)\n              LEFT JOIN build2update AS b2u ON (b2u.buildid=b.id)\n              LEFT JOIN buildupdate AS bu ON (b2u.updateid=bu.id)\n              LEFT JOIN configure AS c ON (c.buildid=b.id)\n              LEFT JOIN buildinformation AS i ON (i.buildid=b.id)\n              LEFT JOIN builderrordiff AS be_diff ON (be_diff.buildid=b.id AND be_diff.type=0)\n              LEFT JOIN builderrordiff AS bw_diff ON (bw_diff.buildid=b.id AND bw_diff.type=1)\n              LEFT JOIN configureerrordiff AS ce_diff ON (ce_diff.buildid=b.id AND ce_diff.type=1)\n              LEFT JOIN buildtesttime AS btt ON (btt.buildid=b.id)\n              LEFT JOIN testdiff AS tnotrun_diff ON (tnotrun_diff.buildid=b.id AND tnotrun_diff.type=0)\n              LEFT JOIN testdiff AS tfailed_diff ON (tfailed_diff.buildid=b.id AND tfailed_diff.type=1)\n              LEFT JOIN testdiff AS tpassed_diff ON (tpassed_diff.buildid=b.id AND tpassed_diff.type=2)\n              LEFT JOIN testdiff AS tstatusfailed_diff ON (tstatusfailed_diff.buildid=b.id AND tstatusfailed_diff.type=3)\n              LEFT JOIN subproject2build AS sp2b ON (sp2b.buildid = b.id)\n              LEFT JOIN subproject as sp ON (sp2b.subprojectid = sp.id)\n              LEFT JOIN label2build AS l2b ON (l2b.buildid = b.id)\n              LEFT JOIN label AS l ON (l.id = l2b.labelid) {$where} {$order}";
            $build = pdo_single_row_query($sql);
            if (empty($build)) {
                continue;
            }
            $build['groupname'] = $buildgroup_name;
            $build['groupid'] = $buildgroup_id;
            $build['position'] = $buildgroup_position;
            $builds[] = $build;
        }
    }
    return $builds;
}
Example #5
0
 function Insert()
 {
     if (!is_numeric($this->ProjectId) || !is_numeric($this->BuildId) || !is_numeric($this->ResourceId) || !is_numeric($this->ResourceType) || !is_numeric($this->Type)) {
         return false;
     }
     $description = pdo_real_escape_string($this->Description);
     // If the projectid is not set but the buildid is we are trying to find
     // the projectid
     if ($this->ProjectId == 0 && $this->BuildId > 0) {
         $query = pdo_query("SELECT projectid FROM build WHERE id='" . $this->BuildId . "'");
         if (pdo_num_rows($query) > 0) {
             $query_array = pdo_fetch_array($query);
             $this->ProjectId = $query_array['projectid'];
         }
     }
     // Insert a new row every time an error exists
     $now = date("Y-m-d H:i:s");
     $sql = "INSERT INTO errorlog (projectid,buildid,type,date,resourcetype,resourceid,description)\n               VALUES ('" . $this->ProjectId . "','" . $this->BuildId . "','" . $this->Type . "','" . $now . "','" . $this->ResourceType . "','" . $this->ResourceId . "','" . $description . "')";
     pdo_query($sql);
     echo pdo_error();
     // We don't log on purpose (loop loop ;)
     return true;
 }
Example #6
0
function rest_post()
{
    global $projectid;
    if (isset($_POST['newbuildgroup'])) {
        // Create a new buildgroup
        $BuildGroup = new BuildGroup();
        $BuildGroup->SetProjectId($projectid);
        $name = htmlspecialchars(pdo_real_escape_string($_POST['newbuildgroup']));
        // Avoid creating a group that uses one of the default names.
        if ($name == "Nightly" || $name == "Experimental" || $name == "Continuous") {
            echo_error("You cannot create a group named 'Nightly','Experimental' or 'Continuous'");
            return;
        }
        $type = htmlspecialchars(pdo_real_escape_string($_POST['type']));
        $BuildGroup->SetName($name);
        $BuildGroup->SetType($type);
        $BuildGroup->Save();
        // Respond with a JSON representation of this new buildgroup
        $response = array();
        $response['id'] = $BuildGroup->GetId();
        $response['name'] = $BuildGroup->GetName();
        $response['autoremovetimeframe'] = $BuildGroup->GetAutoRemoveTimeFrame();
        echo json_encode($response);
        return;
    }
    if (isset($_POST['newLayout'])) {
        // Update the order of the buildgroups for this project.
        $inputRows = $_POST['newLayout'];
        if (count($inputRows) > 0) {
            // Remove old build group layout for this project.
            global $CDASH_DB_TYPE;
            if (isset($CDASH_DB_TYPE) && $CDASH_DB_TYPE == "pgsql") {
                // We use a subquery here because postgres doesn't support
                // JOINs in a DELETE statement.
                $sql = "\n          DELETE FROM buildgroupposition WHERE buildgroupid IN\n            (SELECT bgp.buildgroupid FROM buildgroupposition AS bgp\n             LEFT JOIN buildgroup AS bg ON (bgp.buildgroupid = bg.id)\n             WHERE bg.projectid = '{$projectid}')";
            } else {
                $sql = "\n          DELETE bgp FROM buildgroupposition AS bgp\n          LEFT JOIN buildgroup AS bg ON (bgp.buildgroupid = bg.id)\n          WHERE bg.projectid = '{$projectid}'";
            }
            pdo_query($sql);
            add_last_sql_error("manageBuildGroup::newLayout::DELETE", $projectid);
            // construct query to insert the new layout
            $query = "INSERT INTO buildgroupposition (buildgroupid, position) VALUES ";
            foreach ($inputRows as $inputRow) {
                $query .= "(" . qnum(pdo_real_escape_numeric($inputRow["buildgroupid"])) . ", " . qnum(pdo_real_escape_numeric($inputRow["position"])) . "), ";
            }
            // remove the trailing comma and space, then insert our new values
            $query = rtrim($query, ", ");
            pdo_query($query);
            add_last_sql_error("API::buildgroup::newLayout::INSERT", $projectid);
        }
        return;
    }
    if (isset($_POST['builds'])) {
        // Move builds to a new group.
        $group = $_POST['group'];
        if ($group['id'] < 1) {
            echo_error("Please select a group for these builds");
            return;
        }
        $builds = $_POST['builds'];
        if (array_key_exists('expected', $_POST)) {
            $expected = $_POST['expected'];
        } else {
            $expected = 0;
        }
        foreach ($builds as $buildinfo) {
            $groupid = pdo_real_escape_numeric($group['id']);
            $Build = new Build();
            $buildid = pdo_real_escape_numeric($buildinfo['id']);
            $Build->Id = $buildid;
            $Build->FillFromId($Build->Id);
            $prevgroupid = $Build->GroupId;
            // Change the group for this build.
            pdo_query("UPDATE build2group SET groupid='{$groupid}'\n         WHERE groupid='{$prevgroupid}' AND buildid='{$buildid}'");
            // Delete any previous rules
            pdo_query("\n        DELETE FROM build2grouprule\n        WHERE groupid='{$prevgroupid}' AND buildtype='{$Build->Type}' AND\n              buildname='{$Build->Name}' AND siteid='{$Build->SiteId}'");
            // Add the new rule
            pdo_query("\n        INSERT INTO build2grouprule\n          (groupid,buildtype,buildname,siteid,expected,starttime,endtime)\n        VALUES\n          ('{$groupid}','{$Build->Type}','{$Build->Name}','{$Build->SiteId}',\n           '{$expected}','1980-01-01 00:00:00','1980-01-01 00:00:00')");
        }
    }
    if (isset($_POST['nameMatch'])) {
        // Define a BuildGroup by Build name.
        $group = $_POST['group'];
        $groupid = $group['id'];
        if ($groupid < 1) {
            echo_error("Please select a BuildGroup to define.");
            return;
        }
        $nameMatch = "%" . htmlspecialchars(pdo_real_escape_string($_POST["nameMatch"])) . "%";
        $type = htmlspecialchars(pdo_real_escape_string($_POST["type"]));
        $sql = "INSERT INTO build2grouprule (groupid, buildtype, buildname, siteid)\n       VALUES ('{$groupid}', '{$type}', '{$nameMatch}', '-1')";
        if (!pdo_query($sql)) {
            echo_error(pdo_error());
        }
    }
    if (isset($_POST['dynamic']) && !empty($_POST['dynamic'])) {
        // Add a build row to a dynamic group
        $groupid = pdo_real_escape_numeric($_POST['dynamic']['id']);
        if (empty($_POST['buildgroup'])) {
            $parentgroupid = 0;
        } else {
            $parentgroupid = pdo_real_escape_numeric($_POST['buildgroup']['id']);
        }
        if (empty($_POST['site'])) {
            $siteid = 0;
        } else {
            $siteid = pdo_real_escape_numeric($_POST['site']['id']);
        }
        if (empty($_POST['match'])) {
            $match = "";
        } else {
            $match = "%" . htmlspecialchars(pdo_real_escape_string($_POST['match'])) . "%";
        }
        $sql = "INSERT INTO build2grouprule (groupid, buildname, siteid, parentgroupid)\n       VALUES ('{$groupid}', '{$match}', '{$siteid}', '{$parentgroupid}')";
        if (!pdo_query($sql)) {
            echo_error(pdo_error());
        } else {
            // Respond with a JSON representation of this new rule.
            $response = array();
            $response['match'] = htmlspecialchars(pdo_real_escape_string($_POST['match']));
            $response['siteid'] = $siteid;
            if ($siteid > 0) {
                $response['sitename'] = htmlspecialchars(pdo_real_escape_string($_POST['site']['name']));
            } else {
                $response['sitename'] = 'Any';
            }
            $response['parentgroupid'] = $parentgroupid;
            if ($parentgroupid > 0) {
                $response['parentgroupname'] = htmlspecialchars(pdo_real_escape_string($_POST['buildgroup']['name']));
            } else {
                $response['parentgroupname'] = 'Any';
            }
            echo json_encode($response);
            return;
        }
    }
}
Example #7
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");
    }
}
Example #8
0
        }
        $dynamics_response[] = $dynamic_response;
    }
}
$response['buildgroups'] = $buildgroups_response;
$response['dynamics'] = $dynamics_response;
// Store some additional details about this project.
$project_response = array();
$project_response['id'] = $projectid;
$project_name = $Project->GetName();
$project_response['name'] = $project_name;
$project_response['name_encoded'] = urlencode($project_name);
$response['project'] = $project_response;
// Generate response for any wildcard groups.
$wildcards = pdo_query("\n  SELECT bg.name, bg.id, b2gr.buildtype, b2gr.buildname\n  FROM build2grouprule AS b2gr, buildgroup AS bg\n  WHERE b2gr.buildname LIKE '\\%%\\%' AND b2gr.groupid = bg.id AND\n        bg.type = 'Daily' AND bg.projectid='{$projectid}'");
$err = pdo_error();
if (!empty($err)) {
    $response['error'] = $err;
}
$wildcards_response = array();
while ($wildcard_array = pdo_fetch_array($wildcards)) {
    $wildcard_response = array();
    $wildcard_response['buildgroupname'] = $wildcard_array['name'];
    $wildcard_response['buildgroupid'] = $wildcard_array['id'];
    $wildcard_response['buildtype'] = $wildcard_array['buildtype'];
    $match = $wildcard_array['buildname'];
    $match = str_replace("%", "", $match);
    $wildcard_response['match'] = $match;
    $wildcards_response[] = $wildcard_response;
}
$response['wildcards'] = $wildcards_response;
Example #9
0
 /** Insert a new site */
 public function Insert()
 {
     $justSetIP = false;
     if (strlen($this->Ip) == 0) {
         $this->LookupIP();
         $justSetIP = true;
     }
     if ($this->Exists()) {
         if ($justSetIP) {
             $this->Update();
         }
         return $this->Id;
     }
     // Get the geolocation
     if (strlen($this->Latitude) == 0) {
         $location = get_geolocation($this->Ip);
         $this->Latitude = $location['latitude'];
         $this->Longitude = $location['longitude'];
     }
     $query = "INSERT INTO site (name,ip,latitude,longitude)\n            VALUES\n            ('{$this->Name}','{$this->Ip}','{$this->Latitude}','{$this->Longitude}')";
     if (!pdo_query($query)) {
         $error = pdo_error();
         // This error might be due to a unique constraint violation.
         // Query for a previously existing site with this name & ip.
         $existing_id_result = pdo_single_row_query("SELECT id FROM site WHERE name='{$this->Name}'\n                    AND ip='{$this->Ip}'");
         if ($existing_id_result && array_key_exists('id', $existing_id_result)) {
             $this->Id = $existing_id_result['id'];
             return true;
         }
         add_log("SQL error: {$error}", 'Site Insert', LOG_ERR);
         return false;
     } else {
         $this->Id = pdo_insert_id('site');
     }
 }
Example #10
0
/** return an array of public projects */
function get_projects($onlyactive = true)
{
    $projects = array();
    include "cdash/config.php";
    require_once "cdash/pdo.php";
    require_once 'models/project.php';
    $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
    pdo_select_db("{$CDASH_DB_NAME}", $db);
    $projectres = pdo_query("SELECT id,name,description FROM project WHERE public='1' ORDER BY name");
    while ($project_array = pdo_fetch_array($projectres)) {
        $project = array();
        $project['id'] = $project_array["id"];
        $project['name'] = $project_array["name"];
        $project['description'] = $project_array["description"];
        $projectid = $project['id'];
        $project['last_build'] = "NA";
        $lastbuildquery = pdo_query("SELECT submittime FROM build WHERE projectid='{$projectid}' ORDER BY submittime DESC LIMIT 1");
        if (pdo_num_rows($lastbuildquery) > 0) {
            $lastbuild_array = pdo_fetch_array($lastbuildquery);
            $project['last_build'] = $lastbuild_array["submittime"];
        }
        // Display if the project is considered active or not
        $dayssincelastsubmission = $CDASH_ACTIVE_PROJECT_DAYS + 1;
        if ($project['last_build'] != 'NA') {
            $dayssincelastsubmission = (time() - strtotime($project['last_build'])) / 86400;
        }
        $project['dayssincelastsubmission'] = $dayssincelastsubmission;
        if ($project['last_build'] != 'NA' && $project['dayssincelastsubmission'] <= $CDASH_ACTIVE_PROJECT_DAYS) {
            // Get the number of builds in the past 7 days
            $submittime_UTCDate = gmdate(FMT_DATETIME, time() - 604800);
            $buildquery = pdo_query("SELECT count(id) FROM build WHERE projectid='{$projectid}' AND starttime>'" . $submittime_UTCDate . "'");
            echo pdo_error();
            $buildquery_array = pdo_fetch_array($buildquery);
            $project['nbuilds'] = $buildquery_array[0];
        }
        /** Not showing the upload size for now for performance reasons */
        //$Project = new Project;
        //$Project->Id = $project['id'];
        //$project['uploadsize'] = $Project->GetUploadsTotalSize();
        if (!$onlyactive || $project['dayssincelastsubmission'] <= $CDASH_ACTIVE_PROJECT_DAYS) {
            $projects[] = $project;
        }
    }
    return $projects;
}
Example #11
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));
}
Example #12
0
/** Generate the main dashboard XML */
function generate_main_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;
    }
    $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);
        $svnurl = make_cdash_url(htmlentities($project_array["cvsurl"]));
        $homeurl = make_cdash_url(htmlentities($project_array["homeurl"]));
        $bugurl = make_cdash_url(htmlentities($project_array["bugtrackerurl"]));
        $googletracker = htmlentities($project_array["googletracker"]);
        $docurl = make_cdash_url(htmlentities($project_array["documentationurl"]));
        $projectpublic = $project_array["public"];
        $projectname = $project_array["name"];
        if (isset($project_array['testingdataurl']) && $project_array['testingdataurl'] != '') {
            $testingdataurl = make_cdash_url(htmlentities($project_array['testingdataurl']));
        }
    } else {
        redirect_error('This project doesn\'t exist. Maybe the URL you are trying to access is wrong.');
        return false;
    }
    checkUserPolicy(@$_SESSION['cdash']['loginid'], $project_array["id"]);
    $xml = begin_XML_for_XSLT();
    $xml .= "<title>CDash - " . $projectname . "</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>";
    }
    $sitexml = "";
    list($previousdate, $currentstarttime, $nextdate) = get_dates($date, $project_array["nightlytime"]);
    $logoid = getLogoID($projectid);
    // 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>" . $logoid . "</logoid>\n  <projectid>" . $projectid . "</projectid>\n  <projectname>" . $projectname . "</projectname>\n  <projectname_encoded>" . urlencode($projectname) . "</projectname_encoded>\n  <previousdate>" . $previousdate . "</previousdate>\n  <projectpublic>" . $projectpublic . "</projectpublic>\n  <displaylabels>" . $project_array["displaylabels"] . "</displaylabels>\n  <nextdate>" . $nextdate . "</nextdate>";
    if (empty($project_array["homeurl"])) {
        $xml .= "<home>index.php?project=" . urlencode($projectname) . "</home>";
    } else {
        $xml .= "<home>" . $homeurl . "</home>";
    }
    if (isset($_GET["parentid"])) {
        $xml .= "<childview>1</childview>";
    } else {
        $xml .= "<childview>0</childview>";
    }
    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>";
    // Check the builds
    $beginning_timestamp = $currentstarttime;
    $end_timestamp = $currentstarttime + 3600 * 24;
    $beginning_UTCDate = gmdate(FMT_DATETIME, $beginning_timestamp);
    $end_UTCDate = gmdate(FMT_DATETIME, $end_timestamp);
    // Add the extra url if necessary
    if (isset($_GET["display"]) && $_GET["display"] == "project") {
        $xml .= add_XML_value("extraurl", "&display=project");
    }
    // If we have a subproject
    $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
            $xml .= add_XML_value("extraurl", "&subproject=" . urlencode($subproject_name));
            $xml .= add_XML_value("subprojectname", $subproject_name);
            $xml .= "<subproject>";
            $xml .= add_XML_value("name", $SubProject->GetName());
            $rowparity = 0;
            $dependencies = $SubProject->GetDependencies();
            if ($dependencies) {
                foreach ($dependencies as $dependency) {
                    $xml .= "<dependency>";
                    $DependProject = new SubProject();
                    $DependProject->SetId($dependency);
                    $xml .= add_XML_value("rowparity", $rowparity);
                    $xml .= add_XML_value("name", $DependProject->GetName());
                    $xml .= add_XML_value("name_encoded", urlencode($DependProject->GetName()));
                    $xml .= add_XML_value("nbuilderror", $DependProject->GetNumberOfErrorBuilds($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("nbuildwarning", $DependProject->GetNumberOfWarningBuilds($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("nbuildpass", $DependProject->GetNumberOfPassingBuilds($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("nconfigureerror", $DependProject->GetNumberOfErrorConfigures($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("nconfigurewarning", $DependProject->GetNumberOfWarningConfigures($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("nconfigurepass", $DependProject->GetNumberOfPassingConfigures($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("ntestpass", $DependProject->GetNumberOfPassingTests($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("ntestfail", $DependProject->GetNumberOfFailingTests($beginning_UTCDate, $end_UTCDate));
                    $xml .= add_XML_value("ntestnotrun", $DependProject->GetNumberOfNotRunTests($beginning_UTCDate, $end_UTCDate));
                    if (strlen($DependProject->GetLastSubmission()) == 0) {
                        $xml .= add_XML_value("lastsubmission", "NA");
                    } else {
                        $xml .= add_XML_value("lastsubmission", $DependProject->GetLastSubmission());
                    }
                    $rowparity = $rowparity == 1 ? 0 : 1;
                    $xml .= "</dependency>";
                }
            }
            $xml .= "</subproject>";
        } else {
            add_log("SubProject '{$subproject_name}' does not exist", __FILE__ . ':' . __LINE__ . ' - ' . __FUNCTION__, LOG_WARNING);
        }
    }
    if (isset($testingdataurl)) {
        $xml .= add_XML_value("testingdataurl", $testingdataurl);
    }
    // updates
    $xml .= "<updates>";
    $gmdate = gmdate(FMT_DATE, $currentstarttime);
    $xml .= "<url>viewChanges.php?project=" . urlencode($projectname) . "&amp;date=" . $gmdate . "</url>";
    $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);
        $xml .= "<nchanges>" . $dailupdate_array[0] . "</nchanges>";
        $xml .= "<nauthors>" . $dailupdate_array[1] . "</nauthors>";
    } else {
        $xml .= "<nchanges>-1</nchanges>";
    }
    $xml .= add_XML_value("timestamp", date("l, F d Y - H:i T", $currentstarttime));
    $xml .= "</updates>";
    // 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>";
    }
    // Filters:
    //
    $filterdata = get_filterdata_from_request();
    $filter_sql = $filterdata['sql'];
    $limit_sql = '';
    if ($filterdata['limit'] > 0) {
        $limit_sql = ' LIMIT ' . $filterdata['limit'];
    }
    $xml .= $filterdata['xml'];
    // Local function to add expected builds
    function add_expected_builds($groupid, $currentstarttime, $received_builds)
    {
        include 'cdash/config.php';
        $currentUTCTime = gmdate(FMT_DATETIME, $currentstarttime + 3600 * 24);
        $xml = "";
        $build2grouprule = pdo_query("SELECT g.siteid,g.buildname,g.buildtype,s.name,s.outoforder FROM build2grouprule AS g,site as s\n                                  WHERE g.expected='1' AND g.groupid='{$groupid}' AND s.id=g.siteid\n                                  AND g.starttime<'{$currentUTCTime}' AND (g.endtime>'{$currentUTCTime}' OR g.endtime='1980-01-01 00:00:00')\n                                  ");
        while ($build2grouprule_array = pdo_fetch_array($build2grouprule)) {
            $key = $build2grouprule_array["name"] . "_" . $build2grouprule_array["buildname"];
            if (array_search($key, $received_builds) === FALSE) {
                $site = $build2grouprule_array["name"];
                $siteid = $build2grouprule_array["siteid"];
                $siteoutoforder = $build2grouprule_array["outoforder"];
                $buildtype = $build2grouprule_array["buildtype"];
                $buildname = $build2grouprule_array["buildname"];
                $xml .= "<build>";
                $xml .= add_XML_value("site", $site);
                $xml .= add_XML_value("siteoutoforder", $siteoutoforder);
                $xml .= add_XML_value("siteid", $siteid);
                $xml .= add_XML_value("buildname", $buildname);
                $xml .= add_XML_value("buildtype", $buildtype);
                $xml .= add_XML_value("buildgroupid", $groupid);
                $xml .= add_XML_value("expected", "1");
                // compute historical average to get approximate expected time
                // PostgreSQL doesn't have the necessary functions for this
                if ($CDASH_DB_TYPE == 'pgsql') {
                    $query = pdo_query("SELECT submittime FROM build,build2group\n                              WHERE build2group.buildid=build.id AND siteid='{$siteid}' AND name='{$buildname}'\n                              AND type='{$buildtype}' AND build2group.groupid='{$groupid}'\n                              ORDER BY id DESC LIMIT 5");
                    $time = 0;
                    while ($query_array = pdo_fetch_array($query)) {
                        $time += strtotime(date("H:i:s", strtotime($query_array['submittime'])));
                    }
                    if (pdo_num_rows($query) > 0) {
                        $time /= pdo_num_rows($query);
                    }
                    $nextExpected = strtotime(date("H:i:s", $time) . " UTC");
                } else {
                    $query = pdo_query("SELECT AVG(TIME_TO_SEC(TIME(submittime))) FROM (SELECT submittime FROM build,build2group\n                                WHERE build2group.buildid=build.id AND siteid='{$siteid}' AND name='{$buildname}'\n                                AND type='{$buildtype}' AND build2group.groupid='{$groupid}'\n                                ORDER BY id DESC LIMIT 5) as t");
                    $query_array = pdo_fetch_array($query);
                    $time = $query_array[0];
                    $hours = floor($time / 3600);
                    $time = $time % 3600;
                    $minutes = floor($time / 60);
                    $seconds = $time % 60;
                    $nextExpected = strtotime($hours . ":" . $minutes . ":" . $seconds . " UTC");
                }
                $divname = $build2grouprule_array["siteid"] . "_" . $build2grouprule_array["buildname"];
                $divname = str_replace("+", "_", $divname);
                $divname = str_replace(".", "_", $divname);
                $divname = str_replace(':', "_", $divname);
                $divname = str_replace(' ', "_", $divname);
                $xml .= add_XML_value("expecteddivname", $divname);
                $xml .= add_XML_value("submitdate", "No Submission");
                $xml .= add_XML_value("expectedstarttime", date(FMT_TIME, $nextExpected));
                $xml .= "</build>";
            }
        }
        return $xml;
    }
    // add a request for the subproject
    $subprojectsql = "";
    $subprojecttablesql = "";
    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 = "";
    } else {
        if (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'])) {
        $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,";
    }
    // Postgres differs from MySQL on how to aggregate results
    // into a single column.
    $label_sql = "";
    $groupby_sql = "";
    if ($CDASH_DB_TYPE != 'pgsql') {
        $label_sql = "GROUP_CONCAT(l.text SEPARATOR ', ') AS labels,";
        $groupby_sql = " GROUP BY b.id";
    }
    $sql = "SELECT b.id,b.siteid,b.parentid,\n                  bu.status AS updatestatus,\n                  i.osname AS osname,\n                  bu.starttime AS updatestarttime,\n                  bu.endtime AS updateendtime,\n                  bu.nfiles AS countupdatefiles,\n                  bu.warnings AS countupdatewarnings,\n                  c.status AS configurestatus,\n                  c.starttime AS configurestarttime,\n                  c.endtime AS configureendtime,\n                  be_diff.difference_positive AS countbuilderrordiffp,\n                  be_diff.difference_negative AS countbuilderrordiffn,\n                  bw_diff.difference_positive AS countbuildwarningdiffp,\n                  bw_diff.difference_negative AS countbuildwarningdiffn,\n                  ce_diff.difference AS countconfigurewarningdiff,\n                  btt.time AS testsduration,\n                  tnotrun_diff.difference_positive AS counttestsnotrundiffp,\n                  tnotrun_diff.difference_negative AS counttestsnotrundiffn,\n                  tfailed_diff.difference_positive AS counttestsfaileddiffp,\n                  tfailed_diff.difference_negative AS counttestsfaileddiffn,\n                  tpassed_diff.difference_positive AS counttestspasseddiffp,\n                  tpassed_diff.difference_negative AS counttestspasseddiffn,\n                  tstatusfailed_diff.difference_positive AS countteststimestatusfaileddiffp,\n                  tstatusfailed_diff.difference_negative AS countteststimestatusfaileddiffn,\n                  (SELECT count(buildid) FROM build2note WHERE buildid=b.id)  AS countnotes,\n                  (SELECT count(buildid) FROM buildnote WHERE buildid=b.id) AS countbuildnotes," . $userupdatesql . "\n                  s.name AS sitename,\n                  s.outoforder AS siteoutoforder,\n                  b.stamp,b.name,b.type,b.generator,b.starttime,b.endtime,b.submittime,\n                  b.configureerrors AS countconfigureerrors,\n                  b.configurewarnings AS countconfigurewarnings,\n                  b.builderrors AS countbuilderrors,\n                  b.buildwarnings AS countbuildwarnings,\n                  b.testnotrun AS counttestsnotrun,\n                  b.testfailed AS counttestsfailed,\n                  b.testpassed AS counttestspassed,\n                  b.testtimestatusfailed AS countteststimestatusfailed,\n                  sp.id AS subprojectid,\n                  sp.groupid AS subprojectgroup,\n                  g.name as groupname,gp.position,g.id as groupid,\n                  {$label_sql}\n                  (SELECT count(buildid) FROM errorlog WHERE buildid=b.id) AS nerrorlog,\n                  (SELECT count(buildid) FROM build2uploadfile WHERE buildid=b.id) AS builduploadfiles\n                  FROM build AS b\n                  LEFT JOIN build2group AS b2g ON (b2g.buildid=b.id)\n                  LEFT JOIN buildgroup AS g ON (g.id=b2g.groupid)\n                  LEFT JOIN buildgroupposition AS gp ON (gp.buildgroupid=g.id)\n                  LEFT JOIN site AS s ON (s.id=b.siteid)\n                  LEFT JOIN build2update AS b2u ON (b2u.buildid=b.id)\n                  LEFT JOIN buildupdate AS bu ON (b2u.updateid=bu.id)\n                  LEFT JOIN configure AS c ON (c.buildid=b.id)\n                  LEFT JOIN buildinformation AS i ON (i.buildid=b.id)\n                  LEFT JOIN builderrordiff AS be_diff ON (be_diff.buildid=b.id AND be_diff.type=0)\n                  LEFT JOIN builderrordiff AS bw_diff ON (bw_diff.buildid=b.id AND bw_diff.type=1)\n                  LEFT JOIN configureerrordiff AS ce_diff ON (ce_diff.buildid=b.id AND ce_diff.type=1)\n                  LEFT JOIN buildtesttime AS btt ON (btt.buildid=b.id)\n                  LEFT JOIN testdiff AS tnotrun_diff ON (tnotrun_diff.buildid=b.id AND tnotrun_diff.type=0)\n                  LEFT JOIN testdiff AS tfailed_diff ON (tfailed_diff.buildid=b.id AND tfailed_diff.type=1)\n                  LEFT JOIN testdiff AS tpassed_diff ON (tpassed_diff.buildid=b.id AND tpassed_diff.type=2)\n                  LEFT JOIN testdiff AS tstatusfailed_diff ON (tstatusfailed_diff.buildid=b.id AND tstatusfailed_diff.type=3)\n                  LEFT JOIN subproject2build AS sp2b ON (sp2b.buildid = b.id)\n                  LEFT JOIN subproject as sp ON (sp2b.subprojectid = sp.id)\n                  LEFT JOIN label2build AS l2b ON (l2b.buildid = b.id)\n                  LEFT JOIN label AS l ON (l.id = l2b.labelid)\n                  WHERE b.projectid='{$projectid}' AND g.type='Daily'\n                  {$parent_clause} {$date_clause}\n                  " . $subprojectsql . " " . $filter_sql . " " . $groupby_sql . $limit_sql;
    // We shouldn't get any builds for group that have been deleted (otherwise something is wrong)
    $builds = pdo_query($sql);
    echo pdo_error();
    // Sort results from this query.
    // We used to do this in MySQL with the following directive:
    // ORDER BY gp.position ASC,b.name ASC,b.siteid ASC,b.stamp DESC
    // But this dramatically impacted performance when the number of rows was
    // relatively large (in the thousands).  So now we accomplish the same
    // sorting within PHP instead.
    $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);
        $build_data = array_merge($build_data, $dynamic_builds);
    }
    $positions = array();
    $names = array();
    $siteids = array();
    $stamps = array();
    foreach ($build_data as $key => $row) {
        $positions[$key] = $row['position'];
        $names[$key] = $row['name'];
        $siteids[$key] = $row['siteid'];
        $stamps[$key] = $row['stamp'];
    }
    array_multisort($positions, SORT_ASC, $names, SORT_ASC, $siteids, SORT_ASC, $stamps, SORT_DESC, $build_data);
    // The SQL results are ordered by group so this should work
    // Group position have to be continuous
    $previousgroupposition = -1;
    $received_builds = array();
    // Find the last position of the group
    $groupposition_array = pdo_fetch_array(pdo_query("SELECT gp.position FROM buildgroupposition AS gp,buildgroup AS g\n                                                        WHERE g.projectid='{$projectid}' AND g.id=gp.buildgroupid\n                                                        AND gp.starttime<'{$end_UTCDate}' AND (gp.endtime>'{$end_UTCDate}' OR gp.endtime='1980-01-01 00:00:00')\n                                                        ORDER BY gp.position DESC LIMIT 1"));
    $lastGroupPosition = $groupposition_array["position"];
    // 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.
    $subproject_groups = array();
    $subproject_group_coverage = array();
    if (isset($_GET["parentid"]) && $_GET["parentid"] > 0 && $project_instance->GetNumberOfSubProjects($end_UTCDate) > 0) {
        $groups = $project_instance->GetSubProjectGroups();
        foreach ($groups as $group) {
            // Create an Id -> Object mapping for our subproject groups.
            $subproject_groups[$group->GetId()] = $group;
            // Also keep track of coverage info on a per-group basis.
            $subproject_group_coverage[$group->GetId()] = array();
            $subproject_group_coverage[$group->GetId()]["tested"] = 0;
            $subproject_group_coverage[$group->GetId()]["untested"] = 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
        //  configurestatus
        //  countconfigureerrors
        //  countconfigurewarnings
        //  countconfigurewarningdiff
        //  counttestsnotrun
        //  counttestsnotrundiff
        //  counttestsfailed
        //  counttestsfaileddiff
        //  counttestspassed
        //  counttestspasseddiff
        //  countteststimestatusfailed
        //  countteststimestatusfaileddiff
        //  testsduration
        //
        // Fields that we add within this loop:
        //  maxstarttime
        //  buildids (array of buildids for summary rows)
        //  countbuildnotes (added by users)
        //  labels
        //  updateduration
        //  countupdateerrors
        //  buildduration
        //  hasconfigurestatus
        //  configureduration
        //  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'];
        // Split out labels
        if (empty($build_row['labels'])) {
            $build_row['labels'] = array();
        } else {
            $build_row['labels'] = explode(",", $build_row['labels']);
        }
        // If this is a parent build get the labels from all the children too.
        if ($parentid == -1) {
            $query = "SELECT l.text FROM build AS b\n        INNER JOIN label2build AS l2b ON l2b.buildid = b.id\n        INNER JOIN label AS l ON l.id = l2b.labelid\n        WHERE b.parentid='{$buildid}'";
            $childLabelsResult = pdo_query($query);
            while ($childLabelsArray = pdo_fetch_array($childLabelsResult)) {
                $build_row['labels'][] = $childLabelsArray['text'];
            }
        }
        // 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;
        }
        $build_row['buildduration'] = round((strtotime($build_row['endtime']) - strtotime($build_row['starttime'])) / 60, 1);
        // 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;
        }
        if ($build_row['countconfigureerrors'] < 0) {
            $build_row['countconfigureerrors'] = 0;
        }
        if ($build_row['countconfigurewarnings'] < 0) {
            $build_row['countconfigurewarnings'] = 0;
        }
        $build_row['hasconfigurestatus'] = 0;
        $build_row['configureduration'] = 0;
        if (strlen($build_row['configurestatus']) > 0) {
            $build_row['hasconfigurestatus'] = 1;
            $build_row['configureduration'] = round((strtotime($build_row["configureendtime"]) - strtotime($build_row["configurestarttime"])) / 60, 1);
        }
        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['testsduration'])) {
            $time_array = pdo_fetch_array(pdo_query("SELECT SUM(time) FROM build2test WHERE buildid='{$buildid}'"));
            $build_row['testsduration'] = round($time_array[0] / 60, 1);
        } else {
            $build_row['testsduration'] = round($build_row['testsduration'], 1);
            //already in minutes
        }
        $build_rows[] = $build_row;
    }
    // Generate the xml from the rows of builds:
    //
    $totalUpdatedFiles = 0;
    $totalUpdateError = 0;
    $totalUpdateWarning = 0;
    $totalUpdateDuration = 0;
    $totalConfigureError = 0;
    $totalConfigureWarning = 0;
    $totalConfigureDuration = 0;
    $totalerrors = 0;
    $totalwarnings = 0;
    $totalBuildDuration = 0;
    $totalnotrun = 0;
    $totalfail = 0;
    $totalpass = 0;
    $totalTestsDuration = 0;
    foreach ($build_rows as $build_array) {
        $groupposition = $build_array["position"];
        if ($previousgroupposition != $groupposition) {
            $groupname = $build_array["groupname"];
            if ($previousgroupposition != -1) {
                if (!$filter_sql) {
                    $xml .= add_expected_builds($groupid, $currentstarttime, $received_builds);
                }
                $xml .= add_XML_value("totalUpdatedFiles", $totalUpdatedFiles);
                $xml .= add_XML_value("totalUpdateError", $totalUpdateError);
                $xml .= add_XML_value("totalUpdateWarning", $totalUpdateWarning);
                $xml .= add_XML_value("totalUpdateDuration", $totalUpdateDuration);
                $xml .= add_XML_value("totalConfigureDuration", $totalConfigureDuration);
                $xml .= add_XML_value("totalConfigureError", $totalConfigureError);
                $xml .= add_XML_value("totalConfigureWarning", $totalConfigureWarning);
                $xml .= add_XML_value("totalError", $totalerrors);
                $xml .= add_XML_value("totalWarning", $totalwarnings);
                $xml .= add_XML_value("totalBuildDuration", $totalBuildDuration);
                $xml .= add_XML_value("totalNotRun", $totalnotrun);
                $xml .= add_XML_value("totalFail", $totalfail);
                $xml .= add_XML_value("totalPass", $totalpass);
                $xml .= add_XML_value("totalTestsDuration", time_difference($totalTestsDuration * 60.0, true));
                $xml .= "</buildgroup>";
            }
            // We assume that the group position are continuous in N
            // So we fill in the gap if we are jumping
            $prevpos = $previousgroupposition + 1;
            if ($prevpos == 0) {
                $prevpos = 1;
            }
            for ($i = $prevpos; $i < $groupposition; $i++) {
                $group = pdo_fetch_array(pdo_query("SELECT g.name,g.id FROM buildgroup AS g,buildgroupposition AS gp WHERE g.id=gp.buildgroupid\n                                                AND gp.position='{$i}' AND g.projectid='{$projectid}'\n                                                AND gp.starttime<'{$end_UTCDate}' AND (gp.endtime>'{$end_UTCDate}'  OR gp.endtime='1980-01-01 00:00:00')\n                                                "));
                $xml .= "<buildgroup>";
                $xml .= add_buildgroup_sortlist($group['name']);
                $xml .= add_XML_value("name", $group["name"]);
                $xml .= add_XML_value("linkname", str_replace(" ", "_", $group["name"]));
                $xml .= add_XML_value("id", $group["id"]);
                if (!$filter_sql) {
                    $xml .= add_expected_builds($group["id"], $currentstarttime, $received_builds);
                }
                $xml .= "</buildgroup>";
            }
            $xml .= "<buildgroup>";
            $totalUpdatedFiles = 0;
            $totalUpdateError = 0;
            $totalUpdateWarning = 0;
            $totalUpdateDuration = 0;
            $totalConfigureError = 0;
            $totalConfigureWarning = 0;
            $totalConfigureDuration = 0;
            $totalerrors = 0;
            $totalwarnings = 0;
            $totalBuildDuration = 0;
            $totalnotrun = 0;
            $totalfail = 0;
            $totalpass = 0;
            $totalTestsDuration = 0;
            $xml .= add_buildgroup_sortlist($groupname);
            $xml .= add_XML_value("name", $groupname);
            $xml .= add_XML_value("linkname", str_replace(" ", "_", $groupname));
            $xml .= add_XML_value("id", $build_array["groupid"]);
            $received_builds = array();
            $previousgroupposition = $groupposition;
        }
        $xml .= "<build>";
        $received_builds[] = $build_array["sitename"] . "_" . $build_array["name"];
        $buildid = $build_array["id"];
        $groupid = $build_array["groupid"];
        $siteid = $build_array["siteid"];
        $countChildrenResult = pdo_single_row_query("SELECT count(id) AS nchildren FROM build WHERE parentid=" . qnum($buildid));
        $countchildren = $countChildrenResult['nchildren'];
        $xml .= add_XML_value("countchildren", $countchildren);
        $child_builds_hyperlink = "";
        if ($countchildren > 0) {
            $child_builds_hyperlink = get_child_builds_hyperlink($build_array["id"], $filterdata);
            $xml .= add_XML_value("multiplebuildshyperlink", $child_builds_hyperlink);
        }
        $xml .= add_XML_value("type", strtolower($build_array["type"]));
        // Attempt to determine the platform based on the OSName and the buildname
        $buildplatform = '';
        if (strtolower(substr($build_array["osname"], 0, 7)) == 'windows') {
            $buildplatform = 'windows';
        } else {
            if (strtolower(substr($build_array["osname"], 0, 8)) == 'mac os x') {
                $buildplatform = 'mac';
            } else {
                if (strtolower(substr($build_array["osname"], 0, 5)) == 'linux' || strtolower(substr($build_array["osname"], 0, 3)) == 'aix') {
                    $buildplatform = 'linux';
                } else {
                    if (strtolower(substr($build_array["osname"], 0, 7)) == 'freebsd') {
                        $buildplatform = 'freebsd';
                    } else {
                        if (strtolower(substr($build_array["osname"], 0, 3)) == 'gnu') {
                            $buildplatform = 'gnu';
                        }
                    }
                }
            }
        }
        if (isset($_GET["parentid"]) && empty($sitexml)) {
            $sitexml .= add_XML_value("site", $build_array["sitename"]);
            $sitexml .= add_XML_value("siteoutoforder", $build_array["siteoutoforder"]);
            $sitexml .= add_XML_value("siteid", $siteid);
            $sitexml .= add_XML_value("buildname", $build_array["name"]);
            $sitexml .= add_XML_value("buildplatform", $buildplatform);
        } else {
            $xml .= add_XML_value("site", $build_array["sitename"]);
            $xml .= add_XML_value("siteoutoforder", $build_array["siteoutoforder"]);
            $xml .= add_XML_value("siteid", $siteid);
            $xml .= add_XML_value("buildname", $build_array["name"]);
            $xml .= add_XML_value("buildplatform", $buildplatform);
        }
        if (isset($build_array["userupdates"])) {
            $xml .= add_XML_value("userupdates", $build_array["userupdates"]);
        }
        $xml .= add_XML_value("buildid", $build_array["id"]);
        $xml .= add_XML_value("generator", $build_array["generator"]);
        $xml .= add_XML_value("upload-file-count", $build_array["builduploadfiles"]);
        if ($build_array['countbuildnotes'] > 0) {
            $xml .= add_XML_value("buildnote", "1");
        }
        if ($build_array['countnotes'] > 0) {
            $xml .= add_XML_value("note", "1");
        }
        // Are there labels for this build?
        //
        $labels_array = $build_array['labels'];
        if (!empty($labels_array)) {
            $xml .= '<labels>';
            foreach ($labels_array as $label) {
                $xml .= add_XML_value("label", $label);
            }
            $xml .= '</labels>';
        }
        $xml .= "<update>";
        $countupdatefiles = $build_array['countupdatefiles'];
        $totalUpdatedFiles += $countupdatefiles;
        $xml .= add_XML_value("files", $countupdatefiles);
        if (!empty($build_array['updatestarttime'])) {
            $xml .= add_XML_value("defined", 1);
            if ($build_array['countupdateerrors'] > 0) {
                $xml .= add_XML_value("errors", 1);
                $totalUpdateError += 1;
            } else {
                $xml .= add_XML_value("errors", 0);
                if ($build_array['countupdatewarnings'] > 0) {
                    $xml .= add_XML_value("warning", 1);
                    $totalUpdateWarning += 1;
                }
            }
            $duration = $build_array['updateduration'];
            $totalUpdateDuration += $duration;
            $xml .= add_XML_value("time", time_difference($duration * 60.0, true));
            $xml .= add_XML_value("timefull", $duration);
        }
        // end if we have an update
        $xml .= "</update>";
        $xml .= "<compilation>";
        if ($build_array['countbuilderrors'] >= 0) {
            $nerrors = $build_array['countbuilderrors'];
            $totalerrors += $nerrors;
            $xml .= add_XML_value("error", $nerrors);
            $nwarnings = $build_array['countbuildwarnings'];
            $totalwarnings += $nwarnings;
            $xml .= add_XML_value("warning", $nwarnings);
            $duration = $build_array['buildduration'];
            $totalBuildDuration += $duration;
            $xml .= add_XML_value("time", time_difference($duration * 60.0, true));
            $xml .= add_XML_value("timefull", $duration);
            $diff = $build_array['countbuilderrordiffp'];
            if ($diff != 0) {
                $xml .= add_XML_value("nerrordiffp", $diff);
            }
            $diff = $build_array['countbuilderrordiffn'];
            if ($diff != 0) {
                $xml .= add_XML_value("nerrordiffn", $diff);
            }
            $diff = $build_array['countbuildwarningdiffp'];
            if ($diff != 0) {
                $xml .= add_XML_value("nwarningdiffp", $diff);
            }
            $diff = $build_array['countbuildwarningdiffn'];
            if ($diff != 0) {
                $xml .= add_XML_value("nwarningdiffn", $diff);
            }
        }
        $xml .= "</compilation>";
        $xml .= "<configure>";
        $xml .= add_XML_value("error", $build_array['countconfigureerrors']);
        $totalConfigureError += $build_array['countconfigureerrors'];
        $nconfigurewarnings = $build_array['countconfigurewarnings'];
        $xml .= add_XML_value("warning", $nconfigurewarnings);
        $totalConfigureWarning += $nconfigurewarnings;
        $diff = $build_array['countconfigurewarningdiff'];
        if ($diff != 0) {
            $xml .= add_XML_value("warningdiff", $diff);
        }
        if ($build_array['hasconfigurestatus'] != 0) {
            $duration = $build_array['configureduration'];
            $totalConfigureDuration += $duration;
            $xml .= add_XML_value("time", time_difference($duration * 60.0, true));
            $xml .= add_XML_value("timefull", $duration);
        }
        $xml .= "</configure>";
        if ($build_array['hastest'] != 0) {
            $xml .= "<test>";
            $nnotrun = $build_array['counttestsnotrun'];
            if ($build_array['counttestsnotrundiffp'] != 0) {
                $xml .= add_XML_value("nnotrundiffp", $build_array['counttestsnotrundiffp']);
            }
            if ($build_array['counttestsnotrundiffn'] != 0) {
                $xml .= add_XML_value("nnotrundiffn", $build_array['counttestsnotrundiffn']);
            }
            $nfail = $build_array['counttestsfailed'];
            if ($build_array['counttestsfaileddiffp'] != 0) {
                $xml .= add_XML_value("nfaildiffp", $build_array['counttestsfaileddiffp']);
            }
            if ($build_array['counttestsfaileddiffn'] != 0) {
                $xml .= add_XML_value("nfaildiffn", $build_array['counttestsfaileddiffn']);
            }
            $npass = $build_array['counttestspassed'];
            if ($build_array['counttestspasseddiffp'] != 0) {
                $xml .= add_XML_value("npassdiffp", $build_array['counttestspasseddiffp']);
            }
            if ($build_array['counttestspasseddiffn'] != 0) {
                $xml .= add_XML_value("npassdiffn", $build_array['counttestspasseddiffn']);
            }
            if ($project_array["showtesttime"] == 1) {
                $xml .= add_XML_value("timestatus", $build_array['countteststimestatusfailed']);
                if ($build_array['countteststimestatusfaileddiffp'] != 0) {
                    $xml .= add_XML_value("ntimediffp", $build_array['countteststimestatusfaileddiffp']);
                }
                if ($build_array['countteststimestatusfaileddiffn'] != 0) {
                    $xml .= add_XML_value("ntimediffn", $build_array['countteststimestatusfaileddiffn']);
                }
            }
            $totalnotrun += $nnotrun;
            $totalfail += $nfail;
            $totalpass += $npass;
            $xml .= add_XML_value("notrun", $nnotrun);
            $xml .= add_XML_value("fail", $nfail);
            $xml .= add_XML_value("pass", $npass);
            $duration = $build_array['testsduration'];
            $totalTestsDuration += $duration;
            $xml .= add_XML_value("time", time_difference($duration * 60.0, true));
            $xml .= add_XML_value("timefull", $duration);
            $xml .= "</test>";
        }
        $starttimestamp = strtotime($build_array["starttime"] . " UTC");
        $submittimestamp = strtotime($build_array["submittime"] . " UTC");
        $xml .= add_XML_value("builddatefull", $starttimestamp);
        // use the default timezone
        // If the data is more than 24h old then we switch from an elapsed to a normal representation
        if (time() - $starttimestamp < 86400) {
            $xml .= add_XML_value("builddate", date(FMT_DATETIMEDISPLAY, $starttimestamp));
            // use the default timezone
            $xml .= add_XML_value("builddateelapsed", time_difference(time() - $starttimestamp, false, 'ago'));
            // use the default timezone
        } else {
            $xml .= add_XML_value("builddateelapsed", date(FMT_DATETIMEDISPLAY, $starttimestamp));
            // use the default timezone
            $xml .= add_XML_value("builddate", time_difference(time() - $starttimestamp, false, 'ago'));
            // use the default timezone
        }
        $xml .= add_XML_value("submitdate", date(FMT_DATETIMEDISPLAY, $submittimestamp));
        // use the default timezone
        $xml .= add_XML_value("nerrorlog", $build_array["nerrorlog"]);
        // use the default timezone
        $xml .= "</build>";
        // Coverage
        //
        // Determine if this is a parent build with no actual coverage of its own.
        $linkToChildCoverage = false;
        if ($countchildren > 0) {
            $countChildrenResult = pdo_single_row_query("SELECT count(fileid) AS nfiles FROM coverage\n         WHERE buildid=" . qnum($buildid));
            if ($countChildrenResult['nfiles'] == 0) {
                $linkToChildCoverage = true;
            }
        }
        $coverages = pdo_query("SELECT * FROM coveragesummary WHERE buildid='{$buildid}'");
        while ($coverage_array = pdo_fetch_array($coverages)) {
            $xml .= "<coverage>";
            $xml .= "  <site>" . $build_array["sitename"] . "</site>";
            $xml .= "  <buildname>" . $build_array["name"] . "</buildname>";
            $xml .= "  <buildid>" . $build_array["id"] . "</buildid>";
            if ($linkToChildCoverage) {
                $xml .= add_XML_value("childlink", "{$child_builds_hyperlink}#Coverage");
            }
            @($percent = round($coverage_array["loctested"] / ($coverage_array["loctested"] + $coverage_array["locuntested"]) * 100, 2));
            $coverageThreshold = $project_array["coveragethreshold"];
            if ($build_array["subprojectgroup"]) {
                $groupId = $build_array["subprojectgroup"];
                $coverageThreshold = $subproject_groups[$groupId]->GetCoverageThreshold();
                $subproject_group_coverage[$groupId]["tested"] += $coverage_array["loctested"];
                $subproject_group_coverage[$groupId]["untested"] += $coverage_array["locuntested"];
                $xml .= "  <group>{$groupId}</group>";
            }
            $xml .= "  <percentage>" . $percent . "</percentage>";
            $xml .= "  <percentagegreen>" . $coverageThreshold . "</percentagegreen>";
            $xml .= "  <fail>" . $coverage_array["locuntested"] . "</fail>";
            $xml .= "  <pass>" . $coverage_array["loctested"] . "</pass>";
            // Compute the diff
            $coveragediff = pdo_query("SELECT * FROM coveragesummarydiff WHERE buildid='{$buildid}'");
            if (pdo_num_rows($coveragediff) > 0) {
                $coveragediff_array = pdo_fetch_array($coveragediff);
                $loctesteddiff = $coveragediff_array['loctested'];
                $locuntesteddiff = $coveragediff_array['locuntested'];
                @($previouspercent = round(($coverage_array["loctested"] - $loctesteddiff) / ($coverage_array["loctested"] - $loctesteddiff + $coverage_array["locuntested"] - $locuntesteddiff) * 100, 2));
                $percentdiff = round($percent - $previouspercent, 2);
                $xml .= "<percentagediff>" . $percentdiff . "</percentagediff>";
                $xml .= "<faildiff>" . $locuntesteddiff . "</faildiff>";
                $xml .= "<passdiff>" . $loctesteddiff . "</passdiff>";
            }
            $starttimestamp = strtotime($build_array["starttime"] . " UTC");
            $xml .= add_XML_value("datefull", $starttimestamp);
            // use the default timezone
            // If the data is more than 24h old then we switch from an elapsed to a normal representation
            if (time() - $starttimestamp < 86400) {
                $xml .= add_XML_value("date", date(FMT_DATETIMEDISPLAY, $starttimestamp));
                // use the default timezone
                $xml .= add_XML_value("dateelapsed", time_difference(time() - $starttimestamp, false, 'ago'));
                // use the default timezone
            } else {
                $xml .= add_XML_value("dateelapsed", date(FMT_DATETIMEDISPLAY, $starttimestamp));
                // use the default timezone
                $xml .= add_XML_value("date", time_difference(time() - $starttimestamp, false, 'ago'));
                // use the default timezone
            }
            // Are there labels for this build?
            //
            if (!empty($labels_array)) {
                $xml .= '<labels>';
                foreach ($labels_array as $label) {
                    $xml .= add_XML_value("label", $label);
                }
                $xml .= '</labels>';
            }
            $xml .= "</coverage>";
        }
        // end coverage
        // Dynamic Analysis
        //
        $dynanalysis = pdo_query("SELECT checker,status FROM dynamicanalysis WHERE buildid='{$buildid}' LIMIT 1");
        while ($dynanalysis_array = pdo_fetch_array($dynanalysis)) {
            $xml .= "<dynamicanalysis>";
            $xml .= "  <site>" . $build_array["sitename"] . "</site>";
            $xml .= "  <buildname>" . $build_array["name"] . "</buildname>";
            $xml .= "  <buildid>" . $build_array["id"] . "</buildid>";
            $xml .= "  <checker>" . $dynanalysis_array["checker"] . "</checker>";
            $xml .= "  <status>" . $dynanalysis_array["status"] . "</status>";
            $defect = pdo_query("SELECT sum(dd.value) FROM dynamicanalysisdefect AS dd,dynamicanalysis as d\n                                              WHERE d.buildid='{$buildid}' AND dd.dynamicanalysisid=d.id");
            $defectcount = pdo_fetch_array($defect);
            if (!isset($defectcount[0])) {
                $defectcounts = 0;
            } else {
                $defectcounts = $defectcount[0];
            }
            $xml .= "  <defectcount>" . $defectcounts . "</defectcount>";
            $starttimestamp = strtotime($build_array["starttime"] . " UTC");
            $xml .= add_XML_value("datefull", $starttimestamp);
            // use the default timezone
            // If the data is more than 24h old then we switch from an elapsed to a normal representation
            if (time() - $starttimestamp < 86400) {
                $xml .= add_XML_value("date", date(FMT_DATETIMEDISPLAY, $starttimestamp));
                // use the default timezone
                $xml .= add_XML_value("dateelapsed", time_difference(time() - $starttimestamp, false, 'ago'));
                // use the default timezone
            } else {
                $xml .= add_XML_value("dateelapsed", date(FMT_DATETIMEDISPLAY, $starttimestamp));
                // use the default timezone
                $xml .= add_XML_value("date", time_difference(time() - $starttimestamp, false, 'ago'));
                // use the default timezone
            }
            // Are there labels for this build?
            //
            if (!empty($labels_array)) {
                $xml .= '<labels>';
                foreach ($labels_array as $label) {
                    $xml .= add_XML_value("label", $label);
                }
                $xml .= '</labels>';
            }
            $xml .= "</dynamicanalysis>";
        }
        // end dynamicanalysis
    }
    // end looping through builds
    if (pdo_num_rows($builds) + count($dynamic_builds) > 0) {
        if (!$filter_sql) {
            $xml .= add_expected_builds($groupid, $currentstarttime, $received_builds);
        }
        $xml .= add_XML_value("totalUpdatedFiles", $totalUpdatedFiles);
        $xml .= add_XML_value("totalUpdateError", $totalUpdateError);
        $xml .= add_XML_value("totalUpdateWarning", $totalUpdateWarning);
        $xml .= add_XML_value("totalUpdateDuration", $totalUpdateDuration);
        $xml .= add_XML_value("totalConfigureDuration", $totalConfigureDuration);
        $xml .= add_XML_value("totalConfigureError", $totalConfigureError);
        $xml .= add_XML_value("totalConfigureWarning", $totalConfigureWarning);
        $xml .= add_XML_value("totalError", $totalerrors);
        $xml .= add_XML_value("totalWarning", $totalwarnings);
        $xml .= add_XML_value("totalBuildDuration", $totalBuildDuration);
        $xml .= add_XML_value("totalNotRun", $totalnotrun);
        $xml .= add_XML_value("totalFail", $totalfail);
        $xml .= add_XML_value("totalPass", $totalpass);
        $xml .= add_XML_value("totalTestsDuration", time_difference($totalTestsDuration * 60.0, true));
        $xml .= "</buildgroup>";
    }
    // generate subproject coverage by group here.
    if (!empty($subproject_groups)) {
        foreach ($subproject_groups as $groupid => $group) {
            $group_cov = $subproject_group_coverage[$groupid];
            $tested = $group_cov['tested'];
            $untested = $group_cov['untested'];
            if ($tested == 0 && $untested == 0) {
                continue;
            }
            $coverage = round($tested / ($tested + $untested) * 100, 2);
            $xml .= "<subprojectgroup>";
            $xml .= add_XML_value("name", $group->GetName());
            $xml .= add_XML_value("id", $group->GetId());
            $xml .= add_XML_value("threshold", $group->GetCoverageThreshold());
            $xml .= add_XML_value("coverage", $coverage);
            $xml .= add_XML_value("tested", $tested);
            $xml .= add_XML_value("untested", $untested);
            $xml .= "</subprojectgroup>";
        }
    }
    // Fill in the rest of the info
    $prevpos = $previousgroupposition + 1;
    if ($prevpos == 0) {
        $prevpos = 1;
    }
    for ($i = $prevpos; $i <= $lastGroupPosition; $i++) {
        $group = pdo_fetch_array(pdo_query("SELECT g.name,g.id FROM buildgroup AS g,buildgroupposition AS gp WHERE g.id=gp.buildgroupid\n                                                                                     AND gp.position='{$i}' AND g.projectid='{$projectid}'\n                                                                                     AND gp.starttime<'{$end_UTCDate}' AND (gp.endtime>'{$end_UTCDate}'  OR gp.endtime='1980-01-01 00:00:00')"));
        $xml .= "<buildgroup>";
        $xml .= add_buildgroup_sortlist($group['name']);
        $xml .= add_XML_value("id", $group["id"]);
        $xml .= add_XML_value("name", $group["name"]);
        $xml .= add_XML_value("linkname", str_replace(" ", "_", $group["name"]));
        if (!$filter_sql) {
            $xml .= add_expected_builds($group["id"], $currentstarttime, $received_builds);
        }
        $xml .= "</buildgroup>";
    }
    $xml .= add_XML_value("enableTestTiming", $project_array["showtesttime"]);
    $end = microtime_float();
    $xml .= "<generationtime>" . round($end - $start, 3) . "</generationtime>";
    if (!empty($sitexml)) {
        $xml .= $sitexml;
    }
    $xml .= "</cdash>";
    return $xml;
}
Example #13
0
 function register_user($projectid, $email, $firstName, $lastName, $repositoryCredential)
 {
     include dirname(__DIR__) . '/config/config.php';
     $UserProject = new UserProject();
     $UserProject->ProjectId = $projectid;
     // Check if the user is already registered
     $user = pdo_query('SELECT id FROM ' . qid('user') . " WHERE email='{$email}'");
     if (pdo_num_rows($user) > 0) {
         // Check if the user has been registered to the project
         $user_array2 = pdo_fetch_array($user);
         $userid = $user_array2['id'];
         $user = pdo_query("SELECT userid FROM user2project WHERE userid='{$userid}' AND projectid='{$projectid}'");
         if (pdo_num_rows($user) == 0) {
             // not registered
             // We register the user to the project
             pdo_query("INSERT INTO user2project (userid,projectid,role,emailtype)\n                                  VALUES ('{$userid}','{$projectid}','0','1')");
             // We add the credentials if not already added
             $UserProject->UserId = $userid;
             $UserProject->AddCredential($repositoryCredential);
             $UserProject->ProjectId = 0;
             $UserProject->AddCredential($email);
             // Add the email by default
             echo pdo_error();
             return false;
         }
         return '<error>User ' . $email . ' already registered.</error>';
     }
     // already registered
     // Check if the repositoryCredential exists for this project
     $UserProject->RepositoryCredential = $repositoryCredential;
     if ($UserProject->FillFromRepositoryCredential() === true) {
         return '<error>' . $repositoryCredential . ' was already registered for this project under a different email address</error>';
     }
     // Register the user
     // Create a new password
     $keychars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
     $length = 10;
     $pass = '';
     $max = strlen($keychars) - 1;
     for ($i = 0; $i <= $length; $i++) {
         // random_int is available in PHP 7 and the random_compat PHP 5.x
         // polyfill included in the Composer package.json dependencies.
         $pass .= substr($keychars, random_int(0, $max), 1);
     }
     $encrypted = md5($pass);
     pdo_query('INSERT INTO ' . qid('user') . " (email,password,firstname,lastname,institution,admin)\n                 VALUES ('{$email}','{$encrypted}','{$firstName}','{$lastName}','','0')");
     add_last_sql_error('register_user');
     $userid = pdo_insert_id('user');
     // Insert the user into the project
     pdo_query("INSERT INTO user2project (userid,projectid,role,emailtype)\n                                VALUES ('{$userid}','{$projectid}','0','1')");
     add_last_sql_error('register_user');
     // We add the credentials if not already added
     $UserProject->UserId = $userid;
     $UserProject->AddCredential($repositoryCredential);
     $UserProject->ProjectId = 0;
     $UserProject->AddCredential($email);
     // Add the email by default
     $currentURI = get_server_URI();
     $prefix = '';
     if (strlen($firstName) > 0) {
         $prefix = ' ';
     }
     $project = pdo_query("SELECT name FROM project WHERE id='{$projectid}'");
     $project_array = pdo_fetch_array($project);
     $projectname = $project_array['name'];
     // Send the email
     $text = 'Hello' . $prefix . $firstName . ",\n\n";
     $text .= 'You have been registered to CDash because you have CVS/SVN access to the repository for ' . $projectname . "\n";
     $text .= 'To access your CDash account: ' . $currentURI . "/user.php\n";
     $text .= 'Your login is: ' . $email . "\n";
     $text .= 'Your password is: ' . $pass . "\n\n";
     $text .= 'Generated by CDash.';
     if (cdashmail("{$email}", 'CDash - ' . $projectname . ' : Subscription', "{$text}")) {
         echo 'Email sent to: ' . $email . '<br>';
     } else {
         add_log("cannot send email to: {$email}", 'register_user', LOG_ERR);
     }
     return true;
 }
Example #14
0
File: pdo.php Project: rpshaw/CDash
function pdo_query_and_log_if_failed($qry, $caller)
{
    $result = pdo_query($qry);
    if (FALSE === $result) {
        add_log('error: pdo_query failed: ' . pdo_error(), $caller, LOG_ERR);
        // Also log a bit of the query so we can tell where it came from:
        if (strlen($qry) > 100) {
            $log_qry = substr($qry, 0, 100) . '...';
        } else {
            $log_qry = $qry;
        }
        add_log('query: ' . $log_qry, $caller, LOG_INFO);
        return FALSE;
    }
    return TRUE;
}
Example #15
0
 public function fillDb($sqlfile)
 {
     if (!$this->dbconnect) {
         $this->connect();
     }
     $file_content = file($sqlfile);
     //print_r($file_content);
     $query = '';
     $line_number = 0;
     foreach ($file_content as $sql_line) {
         $tsl = trim($sql_line);
         if ($sql_line != '' && substr($tsl, 0, 2) != '--' && substr($tsl, 0, 1) != '#') {
             $query .= $sql_line;
             if (preg_match("/;\\s*\$/", $sql_line)) {
                 $query = str_replace(';', '', "{$query}");
                 $result = pdo_query($query);
                 if (!$result) {
                     echo 'Error line:' . $line_number . '<br/>';
                     return pdo_error();
                 }
                 $query = '';
             }
         }
         $line_number++;
     }
     $pwd = md5('simpletest');
     $query = 'INSERT INTO "user" (email, password, firstname, lastname, institution, admin) ';
     $query .= "VALUES ('simpletest@localhost', '{$pwd}', 'administrator', '','Kitware Inc.', 1)";
     pdo_query($query);
     echo pdo_error();
     // Create the language. PgSQL has no way to know if the language already
     // exists
     @pdo_query('CREATE LANGUAGE plpgsql');
     $sqlfile = str_replace('.sql', '.ext.sql', $sqlfile);
     // If we are with PostGreSQL we need to add some extra functions
     $file_content = file($sqlfile);
     $query = '';
     foreach ($file_content as $sql_line) {
         $tsl = trim($sql_line);
         if ($sql_line != '' && substr($tsl, 0, 2) != '--') {
             $query .= $sql_line;
             if (strpos('CREATE ', $sql_line) !== false) {
                 // We need to remove only the last semicolon
                 $pos = strrpos($query, ';');
                 if ($pos !== false) {
                     $query = substr($query, 0, $pos) . substr($query, $pos + 1);
                 }
                 $result = pdo_query($query);
                 if (!$result) {
                     $xml = '<db_created>0</db_created>';
                     die(pdo_error());
                 }
                 $query = '';
             }
         }
     }
     // Run the last query
     $pos = strrpos($query, ';');
     if ($pos !== false) {
         $query = substr($query, 0, $pos) . substr($query, $pos + 1);
     }
     $result = pdo_query($query);
     if (!$result) {
         $xml = '<db_created>0</db_created>';
         die(pdo_error());
     }
     $this->disconnect();
     return true;
 }
Example #16
0
// $className = $_GET['classname'];
//the length we want the unique reference number to be
$unique_ref_length = 6;
//A true/false variable that lets us know if we've found a unique reference number or not
$unique_ref_found = false;
//possible characters we can include in our ID
$possible_chars = " 23456789BCDEFGHJKMNPQRSTVQXYZ";
//keep generating new IDs until we find a unique one
while (!$unique_ref_found) {
    //start with blank ref number
    $unique_ref = "";
    //set up a counter to keep track of how many characters have been added
    $i = 0;
    //add random chars from $possible_chars to $unique_ref have currently been added
    while ($i < $unique_ref_length) {
        $char = substr($possible_chars, mt_rand(0, strlen($possible_chars) - 1), 1);
        $unique_ref .= $char;
        $i++;
    }
    $query = "SELECT `classID` FROM `enqueue` WHERE `classID` = ' " . $unique_ref . "'";
    $result = pdo_query($query) or die(pdo_error() . ' ' . $query);
    if (pdo_num_rows($result) == 0) {
        $unique_ref_found = true;
    }
}
echo $unique_ref;
//'for class: ' $_POST[className];
?>
</body>
</html>
Example #17
0
/** Authentication function */
function register()
{
    global $reg;
    include "cdash/config.php";
    require_once "cdash/pdo.php";
    if (isset($_GET["key"])) {
        $key = pdo_real_escape_string($_GET["key"]);
        $sql = "SELECT * FROM " . qid("usertemp") . " WHERE registrationkey='{$key}'";
        $query = pdo_query($sql);
        if (pdo_num_rows($query) == 0) {
            $reg = "The key is invalid.";
            return 0;
        }
        $query_array = pdo_fetch_array($query);
        $email = $query_array['email'];
        $passwd = $query_array['password'];
        $fname = $query_array['firstname'];
        $lname = $query_array['lastname'];
        $institution = $query_array['institution'];
        // We copy the data from usertemp to user
        $sql = "INSERT INTO " . qid("user") . " (email,password,firstname,lastname,institution)\n          VALUES ('{$email}','{$passwd}','{$fname}','{$lname}','{$institution}')";
        if (pdo_query($sql)) {
            pdo_query("DELETE FROM usertemp WHERE email='" . $email . "'");
            return 1;
        } else {
            $reg = pdo_error();
            return 0;
        }
    } else {
        if (isset($_POST["sent"])) {
            $url = $_POST["url"];
            if ($url != "catchbot") {
                $reg = "Bots are not allowed to obtain CDash accounts!";
                return 0;
            }
            $email = $_POST["email"];
            $passwd = $_POST["passwd"];
            $passwd2 = $_POST["passwd2"];
            if (!($passwd == $passwd2)) {
                $reg = "Passwords do not match!";
                return 0;
            }
            $fname = $_POST["fname"];
            $lname = $_POST["lname"];
            $institution = $_POST["institution"];
            if ($email && $passwd && $passwd2 && $fname && $lname && $institution) {
                $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
                pdo_select_db("{$CDASH_DB_NAME}", $db);
                $passwd = md5($passwd);
                $email = pdo_real_escape_string($email);
                $sql = "SELECT email FROM " . qid("user") . " WHERE email='{$email}'";
                if (pdo_num_rows(pdo_query($sql)) > 0) {
                    $reg = "{$email} is already registered.";
                    return 0;
                }
                $sql = "SELECT email  FROM " . qid("usertemp") . " WHERE email='{$email}'";
                if (pdo_num_rows(pdo_query($sql)) > 0) {
                    $reg = "{$email} is already registered. Check your email if you haven't received the link to activate yet.";
                    return 0;
                }
                $passwd = pdo_real_escape_string($passwd);
                $fname = pdo_real_escape_string($fname);
                $lname = pdo_real_escape_string($lname);
                $institution = pdo_real_escape_string($institution);
                if ($CDASH_REGISTRATION_EMAIL_VERIFY) {
                    // Create a key
                    srand(microtime_float());
                    $keychars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                    $length = 40;
                    $key = "";
                    $max = strlen($keychars) - 1;
                    for ($i = 0; $i < $length; $i++) {
                        $key .= substr($keychars, rand(0, $max), 1);
                    }
                    $date = date(FMT_DATETIME);
                    $sql = "INSERT INTO " . qid("usertemp") . " (email,password,firstname,lastname,institution,registrationkey,registrationdate)\n              VALUES ('{$email}','{$passwd}','{$fname}','{$lname}','{$institution}','{$key}','{$date}')";
                } else {
                    $sql = "INSERT INTO " . qid("user") . " (email,password,firstname,lastname,institution)\n              VALUES ('{$email}','{$passwd}','{$fname}','{$lname}','{$institution}')";
                }
                if (pdo_query($sql)) {
                    if ($CDASH_REGISTRATION_EMAIL_VERIFY) {
                        $currentURI = get_server_URI();
                        // Send the email
                        $emailtitle = "Welcome to CDash!";
                        $emailbody = "Hello " . $fname . ",\n\n";
                        $emailbody .= "Welcome to CDash! In order to validate your registration please follow this link: \n";
                        $emailbody .= $currentURI . "/register.php?key=" . $key . "\n";
                        $serverName = $CDASH_SERVER_NAME;
                        if (strlen($serverName) == 0) {
                            $serverName = $_SERVER['SERVER_NAME'];
                        }
                        $emailbody .= "\n-CDash on " . $serverName . "\n";
                        if (cdashmail("{$email}", $emailtitle, $emailbody, "From: CDash <" . $CDASH_EMAIL_FROM . ">\nReply-To: " . $CDASH_EMAIL_REPLY . "\nContent-type: text/plain; charset=utf-8\nX-Mailer: PHP/" . phpversion() . "\nMIME-Version: 1.0")) {
                            add_log("email sent to: " . $email, "Registration");
                        } else {
                            add_log("cannot send email to: " . $email, "Registration", LOG_ERR);
                        }
                        $reg = "A confirmation email has been sent. Check your email (including your spam folder) to confirm your registration!\n";
                        $reg .= "You need to activate your account within 24 hours.";
                        return 0;
                    }
                    return 1;
                } else {
                    $reg = pdo_error();
                    return 0;
                }
            } else {
                $reg = "Please fill in all of the required fields";
                return 0;
            }
        }
    }
    // end register
    return 0;
}
Example #18
0
/** Delete unused rows */
function delete_unused_rows($table, $field, $targettable, $selectfield = 'id')
{
    pdo_query("DELETE FROM {$table} WHERE {$field} NOT IN (SELECT {$selectfield} AS {$field} FROM {$targettable})");
    echo pdo_error();
}
Example #19
0
 /** Return the number of defects per number of checkins */
 private function ListCheckinsDefects()
 {
     include_once 'cdash/common.php';
     if (!isset($this->Parameters['project'])) {
         echo "Project not set";
         return;
     }
     $projectid = get_project_id($this->Parameters['project']);
     if (!is_numeric($projectid) || $projectid <= 0) {
         echo "Project not found";
         return;
     }
     $builds = array();
     $query = pdo_query("SELECT nfiles, builderrors, buildwarnings, testnotrun, testfailed\n                FROM build,buildupdate,build2update WHERE build.projectid=" . $projectid . "\n                AND buildupdate.id=build2update.updateid\n                AND build2update.buildid=build.id\n                AND nfiles>0\n                AND build.starttime<NOW()\n                ORDER BY build.starttime DESC LIMIT 1000");
     // limit the request
     echo pdo_error();
     while ($query_array = pdo_fetch_array($query)) {
         $build['nfiles'] = $query_array['nfiles'];
         $build['builderrors'] = 0;
         if ($query_array['builderrors'] >= 0) {
             $build['builderrors'] = $query_array['builderrors'];
         }
         $build['buildwarnings'] = 0;
         if ($query_array['buildwarnings'] >= 0) {
             $build['buildwarnings'] = $query_array['buildwarnings'];
         }
         $build['testnotrun'] = 0;
         if ($query_array['testnotrun'] >= 0) {
             $build['testnotrun'] = $query_array['testnotrun'];
         }
         $build['testfailed'] = 0;
         if ($query_array['testfailed'] >= 0) {
             $build['testfailed'] = $query_array['testfailed'];
         }
         $builds[] = $build;
     }
     return $builds;
 }
Example #20
0
 public function Save()
 {
     // Assign it to the default group if necessary.
     if ($this->GroupId < 1) {
         $row = pdo_single_row_query('SELECT id from subprojectgroup
      WHERE projectid=' . qnum($this->ProjectId) . ' AND is_default=1');
         if (!empty($row)) {
             $this->GroupId = $row['id'];
         }
     }
     // Check if the subproject already exists.
     if ($this->Exists()) {
         // Trim the name
         $this->Name = trim($this->Name);
         // Update the subproject
         $query = 'UPDATE subproject SET ';
         $query .= "name='" . $this->Name . "'";
         $query .= ',projectid=' . qnum($this->ProjectId);
         $query .= ',groupid=' . qnum($this->GroupId);
         $query .= ",path='" . $this->Path . "'";
         $query .= ' WHERE id=' . qnum($this->Id) . '';
         if (!pdo_query($query)) {
             add_last_sql_error('SubProject Update');
             return false;
         }
     } else {
         // insert the subproject
         $id = '';
         $idvalue = '';
         if ($this->Id) {
             $id = 'id,';
             $idvalue = "'" . $this->Id . "',";
         }
         // Trim the name
         $this->Name = trim($this->Name);
         // Double check that it's not already in the database.
         $select_query = "SELECT id FROM subproject WHERE name='{$this->Name}' AND\n            projectid=" . qnum($this->ProjectId) . " AND\n            endtime='1980-01-01 00:00:00'";
         $result = pdo_query($select_query);
         if (!$result) {
             add_last_sql_error('SubProject Update');
             return false;
         }
         if (pdo_num_rows($result) > 0) {
             $row = pdo_fetch_array($result);
             $this->Id = $row['id'];
             return true;
         }
         $starttime = gmdate(FMT_DATETIME);
         $endtime = '1980-01-01 00:00:00';
         $insert_query = 'INSERT INTO subproject(' . $id . 'name,projectid,groupid,path,starttime,endtime)
             VALUES (' . $idvalue . "'{$this->Name}'," . qnum($this->ProjectId) . ',' . qnum($this->GroupId) . ",'{$this->Path}','{$starttime}','{$endtime}')";
         if (!pdo_query($insert_query)) {
             $error = pdo_error();
             // Check if the query failed due to a race condition during
             // parallel submission processing.
             $result = pdo_query($select_query);
             if (!$result || pdo_num_rows($result) == 0) {
                 add_log("SQL error: {$error}", 'SubProject Create', LOG_ERR, $this->ProjectId);
                 return false;
             }
             $row = pdo_fetch_array($result);
             $this->Id = $row['id'];
         }
         if ($this->Id < 1) {
             $this->Id = pdo_insert_id('subproject');
         }
     }
     return true;
 }
Example #21
0
 function register_user($projectid, $email, $firstName, $lastName, $repositoryCredential)
 {
     include "cdash/config.php";
     $UserProject = new UserProject();
     $UserProject->ProjectId = $projectid;
     // Check if the user is already registered
     $user = pdo_query("SELECT id FROM " . qid("user") . " WHERE email='{$email}'");
     if (pdo_num_rows($user) > 0) {
         // Check if the user has been registered to the project
         $user_array2 = pdo_fetch_array($user);
         $userid = $user_array2["id"];
         $user = pdo_query("SELECT userid FROM user2project WHERE userid='{$userid}' AND projectid='{$projectid}'");
         if (pdo_num_rows($user) == 0) {
             // We register the user to the project
             pdo_query("INSERT INTO user2project (userid,projectid,role,emailtype)\n                                  VALUES ('{$userid}','{$projectid}','0','1')");
             // We add the credentials if not already added
             $UserProject->UserId = $userid;
             $UserProject->AddCredential($repositoryCredential);
             $UserProject->ProjectId = 0;
             $UserProject->AddCredential($email);
             // Add the email by default
             echo pdo_error();
             return false;
         }
         return "<error>User " . $email . " already registered.</error>";
     }
     // already registered
     // Check if the repositoryCredential exists for this project
     $UserProject->RepositoryCredential = $repositoryCredential;
     if ($UserProject->FillFromRepositoryCredential() === true) {
         return "<error>" . $repositoryCredential . " was already registered for this project under a different email address</error>";
     }
     // Register the user
     // Create a new password
     $keychars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
     $length = 10;
     srand(make_seed_recoverpass());
     $pass = "";
     $max = strlen($keychars) - 1;
     for ($i = 0; $i <= $length; $i++) {
         $pass .= substr($keychars, rand(0, $max), 1);
     }
     $encrypted = md5($pass);
     pdo_query("INSERT INTO " . qid("user") . " (email,password,firstname,lastname,institution,admin)\n                 VALUES ('{$email}','{$encrypted}','{$firstName}','{$lastName}','','0')");
     add_last_sql_error("register_user");
     $userid = pdo_insert_id("user");
     // Insert the user into the project
     pdo_query("INSERT INTO user2project (userid,projectid,role,emailtype)\n                                VALUES ('{$userid}','{$projectid}','0','1')");
     add_last_sql_error("register_user");
     // We add the credentials if not already added
     $UserProject->UserId = $userid;
     $UserProject->AddCredential($repositoryCredential);
     $UserProject->ProjectId = 0;
     $UserProject->AddCredential($email);
     // Add the email by default
     $currentURI = get_server_URI();
     $prefix = "";
     if (strlen($firstName) > 0) {
         $prefix = " ";
     }
     $project = pdo_query("SELECT name FROM project WHERE id='{$projectid}'");
     $project_array = pdo_fetch_array($project);
     $projectname = $project_array['name'];
     // Send the email
     $text = "Hello" . $prefix . $firstName . ",<br><br>";
     $text .= "You have been registered to CDash because you have CVS/SVN access to the repository for " . $projectname . " <br>";
     $text .= "To access your CDash account: " . $currentURI . "/user.php<br>";
     $text .= "Your login is: " . $email . "<br>";
     $text .= "Your password is: " . $pass . "<br>";
     $text .= "<br>Generated by CDash.";
     if (@cdashmail("{$email}", "CDash - " . $projectname . " : Subscription", "{$text}", "From: {$CDASH_EMAILADMIN}\nReply-To: no-reply\nContent-type: text/plain; charset=utf-8\nX-Mailer: PHP/" . phpversion() . "\nMIME-Version: 1.0\nContent-type: text/html; charset=UTF-8")) {
         echo "Email sent to: " . $email . "<br>";
     }
     return true;
 }
Example #22
0
 function mysql_error($link_identifier = NULL)
 {
     return pdo_error(func_get_args());
 }
Example #23
0
        $xml .= add_XML_value('description', stripslashes($siteinformation_array['description']));
        $xml .= add_XML_value('processoris64bits', $siteinformation_array['processoris64bits']);
        $xml .= add_XML_value('processorvendor', $siteinformation_array['processorvendor']);
        $xml .= add_XML_value('processorvendorid', $siteinformation_array['processorvendorid']);
        $xml .= add_XML_value('processorfamilyid', $siteinformation_array['processorfamilyid']);
        $xml .= add_XML_value('processormodelid', $siteinformation_array['processormodelid']);
        $xml .= add_XML_value('processorcachesize', $siteinformation_array['processorcachesize']);
        $xml .= add_XML_value('numberlogicalcpus', $siteinformation_array['numberlogicalcpus']);
        $xml .= add_XML_value('numberphysicalcpus', $siteinformation_array['numberphysicalcpus']);
        $xml .= add_XML_value('totalvirtualmemory', $siteinformation_array['totalvirtualmemory']);
        $xml .= add_XML_value('totalphysicalmemory', $siteinformation_array['totalphysicalmemory']);
        $xml .= add_XML_value('logicalprocessorsperphysical', $siteinformation_array['logicalprocessorsperphysical']);
        $xml .= add_XML_value('processorclockfrequency', $siteinformation_array['processorclockfrequency']);
        $xml .= add_XML_value('ip', $site_array['ip']);
        $xml .= add_XML_value('latitude', $site_array['latitude']);
        $xml .= add_XML_value('longitude', $site_array['longitude']);
        $xml .= add_XML_value('outoforder', $site_array['outoforder']);
        $xml .= '</site>';
        $user2site = pdo_query("SELECT su.userid FROM site2user AS su,user2project AS up\n                            WHERE su.userid=up.userid AND up.role>0 AND su.siteid='{$siteid}' and su.userid='{$userid}'");
        echo pdo_error();
        if (pdo_num_rows($user2site) == 0) {
            $xml .= add_XML_value('siteclaimed', '0');
        } else {
            $xml .= add_XML_value('siteclaimed', '1');
        }
        $xml .= '</user>';
    }
    $xml .= '</cdash>';
    // Now doing the xslt transition
    generate_XSLT($xml, 'editSite');
}
Example #24
0
        $directory_array[$fullpath]['nfiles']++;
    }
    // Compute the average
    foreach ($directory_array as $fullpath => $covdir) {
        $directory_array[$fullpath]['percentcoverage'] = sprintf('%3.2f', 100.0 * ($covdir['loctested'] / ($covdir['loctested'] + $covdir['locuntested'])));
        $directory_array[$fullpath]['coveragemetric'] = sprintf('%3.2f', $covdir['coveragemetric'] / $covdir['nfiles']);
    }
    $covfile_array = array_merge($covfile_array, $directory_array);
    //$covfile_array = $directory_array;
} elseif ($status == 0) {
    // Add the untested files if the coverage is low
    $sql = 'SELECT cf.fullpath,cfp.priority' . $SQLDisplayAuthor . ' FROM coverage AS c,coveragefile AS cf ' . $SQLDisplayAuthors . '
              LEFT JOIN coveragefilepriority AS cfp ON (cfp.fullpath=cf.fullpath AND projectid=' . qnum($projectid) . ")\n              WHERE c.buildid='{$buildid}' AND cf.id=c.fileid AND c.covered=0 " . $SQLsearchTerm;
    $coveragefile = pdo_query($sql);
    if (false === $coveragefile) {
        add_log('error: pdo_query 2 failed: ' . pdo_error(), __FILE__, LOG_ERR);
    }
    while ($coveragefile_array = pdo_fetch_array($coveragefile)) {
        $covfile['filename'] = substr($coveragefile_array['fullpath'], strrpos($coveragefile_array['fullpath'], '/') + 1);
        $covfile['fullpath'] = $coveragefile_array['fullpath'];
        $covfile['fileid'] = 0;
        $covfile['covered'] = 0;
        $covfile['locuntested'] = 0;
        $covfile['loctested'] = 0;
        $covfile['branchesuntested'] = 0;
        $covfile['branchestested'] = 0;
        $covfile['functionsuntested'] = 0;
        $covfile['functionstested'] = 0;
        $covfile['percentcoverage'] = 0;
        $covfile['coveragemetric'] = 0;
        $covfile['priority'] = $coveragefile_array['priority'];
Example #25
0
 /** Delete this BuildGroup. */
 public function Delete()
 {
     if (!$this->Exists()) {
         return false;
     }
     // We delete all the build2grouprule associated with the group
     pdo_query("DELETE FROM build2grouprule WHERE groupid='{$this->Id}'");
     // We delete the buildgroup
     pdo_query("DELETE FROM buildgroup WHERE id='{$this->Id}'");
     // Restore the builds that were associated with this group
     $oldbuilds = pdo_query("\n      SELECT id,type FROM build WHERE id IN\n        (SELECT buildid AS id FROM build2group WHERE groupid='{$this->Id}')");
     echo pdo_error();
     while ($oldbuilds_array = pdo_fetch_array($oldbuilds)) {
         // Move the builds
         $buildid = $oldbuilds_array['id'];
         $buildtype = $oldbuilds_array['type'];
         // Find the group corresponding to the build type
         $query = pdo_query("\n        SELECT id FROM buildgroup\n        WHERE name='{$buildtype}' AND projectid='{$this->ProjectId}'");
         if (pdo_num_rows($query) == 0) {
             $query = pdo_query("\n          SELECT id FROM buildgroup\n          WHERE name='Experimental' AND projectid='{$this->ProjectId}'");
         }
         echo pdo_error();
         $grouptype_array = pdo_fetch_array($query);
         $grouptype = $grouptype_array['id'];
         pdo_query("\n        UPDATE build2group SET groupid='{$grouptype}' WHERE buildid='{$buildid}'");
         echo pdo_error();
     }
     // Delete the buildgroupposition and update the position
     // of the other groups.
     pdo_query("DELETE FROM buildgroupposition WHERE buildgroupid='{$this->Id}'");
     $buildgroupposition = pdo_query("\n      SELECT bg.buildgroupid FROM buildgroupposition AS bg, buildgroup AS g\n      WHERE g.projectid='{$this->ProjectId}' AND bg.buildgroupid=g.id\n      ORDER BY bg.position ASC");
     $p = 1;
     while ($buildgroupposition_array = pdo_fetch_array($buildgroupposition)) {
         $buildgroupid = $buildgroupposition_array['buildgroupid'];
         pdo_query("\n        UPDATE buildgroupposition SET position='{$p}'\n        WHERE buildgroupid='{$buildgroupid}'");
         $p++;
     }
 }
Example #26
0
/** Authentication function */
function register()
{
    global $reg;
    include dirname(__DIR__) . '/config/config.php';
    require_once 'include/pdo.php';
    if (isset($_GET['key'])) {
        $key = pdo_real_escape_string($_GET['key']);
        $sql = 'SELECT * FROM ' . qid('usertemp') . " WHERE registrationkey='{$key}'";
        $query = pdo_query($sql);
        if (pdo_num_rows($query) == 0) {
            $reg = 'The key is invalid.';
            return 0;
        }
        $query_array = pdo_fetch_array($query);
        $email = $query_array['email'];
        // We copy the data from usertemp to user
        $user = new User();
        $user->Email = $email;
        $user->Password = $query_array['password'];
        $user->FirstName = $query_array['firstname'];
        $user->LastName = $query_array['lastname'];
        $user->Institution = $query_array['institution'];
        if ($user->Save()) {
            pdo_query("DELETE FROM usertemp WHERE email='{$email}'");
            return 1;
        } else {
            $reg = pdo_error();
            return 0;
        }
    } elseif (isset($_POST['sent'])) {
        // arrive from register form
        $url = $_POST['url'];
        if ($url != 'catchbot') {
            $reg = 'Bots are not allowed to obtain CDash accounts!';
            return 0;
        }
        $email = $_POST['email'];
        $passwd = $_POST['passwd'];
        $passwd2 = $_POST['passwd2'];
        if (!($passwd == $passwd2)) {
            $reg = 'Passwords do not match!';
            return 0;
        }
        global $CDASH_MINIMUM_PASSWORD_LENGTH, $CDASH_MINIMUM_PASSWORD_COMPLEXITY, $CDASH_PASSWORD_COMPLEXITY_COUNT;
        $complexity = getPasswordComplexity($passwd);
        if ($complexity < $CDASH_MINIMUM_PASSWORD_COMPLEXITY) {
            if ($CDASH_PASSWORD_COMPLEXITY_COUNT > 1) {
                $reg = "Your password must contain at least {$CDASH_PASSWORD_COMPLEXITY_COUNT} characters from {$CDASH_MINIMUM_PASSWORD_COMPLEXITY} of the following types: uppercase, lowercase, numbers, and symbols.";
            } else {
                $reg = "Your password must contain at least {$CDASH_MINIMUM_PASSWORD_COMPLEXITY} of the following: uppercase, lowercase, numbers, and symbols.";
            }
            return 0;
        }
        if (strlen($passwd) < $CDASH_MINIMUM_PASSWORD_LENGTH) {
            $reg = "Your password must be at least {$CDASH_MINIMUM_PASSWORD_LENGTH} characters.";
            return 0;
        }
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $institution = $_POST['institution'];
        if ($email && $passwd && $passwd2 && $fname && $lname && $institution) {
            $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}");
            pdo_select_db("{$CDASH_DB_NAME}", $db);
            $passwd = md5($passwd);
            $email = pdo_real_escape_string($email);
            $sql = 'SELECT email FROM ' . qid('user') . " WHERE email='{$email}'";
            if (pdo_num_rows(pdo_query($sql)) > 0) {
                $reg = "{$email} is already registered.";
                return 0;
            }
            $sql = 'SELECT email  FROM ' . qid('usertemp') . " WHERE email='{$email}'";
            if (pdo_num_rows(pdo_query($sql)) > 0) {
                $reg = "{$email} is already registered. Check your email if you haven't received the link to activate yet.";
                return 0;
            }
            $passwd = pdo_real_escape_string($passwd);
            $fname = pdo_real_escape_string($fname);
            $lname = pdo_real_escape_string($lname);
            $institution = pdo_real_escape_string($institution);
            if ($CDASH_REGISTRATION_EMAIL_VERIFY) {
                $keychars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                $length = 40;
                $key = '';
                $max = strlen($keychars) - 1;
                for ($i = 0; $i < $length; $i++) {
                    // random_int is available in PHP 7 and the random_compat PHP 5.x
                    // polyfill included in the Composer package.json dependencies.
                    $key .= substr($keychars, random_int(0, $max), 1);
                }
                $date = date(FMT_DATETIME);
                $sql = 'INSERT INTO ' . qid('usertemp') . " (email,password,firstname,lastname,institution,registrationkey,registrationdate)\n                    VALUES ('{$email}','{$passwd}','{$fname}','{$lname}','{$institution}','{$key}','{$date}')";
            } else {
                $user = new User();
                $user->Email = $email;
                $user->Password = $passwd;
                $user->FirstName = $fname;
                $user->LastName = $lname;
                $user->Institution = $institution;
                $user->Save();
            }
            if (pdo_query($sql)) {
                if ($CDASH_REGISTRATION_EMAIL_VERIFY) {
                    $currentURI = get_server_URI();
                    // Send the email
                    $emailtitle = 'Welcome to CDash!';
                    $emailbody = 'Hello ' . $fname . ",\n\n";
                    $emailbody .= "Welcome to CDash! In order to validate your registration please follow this link: \n";
                    $emailbody .= $currentURI . '/register.php?key=' . $key . "\n";
                    $serverName = $CDASH_SERVER_NAME;
                    if (strlen($serverName) == 0) {
                        $serverName = $_SERVER['SERVER_NAME'];
                    }
                    $emailbody .= "\n-CDash on " . $serverName . "\n";
                    if (cdashmail("{$email}", $emailtitle, $emailbody)) {
                        add_log('email sent to: ' . $email, 'Registration');
                    } else {
                        add_log('cannot send email to: ' . $email, 'Registration', LOG_ERR);
                    }
                    $reg = "A confirmation email has been sent. Check your email (including your spam folder) to confirm your registration!\n";
                    $reg .= 'You need to activate your account within 24 hours.';
                    return 0;
                }
                return 1;
            } else {
                $reg = pdo_error();
                return 0;
            }
        } else {
            $reg = 'Please fill in all of the required fields';
            return 0;
        }
    }
    return 0;
}
Example #27
0
    $host = 'dbserver.engr.scu.edu';
    $username = '******';
    $password = '******';
    $database = 'sdb_pnguyen';
    if (!($conn = pdo_connect("{$host}", $username, $password))) {
        die('Error connecting to ' . host . '.' . pdo_error());
    }
    if (!pdo_select_db($database, $conn)) {
        die('Error selecting ' . $database . '. ' . pdo_error());
    }
    //      $studentName = $_POST['name'];
    $studentName = $_SESSION['userName'];
    $descr = $_POST['description'];
    $category = $_POST['category'];
    $classID = $_SESSION['classID'];
    $className = "COEN175";
    $instrName = "Nate";
    $isSolved = 1;
    $studentName = pdo_escape_string($studentName);
    $descr = pdo_escape_string($descr);
    $countQuery = "SELECT * FROM `enqueue` WHERE `classID` = '{$classID}'";
    $getCountQuery = pdo_query($countQuery);
    $row_count = pdo_num_rows($getCountQuery);
    $NewRequestQuery = "INSERT INTO `enqueue` (`classID`, `reqCount`, `order`, `className`, `instructorName`, `studentName`,`reqDescrip`, `category`, `timeIn`, `timeSpent`, `isSolved`) VALUES ('{$classID}', '{$row_count}', '100', 'none','none', '{$studentName}', '{$descr}', '{$category}', now(),'0', '0')";
    if (pdo_query($NewRequestQuery)) {
    } else {
        echo 'insert not completed';
        die(pdo_error());
    }
    header("Location:student_session_page.php?");
}
Example #28
0
 /** process an SQL file */
 function _processSQLfile($filename)
 {
     $file_content = file($filename);
     $query = '';
     foreach ($file_content as $sql_line) {
         $tsl = trim($sql_line);
         if ($sql_line != '' && substr($tsl, 0, 2) != '--' && substr($tsl, 0, 1) != '#') {
             $query .= $sql_line;
             if (preg_match("/;\\s*\$/", $sql_line)) {
                 // We need to remove only the last semicolon
                 $pos = strrpos($query, ';');
                 if ($pos !== false) {
                     $query = substr($query, 0, $pos) . substr($query, $pos + 1);
                 }
                 $result = pdo_query($query);
                 if (!$result) {
                     $xml = '<db_created>0</db_created>';
                     die(pdo_error());
                 }
                 $query = '';
             }
         }
     }
 }
Example #29
0
 public function Save()
 {
     $this->StartTime = pdo_real_escape_string($this->StartTime);
     $this->EndTime = pdo_real_escape_string($this->EndTime);
     $this->SubmitTime = pdo_real_escape_string($this->SubmitTime);
     $this->Command = pdo_real_escape_string(trim($this->Command));
     $this->Log = pdo_real_escape_string(trim($this->Log));
     // Compute the number of errors and warnings.
     // This speeds up the display of the main table.
     $nbuilderrors = -1;
     $nbuildwarnings = -1;
     if ($this->InsertErrors) {
         $nbuilderrors = 0;
         $nbuildwarnings = 0;
         foreach ($this->Errors as $error) {
             if ($error->Type == 0) {
                 $nbuilderrors++;
             } else {
                 $nbuildwarnings++;
             }
         }
     }
     if (!$this->Exists()) {
         $id = '';
         $idvalue = '';
         if ($this->Id) {
             $id = 'id,';
             $idvalue = qnum($this->Id) . ',';
         }
         if (strlen($this->Type) == 0) {
             $this->Type = extract_type_from_buildstamp($this->Stamp);
         }
         $this->Name = pdo_real_escape_string($this->Name);
         $this->Stamp = pdo_real_escape_string($this->Stamp);
         $this->Type = pdo_real_escape_string($this->Type);
         $this->Generator = pdo_real_escape_string($this->Generator);
         $this->SetParentId(0);
         $justCreatedParent = false;
         if ($this->SubProjectName) {
             $this->SetParentId($this->LookupParentBuildId());
             if ($this->ParentId == 0) {
                 // This is the first subproject to submit for a new build.
                 // Create a new parent build for it.
                 $justCreatedParent = $this->CreateParentBuild($nbuilderrors, $nbuildwarnings);
             }
         }
         $this->Uuid = Build::GenerateUuid($this->Stamp, $this->Name, $this->SiteId, $this->ProjectId, $this->SubProjectName);
         $query = 'INSERT INTO build
             (' . $id . 'siteid, projectid, stamp, name, type, generator,
              starttime, endtime, submittime, command, log, builderrors,
              buildwarnings, parentid, uuid, changeid)
             VALUES
             (' . $idvalue . "'{$this->SiteId}', '{$this->ProjectId}',\n                 '{$this->Stamp}', '{$this->Name}', '{$this->Type}',\n                 '{$this->Generator}', '{$this->StartTime}', '{$this->EndTime}',\n                 '{$this->SubmitTime}', '{$this->Command}', '{$this->Log}',\n                 {$nbuilderrors}, {$nbuildwarnings}, {$this->ParentId},\n                 '{$this->Uuid}', '{$this->PullRequest}')";
         if (!pdo_query($query)) {
             $error = pdo_error(null, false);
             // This error might be due to a unique constraint violation
             // for this UUID.  Query for such a previously existing build.
             $existing_id_result = pdo_single_row_query("SELECT id FROM build WHERE uuid = '{$this->Uuid}'");
             if ($existing_id_result && array_key_exists('id', $existing_id_result)) {
                 $this->Id = $existing_id_result['id'];
                 // If a previously existing build with this UUID was found
                 // call UpdateBuild() on it.  This also sets ParentId
                 // if an existing parent was found.
                 $this->UpdateBuild($this->Id, $nbuilderrors, $nbuildwarnings);
                 // Does the parent still need to be created?
                 if ($this->SubProjectName && $this->ParentId < 1) {
                     if (!$this->CreateParentBuild($nbuilderrors, $nbuildwarnings)) {
                         // Someone else created the parent after we called
                         // UpdateBuild(this->Id,...).
                         // In this case we also need to manually update
                         // the parent as well.
                         $this->UpdateBuild($this->ParentId, $nbuilderrors, $nbuildwarnings);
                     }
                 }
                 // Now that the existing build and its parent (if any) have
                 // been updated we can return early.
                 return true;
             }
             add_log("SQL error: {$error}", 'Build Insert', LOG_ERR, $this->ProjectId, $this->Id);
             return false;
         }
         if (!$this->Id) {
             $this->Id = pdo_insert_id('build');
         }
         // Add the groupid
         if ($this->GroupId) {
             $query = "INSERT INTO build2group (groupid,buildid) VALUES ('{$this->GroupId}','{$this->Id}')";
             if (!pdo_query($query)) {
                 add_last_sql_error('Build2Group Insert', $this->ProjectId, $this->Id);
             }
             // Associate the parent with this group too.
             if ($this->ParentId > 0) {
                 $result = pdo_query('SELECT groupid FROM build2group WHERE buildid=' . qnum($this->ParentId));
                 if (pdo_num_rows($result) == 0) {
                     global $CDASH_DB_TYPE;
                     $duplicate_sql = '';
                     if ($CDASH_DB_TYPE !== 'pgsql') {
                         $duplicate_sql = 'ON DUPLICATE KEY UPDATE groupid=groupid';
                     }
                     $query = "INSERT INTO build2group (groupid,buildid)\n                            VALUES ('{$this->GroupId}','{$this->ParentId}')\n                            {$duplicate_sql}";
                     if (!pdo_query($query)) {
                         add_last_sql_error('Parent Build2Group Insert', $this->ProjectId, $this->ParentId);
                     }
                 }
             }
         }
         // Add the subproject2build relationship:
         if ($this->SubProjectId) {
             $query = "INSERT INTO subproject2build (subprojectid,buildid) VALUES ('{$this->SubProjectId}','{$this->Id}')";
             if (!pdo_query($query)) {
                 add_last_sql_error('SubProject2Build Insert', $this->ProjectId, $this->Id);
             }
         }
         // Save the information
         if (!empty($this->Information)) {
             $this->Information->BuildId = $this->Id;
             $this->Information->Save();
         }
         // Update parent's tally of total build errors & warnings.
         if (!$justCreatedParent) {
             $this->UpdateBuild($this->ParentId, $nbuilderrors, $nbuildwarnings);
         } elseif ($this->ParentId > 0) {
             // If we just created a child build, associate it with
             // the parent's updates (if any).
             require_once 'models/buildupdate.php';
             BuildUpdate::AssignUpdateToChild($this->Id, $this->ParentId);
         }
     } else {
         // Build already exists.
         // Update this build and its parent (if necessary).
         $this->UpdateBuild($this->Id, $nbuilderrors, $nbuildwarnings);
     }
     // Add errors/warnings
     foreach ($this->Errors as $error) {
         $error->BuildId = $this->Id;
         $error->Insert();
     }
     // Add ErrorDiff
     foreach ($this->ErrorDiffs as $diff) {
         $diff->BuildId = $this->Id;
         $diff->Insert();
     }
     // Add label associations regardless of how Build::Save gets called:
     //
     $this->InsertLabelAssociations();
     // Should we post build errors to a pull request?
     if (isset($this->PullRequest)) {
         $hasErrors = false;
         foreach ($this->Errors as $error) {
             if ($error->Type == 0) {
                 $hasErrors = true;
                 break;
             }
         }
         if ($hasErrors) {
             $message = 'This build experienced errors';
             $url = get_server_URI(false) . "/viewBuildError.php?buildid={$this->Id}";
             $this->NotifyPullRequest($message, $url);
         }
     }
     return true;
 }