function CreateRSSFeed($projectid) { // Checks if (!isset($projectid) || !is_numeric($projectid)) { echo 'Not a valid projectid!'; return; } // Find the project name $project = pdo_query("SELECT public,name FROM project WHERE id='{$projectid}'"); $project_array = pdo_fetch_array($project); $projectname = $project_array['name']; // Don't create RSS feed for private projects if ($project_array['public'] != 1) { return; } global $CDASH_ROOT_DIR; $filename = $CDASH_ROOT_DIR . '/public/rss/SubmissionRSS' . $projectname . '.xml'; $currentURI = get_server_URI(); $currenttime = time(); $feed = new Feed(); $channel = new Channel(); $channel->title("CDash for {$projectname}")->url("{$currentURI}/index.php?project={$projectname}")->description("Recent CDash submissions for {$projectname}")->language('en-US')->lastBuildDate($currenttime)->appendTo($feed); // Get the last 24hrs submissions $beginning_timestamp = $currenttime - 24 * 3600; $end_timestamp = $currenttime; $builds = pdo_query("SELECT * FROM build\n WHERE UNIX_TIMESTAMP(starttime)<{$end_timestamp} AND UNIX_TIMESTAMP(starttime)>{$beginning_timestamp}\n AND projectid='{$projectid}'\n "); while ($build_array = pdo_fetch_array($builds)) { $siteid = $build_array['siteid']; $buildid = $build_array['id']; $site_array = pdo_fetch_array(pdo_query("SELECT name FROM site WHERE id='{$siteid}'")); // Find the number of errors and warnings $nerrors = $build_array['builderrors']; $nwarnings = $build_array['buildwarnings']; $nnotrun = $build_array['testnotrun']; $nfail = $build_array['testfailed']; $title = 'CDash(' . $projectname . ') - ' . $site_array['name'] . ' - ' . $build_array['name'] . ' - ' . $build_array['type']; $title .= ' - ' . $build_array['submittime'] . ' - ' . $nerrors . ' errors, ' . $nwarnings . ' warnings, ' . $nnotrun . ' not run, ' . $nfail . ' failed.'; // Should link to the errors... $link = $currentURI . '/buildSummary.php?buildid=' . $buildid; $description = 'A new ' . $build_array['type'] . ' submission from ' . $site_array['name'] . ' - ' . $build_array['name'] . ' is available: '; $description .= $nerrors . ' errors, ' . $nwarnings . ' warnings, ' . $nnotrun . ' not run, ' . $nfail . ' failed.'; $item = new Item(); $item->guid($currentURI . '/buildSummary.php?buildid=' . $buildid)->title($title)->url($link)->description($description)->pubDate($currenttime)->appendTo($channel); } if (file_put_contents($filename, $feed) === false) { add_log('Cannot write file ' . $filename, 'CreateRSSFeed', LOG_ERR, $projectid); } }
/** Send email if expected build from last day have not been submitting */ function sendEmailExpectedBuilds($projectid, $currentstarttime) { include "cdash/config.php"; include_once "cdash/common.php"; $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}"); pdo_select_db("{$CDASH_DB_NAME}", $db); $currentURI = get_server_URI(); if ($CDASH_BASE_URL == '' && $CDASH_ASYNCHRONOUS_SUBMISSION) { $currentURI = substr($currentURI, 0, strrpos($currentURI, "/")); } $currentEndUTCTime = gmdate(FMT_DATETIME, $currentstarttime); $currentBeginUTCTime = gmdate(FMT_DATETIME, $currentstarttime - 3600 * 24); $sql = "SELECT buildtype,buildname,siteid,groupid,site.name FROM (SELECT g.siteid,g.buildtype,g.buildname,g.groupid FROM build2grouprule as g LEFT JOIN build as b ON(\n g.expected='1' AND (b.type=g.buildtype AND b.name=g.buildname AND b.siteid=g.siteid)\n AND b.projectid='{$projectid}' AND b.starttime>'{$currentBeginUTCTime}' AND b.starttime<'{$currentEndUTCTime}')\n WHERE (b.type is null AND b.name is null AND b.siteid is null)\n AND g.expected='1'\n AND g.starttime<'{$currentBeginUTCTime}' AND (g.endtime>'{$currentEndUTCTime}' OR g.endtime='1980-01-01 00:00:00')) as t1, buildgroup as bg, site\n WHERE t1.groupid=bg.id AND bg.projectid='{$projectid}' AND bg.starttime<'{$currentBeginUTCTime}' AND (bg.endtime>'{$currentEndUTCTime}' OR bg.endtime='1980-01-01 00:00:00')\n AND site.id=t1.siteid\n "; $build2grouprule = pdo_query($sql); $projectname = get_project_name($projectid); $summary = "The following expected build(s) for the project *" . $projectname . "* didn't submit yesterday:\n"; $missingbuilds = 0; $serverName = $CDASH_SERVER_NAME; if (strlen($serverName) == 0) { $serverName = $_SERVER['SERVER_NAME']; } while ($build2grouprule_array = pdo_fetch_array($build2grouprule)) { $builtype = $build2grouprule_array["buildtype"]; $buildname = $build2grouprule_array["buildname"]; $sitename = $build2grouprule_array["name"]; $siteid = $build2grouprule_array["siteid"]; $summary .= "* " . $sitename . " - " . $buildname . " (" . $builtype . ")\n"; // Find the site maintainers $email = ""; $emails = pdo_query("SELECT email FROM " . qid("user") . ",site2user WHERE " . qid("user") . ".id=site2user.userid AND site2user.siteid='{$siteid}'"); while ($emails_array = pdo_fetch_array($emails)) { if ($email != "") { $email .= ", "; } $email .= $emails_array["email"]; } if ($email != "") { $missingTitle = "CDash [" . $projectname . "] - Missing Build for " . $sitename; $missingSummary = "The following expected build(s) for the project " . $projectname . " didn't submit yesterday:\n"; $missingSummary .= "* " . $sitename . " - " . $buildname . " (" . $builtype . ")\n"; $missingSummary .= "\n" . $currentURI . "/index.php?project=" . urlencode($projectname) . "\n"; $missingSummary .= "\n-CDash on " . $serverName . "\n"; if (cdashmail("{$email}", $missingTitle, $missingSummary, "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, "sendEmailExpectedBuilds"); return; } else { add_log("cannot send email to: " . $email, "sendEmailExpectedBuilds"); } } $missingbuilds = 1; } // Send a summary email to the project administrator or users who want to receive notification // of missing builds if ($missingbuilds == 1) { $summary .= "\n" . $currentURI . "/index.php?project=" . urlencode($projectname) . "\n"; $summary .= "\n-CDash on " . $serverName . "\n"; $title = "CDash [" . $projectname . "] - Missing Builds"; // Find the site administrators or users who want to receive the builds $email = ""; $emails = pdo_query("SELECT email FROM " . qid("user") . ",user2project WHERE " . qid("user") . ".id=user2project.userid\n AND user2project.projectid='{$projectid}' AND (user2project.role='2' OR user2project.emailmissingsites=1)"); while ($emails_array = pdo_fetch_array($emails)) { if ($email != "") { $email .= ", "; } $email .= $emails_array["email"]; } // Send the email if ($email != "") { if (cdashmail("{$email}", $title, $summary, "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, "sendEmailExpectedBuilds"); return; } else { add_log("cannot send email to: " . $email, "sendEmailExpectedBuilds"); } } } }
function trigger_process_submissions($projectid) { global $CDASH_USE_HTTPS; $currentURI = get_server_URI(true); $request = $currentURI . "/cdash/processsubmissions.php?projectid=" . $projectid; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 1); if ($CDASH_USE_HTTPS) { curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); } // It's likely that the process timesout because the processing takes more // than 1s to run. This is OK as we just need to trigger it. // 28 = CURLE_OPERATION_TIMEDOUT if (curl_exec($ch) === false && curl_errno($ch) != 28) { add_log("cURL error: " . curl_error($ch) . ' for request: ' . $request, "do_submit_asynchronous", LOG_ERR, $projectid); } curl_close($ch); }
/** 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; }
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; }
/** Google authentication */ function googleAuthenticate($code) { $state = getGoogleAuthenticateState(); if ($state === false) { return; } include dirname(__DIR__) . '/config/config.php'; global $CDASH_DB_HOST, $CDASH_DB_LOGIN, $CDASH_DB_PASS, $CDASH_DB_NAME; $SessionCachePolicy = 'private_no_expire'; // initialize the session session_name('CDash'); session_cache_limiter($SessionCachePolicy); session_set_cookie_params($CDASH_COOKIE_EXPIRATION_TIME); @ini_set('session.gc_maxlifetime', $CDASH_COOKIE_EXPIRATION_TIME + 600); session_start(); // check that the anti-forgery token is valid if ($state->csrfToken != $_SESSION['cdash']['csrfToken']) { add_log('state anti-forgery token mismatch: ' . $state->csrfToken . ' vs ' . $_SESSION['cdash']['csrfToken'], 'googleAuthenticate', LOG_ERR); return; } $redirectURI = strtok(get_server_URI(false), '?'); // The return value of get_server_URI can be inconsistent. // It simply returns $CDASH_BASE_URL if that variable is set, yielding a // return value like http://mydomain.com/CDash. // If this variable is not set, then it will return the full URI including // the current script, ie // http://mydomain.com/CDash/googleauth_callback.php. // // Make sure that redirectURI contains the path to our callback script. if (strpos($redirectURI, 'googleauth_callback.php') === false) { $redirectURI .= '/googleauth_callback.php'; } try { $config = new Google_Config(); if ($CDASH_MEMCACHE_ENABLED) { $config->setCacheClass('Google_Cache_Memcache'); list($server, $port) = $CDASH_MEMCACHE_SERVER; $config->setClassConfig('Google_Cache_Memcache', 'host', $server); $config->setClassConfig('Google_Cache_Memcache', 'port', $port); } $client = new Google_Client($config); $client->setClientId($GOOGLE_CLIENT_ID); $client->setClientSecret($GOOGLE_CLIENT_SECRET); $client->setRedirectUri($redirectURI); $client->authenticate($_GET['code']); $oauth = new Google_Service_Oauth2($client); $me = $oauth->userinfo->get(); $tokenResponse = json_decode($client->getAccessToken()); } catch (Google_Auth_Exception $e) { add_log('Google access token request failed: ' . $e->getMessage(), 'googleAuthenticate', LOG_ERR); return; } // Check if this email address appears in our user database $email = strtolower($me->getEmail()); $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}"); pdo_select_db("{$CDASH_DB_NAME}", $db); $sql = 'SELECT id,password FROM ' . qid('user') . " WHERE email='" . pdo_real_escape_string($email) . "'"; $result = pdo_query("{$sql}"); if (pdo_num_rows($result) == 0) { // if no match is found, redirect to pre-filled out registration page pdo_free_result($result); $firstname = $me->getGivenName(); $lastname = $me->getFamilyName(); header("Location: register.php?firstname={$firstname}&lastname={$lastname}&email={$email}"); return false; } $user_array = pdo_fetch_array($result); $pass = $user_array['password']; if ($state->rememberMe) { require_once 'include/login_functions.php'; setRememberMeCookie($user_array['id']); } $sessionArray = array('login' => $email, 'passwd' => $user_array['password'], 'ID' => session_id(), 'valid' => 1, 'loginid' => $user_array['id']); $_SESSION['cdash'] = $sessionArray; session_write_close(); pdo_free_result($result); header("Location: {$state->requestedURI}"); return true; // authentication succeeded }
// Create a new password $keychars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#\$%&"; $length = 10; // seed with microseconds function make_seed_recoverpass() { list($usec, $sec) = explode(' ', microtime()); return (double) $sec + (double) $usec * 100000; } srand(make_seed_recoverpass()); $password = ""; $max = strlen($keychars) - 1; for ($i = 0; $i <= $length; $i++) { $password .= substr($keychars, rand(0, $max), 1); } $currentURI = get_server_URI(); $url = $currentURI . "/user.php"; $text = "Hello,\n\n You have asked to recover your password for CDash.\n\n"; $text .= "Your new password is: " . $password . "\n"; $text .= "Please go to this page to login: "******"{$url}\n"; $text .= "\n\nGenerated by CDash"; if (cdashmail("{$email}", "CDash password recovery", $text, "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")) { $md5pass = md5($password); // If we can send the email we update the database pdo_query("UPDATE " . qid("user") . " SET password='******' WHERE email='{$email}'"); add_last_sql_error("recoverPassword"); $xml .= "<message>A confirmation message has been sent to your inbox.</message>"; } else { $xml .= "<warning>Cannot send recovery email</warning>"; }
/** Redirect to the error page */ function redirect_error($text = '') { setcookie('cdash_error', $text); header('Location: ' . get_server_URI() . '/error.php'); }
function trigger_process_submissions($projectid) { global $CDASH_USE_HTTPS, $CDASH_ASYNC_WORKERS; $currentURI = get_server_URI(true); if ($CDASH_ASYNC_WORKERS > 1) { // Parallel processing. // Obtain the processing lock before firing off parallel workers. $mypid = getmypid(); include 'include/submission_functions.php'; if (AcquireProcessingLock($projectid, false, $mypid)) { $url = $currentURI . '/ajax/processsubmissions.php'; $params = array('projectid' => $projectid, 'pid' => $mypid); for ($i = 0; $i < $CDASH_ASYNC_WORKERS; $i++) { curl_request_async($url, $params, 'GET'); } } } else { // Serial processing. $request = $currentURI . '/ajax/processsubmissions.php?projectid=' . $projectid; curl_request($request); } }
/** Update the test numbers */ function UpdateTestNumbers($numberTestsPassed, $numberTestsFailed, $numberTestsNotRun) { if (!is_numeric($numberTestsPassed) || !is_numeric($numberTestsFailed) || !is_numeric($numberTestsNotRun)) { return; } // If this is a subproject build, we also have to update its parents test numbers. $newFailed = $numberTestsFailed - $this->GetNumberOfFailedTests(); $newNotRun = $numberTestsNotRun - $this->GetNumberOfNotRunTests(); $newPassed = $numberTestsPassed - $this->GetNumberOfPassedTests(); $this->ParentId = $this->GetParentBuildId(); $this->UpdateParentTestNumbers($newFailed, $newNotRun, $newPassed); // Update this build's test numbers. pdo_query("UPDATE build SET testnotrun='{$numberTestsNotRun}',\n testfailed='{$numberTestsFailed}',\n testpassed='{$numberTestsPassed}' WHERE id=" . qnum($this->Id)); add_last_sql_error("Build:UpdateTestNumbers", $this->ProjectId, $this->Id); // Check if we should post test failures to a pull request. if (isset($this->PullRequest) && $numberTestsFailed > 0) { $idToNotify = $this->Id; if ($this->ParentId > 0) { $idToNotify = $this->ParentId; } $notified = true; $row = pdo_single_row_query("SELECT notified FROM build WHERE id=" . qnum($idToNotify)); if ($row && array_key_exists('notified', $row)) { $notified = $row['notified']; } if (!$notified) { $url = get_server_URI(false); $url .= "/viewTest.php?onlyfailed&buildid={$this->Id}"; post_pull_request_comment($this->ProjectId, $this->PullRequest, "This build experienced failing tests.", $url); pdo_query("UPDATE build SET notified='1' WHERE id=" . qnum($idToNotify)); } } }
/** 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; }
function CreateRSSFeed($projectid) { // Checks if (!isset($projectid) || !is_numeric($projectid)) { echo "Not a valid projectid!"; return; } // Find the project name $project = pdo_query("SELECT public,name FROM project WHERE id='{$projectid}'"); $project_array = pdo_fetch_array($project); $projectname = $project_array["name"]; // Don't create RSS feed for private projects if ($project_array["public"] != 1) { return; } global $CDASH_ROOT_DIR; $filename = $CDASH_ROOT_DIR . "/rss/SubmissionRSS" . $projectname . ".xml"; if (!($fp = fopen($filename, 'w'))) { add_log("CreateRSSFeed", "Cannot write file " . $filename, LOG_ERR, $projectid); return; } $currentURI = get_server_URI(); fputs($fp, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); fputs($fp, "<rss version=\"2.0\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"); fputs($fp, "<channel>\n"); fputs($fp, "<atom:link href=\"" . $currentURI . "/rssSubmissionRSS" . $projectname . ".xml\" rel=\"self\" type=\"application/rss+xml\" />\n"); fputs($fp, "<title>Recent CDash submissions for {$projectname}</title>\n"); fputs($fp, "<link>{$currentURI}/index.php?project={$projectname}</link>\n"); fputs($fp, "<description>CDash for {$projectname}</description>\n"); fputs($fp, "<generator>CDash</generator>\n"); fputs($fp, "<language>en-us</language>\n"); fputs($fp, "<image>\n"); fputs($fp, " <title>Recent CDash submissions for {$projectname}</title>\n"); fputs($fp, " <link>{$currentURI}/index.php?project={$projectname}</link>\n"); fputs($fp, " <url>{$currentURI}/images/cdash.gif</url>\n"); fputs($fp, "</image>\n"); $date = date('r'); fputs($fp, "<lastBuildDate>{$date}</lastBuildDate>\n"); // Get the last 24hrs submissions $currenttime = time(); $beginning_timestamp = $currenttime - 24 * 3600; $end_timestamp = $currenttime; $builds = pdo_query("SELECT * FROM build\n WHERE UNIX_TIMESTAMP(starttime)<{$end_timestamp} AND UNIX_TIMESTAMP(starttime)>{$beginning_timestamp}\n AND projectid='{$projectid}'\n "); while ($build_array = pdo_fetch_array($builds)) { $siteid = $build_array["siteid"]; $buildid = $build_array["id"]; $site_array = pdo_fetch_array(pdo_query("SELECT name FROM site WHERE id='{$siteid}'")); // Find the number of errors and warnings $builderror = pdo_query("SELECT buildid FROM builderror WHERE buildid='{$buildid}' AND type='0'"); $nerrors = pdo_num_rows($builderror); $buildwarning = pdo_query("SELECT buildid FROM builderror WHERE buildid='{$buildid}' AND type='1'"); $nwarnings = pdo_num_rows($buildwarning); $nnotrun = pdo_num_rows(pdo_query("SELECT buildid FROM build2test WHERE buildid='{$buildid}' AND status='notrun'")); $nfail = pdo_num_rows(pdo_query("SELECT buildid FROM build2test WHERE buildid='{$buildid}' AND status='failed'")); $title = "CDash(" . $projectname . ") - " . $site_array["name"] . " - " . $build_array["name"] . " - " . $build_array["type"]; $title .= " - " . $build_array["submittime"] . " - " . $nerrors . " errors, " . $nwarnings . " warnings, " . $nnotrun . " not run, " . $nfail . " failed."; // Should link to the errors... $link = $currentURI . "/buildSummary.php?buildid=" . $buildid; $description = "A new " . $build_array["type"] . " submission from " . $site_array["name"] . " - " . $build_array["name"] . " is available: "; $description .= $nerrors . " errors, " . $nwarnings . " warnings, " . $nnotrun . " not run, " . $nfail . " failed."; $pubDate = date(DATE_RSS); $date = date(DATE_W3C); fputs($fp, "<item>\n"); fputs($fp, " <guid>" . $currentURI . "/buildSummary.php?buildid=" . $buildid . "</guid>"); fputs($fp, " <title>{$title}</title>"); fputs($fp, " <link>{$link}</link>"); fputs($fp, " <description>{$description}</description>\n"); fputs($fp, " <pubDate>{$pubDate}</pubDate>\n"); fputs($fp, " <dc:creator>CDash</dc:creator>\n"); fputs($fp, "</item>\n"); } fputs($fp, "</channel>\n"); fputs($fp, "</rss>\n"); fclose($fp); unset($fp); }
/** Send email if expected build from last day have not been submitting */ function sendEmailExpectedBuilds($projectid, $currentstarttime) { include 'config/config.php'; include_once 'include/common.php'; $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}"); pdo_select_db("{$CDASH_DB_NAME}", $db); $currentURI = get_server_URI(); if ($CDASH_BASE_URL == '' && $CDASH_ASYNCHRONOUS_SUBMISSION) { $currentURI = substr($currentURI, 0, strrpos($currentURI, '/')); } $currentEndUTCTime = gmdate(FMT_DATETIME, $currentstarttime); $currentBeginUTCTime = gmdate(FMT_DATETIME, $currentstarttime - 3600 * 24); $sql = "SELECT buildtype,buildname,siteid,groupid,site.name FROM (SELECT g.siteid,g.buildtype,g.buildname,g.groupid FROM build2grouprule as g LEFT JOIN build as b ON(\n g.expected='1' AND (b.type=g.buildtype AND b.name=g.buildname AND b.siteid=g.siteid)\n AND b.projectid='{$projectid}' AND b.starttime>'{$currentBeginUTCTime}' AND b.starttime<'{$currentEndUTCTime}')\n WHERE (b.type is null AND b.name is null AND b.siteid is null)\n AND g.expected='1'\n AND g.starttime<'{$currentBeginUTCTime}' AND (g.endtime>'{$currentEndUTCTime}' OR g.endtime='1980-01-01 00:00:00')) as t1, buildgroup as bg, site\n WHERE t1.groupid=bg.id AND bg.projectid='{$projectid}' AND bg.starttime<'{$currentBeginUTCTime}' AND (bg.endtime>'{$currentEndUTCTime}' OR bg.endtime='1980-01-01 00:00:00')\n AND site.id=t1.siteid\n "; $build2grouprule = pdo_query($sql); $projectname = get_project_name($projectid); $summary = 'The following expected build(s) for the project *' . $projectname . "* didn't submit yesterday:\n"; $missingbuilds = 0; $serverName = $CDASH_SERVER_NAME; if (strlen($serverName) == 0) { $serverName = $_SERVER['SERVER_NAME']; } while ($build2grouprule_array = pdo_fetch_array($build2grouprule)) { $builtype = $build2grouprule_array['buildtype']; $buildname = $build2grouprule_array['buildname']; $sitename = $build2grouprule_array['name']; $siteid = $build2grouprule_array['siteid']; $summary .= '* ' . $sitename . ' - ' . $buildname . ' (' . $builtype . ")\n"; // Find the site maintainers $email = ''; $emails = pdo_query('SELECT email FROM ' . qid('user') . ',site2user WHERE ' . qid('user') . ".id=site2user.userid AND site2user.siteid='{$siteid}'"); while ($emails_array = pdo_fetch_array($emails)) { if ($email != '') { $email .= ', '; } $email .= $emails_array['email']; } if ($email != '') { $missingTitle = 'CDash [' . $projectname . '] - Missing Build for ' . $sitename; $missingSummary = 'The following expected build(s) for the project ' . $projectname . " didn't submit yesterday:\n"; $missingSummary .= '* ' . $sitename . ' - ' . $buildname . ' (' . $builtype . ")\n"; $missingSummary .= "\n" . $currentURI . '/index.php?project=' . urlencode($projectname) . "\n"; $missingSummary .= "\n-CDash on " . $serverName . "\n"; if (cdashmail("{$email}", $missingTitle, $missingSummary)) { add_log('email sent to: ' . $email, 'sendEmailExpectedBuilds'); return; } else { add_log('cannot send email to: ' . $email, 'sendEmailExpectedBuilds'); } } $missingbuilds = 1; } // Send a summary email to the project administrator or users who want to receive notification // of missing builds if ($missingbuilds == 1) { $summary .= "\n" . $currentURI . '/index.php?project=' . urlencode($projectname) . "\n"; $summary .= "\n-CDash on " . $serverName . "\n"; $title = 'CDash [' . $projectname . '] - Missing Builds'; // Find the site administrators or users who want to receive the builds $email = ''; $emails = pdo_query('SELECT email FROM ' . qid('user') . ',user2project WHERE ' . qid('user') . ".id=user2project.userid\n AND user2project.projectid='{$projectid}' AND (user2project.role='2' OR user2project.emailmissingsites=1)"); while ($emails_array = pdo_fetch_array($emails)) { if ($email != '') { $email .= ', '; } $email .= $emails_array['email']; } // Send the email if ($email != '') { if (cdashmail("{$email}", $title, $summary)) { add_log('email sent to: ' . $email, 'sendEmailExpectedBuilds'); return; } else { add_log('cannot send email to: ' . $email, 'sendEmailExpectedBuilds'); } } } }
/** Google authentication */ function googleAuthenticate($code) { include("cdash/config.php"); global $CDASH_DB_HOST, $CDASH_DB_LOGIN, $CDASH_DB_PASS, $CDASH_DB_NAME; $SessionCachePolicy = 'private_no_expire'; // initialize the session session_name("CDash"); session_cache_limiter($SessionCachePolicy); session_set_cookie_params($CDASH_COOKIE_EXPIRATION_TIME); @ini_set('session.gc_maxlifetime', $CDASH_COOKIE_EXPIRATION_TIME+600); session_start(); if (!isset($_GET["state"])) { add_log("no state value passed via GET", LOG_ERR); return; } // Both the anti-forgery token and the user's requested URL are specified // in the same "state" GET parameter. Split them out here. $splitState = explode("_AND_STATE_IS_", $_GET["state"]); if (sizeof($splitState) != 2) { add_log("Expected two values after splitting state parameter, found " . sizeof($splitState), LOG_ERR); return; } $requestedURI = $splitState[0]; @$state = $splitState[1]; // don't send the user back to login.php if that's where they came from if (strpos($requestedURI, "login.php") !== false) { $requestedURI = "user.php"; } // check that the anti-forgery token is valid if ($state != $_SESSION['cdash']['state']) { add_log("state anti-forgery token mismatch: " . $state . " vs " . $_SESSION['cdash']['state'], LOG_ERR); return; } // Request the access token $headers = array( 'Content-Type: application/x-www-form-urlencoded;charset=UTF-8', 'Connection: Keep-Alive' ); $redirectURI = strtok(get_server_URI(false), '?'); $postData = join('&', array( 'grant_type=authorization_code', 'code='.$_GET["code"], 'client_id='.$GOOGLE_CLIENT_ID, 'client_secret='.$GOOGLE_CLIENT_SECRET, 'redirect_uri='.$redirectURI )); $url = 'https://accounts.google.com/o/oauth2/token'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_PORT, 443); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); $resp = curl_exec($curl); $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($httpStatus != 200) { add_log("Google access token request failed: $resp", LOG_ERR); return; } $resp = json_decode($resp); $accessToken = $resp->access_token; $tokenType = $resp->token_type; // Use the access token to get the user's email address $headers = array( 'Authorization: '.$tokenType.' '.$accessToken ); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/plus/v1/people/me'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_PORT, 443); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); $resp = curl_exec($curl); $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($httpStatus != 200) { add_log("Get Google user email address request failed: $resp", LOG_ERR); return; } // Extract the user's email address from the response. $resp = json_decode($resp); $email = strtolower($resp->emails[0]->value); // Check if this email address appears in our user database $db = pdo_connect("$CDASH_DB_HOST", "$CDASH_DB_LOGIN","$CDASH_DB_PASS"); pdo_select_db("$CDASH_DB_NAME",$db); $sql="SELECT id,password FROM ".qid("user")." WHERE email='".pdo_real_escape_string($email)."'"; $result = pdo_query("$sql"); if(pdo_num_rows($result)==0) { // if no match is found, redirect to pre-filled out registration page pdo_free_result($result); $firstname = $resp->name->givenName; $lastname = $resp->name->familyName; header("Location: register.php?firstname=$firstname&lastname=$lastname&email=$email"); return false; } $user_array = pdo_fetch_array($result); $pass = $user_array["password"]; $sessionArray = array( "login" => $email, "passwd" => $user_array['password'], "ID" => session_id(), "valid" => 1, "loginid" => $user_array["id"]); $_SESSION['cdash'] = $sessionArray; session_write_close(); pdo_free_result($result); header("Location: $requestedURI"); return true; // authentication succeeded }
/** Sets a session variable forcing the redirect if the user needs * to change their password. */ function checkForExpiredPassword() { global $CDASH_PASSWORD_EXPIRATION; if ($CDASH_PASSWORD_EXPIRATION < 1) { return false; } if (!isset($_SESSION['cdash']) || !array_key_exists('loginid', $_SESSION['cdash'])) { return false; } unset($_SESSION['cdash']['redirect']); $uri = get_server_URI(false); $uri .= '/editUser.php?reason=expired'; $userid = $_SESSION['cdash']['loginid']; $result = pdo_query("\n SELECT date FROM password\n WHERE userid={$userid} ORDER BY date DESC LIMIT 1"); if (pdo_num_rows($result) < 1) { // If no result, then password rotation must have been enabled // after this user set their password. Force them to change it now. $_SESSION['cdash']['redirect'] = $uri; return true; } $row = pdo_fetch_array($result); $password_created_time = strtotime($row['date']); $password_expiration_time = strtotime("+{$CDASH_PASSWORD_EXPIRATION} days", $password_created_time); if (time() > $password_expiration_time) { $_SESSION['cdash']['redirect'] = $uri; return true; } return false; }
require_once 'models/buildfailure.php'; require_once 'include/filterdataFunctions.php'; require_once 'include/index_functions.php'; @set_time_limit(0); // Check if we can connect to the database. $db = pdo_connect("{$CDASH_DB_HOST}", "{$CDASH_DB_LOGIN}", "{$CDASH_DB_PASS}"); if (!$db || pdo_select_db("{$CDASH_DB_NAME}", $db) === false || pdo_query('SELECT id FROM ' . qid('user') . ' LIMIT 1', $db) === false) { if ($CDASH_PRODUCTION_MODE) { $response = array(); $response['error'] = 'CDash cannot connect to the database.'; echo json_encode($response); return; } else { // redirect to the install.php script $response = array(); $response['redirect'] = get_server_URI() . '/install.php'; echo json_encode($response); return; } return; } @($projectname = $_GET['project']); $projectname = htmlspecialchars(pdo_real_escape_string($projectname)); $projectid = get_project_id($projectname); $Project = new Project(); $Project->Id = $projectid; $Project->Fill(); @($date = $_GET['date']); if ($date != null) { $date = htmlspecialchars(pdo_real_escape_string($date)); }
/** function to send email to site maintainers when the update * step fails */ function send_update_email($handler, $projectid) { include "cdash/config.php"; include_once "cdash/common.php"; require_once "cdash/pdo.php"; require_once "models/build.php"; require_once "models/project.php"; require_once "models/buildgroup.php"; $Project = new Project(); $Project->Id = $projectid; $Project->Fill(); // If we shouldn't sent any emails we stop if ($Project->EmailBrokenSubmission == 0) { return; } // If the handler has a buildid (it should), we use it if (isset($handler->BuildId) && $handler->BuildId > 0) { $buildid = $handler->BuildId; } else { // Get the build id $name = $handler->getBuildName(); $stamp = $handler->getBuildStamp(); $sitename = $handler->getSiteName(); $buildid = get_build_id($name, $stamp, $projectid, $sitename); } if ($buildid < 0) { return; } // Check if the group as no email $Build = new Build(); $Build->Id = $buildid; $groupid = $Build->GetGroup(); $BuildGroup = new BuildGroup(); $BuildGroup->SetId($groupid); // If we specified no email we stop here if ($BuildGroup->GetSummaryEmail() == 2) { return; } // Send out update errors to site maintainers $update_errors = check_email_update_errors($buildid); if ($update_errors['errors']) { // Find the site maintainer(s) $sitename = $handler->getSiteName(); $siteid = $handler->getSiteId(); $to_address = ""; $email_addresses = pdo_query("SELECT email FROM " . qid("user") . ",site2user WHERE " . qid("user") . ".id=site2user.userid AND site2user.siteid='{$siteid}'"); while ($email_addresses_array = pdo_fetch_array($email_addresses)) { if ($to_address != "") { $to_address .= ", "; } $to_address .= $email_addresses_array["email"]; } if ($to_address != "") { $serverURI = get_server_URI(); // In the case of asynchronous submission, the serverURI contains /cdash // we need to remove it if ($CDASH_BASE_URL == '' && $CDASH_ASYNCHRONOUS_SUBMISSION) { $serverURI = substr($serverURI, 0, strrpos($serverURI, "/")); } // Generate the email to send $subject = "CDash [" . $Project->Name . "] - Update Errors for " . $sitename; $update_info = pdo_query("SELECT command,status FROM buildupdate AS u,build2update AS b2u\n WHERE b2u.updateid=u.id AND b2u.buildid=" . qnum($buildid)); $update_array = pdo_fetch_array($update_info); $body = "{$sitename} has encountered errors during the Update step and you have been identified as the maintainer of this site.\n\n"; $body .= "*Update Errors*\n"; $body .= "Status: " . $update_array["status"] . " (" . $serverURI . "/viewUpdate.php?buildid=" . $buildid . ")\n"; $header = "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"; if ($CDASH_TESTING_MODE) { add_log($to_address, "TESTING: EMAIL", LOG_TESTING); add_log($subject, "TESTING: EMAILTITLE", LOG_TESTING); add_log($body, "TESTING: EMAILBODY", LOG_TESTING); } else { if (cdashmail("{$to_address}", $subject, $body, $header)) { add_log("email sent to: " . $to_address, "sendEmailExpectedBuilds"); return; } else { add_log("cannot send email to: " . $to_address, "sendEmailExpectedBuilds"); } } } } }
/** function to send email to site maintainers when the update * step fails */ function send_update_email($handler, $projectid) { include 'config/config.php'; include_once 'include/common.php'; require_once 'include/pdo.php'; require_once 'models/build.php'; require_once 'models/project.php'; require_once 'models/buildgroup.php'; $Project = new Project(); $Project->Id = $projectid; $Project->Fill(); // If we shouldn't sent any emails we stop if ($Project->EmailBrokenSubmission == 0) { return; } // If the handler has a buildid (it should), we use it if (isset($handler->BuildId) && $handler->BuildId > 0) { $buildid = $handler->BuildId; } else { // Get the build id $name = $handler->getBuildName(); $stamp = $handler->getBuildStamp(); $sitename = $handler->getSiteName(); $buildid = get_build_id($name, $stamp, $projectid, $sitename); } if ($buildid < 0) { return; } // Check if the group as no email $Build = new Build(); $Build->Id = $buildid; $groupid = $Build->GetGroup(); $BuildGroup = new BuildGroup(); $BuildGroup->SetId($groupid); // If we specified no email we stop here if ($BuildGroup->GetSummaryEmail() == 2) { return; } // Send out update errors to site maintainers $update_errors = check_email_update_errors($buildid); if ($update_errors['errors']) { // Find the site maintainer(s) $sitename = $handler->getSiteName(); $siteid = $handler->getSiteId(); $to_address = ''; $email_addresses = pdo_query('SELECT email FROM ' . qid('user') . ',site2user WHERE ' . qid('user') . ".id=site2user.userid AND site2user.siteid='{$siteid}'"); while ($email_addresses_array = pdo_fetch_array($email_addresses)) { if ($to_address != '') { $to_address .= ', '; } $to_address .= $email_addresses_array['email']; } if ($to_address != '') { $serverURI = get_server_URI(); // In the case of asynchronous submission, the serverURI contains /cdash // we need to remove it if ($CDASH_BASE_URL == '' && $CDASH_ASYNCHRONOUS_SUBMISSION) { $serverURI = substr($serverURI, 0, strrpos($serverURI, '/')); } // Generate the email to send $subject = 'CDash [' . $Project->Name . '] - Update Errors for ' . $sitename; $update_info = pdo_query('SELECT command,status FROM buildupdate AS u,build2update AS b2u WHERE b2u.updateid=u.id AND b2u.buildid=' . qnum($buildid)); $update_array = pdo_fetch_array($update_info); $body = "{$sitename} has encountered errors during the Update step and you have been identified as the maintainer of this site.\n\n"; $body .= "*Update Errors*\n"; $body .= 'Status: ' . $update_array['status'] . ' (' . $serverURI . '/viewUpdate.php?buildid=' . $buildid . ")\n"; if ($CDASH_TESTING_MODE) { add_log($to_address, 'TESTING: EMAIL', LOG_DEBUG); add_log($subject, 'TESTING: EMAILTITLE', LOG_DEBUG); add_log($body, 'TESTING: EMAILBODY', LOG_DEBUG); } else { if (cdashmail("{$to_address}", $subject, $body)) { add_log('email sent to: ' . $to_address, 'sendEmailExpectedBuilds'); return; } else { add_log('cannot send email to: ' . $to_address, 'sendEmailExpectedBuilds'); } } } } }
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; }
$file['path'] = $coveragefile->GetPath(); $file['id'] = $fileid; $files[] = $file; } } // Send an email if the number of uncovered file is greater than one if (count($files) > 0) { // Writing the message $messagePlainText = "The following files for the project " . $Project->GetName(); $messagePlainText .= " have a low coverage and "; $messagePlainText .= "you have been identified as one of the authors of these files.\n"; foreach ($files as $file) { $messagePlainText .= $file['path'] . " (" . round($file['percent'], 2) . "%)\n"; } $messagePlainText .= "Details on the submission can be found at "; $messagePlainText .= get_server_URI(); $messagePlainText .= "\n\n"; $serverName = $CDASH_SERVER_NAME; if (strlen($serverName) == 0) { $serverName = $_SERVER['SERVER_NAME']; } $messagePlainText .= "\n-CDash on " . $serverName . "\n"; // Send the email $title = "CDash [" . $Project->GetName() . "] - Low Coverage"; $User = new User(); $User->Id = $userid; $email = $User->GetEmail(); cdashmail("{$email}", $title, $messagePlainText, "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"); $xml .= add_XML_value("warning", "*The email has been sent successfully."); } else { $xml .= add_XML_value("warning", "*No email sent because the coverage is green.");
/** Set number of configure errors for this build. */ public function SetNumberOfConfigureErrors($numErrors) { if (!$this->Id || !is_numeric($this->Id)) { return; } pdo_query("UPDATE build SET configureerrors='{$numErrors}'\n WHERE id=" . qnum($this->Id)); add_last_sql_error('Build:SetNumberOfConfigureErrors', $this->ProjectId, $this->Id); // Should we post configure errors to a pull request? if (isset($this->PullRequest) && $numErrors > 0) { $message = 'This build failed to configure'; $url = get_server_URI(false) . "/viewConfigure.php?buildid={$this->Id}"; $this->NotifyPullRequest($message, $url); } }