rowCount(); $i++) { $row = $resultCoordinates->fetch(); $targetName = $row['targetName']; // $resultCoordinates $ra = $row['RA']; // $resultCoordinates $declination = $row['declination']; // $resultCoordinates $coordinates[$targetName][0] = $ra; $coordinates[$targetName][1] = $declination; } //See how many exceptions there are per script $queryScript = "SELECT COUNT(`time`) AS `number`, `script` "; $queryScript .= "FROM `exceptions` "; $queryScript .= "WHERE `time`>='$date' AND `status` LIKE '$status' GROUP BY `script` ORDER BY FIELD(`script`,'monitoring_pipeline.py', 'monitoring_xrtgrblc.py')"; $resultScript = db_query_prepare($queryScript, $dbh, array()); if ($resultScript->rowCount() > 0) { for ($i = 0; $i < $resultScript->rowCount(); $i++) { $this->exceptions->script[$i]->name = $row["script"]; // $resultScript $this->exceptions->script[$i]->number = $row["number"]; // $resultScript $query = "SELECT `exceptions`.`ID`, DATE_FORMAT(`exceptions`.`time`,'%m-%d-%Y %H:%i:%s') AS `time`, `exceptions`.`targetName`, `exceptions`.`observationID`, `exceptions`.`description`, `exceptions`.`status`, `exceptions`.`comments`, "; $query .= "`observation`.`targetID`, `observation`.`segment`, "; $query .= "`observation`.`pipeline_wt`, `observation`.`wttime`, `observation`.`wtsnapshots`, `observation`.`wtevents`, "; $query .= "`observation`.`pipeline_pc`, `observation`.`pctime`, `observation`.`pcsnapshots`, `observation`.`pcevents`, "; $query .= "`observation`.`pipeline`, `observation`.`xrtgrblc`, `observation`.`plot`, "; $query .= "TIMESTAMPDIFF(SECOND,`exceptions`.`time`,NOW()) AS `timeSinceProcessed` "; $query .= "FROM `exceptions`, `observation` "; $query .= "WHERE `script` LIKE ? AND `time`>=? AND `exceptions`.`status` LIKE ? AND "; $query .= "`exceptions`.`observationID` LIKE `observation`.`observationID` AND `exceptions`.`targetName` LIKE `observation`.`targetName` ORDER BY `ID`"; $result = db_query_prepare($query, $dbh, array($this->exceptions->script[$i]->name, $date, $status)); //Grab individual exceptions to report back for ($j = 0; $j < $result->rowCount(); $j++) { $this->exceptions->script[$i]->exception[$j]->ID = $row["ID"]; // $result $this->exceptions->script[$i]->exception[$j]->time = $row["time"]; // $result $this->exceptions->script[$i]->exception[$j]->targetName = $row["targetName"]; // $result $this->exceptions->script[$i]->exception[$j]->observationID = $row["observationID"]; // $result $this->exceptions->script[$i]->exception[$j]->description = $row["description"]; // $result $this->exceptions->script[$i]->exception[$j]->targetID = $row["targetID"]; // $result $this->exceptions->script[$i]->exception[$j]->segment = $row["segment"]; // $result $this->exceptions->script[$i]->exception[$j]->status = $row["status"]; // $result $this->exceptions->script[$i]->exception[$j]->comments = $row["comments"]; // $result $this->exceptions->script[$i]->exception[$j]->pipeline = $row["pipeline"]; // $result $this->exceptions->script[$i]->exception[$j]->xrtgrblc = $row["xrtgrblc"]; // $result $this->exceptions->script[$i]->exception[$j]->plot = $row["plot"]; // $result $this->exceptions->script[$i]->exception[$j]->timeSinceProcessed = $row["timeSinceProcessed"]; // $result $afst = new AFST(); $afst->SimpleStatistics($this->exceptions->script[$i]->exception[$j]->targetID, $this->exceptions->script[$i]->exception[$j]->segment); $this->exceptions->script[$i]->exception[$j]->observationEnd = $afst->observation->end; $this->exceptions->script[$i]->exception[$j]->timeSince = $afst->observation->timeSince; $this->exceptions->script[$i]->exception[$j]->RA = $afst->observation->ra; $this->exceptions->script[$i]->exception[$j]->declination = $afst->observation->declination; $sourceCoordinates = $coordinates[$this->exceptions->script[$i]->exception[$j]->targetName]; if ($afst->observation->ra != '') { $observationCoordinates = array($afst->observation->ra, $afst->observation->declination); $this->exceptions->script[$i]->exception[$j]->separation = Separation($sourceCoordinates, $observationCoordinates); } else { $this->exceptions->script[$i]->exception[$j]->separation = "Not observed"; } //There is not as much information if the observation doesn't get through the pipeline. Try the AFST instead. if ($this->exceptions->script[$i]->name == 'monitoring_pipeline.py') { $this->exceptions->script[$i]->exception[$j]->pipeline_wt = $row["pipeline_wt"]; // $result $this->exceptions->script[$i]->exception[$j]->wtTime = 0; $this->exceptions->script[$i]->exception[$j]->wtSnapshots = 0; $this->exceptions->script[$i]->exception[$j]->wtEvents = 0; $this->exceptions->script[$i]->exception[$j]->pipeline_pc = $row["pipeline_pc"]; // $result $this->exceptions->script[$i]->exception[$j]->pcTime = 0; $this->exceptions->script[$i]->exception[$j]->pcSnapshots = 0; $this->exceptions->script[$i]->exception[$j]->pcEvents = 0; if ($afst->observation->xrt == 6) { $this->exceptions->script[$i]->exception[$j]->wtTime = $afst->observation->duration; $this->exceptions->script[$i]->exception[$j]->wtSnapshots = $afst->observation->snapshots; $this->exceptions->script[$i]->exception[$j]->mode = 'WT'; } elseif ($afst->observation->xrt == 7) { $this->exceptions->script[$i]->exception[$j]->pcTime = $afst->observation->duration; $this->exceptions->script[$i]->exception[$j]->pcSnapshots = $afst->observation->snapshots; $this->exceptions->script[$i]->exception[$j]->mode = 'PC'; } else { $this->exceptions->script[$i]->exception[$j]->wtTime = $afst->observation->duration; $this->exceptions->script[$i]->exception[$j]->wtSnapshots = $afst->observation->snapshots; $this->exceptions->script[$i]->exception[$j]->pcTime = $afst->observation->duration; $this->exceptions->script[$i]->exception[$j]->pcSnapshots = $afst->observation->snapshots; if ($afst->observation->xrt == 0) { $this->exceptions->script[$i]->exception[$j]->mode = 'Auto'; } else { $this->exceptions->script[$i]->exception[$j]->mode = 'Unknown'; } } } else { $this->exceptions->script[$i]->exception[$j]->pipeline_wt = $row["pipeline_wt"]; // $result $this->exceptions->script[$i]->exception[$j]->wtTime = $row["wttime"]; // $result $this->exceptions->script[$i]->exception[$j]->wtSnapshots = $row["wtsnapshots"]; // $result $this->exceptions->script[$i]->exception[$j]->wtEvents = $row["wtevents"]; // $result $this->exceptions->script[$i]->exception[$j]->pipeline_pc = $row["pipeline_pc"]; // $result $this->exceptions->script[$i]->exception[$j]->pcTime = $row["pctime"]; // $result $this->exceptions->script[$i]->exception[$j]->pcSnapshots = $row["pcsnapshots"]; // $result $this->exceptions->script[$i]->exception[$j]->pcEvents = $row["pcevents"]; // $result if ($this->exceptions->script[$i]->exception[$j]->pcSnapshots > 0 && $this->exceptions->script[$i]->exception[$j]->wtSnapshots > 0) { $this->exceptions->script[$i]->exception[$j]->mode = 'Auto'; } else if ($this->exceptions->script[$i]->exception[$j]->wtSnapshots > 0) { $this->exceptions->script[$i]->exception[$j]->mode = 'WT'; } else if ($this->exceptions->script[$i]->exception[$j]->pcSnapshots > 0) { $this->exceptions->script[$i]->exception[$j]->mode = 'PC'; } else { $this->exceptions->script[$i]->exception[$j]->mode = 'Unknown'; } } } } } else { unset($this->exceptions); } } public function UserViaEmail($email) { $dbh = mon_db_connect(); $query = "SELECT `fname`, `lname`, `email`, `pw`, `status`, `key`, `logIn` FROM `users` WHERE `email` LIKE ?"; $result = db_query_prepare($query, $dbh, array($email)); if ($result->rowCount() > 0) { $row = $result->fetch(); $this->user->fName = $row['fname']; // $result $this->user->lName = $row['lname']; // $result $this->user->email = $row['email']; // $result $this->user->pw = $row['pw']; // $result $this->user->status = $row['status']; // $result $this->user->key = $row['key']; // $result $this->user->logIn = $row['logIn']; // $result $querySources = "SELECT `sources`.`targetName`, `sources`.`folder`, `sources`.`RA`, `sources`.`declination`, "; $querySources .= "`sources`.`type`, `sources`.`plot` FROM `user_defined_sources` "; $querySources .= "JOIN `sources` ON (`user_defined_sources`.`targetName` = `sources`.`targetName`) WHERE `email` LIKE ?"; $resultSources = db_query_prepare($querySources, $dbh, array($this->user->email)); if ($resultSources->rowCount() > 0) { for ($i = 0; $i < $resultSources->rowCount(); $i++) { $srow = $resultSources->fetch(); $this->user->sources[$i]->targetName = $srow['targetName']; // $resultSources // $this->user->sources[$i]->folder = $row['folder']; // $resultSources // $this->user->sources[$i]->RA = $row['RA']; // $resultSources // $this->user->sources[$i]->declination = $row['declination']; // $resultSources // $this->user->sources[$i]->type = $row['type']; // $resultSources // $this->user->sources[$i]->plot = $row['plot']; // $resultSources } } } else { unset($this->user); } } public function UserViaKey($key) { $dbh = mon_db_connect(); $query = "SELECT `fname`, `lname`, `email`, `pw`, `email`, `status`, `key`, `logIn` FROM `users` WHERE `key` LIKE ?"; $result = db_query($query, $dbh, array($key)); if ($result->rowCount() > 0) { $row = $result->fetch(); $this->user->fName = $row['fname']; // $result $this->user->lName = $row['lname']; // $result $this->user->email = $row['email']; // $result $this->user->pw = $row['pw']; // $result $this->user->status = $row['status']; // $result $this->user->key = $row['key']; // $result $this->user->logIn = $row['logIn']; // $result } else { unset($this->user); } } public function GetUsers() { $dbh = mon_db_connect(); $query = "SELECT COUNT(`email`) AS `number`, `status` FROM `users` GROUP BY `status` ORDER BY FIELD(`status`, 'new', 'admin', 'user')"; $resultStatus = db_query($query, $dbh); if ($resultStatus->rowCount() > 0) { for ($i = 0; $i < $resultStatus->rowCount(); $i++) { $row = $resultStatus->fetch(); $this->users->status[$i] = new stdClass(); $this->users->status[$i]->status = $row['status']; // $resultStatus $this->users->status[$i]->number = $row['number']; // $resultStatus $query = "SELECT `fname`, `lname`, `email` FROM `users` WHERE `status` LIKE '" . $this->users->status[$i]->status . "'"; $result = db_query($query, $dbh); for ($j = 0; $j < $result->rowCount(); $j++) { $row = $result->fetch(); $this->users->status[$i]->user[$j] = new stdClass(); $this->users->status[$i]->user[$j]->fName = $row['fname']; // $result $this->users->status[$i]->user[$j]->lName = $row['lname']; // $result $this->users->status[$i]->user[$j]->email = $row['email']; // $result } } } else { $this->users = 0; } } public function UpdateUserStatus($email, $status) { $dbh = mon_db_connect(); if ($email != 'stroh@astroh.org') { if ($status == 'decline') { $command = "DELETE FROM `users` WHERE `email` LIKE '$email'"; } else { $command = "UPDATE `users` SET `status` = '$status' WHERE `email` LIKE '$email'"; } db_query_prepare($command, $dbh, array()); } } public function RemoveSource($targetName) { $dbh = mon_db_connect(); $command = "DELETE FROM `sources` WHERE `targetName`='$targetName'"; db_query_prepare($command, $dbh, array()); } public function AddUserKey($email, $key) { $dbh = mon_db_connect(); $command = "UPDATE `users` SET `key` = '$key', `logIn` = NOW() WHERE `email` LIKE '$email'"; db_query_prepare($command, $dbh, array()); } public function ChangePassword($email, $hash) { $dbh = mon_db_connect(); $command = "UPDATE `users` SET `pw`='$hash' WHERE `email` LIKE '$email'"; db_query_prepare($command, $dbh, array()); } public function ResetSDCObservation($observationID) { $dbh = sdc_db_connect(); $command = "UPDATE `observations` SET `downloaded`='no' WHERE `observationID`=$observationID"; db_query_prepare($command, $dbh, array()); } public function UpdateException($id, $status, $comments, $targetName, $observationID) { $dbh = mon_db_connect(); if ($status == 'reprocess') { $command = "DELETE FROM `observation` WHERE `targetName` LIKE '$targetName' AND `observationID` LIKE '$observationID'"; db_query_prepare($command, $dbh, array()); $command = "UPDATE `exceptions` SET `status`='closed', `comments`='" . $comments . "' WHERE `ID`='$id'"; db_query_prepare($command, $dbh, array()); //Update SDC in case their was a problem with the download $dbh = sdc_db_connect(); $command = "UPDATE `observations` SET `downloaded`='no' WHERE `observationID` LIKE '$observationID'"; db_query_prepare($command, $dbh, array()); self::ResetSDCObservation($observationID); } else { $command = "UPDATE `exceptions` SET `status`='$status', `comments`='" . $comments . "' WHERE `ID`='$id'"; db_query_prepare($command, $dbh, array()); if ($status == 'override') { $query = "SELECT `targetName`, `targetID` AS `exceptions` FROM `override_list` WHERE `exception`=$id"; $result = db_query_prepare($query, $dbh, array()); if ($result->rowCount() < 1) { $commandOverride = "INSERT INTO `override_list` (`targetName`, `targetID`, `segment`, `exception`, `comment`) VALUES "; $targetID = ltrim(substr($observationID, 0, 8), 0); if (substr($observationID, 8, 11) == '000') { $segment = 0; } else { $segment = ltrim(substr($observationID, 8, 11), 0); } $commandOverride .= "('$targetName',$targetID,$segment,$id,'" . $comments . "')"; db_query_prepare($commandOverride, $dbh, array()); } } } } public function MarkToOPrivate($too) { $dbh = mon_db_connect(); $insert = "INSERT INTO `private_ToOs` (`ID`) VALUES (?)"; db_query_prepare($insert, $dbh, array($too)); } public function ChangeReprocess($reprocess) { $dbh = mon_db_connect(); $update = "UPDATE `reprocess` SET `reprocess`=?"; db_query_prepare($update, $dbh, array($reprocess)); } public function AddUserSource($targetName, $email = false) { if ($email == false) { $email = $_SESSION['user']->email; } $dbh = mon_db_connect(); $query = "SELECT `email`, `targetName` FROM `user_defined_sources` WHERE `email` LIKE ? AND `targetName` LIKE ?"; $result = db_query_prepare($query, $dbh, array($email, '$targetName')); //If it doesn't already exist, add it to the database if ($result->rowCount() == 0) { $command = "INSERT INTO `user_defined_sources` (`email`, `targetName`) VALUES (?, ?)"; db_query_prepare($command, $dbh, array($email, $targetName)); return ''; } else { return "This target was already associated with this user account."; } } public function SourceExists($targetName) { $dbh = mon_db_connect(); $query = "SELECT COUNT(`targetName`) AS `number` FROM `sources` WHERE `targetName` LIKE ?"; $result = db_query_prepare($query, $dbh, array($targetName)); $row = $result->fetch(); if ($row['number'] == 1) { return true; } else { return false; } } public function AddNewSource($targetName, $ra, $dec, $type, $email = false) { $dbh = mon_db_connect(); $query = "SELECT `targetName` FROM `sources` WHERE `targetName` LIKE ?"; $result = db_query_prepare($query, $dbh, array($targetName)); //If it doesn't already exist, add it to the database if ($result->rowCount() == 0) { $command = "INSERT INTO `sources` (`targetName`, `RA`, `declination`, `type`) VALUES (?,?,?,?)"; $myResult = db_query_prepare($command, $dbh, array($targetName, $ra, $dec, $type)); if ($myResult) { if ($email == false) { $firstName = $_SESSION['user']->fName; $lastName = $_SESSION['user']->lName; $email = $_SESSION['user']->email; $status = $_SESSION['user']->status; } else { $queryUser = "SELECT `fname`, `lname`, `email`, `pw`, `status`, `key`, `logIn` FROM `users` WHERE `email` LIKE ?"; $resultUser = db_query_prepare($queryUser, $dbh, array($email)); $row = $resultUser->fetch(); if ($resultUser->rowCount() > 0) { $firstName = $row['fname']; // $resultUser $lastName = $row['lname']; // $resultUser $email = $row['email']; // $resultUser $status = $row['status']; // $resultUser } } switch ($type) { case 'main':$myType = 'Main List'; break; case 'public':$myType = 'Extended Public List'; break; case 'private':$myType = $lastName . "'s Private List"; break; } $email_msg = "A new target has been added to the monitoring database.\n\n"; $email_msg .= "Target Name: $targetName\n"; $email_msg .= "R.A.: $ra\n"; $email_msg .= "Dec : $dec\n"; $email_msg .= "Added To: $myType\n"; $email_msg .= "Added By: " . $_SESSION['user']->fName . " " . $_SESSION['user']->lName . "\n"; $email_msg .= "Email: $email\n\n"; $email_msg .= "Data should begin processing during the next time the automated scripts run.\n\n\n"; $email_msg .= "M.C. Stroh (automated)\n\n\n\n"; ///////////////////////////////// //Send to master list //create new smtp object $smtp = new SMTP; $smtp->do_debug = 1; # sets the amount of debug information we get //connect to the smtp server if (!$smtp->connect("email.science.psu.edu")) { echo "Error: " . $smtp->error["error"] . "\n"; } //say hello so we all know who we are $smtp->Hello(); //start the mail transaction with with the return path address $smtp->Mail(""); $smtp->Recipient($GLOBALS['masterEmail']); //send the message including headers (headers must be followed by an empty newline) $smtp->Data("Subject: New monitoring target added\n" . "From: monitoring@swift.psu.edu\n" . "To: " . $GLOBALS['masterEmail'] . "\n" . "\n" . $email_msg . "\n"); //the mail either has been sent or failed either way we are done $smtp->quit(); ///////////////////////////////// //Send to PI //create new smtp object $smtp = new SMTP; $smtp->do_debug = 1; # sets the amount of debug information we get //connect to the smtp server if (!$smtp->connect("email.science.psu.edu")) { echo "Error: " . $smtp->error["error"] . "\n"; } //say hello so we all know who we are $smtp->Hello(); //start the mail transaction with with the return path address $smtp->Mail(""); $smtp->Recipient($email); //send the message including headers (headers must be followed by an empty newline) $smtp->Data("Subject: New monitoring user request\n" . "From: monitoring@swift.psu.edu\n" . "To: $email\n" . "\n" . $email_msg . "\n"); //the mail either has been sent or failed either way we are done $smtp->quit(); } return ''; } else { return "This target was already in the source catalog. You should see the data available to you now."; } } public function Statistics() { $dbh = mon_db_connect(); $scripts = array(array('update_all_targetIDs', 'Checked for New Target IDs'), array('grab_atels.py', 'Searched for Recent ATELs'), array('monitoring_external_links.py', 'Updated External Links for Web Page'), array('sdc_update.py', 'Queried SDC for Observations'), array('download_observations', 'Downloaded Observations'), array('monitoring_pipeline.py', 'Ran xrtpipeline'), //array('monitoring_re_pipeline.py','Reran xrtpipeline for WT files'), array('createLightCurves', 'Created Light Curves'), array('plot_and_create_text_files', 'Created Output Files & Sync to Server'), array('extract_observations', 'Extracted Observations for Spectra'), ); foreach ($scripts as $key => $value) { $processQuery = "SELECT DATE_FORMAT(`start`,'%H:%i:%S %m/%d/%Y') AS `readableStart`, "; $processQuery .= "DATE_FORMAT(`stop`,'%H:%i:%S %m/%d/%Y') AS `readableStop`, `duration` "; $processQuery .= "FROM `process_logs` WHERE `script_name` LIKE ? ORDER BY `start` DESC LIMIT 1"; //echo "$processQuery
"; $procResult = db_query_prepare($processQuery, $dbh, array($value[0])); if ($procResult->rowCount() > 0) { $row = $procResult->fetch(); $this->scripts->script[$key]->description = $value[1]; $this->scripts->script[$key]->start = $row['readableStart']; // $procResult $this->scripts->script[$key]->stop = $row['readableStop']; // $procResult $this->scripts->script[$key]->duration = $row['duration']; // $procResult } } //First we want to screen out which observations have been added to the override list so that we don't non-processed items for them as errors $preQuery = "SELECT `targetID`, `segment` FROM `override_list` ORDER BY `targetID`, `segment`"; $preResult = db_query($preQuery, $dbh); $observationIDs = ''; if ($preResult->rowCount() > 0) { for ($i = 0; $i < $preResult->rowCount(); $i++) { $row = $preResult->fetch(); $targetID = $row['targetID']; // $preResult $segment = $row['segment']; // $preResult $observationID = str_repeat('0', 8 - strlen($targetID)) . $targetID . str_repeat('0', 3 - strlen($segment)) . $segment; //Add to list if ($observationIDs != '') { $observationIDs .= ', '; } $observationIDs .= "'$observationID'"; } } $query = "SELECT (SELECT COUNT(`targetName`) FROM `sources`) AS 'number_sources', "; $query .= "(SELECT COUNT(`targetName`) FROM `sources` WHERE `type`='main') AS 'number_sources_main', "; $query .= "(SELECT COUNT(`targetName`) FROM `sources` WHERE `type`='public') AS 'number_sources_public', "; $query .= "(SELECT COUNT(`targetName`) FROM `sources` WHERE `type`='private') AS 'number_sources_private', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation`) AS 'number_observations', "; $query .= "(SELECT COUNT(DISTINCT(`targetID`)) FROM `targetID`) AS 'number_targetIDs', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='no' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_download_no', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='yes') AS 'number_observations_download_yes', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='yes' AND `pipeline`='no' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_pipeline_no', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='yes' AND `pipeline`='error') AS 'number_observations_pipeline_error', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='yes' AND `pipeline`='yes') AS 'number_observations_pipeline_yes', "; /*Disabled due to xrtgrblc fixes $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='yes' AND `pipeline`='yes' AND `re_pipeline`='no' AND `wtevents`>0 AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_re_pipeline_no', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='yes' AND `pipeline`='yes' AND `re_pipeline`='error') AS 'number_observations_re_pipeline_error', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `downloaded`='yes' AND `pipeline`='yes' AND `re_pipeline`='yes') AS 'number_observations_re_pipeline_yes', "; */ $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `pipeline`='yes' AND `xrtgrblc_commands`='no' AND (`observation`.`wtevents`>0 OR `observation`.`pcevents`>0) AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_waiting', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `pipeline`='yes' AND `xrtgrblc_commands`='yes' AND (`observation`.`wtevents`>0 OR `observation`.`pcevents`>0) AND `xrtgrblc`='no' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_no', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `pipeline`='yes' AND `xrtgrblc_commands`='yes' AND (`observation`.`wtevents`>0 OR `observation`.`pcevents`>0) AND `xrtgrblc`='error' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_error', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `pipeline`='yes' AND `xrtgrblc_commands`='yes' AND (`observation`.`wtevents`>0 OR `observation`.`pcevents`>0) AND `xrtgrblc`='yes' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_yes', "; $query .= "(SELECT COUNT(`ID`) FROM `xrtgrblc_commands` WHERE `processed`='no') AS 'number_jobs_no', "; $query .= "(SELECT COUNT(`ID`) FROM `xrtgrblc_commands` WHERE `processed`='error') AS 'number_jobs_error', "; $query .= "(SELECT COUNT(`ID`) FROM `xrtgrblc_commands` WHERE `processed`='yes') AS 'number_jobs_yes', "; //Snapshot binning LC info $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `xrtgrblc`='yes' AND `xrtgrblc_snapshot_commands`='no' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_snapshot_waiting', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `xrtgrblc`='yes' AND `xrtgrblc_snapshot_commands`='yes' AND `xrtgrblc_snapshot`='no' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_snapshot_no', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `xrtgrblc`='yes' AND `xrtgrblc_snapshot_commands`='yes' AND `xrtgrblc_snapshot`='error' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_snapshot_error', "; $query .= "(SELECT COUNT(`targetName`) FROM `observation` WHERE `xrtgrblc`='yes' AND `xrtgrblc_snapshot_commands`='yes' AND `xrtgrblc_snapshot`='yes' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_snapshot_yes', "; $query .= "(SELECT COUNT(`ID`) FROM `xrtgrblc_snapshot_commands` WHERE `processed`='no') AS 'number_snapshot_jobs_no', "; $query .= "(SELECT COUNT(`ID`) FROM `xrtgrblc_snapshot_commands` WHERE `processed`='error') AS 'number_snapshot_jobs_error', "; $query .= "(SELECT COUNT(`ID`) FROM `xrtgrblc_snapshot_commands` WHERE `processed`='yes') AS 'number_snapshot_jobs_yes', "; //Plotted targets $query .= "(SELECT COUNT(`targetName`) FROM `sources` WHERE `plot`='no') AS 'number_sources_plot_no', "; $query .= "(SELECT COUNT(`targetName`) FROM `sources` WHERE `plot`='yes') AS 'number_sources_plot_yes', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `plot`='no' AND `xrtgrblc_commands`='yes' AND `xrtgrblc`='yes') AS 'number_observations_plot_no', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `plot`='yes' AND `xrtgrblc_commands`='yes' AND `xrtgrblc`='yes') AS 'number_observations_plot_yes', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `extract`='no' AND `xrtgrblc_commands`='yes' AND `xrtgrblc`='yes' AND `detection`='yes') AS 'number_observations_extract_no', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `extract`='yes' AND `xrtgrblc_commands`='yes' AND `xrtgrblc`='yes') AS 'number_observations_extract_yes', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `extract`='error' AND `xrtgrblc_commands`='yes' AND `xrtgrblc`='yes') AS 'number_observations_extract_error', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `spec`='no' AND `extract`='yes' AND `observation`.`observed` IS NOT NULL) AS 'number_observations_spec_no', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `spec`='yes' AND `extract`='yes' AND `observation`.`observed` IS NOT NULL) AS 'number_observations_spec_yes', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `spec`='error' AND `extract`='yes' AND `observation`.`observed` IS NOT NULL) AS 'number_observations_spec_error', "; $query .= "(SELECT SUM(`wttime`) FROM `observation`) AS 'total_time_wt', "; $query .= "(SELECT SUM(`wtsnapshots`) FROM `observation`) AS 'total_snapshots_wt', "; $query .= "(SELECT SUM(`wtevents`) FROM `observation`) AS 'total_events_wt', "; $query .= "(SELECT SUM(`pctime`) FROM `observation`) AS 'total_time_pc', "; $query .= "(SELECT SUM(`pcsnapshots`) FROM `observation`) AS 'total_snapshots_pc', "; $query .= "(SELECT SUM(`pcevents`) FROM `observation`) AS 'total_events_pc', "; $query .= "(SELECT COUNT(`ID`) FROM `exceptions` WHERE `status`='open') AS 'number_open_exceptions', "; $query .= "(SELECT COUNT(`ID`) FROM `exceptions` WHERE `status`='closed') AS 'number_closed_exceptions', "; $query .= "(SELECT COUNT(`ID`) FROM `exceptions` WHERE `status`='bug') AS 'number_bug_exceptions', "; $query .= "(SELECT COUNT(`observationID`) FROM `observation` WHERE `datepipeline`<=(SELECT `reprocess` FROM `reprocess`) AND `pipeline`='yes') AS 'number_left_for_reprocessing' "; //echo "SELECT COUNT(`targetName`) FROM `observation` WHERE `pipeline`='yes' AND `xrtgrblc_commands`='no' AND `observationID` NOT IN ($observationIDs)) AS 'number_observations_xrtgrblc_no' "; $result = db_query($query, $dbh); if ($result->rowCount() > 0) { $row = $result->fetch(); $this->statistics->sources->number = number_format($row['number_sources'], 0, '', ','); // $result $this->statistics->sources->main->number = number_format($row['number_sources_main'], 0, '', ','); // $result $this->statistics->sources->public->number = number_format($row['number_sources_public'], 0, '', ','); // $result $this->statistics->sources->private->number = number_format($row['number_sources_private'], 0, '', ','); // $result $this->statistics->targetIDs->number = number_format($row['number_targetIDs'], 0, '', ','); // $result $this->statistics->observations->number = number_format($row['number_observations'], 0, '', ','); // $result $this->statistics->observations->download->no->number = number_format($row['number_observations_download_no'], 0, '', ','); // $result $this->statistics->observations->download->yes->number = number_format($row['number_observations_download_yes'], 0, '', ','); // $result $this->statistics->observations->pipeline->no->number = number_format($row['number_observations_pipeline_no'], 0, '', ','); // $result $this->statistics->observations->pipeline->error->number = number_format($row['number_observations_pipeline_error'], 0, '', ','); // $result $this->statistics->observations->pipeline->yes->number = number_format($row['number_observations_pipeline_yes'], 0, '', ','); // $result /* $this->statistics->observations->re_pipeline->no->number = number_format($row['number_observations_re_pipeline_no'],0,'',','); // $result $this->statistics->observations->re_pipeline->error->number = number_format($row['number_observations_re_pipeline_error'],0,'',','); // $result $this->statistics->observations->re_pipeline->yes->number = number_format($row['number_observations_re_pipeline_yes'],0,'',','); // $result */ //Reprocessing $this->statistics->observations->reprocessing->number = number_format($row['number_left_for_reprocessing'], 0, '', ','); // $result $this->statistics->observations->xrtgrblc->waiting->number = number_format($row['number_observations_xrtgrblc_waiting'], 0, '', ','); // $result $this->statistics->observations->xrtgrblc->no->number = number_format($row['number_observations_xrtgrblc_no'], 0, '', ','); // $result $this->statistics->observations->xrtgrblc->error->number = number_format($row['number_observations_xrtgrblc_error'], 0, '', ','); // $result $this->statistics->observations->xrtgrblc->yes->number = number_format($row['number_observations_xrtgrblc_yes'], 0, '', ','); // $result $this->statistics->jobs->no->number = number_format($row['number_jobs_no'], 0, '', ','); // $result $this->statistics->jobs->yes->number = number_format($row['number_jobs_yes'], 0, '', ','); // $result $this->statistics->jobs->error->number = number_format($row['number_jobs_error'], 0, '', ','); // $result //Snapshot binning LC info $this->statistics->observations->xrtgrblc_snapshot->waiting->number = number_format($row['number_observations_xrtgrblc_snapshot_waiting'], 0, '', ','); // $result $this->statistics->observations->xrtgrblc_snapshot->no->number = number_format($row['number_observations_xrtgrblc_snapshot_no'], 0, '', ','); // $result $this->statistics->observations->xrtgrblc_snapshot->error->number = number_format($row['number_observations_xrtgrblc_snapshot_error'], 0, '', ','); // $result $this->statistics->observations->xrtgrblc_snapshot->yes->number = number_format($row['number_observations_xrtgrblc_snapshot_yes'], 0, '', ','); // $result $this->statistics->snapshot_jobs->no->number = number_format($row['number_snapshot_jobs_no'], 0, '', ','); // $result $this->statistics->snapshot_jobs->yes->number = number_format($row['number_snapshot_jobs_yes'], 0, '', ','); // $result $this->statistics->snapshot_jobs->error->number = number_format($row['number_snapshot_jobs_error'], 0, '', ','); // $result $this->statistics->observations->extract->no = number_format($row['number_observations_extract_no'], 0, '', ','); // $result $this->statistics->observations->extract->yes = number_format($row['number_observations_extract_yes'], 0, '', ','); // $result $this->statistics->observations->extract->error = number_format($row['number_observations_extract_error'], 0, '', ','); // $result $this->statistics->observations->spec->no = number_format($row['number_observations_spec_no'], 0, '', ','); // $result $this->statistics->observations->spec->yes = number_format($row['number_observations_spec_yes'], 0, '', ','); // $result $this->statistics->observations->spec->error = number_format($row['number_observations_spec_error'], 0, '', ','); // $result $this->statistics->plot->observations->no->number = number_format($row['number_observations_plot_no'], 0, '', ','); // $result $this->statistics->plot->observations->yes->number = number_format($row['number_observations_plot_yes'], 0, '', ','); // $result $this->statistics->plot->sources->no->number = number_format($row['number_sources_plot_no'], 0, '', ','); // $result $this->statistics->plot->sources->yes->number = number_format($row['number_sources_plot_yes'], 0, '', ','); // $result $this->statistics->observations->wt->time = $row['total_time_wt']; // $result $this->statistics->observations->wt->snapshots = $row['total_snapshots_wt']; // $result $this->statistics->observations->wt->events = $row['total_events_wt']; // $result $this->statistics->observations->pc->time = $row['total_time_pc']; // $result $this->statistics->observations->pc->snapshots = $row['total_snapshots_pc']; // $result $this->statistics->observations->pc->events = $row['total_events_pc']; // $result //Exceptions $this->statistics->exceptions->open = number_format($row['number_open_exceptions'], 0, '', ','); // $result $this->statistics->exceptions->closed = number_format($row['number_closed_exceptions'], 0, '', ','); // $result $this->statistics->exceptions->bug = number_format($row['number_bug_exceptions'], 0, '', ','); // $result } } public function Reprocess() { $dbh = mon_db_connect(); $query = "SELECT `reprocess` FROM `reprocess`"; $result = db_query($query, $dbh); if ($result->rowCount() > 0) { $row = $result->fetch(); $this->reprocess->date = $row['reprocess']; // $result } else { $this->reprocess->date = ''; } } public function LightCurve($targetName, $type = 'standard') { $dbh = mon_db_connect(); $query = "SELECT `light_curve_bins`.`xrtgrblc_ID`, `light_curve_bins`.`mode`, "; $query .= "`light_curve_bins`.`time`, `light_curve_bins`.`xax_e`, `light_curve_bins`.`timeDel`, `light_curve_bins`.`fracExp`, "; $query .= "`light_curve_bins`.`rateNet`, `light_curve_bins`.`errorNet`, "; $query .= "`light_curve_bins`.`rateCor`, `light_curve_bins`.`errorCor`, "; $query .= "`light_curve_bins`.`rateRaw`, `light_curve_bins`.`errorRaw`, "; $query .= "`light_curve_bins`.`rateBkg`, `light_curve_bins`.`errorBkg`, "; $query .= "`light_curve_bins`.`rateFlux`, `light_curve_bins`.`errorFlux` FROM `xrtgrblc_commands` "; $query .= "JOIN `light_curve_bins` ON (`xrtgrblc_commands`.`ID` LIKE `light_curve_bins`.`xrtgrblc_ID`) "; $query .= "WHERE `xrtgrblc_commands`.`processed` LIKE 'yes' AND "; $query .= "`xrtgrblc_commands`.`targetName` LIKE '$targetName' AND "; $query .= "`xrtgrblc_commands`.`type` LIKE '$type' "; $query .= "ORDER BY `light_curve_bins`.`time`"; $result = db_query_prepare($query, $dbh, array()); //echo $result->rowCount(); $metToUnixEpoch = date("U", mktime(0, 0, 0, 1, 1, 2001)); $mjdUnixEpoch = 40587.; if ($result->rowCount() > 0) { for ($i = 0; $i < $result->rowCount(); $i++) { $row = $result->fetch(); $this->lightcurve[$i]->ID = $row['xrtgrblc_ID']; // $result $this->lightcurve[$i]->mode = $row['mode']; // $result $this->lightcurve[$i]->time->MET = $row['time']; // $result $this->lightcurve[$i]->time->MJD = ($row['time'] + $metToUnixEpoch) / 86400. + $mjdUnixEpoch; $this->lightcurve[$i]->xax_e->seconds = $row['xax_e']; // $result $this->lightcurve[$i]->xax_e->days = $row['xax_e'] / 86400.; $this->lightcurve[$i]->timeDel->seconds = $row['timeDel']; // $result $this->lightcurve[$i]->timeDel->days = $row['timeDel'] / 86400.; $this->lightcurve[$i]->fracExp = $row['fracExp']; // $result $this->lightcurve[$i]->rateNet = $row['rateNet']; // $result $this->lightcurve[$i]->errorNet = $row['errorNet']; // $result $this->lightcurve[$i]->rateCor = $row['rateCor']; // $result $this->lightcurve[$i]->errorCor = $row['errorCor']; // $result $this->lightcurve[$i]->rateRaw = $row['rateRaw']; // $result $this->lightcurve[$i]->errorRaw = $row['errorRaw']; // $result $this->lightcurve[$i]->rateBkg = $row['rateBkg']; // $result $this->lightcurve[$i]->errorBkg = $row['errorBkg']; // $result $this->lightcurve[$i]->rateFlux = $row['rateFlux']; // $result $this->lightcurve[$i]->errorFlux = $row['errorFlux']; // $result } } else { $this->lightcurve = 0; } } public function SDCLastModified() { $dbh = sdc_db_connect(); $query = "SELECT DATE_FORMAT(MAX(`modified`),'%H:%i:%S %m/%d/%Y') AS `modified`, "; $query .= "IF(DATE_ADD(NOW(), INTERVAL 1 DAY)rowCount() > 0) { $row = $result->fetch(); $this->sdc->lastUpdated = $row['modified']; // $result switch ($row['old']) { case '0':$this->sdc->old = false; $this->sdc->color = '#0c0'; break; case '1':$this->sdc->old = true; $this->sdc->color = '#c00'; break; } } } public function SourcesInfo($type = 'main') { //Offset since server thinks we're in UTC $timeOffset = -1 * date('Z'); $dbh = mon_db_connect(); //Grab source information from the database $query = "SELECT `sources`.`targetName`, `sources`.`folder`, `sources`.`RA`, `sources`.`declination`, `sources`.`type`, `sources`.`fractionalVariabilitySingleBin`, `sources`.`fractionalVariabilityStandard`, "; $query .= "`sources`.`meanSingleBin`, `sources`.`errorMeanSingleBin`, `sources`.`minimumSingleBin`, `sources`.`errorMinimumSingleBin`, `sources`.`maximumSingleBin`, `sources`.`errorMaximumSingleBin`, "; $query .= "ROUND(SUM(`site`.`exposureTime`)) AS `exposureTime`, "; $query .= "DATE_FORMAT(MAX(`site`.`observed`),'%M %D, %Y') AS `lastObserved`, "; $query .= "`sources`.`countsToFluxConversionFactor`, `sources`.`errorCountsToFluxConversionFactor` "; $query .= "FROM "; $query .= "`site` LEFT OUTER JOIN `sources` ON "; $query .= "(`sources`.`targetName`=`site`.`targetName`) "; if ($type != 'main' && $type != 'public' && $type != 'private') { $query .= "JOIN `user_defined_sources` ON (`user_defined_sources`.`targetName` LIKE `sources`.`targetName`) "; } $query .= "WHERE "; $query .= "(`sources`.`new` LIKE 'no' OR `sources`.`plot` LIKE 'yes') AND "; if ($type != 'main' && $type != 'public' && $type != 'private') { $query .= "`user_defined_sources`.`email` LIKE '$type' "; } else { $query .= "`sources`.`type` LIKE '$type' "; } $query .= "GROUP BY `sources`.`targetName` "; $query .= "ORDER BY `sources`.`RA`"; $result = db_query($query, $dbh); if ($result->rowCount() > 0) { for ($i = 0; $i < $result->rowCount(); $i++) { $row = $result->fetch(); $this->source[$i] = new stdClass(); $this->source[$i]->targetName = $row['targetName']; // $result $this->source[$i]->folder = $row['folder']; // $result $this->source[$i]->lastObserved = $row['lastObserved']; // $result $this->source[$i]->exposureTime = $row['exposureTime']; // $result $this->source[$i]->type = $row['type']; // $result $this->source[$i]->fracVar = new stdClass(); $this->source[$i]->fracVar->singleBin = $row['fractionalVariabilitySingleBin']; // $result $this->source[$i]->fracVar->standard = $row['fractionalVariabilityStandard']; // $result $this->source[$i]->countsToFluxConversionFactor = $row['countsToFluxConversionFactor']; // $result $this->source[$i]->errorCountsToFluxConversionFactor = $row['errorCountsToFluxConversionFactor']; // $result $this->source[$i]->RA = $row['RA']; // $result if (is_numeric($this->source[$i]->countsToFluxConversionFactor)) { $fitQuery = "SELECT `start`, `stop`, `rateCor`, `errorCor`, `convFactor`, `errorConvFactor`, "; $fitQuery .= "`mode`, `counts`, `bins`, `degrees_of_freedom`, `statistic_type`, `statistic_value`, "; $fitQuery .= "`unabsorbed_flux`, `positive_error_unabsorbed_flux`, `negative_error_unabsorbed_flux` "; $fitQuery .= "FROM `sources_spectral_fits` WHERE `targetName` LIKE '" . $this->source[$i]->targetName . "' ORDER BY `mode` DESC, `start` ASC"; $fitResult = db_query($fitQuery, $dbh); if ($fitResult->rowCount() > 0) { for ($j = 0; $j < $fitResult->rowCount(); $j++) { $frow = $fitResult->fetch(); $this->source[$i]->fit[$j]->start = $frow['start']; // $fitResult $this->source[$i]->fit[$j]->stop = $frow['stop']; // $fitResult $this->source[$i]->fit[$j]->mode = $frow['mode']; // $fitResult $this->source[$i]->fit[$j]->statistic_value = $frow['statistic_value']; // $fitResult $this->source[$i]->fit[$j]->dof = $frow['degrees_of_freedom']; // $fitResult $this->source[$i]->fit[$j]->unabsorbed_flux = $frow['unabsorbed_flux']; // $fitResult $this->source[$i]->fit[$j]->positive_error_unabsorbed_flux = $frow['positive_error_unabsorbed_flux']; // $fitResult $this->source[$i]->fit[$j]->negative_error_unabsorbed_flux = $frow['negative_error_unabsorbed_flux']; // $fitResult } } $this->source[$i]->nFits = $fitResult->rowCount(); } $testRA = $this->source[$i]->RA * 24 / 360.; $RA[0] = floor($testRA); $testRA1 = $testRA - $RA[0]; $RA[1] = floor(60. * ($testRA1)); $testRA2 = $testRA1 - $RA[1] / 60.; $RA[2] = round(3600. * ($testRA2)); $sexagesimalRA = ''; for ($j = 0; $j < 3; $j++) { if ($RA[$j] == 0) { $RA[$j] = '00'; } if (strlen($RA[$j]) < 2) { $sexagesimalRA .= "0"; } $sexagesimalRA .= $RA[$j]; if ($j != 2) { $sexagesimalRA .= " "; } } $this->source[$i]->sexRA = $sexagesimalRA; $this->source[$i]->declination = $row['declination']; // $result $testDec = abs($this->source[$i]->declination); $declination[0] = floor($testDec); $testDec1 = $testDec - $declination[0]; $declination[1] = floor(60. * ($testDec1)); $testDec2 = $testDec1 - $declination[1] / 60.; $declination[2] = round(3600. * ($testDec2)); if ($this->source[$i]->declination < 0) { $sexagesimalDec = '-'; } else { $sexagesimalDec = '+'; } for ($j = 0; $j < 3; $j++) { if (strlen($declination[$j]) < 2) { $sexagesimalDec .= "0"; } $sexagesimalDec .= $declination[$j]; if ($j != 2) { $sexagesimalDec .= " "; } } $this->source[$i]->sexDeclination = $sexagesimalDec; $this->source[$i]->meanRate = $row['meanSingleBin']; // $result $this->source[$i]->errorMeanRate = $row['errorMeanSingleBin']; // $result $this->source[$i]->minimumRate = $row['minimumSingleBin']; // $result $this->source[$i]->errorMinimumRate = $row['errorMinimumSingleBin']; // $result $this->source[$i]->maximumRate = $row['maximumSingleBin']; // $result $this->source[$i]->errorMaximumRate = $row['errorMaximumSingleBin']; // $result } } else { unset($this->source); } } public function SourcesInfoPaper($type = 'main') { //Offset since server thinks we're in UTC $timeOffset = -1 * date('Z'); $dbh = mon_db_connect(); //Grab source information from the database $query = "SELECT `sources`.`targetName`, `sources`.`folder`, `sources`.`RA`, `sources`.`declination`, `sources`.`type`, `sources`.`fractionalVariabilitySingleBin`, `sources`.`fractionalVariabilityStandard`, "; $query .= "`sources`.`errorFractionalVariabilitySingleBin`, `sources`.`errorFractionalVariabilityStandard`, "; $query .= "`sources`.`meanSingleBin`, `sources`.`errorMeanSingleBin`, `sources`.`minimumSingleBin`, `sources`.`errorMinimumSingleBin`, `sources`.`maximumSingleBin`, `sources`.`errorMaximumSingleBin`, "; $query .= "ROUND(SUM(`light_curve_bins`.`timeDel`*`light_curve_bins`.`fracExp`)/1000.) AS `exposureTime`, "; $query .= "FROM_UNIXTIME((MAX(`light_curve_bins`.`time`-`light_curve_bins`.`xax_e`)+UNIX_TIMESTAMP('2001-01-01'))+" . $timeOffset . ",'%M %D, %Y') AS `lastObserved`, "; $query .= "`sources`.`countsToFluxConversionFactor`, `sources`.`errorCountsToFluxConversionFactor` "; $query .= "FROM "; $query .= "`light_curve_bins` LEFT OUTER JOIN `xrtgrblc_commands` ON "; $query .= "(`xrtgrblc_commands`.`ID`=`light_curve_bins`.`xrtgrblc_ID`) JOIN `sources` "; $query .= "ON (`sources`.`targetName`=`xrtgrblc_commands`.`targetName`) "; if ($type != 'main' && $type != 'public' && $type != 'private') { $query .= "JOIN `user_defined_sources` ON (`user_defined_sources`.`targetName` LIKE `sources`.`targetName`) "; } $query .= "WHERE `xrtgrblc_commands`.`type` LIKE 'single bin' AND `light_curve_bins`.`rateCor`>0 AND (`light_curve_bins`.`rateCor`>`light_curve_bins`.`errorCor` OR `light_curve_bins`.`errorCor` IS NULL) AND `light_curve_bins`.`mode_switching` LIKE 'no' AND "; $query .= "(`sources`.`new` LIKE 'no' OR `sources`.`plot` LIKE 'yes') AND "; if ($type != 'main' && $type != 'public' && $type != 'private') { $query .= "`user_defined_sources`.`email` LIKE '$type' "; } else { $query .= "`sources`.`type` LIKE '$type' "; } //Filter out observations after August 31st, 2012 $query .= "AND `light_curve_bins`.`time`<368150403 "; $query .= "GROUP BY `sources`.`targetName` "; $query .= "ORDER BY `sources`.`RA`"; $result = db_query($query, $dbh); if ($result->rowCount() > 0) { for ($i = 0; $i < $result->rowCount(); $i++) { $row = $result->fetch(); $this->source[$i]->targetName = $row['targetName']; // $result $this->source[$i]->folder = $row['folder']; // $result $this->source[$i]->lastObserved = $row['lastObserved']; // $result $this->source[$i]->exposureTime = $row['exposureTime']; // $result $this->source[$i]->type = $row['type']; // $result $this->source[$i]->fracVar->singleBin = $row['fractionalVariabilitySingleBin']; // $result $this->source[$i]->fracVar->errorSingleBin = $row['errorFractionalVariabilitySingleBin']; // $result $this->source[$i]->fracVar->standard = $row['fractionalVariabilityStandard']; // $result $this->source[$i]->fracVar->errorStandard = $row['errorFractionalVariabilityStandard']; // $result $this->source[$i]->countsToFluxConversionFactor = $row['countsToFluxConversionFactor']; // $result $this->source[$i]->errorCountsToFluxConversionFactor = $row['errorCountsToFluxConversionFactor']; // $result $this->source[$i]->RA = $row['RA']; // $result if (is_numeric($this->source[$i]->countsToFluxConversionFactor)) { $fitQuery = "SELECT `start`, `stop`, `rateCor`, `errorCor`, `convFactor`, `errorConvFactor`, "; $fitQuery .= "`mode`, `counts`, `bins`, `degrees_of_freedom`, `statistic_type`, `statistic_value`, "; $fitQuery .= "`unabsorbed_flux`, `positive_error_unabsorbed_flux`, `negative_error_unabsorbed_flux` "; $fitQuery .= "FROM `sources_spectral_fits` WHERE `targetName` LIKE '" . $this->source[$i]->targetName . "' ORDER BY `mode` DESC, `start` ASC"; $fitResult = db_query($fitQuery, $dbh); if ($fitResult->rowCount() > 0) { for ($j = 0; $j < $fitResult->rowCount(); $j++) { $frow = $fitResult->fetch(); $this->source[$i]->fit[$j]->start = $frow['start']; // $fitResult $this->source[$i]->fit[$j]->stop = $frow['stop']; // $fitResult $this->source[$i]->fit[$j]->mode = $frow['mode']; // $fitResult $this->source[$i]->fit[$j]->statistic_value = $frow['statistic_value']; // $fitResult $this->source[$i]->fit[$j]->dof = $frow['degrees_of_freedom']; // $fitResult $this->source[$i]->fit[$j]->unabsorbed_flux = $frow['unabsorbed_flux']; // $fitResult $this->source[$i]->fit[$j]->positive_error_unabsorbed_flux = $frow['positive_error_unabsorbed_flux']; // $fitResult $this->source[$i]->fit[$j]->negative_error_unabsorbed_flux = $frow['negative_error_unabsorbed_flux']; // $fitResult } } $this->source[$i]->nFits = $fitResult->rowCount(); } $testRA = $this->source[$i]->RA * 24 / 360.; $RA[0] = floor($testRA); $testRA1 = $testRA - $RA[0]; $RA[1] = floor(60. * ($testRA1)); $testRA2 = $testRA1 - $RA[1] / 60.; $RA[2] = round(3600. * ($testRA2)); $sexagesimalRA = ''; for ($j = 0; $j < 3; $j++) { if ($RA[$j] == 0) { $RA[$j] = '00'; } if (strlen($RA[$j]) < 2) { $sexagesimalRA .= "0"; } $sexagesimalRA .= $RA[$j]; if ($j != 2) { $sexagesimalRA .= " "; } } $this->source[$i]->sexRA = $sexagesimalRA; $this->source[$i]->declination = $row['declination']; // $result $testDec = abs($this->source[$i]->declination); $declination[0] = floor($testDec); $testDec1 = $testDec - $declination[0]; $declination[1] = floor(60. * ($testDec1)); $testDec2 = $testDec1 - $declination[1] / 60.; $declination[2] = round(3600. * ($testDec2)); if ($this->source[$i]->declination < 0) { $sexagesimalDec = '-'; } else { $sexagesimalDec = '+'; } for ($j = 0; $j < 3; $j++) { if (strlen($declination[$j]) < 2) { $sexagesimalDec .= "0"; } $sexagesimalDec .= $declination[$j]; if ($j != 2) { $sexagesimalDec .= " "; } } $this->source[$i]->sexDeclination = $sexagesimalDec; $this->source[$i]->meanRate = $row['meanSingleBin']; // $result $this->source[$i]->errorMeanRate = $row['errorMeanSingleBin']; // $result $this->source[$i]->minimumRate = $row['minimumSingleBin']; // $result $this->source[$i]->errorMinimumRate = $row['errorMinimumSingleBin']; // $result $this->source[$i]->maximumRate = $row['maximumSingleBin']; // $result $this->source[$i]->errorMaximumRate = $row['errorMaximumSingleBin']; // $result } } else { unset($this->source); } } public function SourcePlots($target) { //Grab list of sources already in the database -- do this to protect against SQL injection self::GetAllSourceNames(); //See if user input is in the list if (in_array($target, $this->allTargetNames->htmlTargetNames)) { $target = $this->allTargetNames->targetNames[array_search($target, $this->allTargetNames->htmlTargetNames)]; //Connect to the database and get the folder where the information resides $dbh = mon_db_connect(); $query = "SELECT `targetName`, `type`, `folder` FROM `sources` "; //$query .= "WHERE REPLACE(REPLACE(`targetName`,' ',''),'+',' ') LIKE '".$target."'"; - OLD, changed due to potential for SQL injection $query .= "WHERE `targetName` LIKE '$target'"; $result = db_query_prepare($query, $dbh, array()); //Make sure a valid source was given if ($result->rowCount() > 0) { $row = $result->fetch(); $this->plot = new stdClass(); $this->plot->targetName = $row['targetName']; // $result $this->plot->folder = $row['folder']; // $result $this->plot->type = $row['type']; // $result $queryObs = "SELECT `observationID`, DATE_FORMAT(`observed`,'%M %D, %Y') AS `observedFormatted` FROM `site` "; $queryObs .= "WHERE `targetName` LIKE '" . $this->plot->targetName . "' AND "; $queryObs .= "`observed` IS NOT NULL ORDER BY `observed` DESC"; $resObs = db_query($queryObs, $dbh); $querySpec = "SELECT `observationID`, UPPER(`mode`) AS `mode`, `counts`, `grpmin`, `bins`, `degrees_of_freedom`, `statistic_type`, `statistic_value`, "; $querySpec .= "`nH`, `positive_error_nH`, `negative_error_nH`, "; $querySpec .= "`photon_index`, `positive_error_photon_index`, `negative_error_photon_index`, "; $querySpec .= "`normalization`, `positive_error_normalization`, `negative_error_normalization`, "; $querySpec .= "`flux`, `positive_error_flux`, `negative_error_flux`, "; $querySpec .= "`unabsorbed_flux`, `positive_error_unabsorbed_flux`, `negative_error_unabsorbed_flux` "; $querySpec .= "FROM `spectral_fits` WHERE `targetName` LIKE '" . $this->plot->targetName . "' "; $resSpec = db_query($querySpec, $dbh); //Initialize arrays containing information for later proper mapping $wtKeys = array(); $pcKeys = array(); if ($resSpec->rowCount() > 0) { for ($i = 0; $i < $resSpec->rowCount(); $i++) { $tempObsID = $row['observationID']; // $resSpec $tempMode = $row['mode']; // $resSpec switch ($tempMode) { case 'WT':$wtKeys[$tempObsID] = $i; break; case 'PC':$pcKeys[$tempObsID] = $i; break; } } } if ($resObs->rowCount() > 0) { for ($i = 0; $i < $resObs->rowCount(); $i++) { $row = $resObs->fetch(); $this->plot->observation[$i] = new stdClass(); $this->plot->observation[$i]->observationID = $row['observationID']; // $resObs $this->plot->observation[$i]->observed = $row['observedFormatted']; // $resObs $tempObsID = $this->plot->observation[$i]->observationID; $myModes = array('wt', 'pc'); for ($m = 0; $m < count($myModes); $m++) { unset($temp); //Clear this out so we don't pass on old info if ($myModes[$m] == 'wt') { $modeKeys = $wtKeys; } else { $modeKeys = $pcKeys; } if (array_key_exists($tempObsID, $modeKeys)) { $temp = new stdClass(); $temp->observationID = $row['observationID']; // $resSpec $temp->mode = $row['mode']; // $resSpec $temp->counts = $row['counts']; // $resSpec $temp->grpmin = $row['grpmin']; // $resSpec $temp->bins = $row['bins']; // $resSpec $temp->degrees_of_freedom = $row['degrees_of_freedom']; // $resSpec $temp->statistic_type = $row['statistic_type']; // $resSpec $temp->statistic_value = rtrim($row['statistic_value'], '0'); // $resSpec $temp->nH = $row['nH']; // $resSpec $temp->positive_error_nH = $row['positive_error_nH']; // $resSpec $temp->negative_error_nH = $row['negative_error_nH']; // $resSpec $temp->photon_index = $row['photon_index']; // $resSpec $temp->positive_error_photon_index = $row['positive_error_photon_index']; // $resSpec $temp->negative_error_photon_index = $row['negative_error_photon_index']; // $resSpec $temp->normalization = $row['normalization']; // $resSpec $temp->positive_error_normalization = $row['positive_error_normalization']; // $resSpec $temp->negative_error_normalization = $row['negative_error_normalization']; // $resSpec $temp->flux = $row['flux']; // $resSpec $temp->positive_error_flux = $row['positive_error_flux']; // $resSpec $temp->negative_error_flux = $row['negative_error_flux']; // $resSpec $temp->unabsorbed_flux = $row['unabsorbed_flux']; // $resSpec $temp->positive_error_unabsorbed_flux = $row['positive_error_unabsorbed_flux']; // $resSpec $temp->negative_error_unabsorbed_flux = $row['negative_error_unabsorbed_flux']; // $resSpec if ($myModes[$m] == 'wt') { $this->plot->observation[$i]->wt = $temp; } else { $this->plot->observation[$i]->pc = $temp; } } } } } else { unset($this->plot->observationID); } } else { unset($this->plot); } } else { unset($this->plot); } } public function GetExternalLinks($targetName) { //Connect to the database and get the list of links associated with that source $dbh = mon_db_connect(); $query = "SELECT `site`, `link` FROM `external_links` WHERE `targetName` LIKE '$targetName'"; $result = db_query_prepare($query, $dbh, array()); if ($result->rowCount() > 0) { for ($i = 0; $i < $result->rowCount(); $i++) { $row = $result->fetch(); $this->externalLinks[$i] = new stdClass(); $this->externalLinks[$i]->site = preg_replace('/Fermi/', 'Fermi', preg_replace('/Swift/', 'Swift', $row['site'])); // $result $this->externalLinks[$i]->link = $row['link']; // $result } } else { unset($this->externalLinks); } } public function GetSourceSpectralFit($targetName) { //Connect to the database and get the spectral fit parameters $dbh = mon_db_connect(); //Grab spectral fit parameters for individual modes $query = "SELECT `start`, `stop`, `rateCor`, `errorCor`, `convFactor`, `errorConvFactor`, `mode`, "; $query .= "`counts`, `bins`, `degrees_of_freedom`, `statistic_type`, `statistic_value`, "; $query .= "`nH`, `positive_error_nH`, `negative_error_nH`, "; $query .= "`photon_index`, `positive_error_photon_index`, `negative_error_photon_index`, "; $query .= "`unabsorbed_flux`, `positive_error_unabsorbed_flux`, `negative_error_unabsorbed_flux`"; $query .= "FROM `sources_spectral_fits` WHERE `targetName` LIKE '$targetName' ORDER BY `mode` ASC, `start` ASC"; $result = db_query_prepare($query, $dbh, array()); if ($result->rowCount() > 0) { for ($i = 0; $i < $result->rowCount(); $i++) { $row = $result->fetch(); $mode = $row['mode']; // $result $start = $row['start']; // $result $stop = $row['stop']; // $result $this->spectralFit[$i]->mode = $mode; $this->spectralFit[$i]->start = $start; $this->spectralFit[$i]->stop = $stop; $this->spectralFit[$i]->image = "spec_" . strtolower($mode) . "_" . preg_replace('/\-/', '', $start) . "_" . preg_replace('/\-/', '', $stop) . ".gif"; $this->spectralFit[$i]->counts = $row['counts']; // $result $this->spectralFit[$i]->bins = $row['bins']; // $result $this->spectralFit[$i]->degrees_of_freedom = $row['degrees_of_freedom']; // $result $this->spectralFit[$i]->statistic_type = $row['statistic_type']; // $result $this->spectralFit[$i]->statistic_value = rtrim($row['statistic_value'], '0'); // $result $this->spectralFit[$i]->nH = $row['nH']; // $result $this->spectralFit[$i]->positive_error_nH = $row['positive_error_nH']; // $result $this->spectralFit[$i]->negative_error_nH = $row['negative_error_nH']; // $result $this->spectralFit[$i]->photon_index = $row['photon_index']; // $result $this->spectralFit[$i]->positive_error_photon_index = $row['positive_error_photon_index']; // $result $this->spectralFit[$i]->negative_error_photon_index = $row['negative_error_photon_index']; // $result $this->spectralFit[$i]->unabsorbed_flux = $row['unabsorbed_flux']; // $result $this->spectralFit[$i]->positive_error_unabsorbed_flux = $row['positive_error_unabsorbed_flux']; // $result $this->spectralFit[$i]->negative_error_unabsorbed_flux = $row['negative_error_unabsorbed_flux']; // $result } } else { unset($this->spectralFit); } } public function SourcesSpectralTable() { $dbh = mon_db_connect(); $query = "SELECT `sources`.`targetName` FROM `sources` WHERE `sources`.`type` LIKE 'main' ORDER BY `sources`.`RA` ASC"; $result = db_query($query, $dbh); if ($result->rowCount() > 0) { for ($i = 0; $i < $result->rowCount(); $i++) { $targetName = $row['targetName']; // $result $queryS = "SELECT "; $queryS .= "`sources_spectral_fits`.`statistic_value`, `sources_spectral_fits`.`degrees_of_freedom`, "; $queryS .= "`sources_spectral_fits`.`nH`, `sources_spectral_fits`.`positive_error_nH`, `sources_spectral_fits`.`negative_error_nH`, "; $queryS .= "`sources_spectral_fits`.`photon_index`, `sources_spectral_fits`.`positive_error_photon_index`, `sources_spectral_fits`.`negative_error_photon_index`, "; $queryS .= "`sources_spectral_fits`.`normalization`, `sources_spectral_fits`.`positive_error_normalization`, `sources_spectral_fits`.`negative_error_normalization` "; $queryS .= "FROM `sources_spectral_fits` WHERE `sources_spectral_fits`.`targetName` LIKE '$targetName' ORDER BY `sources_spectral_fits`.`start`"; $resultS = db_query_prepare($queryS, $dbh, array()); $nHAv = 0; $nHAvPos = 0; $nHAvNeg = 0; $photonIndexAv = 0; $photonIndexAvPos = 0; $photonIndexAvNeg = 0; $normalizationAv = 0; $normalizationAvPos = 0; $normalizationAvNeg = 0; $chiSqTot = 0; for ($j = 0; $j < $resultS->rowCount(); $j++) { $row = $resultS->fetch(); $statisticValue = $row['statistic_value']; // $resultS $statisticDegreesOfFreedom = $row['degrees_of_freedom']; // $resultS $statisticNh = $row['nH']; // $resultS $statisticNhPos = $row['positive_error_nH']; // $resultS $statisticNhNeg = $row['negative_error_nH']; // $resultS $nHAv += $statisticNh; $nHAvPos += $statisticNh + $statisticNhPos; $nHAvNeg += $statisticNh - $statisticNhNeg; $statisticPhotonIndex = $row['photon_index']; // $resultS $statisticPhotonIndexPos = $row['positive_error_photon_index']; // $resultS $statisticPhotonIndexNeg = $row['negative_error_photon_index']; // $resultS $photonIndexAv += $statisticPhotonIndex; $photonIndexAvPos += $statisticPhotonIndex + $statisticPhotonIndexPos; $photonIndexAvNeg += $statisticPhotonIndex - $statisticPhotonIndexNeg; $statisticNormalization = $row['normalization']; // $resultS $statisticNormalizationPos = $row['positive_error_normalization']; // $resultS $statisticNormalizationNeg = $row['negative_error_normalization']; // $resultS $normalizationAv += $statisticNormalization; $normalizationAvPos += $statisticNormalization + $statisticNormalizationPos; $normalizationAvNeg += $statisticNormalization - $statisticNormalizationNeg; $chiSqTot += $statisticValue / $statisticDegreesOfFreedom; } $n = $resultS->rowCount(); $nHAv = $nHAv / $n; $nHAvPos = $nHAvPos / $n; $nHAvNeg = $nHAvNeg / $n; $photonIndexAv = $photonIndexAv / $n; $photonIndexAvPos = $photonIndexAvPos / $n; $photonIndexAvNeg = $photonIndexAvNeg / $n; $normalizationAv = $normalizationAv / $n; $normalizationAvPos = $normalizationAvPos / $n; $normalizationAvNeg = $normalizationAvNeg / $n; $chiSq = $chiSqTot / $n; //We want to calculate the SDOM $runningTotal = 0; if ($resultS->rowCount() > 1) { for ($j = 0; $j < $resultS->rowCount(); $j++) { $statisticValue = $row['statistic_value']; // $resultS $runningTotal += pow($statisticValue - $chiSq, 2); } $chiSqError = sqrt(1. / ($resultS->rowCount() - 1) * $runningTotal) / sqrt($resultS->rowCount()); } else { $chiSqError = -1; } $this->source[$i]->targetName = $targetName; $this->source[$i]->nH = $nHAv; $this->source[$i]->nHPosError = $nHAvPos - $nHAv; $this->source[$i]->nHNegError = $nHAv - $nHAvNeg; $this->source[$i]->photonIndex = $photonIndexAv; $this->source[$i]->photonIndexPosError = $photonIndexAvPos - $photonIndexAv; $this->source[$i]->photonIndexNegError = $photonIndexAv - $photonIndexAvNeg; $this->source[$i]->normalization = $normalizationAv; $this->source[$i]->normalizationPosError = $normalizationAvPos - $normalizationAv; $this->source[$i]->normalizationNegError = $normalizationAv - $normalizationAvNeg; $this->source[$i]->chiSq = $chiSq; $this->source[$i]->chiSqError = $chiSqError; } } } public function UpcomingObservations($username, $targetName = false, $initialDate = false, $finalDate = false, $maxObservations = false) { //We're going to create a list of dates and times when observations are tentatively scheduled for our program //Play with inputs first if ($initialDate === false) { $initialDate = "NOW()"; } if ($finalDate === false) { $finalDate = "'3001-01-01'"; } //Find ToOs that we want to keep private from the public $dbh = mon_db_connect(); $queryPrivateToO = "SELECT `ID` FROM `private_ToOs` ORDER BY `ID` ASC"; $resultPrivateToO = db_query($queryPrivateToO, $dbh); $privateToOs = '0'; //Need something or else the $queryToo has issues if ($resultPrivateToO->rowCount()) { for ($i = 0; $i < $resultPrivateToO->rowCount(); $i++) { $row = $resultPrivateToO->fetch(); if ($privateToOs != '') { $privateToOs .= ","; } $privateToOs .= $row['ID']; // $resultPrivateToO } } self::GetAllSourceNames(); //See if user input is in the list if ((in_array($targetName, $this->allTargetNames->htmlTargetNames) || in_array($targetName, $this->allTargetNames->targetNames)) || $targetName === false) { //See what targetIDs are associated with a source if ($targetName !== false) { if (in_array($targetName, $this->allTargetNames->targetNames)) { $targetName = $this->allTargetNames->targetNames[array_search($targetName, $this->allTargetNames->targetNames)]; } else { $targetName = $this->allTargetNames->targetNames[array_search($targetName, $this->allTargetNames->htmlTargetNames)]; } //$targetName = preg_replace('/ /','',$targetName); //Trim so we can accept more entries //Need two potential replace statements based on whether we receive targetName through $_GET or database // $queryTargetIDs = "SELECT `targetID` FROM `targetID` WHERE REPLACE(`targetName`,' ','') LIKE '$targetName' OR REPLACE(REPLACE(`targetName`,'+',''),' ','') LIKE '$targetName'"; $queryTargetIDs = "SELECT `targetID` FROM `targetID` WHERE `targetName` LIKE '$targetName'"; // echo $queryTargetIDs; $resultTargetIDs = db_query_prepare($queryTargetIDs, $dbh, array()); $targetIDs = '-1'; //Need something or else the $queryToo has issues if ($resultTargetIDs->rowCount()) { for ($i = 0; $i < $resultTargetIDs->rowCount(); $i++) { if ($targetIDs != '') { $targetIDs .= ","; } $row = $resultTargetIDs->fetch(); $targetIDs .= $row['targetID']; // $resultTargetIDs } } } //Connect to the ToO database $dbToo = db_connect(); //Query a list of current ToOs $queryToo = "SELECT `TOO_ID`, DATE_FORMAT(`DATE`,'%m/%d/%Y') AS `DATE`, `TIME`, `SOURCE_NAME`, `DONE`, DATE_FORMAT(`DATE_END`,'%m/%d/%Y') AS `DATE_END` FROM `TOO` WHERE `DECISION` REGEXP 'Approved' AND `USERNAME` = '$username' AND `DONE`=0 AND `TOO_ID` NOT IN ($privateToOs) ORDER BY `TOO_ID` DESC"; $resultToo = db_query_prepare($queryToo, $dbToo, array()); //Continue if ToOs exist if ($resultToo->rowCount() > 0) { //Create list of ToO IDs we can search for in the calendar $tooIDString = ''; for ($i = 0; $i < $resultToo->rowCount(); $i++) { $row = $resultToo->fetch(); if ($tooIDString != '') { $tooIDString .= ','; } $tooIDString .= $row['TOO_ID']; // $resultToo } //Now search for the targets in the calendar based on our ToOs $dbCalendar = sot_db_connect(); //Query list of future observations $queryCalendar = "SELECT `start`, `stop`, `target_ID`, `target_name`, `duration` "; $queryCalendar .= "FROM `calendar` "; $queryCalendar .= "WHERE `type` LIKE 'TOO' AND `typeID` IN ($tooIDString) "; $queryCalendar .= "AND `start`>=$initialDate and `stop`<=$finalDate "; if ($targetName !== false) { $queryCalendar .= "AND `target_ID` IN ($targetIDs) "; } $queryCalendar .= "ORDER BY `start` ASC, `target_name` ASC"; // echo $queryCalendar; //If we are using maxObservations, limit to the most recent maxObservations entries if ($maxObservations !== false && is_numeric($maxObservations)) { $queryCalendar .= " LIMIT $maxObservations"; } //echo $queryCalendar; $resultCalendar = db_query($queryCalendar, $dbCalendar); //Continue if calendar entries exist if ($resultCalendar->rowCount() > 0) { for ($i = 0; $i < $resultCalendar->rowCount(); $i++) { $row = $resultCalendar->fetch(); $this->observations[$i] = new stdClass(); $this->observations[$i]->start = $row['start']; // $resultCalendar $this->observations[$i]->stop = $row['stop']; // $resultCalendar $this->observations[$i]->targetID = $row['target_ID']; // $resultCalendar $this->observations[$i]->targetName = $row['target_name']; // $resultCalendar $this->observations[$i]->duration = $row['duration']; // $resultCalendar } } else { unset($observations); } } else { unset($observations); } } else { unset($observations); } } public function GetAllSourceNames() { //Connect to the database and get the name of all sources $dbh = mon_db_connect(); $query = "SELECT REPLACE(REPLACE(`targetName`,' ',''),'+',' ') AS `htmlTargetName`, `targetName` FROM `sources` ORDER BY `targetName` ASC"; $result = db_query($query, $dbh); $this->allTargetNames = new stdClass(); if ($result->rowCount() > 0) { for ($i = 0; $i < $result->rowCount(); $i++) { $row = $result->fetch(); $this->allTargetNames->targetNames[$i] = new stdClass(); $this->allTargetNames->targetNames[$i] = $row['targetName']; // $result $this->allTargetNames->htmlTargetNames[$i] = $row['htmlTargetName']; // $result } } else { unset($this->allTargetNames); } } } function RandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $string = ''; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } function check_email_address($email) { // First, we check that there's one @ symbol, // and that the lengths are right. if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) { // Email invalid because wrong number of characters // in one section or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%& ↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } // Check if domain is IP. If not, // it should be valid domain name if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])| ↪([A-Za-z0-9]+))$/", $domain_array[$i])) { return false; } } } return true; } function do_html_header($title) { // print an HTML header echo << $title

Swift-XRT Monitoring of Fermi-LAT Sources of Interest


END; } function do_html_footer() { // print an HTML footer echo <<

Penn State University Goddard Space Flight Center Swift

END; } function do_html_warning_main() { // print an HTML header echo <<
The monitoring data shown on this site provides near real-time results from Swift observations of Fermi-LAT "sources of interest" and flaring sources. While this list is dominated by blazars, some X-ray binaries and Galactic transients are also included. The preliminary results on this page are intended to provide rapid feedback to the scientific community to aid in target of opportunity planning, multiwavelength campaigns, and planning of interesting scientific publications.

Data on this site is available to the public (thanks to support from the Fermi GI program and the Swift Team). If you make use of any of these data, we ask that you reference M.C. Stroh & A.D. Falcone 2013, ApJS, 207, 28; arXiv: 1305.4949 and that you notify Abe Falcone and Michael Stroh at monitoring@swift.psu.edu.


END; } function do_html_warning_data() { $changeLogLocation = '/monitoring/changelog.php'; // print an HTML header echo <<
The results presented on this page are from a preliminary analysis of the Swift-XRT data. The analysis procedure is described in this README file. Since the analysis is performed using automated scripts and the results are not always reviewed by human eyes, we recommend that these data be reviewed by hand before use in publications.

For questions or requests for more detailed analysis, please contact Abe Falcone and Michael Stroh at monitoring@swift.psu.edu. This web site is under construction so please report any web site related problems to the email address listed above.

ChangeLog - Last Updated: 2018-10-07

Upcoming Observations


END; } function LastUpdated() { echo ""; /* $dbh = mon_db_connect(); $queryTime = "SELECT `sdc` FROM `process_log` WHERE `duration` IS NOT NULL ORDER BY `start` DESC LIMIT 1"; $resTime = db_query($queryTime,$dbh) or die('Not found'); $sdcTime = $row['sdc']; // $resTime list($sdcDate,$sdcTime) = preg_split('/ /',$sdcTime); $tz = date("T"); echo<<
Last Updated: $sdcDate $sdcTime $tz

END; */ /*echo<<
Everything should be back to normal. Please let us know if you notice any problems.

END; */ } function Login($newUserSubmitted = false) { if ($newUserSubmitted) { echo "

User request submitted. An email has been sent to an administrator who will handle your request.

\n"; } //if($userError) echo "

Provided user information is incorrect.

\n"; echo <<
Login

END; } function NewUserForm($submitError = '', $fName = '', $lName = '', $email = '', $fNameError = false, $lNameError = false, $emailError = false, $pass1Error = false, $pass2Error = false, $passMatchError = false) { if ($submitError) { echo "

There was an error handling your request, please try again.
\n"; } if ($fNameError) { echo "

Fill-out 'First Name.'
\n"; } if ($lNameError) { echo "

Fill-out 'Last Name.'
\n"; } if ($emailError) { echo "

Email address was not valid or user already exists.
\n"; } if ($pass1Error || $pass2Error) { echo "

Password must be at least 8 digits long.
\n"; } if ($passMatchError) { echo "

Passwords did not match.
\n"; } echo <<
New User Request




END; } function MyCrypt($pass) { return md5($pass); } function AddNewUser($fName, $lName, $email, $hash) { $dbh = mon_db_connect(); $command = "INSERT INTO `users` (`fname`, `lname`, `email`, `pw`) VALUES (?,?,?,?)"; return db_query_prepare($command, $dbh, array($fName, $lName, $email, $hash)); } function CheckLogIn() { if (!isset($_COOKIE[ini_get('session.name')])) { session_start(); } if (!isset($_SESSION['user']) && isset($_COOKIE["MonitoringLogin"])) { $monitoring = new Monitoring(); $monitoring->UserViaKey($_COOKIE["MonitoringLogin"]); if ($monitoring->user && isset($monitoring->user->status) && $monitoring->user->status != 'new') { $logInTime = strptime($monitoring->user->logIn, '%Y-%m-%d %H:%M:%S'); if (mktime($logInTime['tm_hour'], $logInTime['tm_min'], $logInTime['tm_sec'], $logInTime['tm_mon'] + 1, $logInTime['tm_mday'], $logInTime['tm_year'] + 1900) + 14 * 86400. > strtotime('now')) { $monitoring->UserViaEmail($monitoring->user->email); $_SESSION['user'] = $monitoring->user; } else { setcookie('MonitoringLogin', "", time() - 3600); session_unset(); session_destroy(); header("Location: https://www.swift.psu.edu/monitoring/admin.php"); } } } } function GetUserHeader() { if (isset($_SESSION['user']) && $_SESSION['user']->status != 'new') { //Center div echo "\t\t
\n"; //Sub div for source lists echo "\t\t\t
"; echo "Sources"; echo "
\n"; if ($_SESSION['user']->status == 'admin') { //Sub div for statistics echo "\t\t\t
"; echo "Status"; echo "
\n"; //Sub div for exceptions echo "\t\t\t
"; echo "Exceptions"; echo "
\n"; //Sub div for adding sources echo "\t\t\t
"; echo "Add Sources"; echo "
\n"; //Sub div for changing the reprocessing date echo "\t\t\t
"; echo "Reprocess"; echo "
\n"; //Sub div for adding private ToOs echo "\t\t\t
"; echo "Private ToO"; echo "
\n"; //Sub div for user list echo "\t\t\t
"; echo "Users"; echo "
\n"; //Sub div for tables list echo "\t\t\t
"; echo "Tables"; echo "
\n"; } //Sub div for logout echo "\t\t\t
"; echo "Account Info"; echo "
\n"; //Sub div for logout echo "\t\t\t\n"; echo "\t\t
"; } } //Display target list function DisplayTargetList($type = 'main', $administrator = false) { $monitoring = new Monitoring(); $monitoring->SourcesInfo($type); if (isset($monitoring->source)) { // $arrow_image = "Expand"; $arrow_image = ''; echo << END; if ($type == 'main') { echo "\n"; } elseif ($type == 'public') { echo "\n"; } elseif ($type == 'private') { echo "\n"; } else { echo "\n"; } echo << END; #Counter for deciding the color. Can't use $i below because we may need to skip over the source $sourceCounter = 0; #Loop over each source to add to the list for ($i = 0; $i < count($monitoring->source); $i++) { if (fmod($sourceCounter, 2) == 0) { $rowColor = "#ccf"; } else { $rowColor = "#fcc"; } if ($monitoring->source[$i]->type == 'private') { $plotDir = "/monitoring/private_new/"; $link = "mySource.php?source=" . preg_replace('/ /', '', $monitoring->source[$i]->targetName); $plotRel = "private_new/"; } else { $plotDir = "/monitoring/data_new/"; if ($administrator) { $link = "mySource.php?source=" . preg_replace('/ /', '', $monitoring->source[$i]->targetName); } else { $link = "source.php?source=" . preg_replace('/ /', '', $monitoring->source[$i]->targetName); } $plotRel = "data_new/"; } $plot = $plotDir . $monitoring->source[$i]->folder . "/lightcurve.png"; #Skip over source if it isn't plotted if (file_exists($plotRel . $monitoring->source[$i]->folder . "/lightcurve.png")) { $sourceCounter++; echo "\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; /* echo "\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\n"; */ } } echo "\t\t

Original 23 Fermi-LAT Monitored Sources

Additional Sources

All Private Sources

Your Private Sources

Target
RA (J2000)
Dec (J2000)
Exposure
Time (ks)
Last Observation
$arrow_image
\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t
" . $monitoring->source[$i]->sexRA . "
" . $monitoring->source[$i]->sexDeclination . "
" . $monitoring->source[$i]->exposureTime . "
" . $monitoring->source[$i]->lastObserved . "
\n"; $size = getimagesize($plot); $w = floor(0.75*$size[0]); $h = floor(0.75*$size[1]); echo "\t\t\t\t\tFull Swift light curve for ".$monitoring->source[$i]->targetName.""; echo "\t\t\t\t
\n\t\n"; } } function DisplayTargetInfo($target, $private = false, $spec = false) { $monitoring = new Monitoring(); $monitoring->SourcePlots($target); $webDir = "/monitoring/"; if (isset($monitoring->plot) && (($monitoring->plot->type == 'main' || $monitoring->plot->type == 'public') || ($monitoring->plot->type != 'main' && $monitoring->plot->type != 'public' && $private == true))) { $targetName = $monitoring->plot->targetName; $trimTargetName = str_replace(' ', '', $targetName); $type = $monitoring->plot->type; $folder = $monitoring->plot->folder; if ($type == 'main' || $type == 'public') { $folder = "data_new/$folder/"; } else { $folder = "private_new/$folder/"; } //Images - Probably exists but no promises $pcImage = $folder . "pc_image.png"; //Plots $lcPlotSingleBin = $folder . "lightcurve.png"; $hrPlotSingleBin = $folder . "hardness.png"; $lcPlotStandardBin = $folder . "lightcurve3.png"; $hrPlotStandardBin = $folder . "hardness2.png"; $logLcPlotSingleBin = $folder . "loglightcurve.png"; $logHrPlotSingleBin = $folder . "loghardness.png"; $logLcPlotStandardBin = $folder . "loglightcurve3.png"; $logHrPlotStandardBin = $folder . "loghardness2.png"; //Data files $lcData1 = $folder . "lightcurve.txt"; $lcData2 = $folder . "lightcurve2.txt"; $lcData3 = $folder . "lightcurve3.txt"; $lcData4 = $folder . "lightcurve4.txt"; $hrData1 = $folder . "hardness.txt"; $hrData2 = $folder . "hardness2.txt"; $size = getimagesize($lcPlotSingleBin); $w = floor(0.64 * $size[0]); $h = floor(0.64 * $size[1]); //Overall data echo "\t\t
\n"; echo "\t\t\t

$targetName

\n"; echo "\t\t"; echo "\t\t\t\n"; //Show the image if available if (file_exists($pcImage)) { $pcImageSize = getimagesize($pcImage); $pcImageW = floor(0.64 * $pcImageSize[0]); $pcImageH = floor(0.64 * $pcImageSize[1]); echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\n"; //Show spectral fits but only if admin if ($private) { $monitoring->GetSourceSpectralFit($targetName); if (isset($monitoring->spectralFit)) { /* $this->spectralFit[$i]->mode = $mode; $this->spectralFit[$i]->start = $start; $this->spectralFit[$i]->stop = $stop; $this->spectralFit[$i]->image = "spec_".strtolower($mode)."_".$start."_".$stop.".gif"; $this->spectralFit[$i]->counts = $row['counts']; // $result $this->spectralFit[$i]->bins = $row['bins']; // $result $this->spectralFit[$i]->degrees_of_freedom = $row['degrees_of_freedom']; // $result $this->spectralFit[$i]->statistic_type = $row['statistic_type']; // $result $this->spectralFit[$i]->statistic_value = rtrim($row['statistic_value'],'0']; // $result $this->spectralFit[$i]->nH = $row['nH']; // $result $this->spectralFit[$i]->positive_error_nH = $row['positive_error_nH']; // $result $this->spectralFit[$i]->negative_error_nH = $row['negative_error_nH']; // $result $this->spectralFit[$i]->photon_index = $row['photon_index']; // $result $this->spectralFit[$i]->positive_error_photon_index = $row['positive_error_photon_index']; // $result $this->spectralFit[$i]->negative_error_photon_index = $row['negative_error_photon_index']; // $result $this->spectralFit[$i]->unabsorbed_flux = $row['unabsorbed_flux']; // $result $this->spectralFit[$i]->positive_error_unabsorbed_flux = $row['positive_error_unabsorbed_flux']; // $result $this->spectralFit[$i]->negative_error_unabsorbed_flux = $row['negative_error_unabsorbed_flux']; // $result */ for ($i = 0; $i < count($monitoring->spectralFit); $i++) { $specImage = $folder . $monitoring->spectralFit[$i]->image; //Only calculate size parameters if we haven't already. This is to ensure that multiple plots appear the same size. if (!isset($specImageSize)) { $specImageSize = getimagesize($specImage); $specImageW = floor(0.64 * $specImageSize[0]); $specImageH = floor(0.64 * $specImageSize[1]); } //Common parameters $start = $monitoring->spectralFit[$i]->start; $stop = $monitoring->spectralFit[$i]->stop; $mode = $monitoring->spectralFit[$i]->mode; $statisticType = $monitoring->spectralFit[$i]->statistic_type; $statisticValue = $monitoring->spectralFit[$i]->statistic_value; $dof = $monitoring->spectralFit[$i]->degrees_of_freedom; $nH = $monitoring->spectralFit[$i]->nH; //$positive_error_nH = $monitoring->spectralFit[$i]->positive_error_nH; //$negative_error_nH = $monitoring->spectralFit[$i]->negative_error_nH; $photonIndex = $monitoring->spectralFit[$i]->photon_index; //$positive_error_photon_index = $monitoring->spectralFit[$i]->positive_error_photon_index; //$negative_error_photon_index = $monitoring->spectralFit[$i]->negative_error_photon_index; $unabsorbedFlux = $monitoring->spectralFit[$i]->unabsorbed_flux; echo "\t\t\t\n"; if (isset($monitoring->spectralFit)) { echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\n"; } } } echo "\t\t
\n"; echo "\t\t\t\t\t

Summed Photon Counting Image

\n"; echo "\t\t\t\t\t
\n"; echo "\t\t\t\t\t\tSummed PC image of $targetName
\n"; echo "\t\t\t\t
\n"; } else { echo "\t\t\t\t\n"; } //Future Observations $maxObservations = 5; echo "\t\t\t\t\t

Upcoming Monitoring Observations
(not including some ToOs)

\n"; echo "\t\t\t\t\t
\n"; FutureObservations('stroh', $targetName, false, false, $maxObservations); echo "\t\t\t\t\t
\n"; //External Links echo "\t\t\t\t\t

External Links

\n"; echo "\t\t\t\t\t
\n"; $monitoring->GetExternalLinks($targetName); if (isset($monitoring->externalLinks)) { for ($i = 0; $i < count($monitoring->externalLinks); $i++) { echo "\t\t\t\t\t\texternalLinks[$i]->link) . "'>" . $monitoring->externalLinks[$i]->site . "
\n"; } } else { echo "None Found"; } echo "\t\t\t\t\t
\n"; echo "\t\t\t\t
\n"; } else { echo "\t\t\t\t\n"; } echo "\t\t\t\t\t
\n"; echo "\t\t\t\t\t

Spectral Fit Plot - $mode

\n"; echo "\t\t\t\t\t\tSpectral fit of $targetName
\n"; echo "\t\t\t\t
\n"; echo "\t\t\t\t\t
\n"; echo "\t\t\t\t\t

Spectral Fit Parameters - $mode

\n"; echo "\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t
\n"; echo "\t\t\t\t\t\t\t
\n"; echo "\t\t\t\t\t\t\t\tStatistic Type:" . $statisticType . "
\n"; echo "\t\t\t\t\t\t\t
\n"; if ($statisticType == 'Chi-Squared') { echo "\t\t\t\t\t\t\t\tReduced Chi^2:" . number_format($statisticValue / $dof, 2) . "
\n"; } echo "\t\t\t\t\t\t\t
\n"; echo "\t\t\t\t\t\t\t\tnH:" . $nH . " (+" . $positive_error_nH . ",-" . $negative_error_nH . ")
\n"; echo "\t\t\t\t\t\t\t
\n"; echo "\t\t\t\t\t\t\t\tPhoton Index:" . $photonIndex . " (+" . $positive_error_photon_index . ",-" . $negative_error_photon_index . ")
\n"; echo "\t\t\t\t\t\t\t
\n"; echo "\t\t\t\t\t\t\t\tDate Range:" . $start . " to " . $stop . "
\n"; echo "\t\t\t\t\t\t\t
"; echo "\t\t\t\t\t
\n"; echo "\t\t\t\t
"; echo "\t\t\t\t

Overall Light Curves

\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\t
\n"; echo "\t\t\t\t\t\t

Linear Light Curve

\n"; echo "\t\t\t\t\t\tFull Swift light curve for $targetName

Log Light Curve

\n"; echo "\t\t\t\t\t\tFull Swift log light curve for $targetName

\n"; echo "\t\t\t\t

Overall Hardness Ratio

\n"; if (file_exists("$hrPlotSingleBin")) { echo "\t\t\tFull Swift hardness ratio for $targetName
\n"; } echo "\t\t\t\n"; echo "\t\t
\n"; if (isset($monitoring->plot->observation)) { // echo "\t\t
\n"; $lastObs = true; $additionalObs = false; $counter = 0; $maxObservations = 25; foreach ($monitoring->plot->observation as &$obs) { if ($counter > $maxObservations) { break; } $observationID = $obs->observationID; $observed = $obs->observed; //Plots $lcPlotObsStandardBin = $folder . $observationID . "/lightcurve.png"; $hrPlotObsStandardBin = $folder . $observationID . "/hardness.png"; //Data files $lcData1 = $folder . $observationID . "/lightcurve.txt"; $lcData2 = $folder . $observationID . "/lightcurve2.txt"; $hrData1 = $folder . $observationID . "/hardness.txt"; $w = floor(0.5 * $size[0]); $h = floor(0.5 * $size[1]); if (!$additionalObs) { if ($private) { echo "\t\t
\n\t\t\t\n"; } else { echo "\t\t
\n\t\t\t
\n"; } echo "\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\n"; if ($maxObservations < count($monitoring->plot->observation)) { echo "\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\n"; } $additionalObs = true; } if (file_exists($lcPlotObsStandardBin)) { $counter++; echo "\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; //Add a row for individual spectral fits if possible if ($private) { $wtSpecFile = $folder . $observationID . "/spec_wt.gif"; $pcSpecFile = $folder . $observationID . "/spec_pc.gif"; if ((isset($obs->wt) && file_exists($wtSpecFile))) { $wtSpec = true; } else { $wtSpec = false; } if ((isset($obs->pc) && file_exists($pcSpecFile))) { $pcSpec = true; } else { $pcSpec = false; } if ((isset($obs->wt) && file_exists($wtSpecFile)) || (isset($obs->pc) && file_exists($pcSpecFile))) { $myModes = array('wt', 'pc'); for ($m = 0; $m < count($myModes); $m++) { if ($myModes[$m] == 'wt' && isset($obs->wt)) { $modeTest = $wtSpec; $specFile = $wtSpecFile; $specFit = $obs->wt; } else { $modeTest = $pcSpec; $specFile = $pcSpecFile; $specFit = $obs->pc; } if ($modeTest) { $nHOutput = SignificantDigits2($specFit->nH, array($specFit->positive_error_nH, $specFit->negative_error_nH), 22); $photonIndexOutput = SignificantDigits2($specFit->photon_index, array($specFit->positive_error_photon_index, $specFit->negative_error_photon_index)); $fluxOutput = SignificantDigits2($specFit->flux, array($specFit->positive_error_flux, $specFit->negative_error_flux)); $unabsorbedFluxOutput = SignificantDigits2($specFit->unabsorbed_flux, array($specFit->positive_error_unabsorbed_flux, $specFit->negative_error_unabsorbed_flux)); echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; } } } } echo "\t\t\t\t\n"; } } //Close table and div if needed if ($additionalObs) { echo "\t\t\t
\n"; echo "\t\t\t\t\t\t

Last " . number_format(min($maxObservations, count($monitoring->plot->observation)), 0) . " Individual Observations

\n"; echo "\t\t\t\t\t\tSee all " . number_format(count($monitoring->plot->observation), 0) . " Individual Observations
\n"; echo "\t\t\t\t\t\t$observed\n"; echo "\t\t\t\t\t\tSwift light curve for Observation ID $observationID
\n"; echo "\t\t\t\t\t\tLight Curve (txt)
\n"; echo "\t\t\t\t\t\tDetailed Light Curve (txt)
\n"; if (file_exists($hrPlotObsStandardBin)) { echo "\t\t\t\t\t\tSwift hardness ratio for Observation ID $observationID
\n"; echo "\t\t\t\t\t\tHardness Ratio (txt)\n"; } else { echo "\t\t\t\t\t\t "; } echo "
\n"; echo "\t\t\t\t\t\tSwift/XRT " . strtoupper($myModes[$m]) . " spectrum for Observation ID $observationID\n"; echo "\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; //echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t
Statistic Type:" . $specFit->statistic_type . "
Statistic Value:" . $specFit->statistic_value . "
Degrees of Freedom:" . $specFit->degrees_of_freedom . "
NH:".$specFit->nH." (+".$specFit->positive_error_nH.", -".$specFit->negative_error_nH.")$nHOutput cm-2
Photon Index:$photonIndexOutput
Flux (0.3-10.0 keV)
(Observed)
$fluxOutput erg cm-2 s-1
Flux (0.3-10.0 keV)
(Unabsorbed)
$unabsorbedFluxOutput erg cm-2 s-1
\n"; echo "\t\t\t\t\t\t
\n\t\t
"; } } } } function DisplayAllObservationInfo($target, $private = false, $spec = false) { $monitoring = new Monitoring(); $monitoring->SourcePlots($target); $webDir = "/monitoring/"; if (isset($monitoring->plot) && (($monitoring->plot->type == 'main' || $monitoring->plot->type == 'public') || ($monitoring->plot->type != 'main' && $monitoring->plot->type != 'public' && $private == true))) { $targetName = $monitoring->plot->targetName; $type = $monitoring->plot->type; $folder = $monitoring->plot->folder; if ($type == 'main' || $type == 'public') { $folder = "data_new/$folder/"; } else { $folder = "private_new/$folder/"; } //Overall data //padding-bottom:50px; echo "\t\t
\n"; echo "\t\t\t

$targetName

\n"; echo "\t\t
\n"; if (isset($monitoring->plot->observation)) { // echo "\t\t
\n"; $lastObs = true; $additionalObs = false; foreach ($monitoring->plot->observation as &$obs) { $observationID = $obs->observationID; $observed = $obs->observed; //Plots $lcPlotObsStandardBin = $folder . $observationID . "/lightcurve.png"; $hrPlotObsStandardBin = $folder . $observationID . "/hardness.png"; //Data files $lcData1 = $folder . $observationID . "/lightcurve.txt"; $lcData2 = $folder . $observationID . "/lightcurve2.txt"; $hrData1 = $folder . $observationID . "/hardness.txt"; if (!isset($size) && file_exists($lcPlotObsStandardBin)) { $size = getimagesize($lcPlotObsStandardBin); } if (isset($size)) { $w = floor(0.5 * $size[0]); $h = floor(0.5 * $size[1]); if (!$additionalObs) { echo "\t\t
\n\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\n"; $additionalObs = true; } if (file_exists($lcPlotObsStandardBin)) { echo "\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; //Add a row for individual spectral fits if possible if ($private) { $wtSpecFile = $folder . $observationID . "/spec_wt.gif"; $pcSpecFile = $folder . $observationID . "/spec_pc.gif"; if ((isset($obs->wt) && file_exists($wtSpecFile))) { $wtSpec = true; } else { $wtSpec = false; } if ((isset($obs->pc) && file_exists($pcSpecFile))) { $pcSpec = true; } else { $pcSpec = false; } if ((isset($obs->wt) && file_exists($wtSpecFile)) || (isset($obs->pc) && file_exists($pcSpecFile))) { $myModes = array('wt', 'pc'); for ($m = 0; $m < count($myModes); $m++) { if ($myModes[$m] == 'wt' && isset($obs->wt)) { $modeTest = $wtSpec; $specFile = $wtSpecFile; $specFit = $obs->wt; } else { $modeTest = $pcSpec; $specFile = $pcSpecFile; isset($obs->pc) ? $specFit = $obs->pc : $specFit = ''; } if ($modeTest) { $nHOutput = SignificantDigits2($specFit->nH, array($specFit->positive_error_nH, $specFit->negative_error_nH), 22); $photonIndexOutput = SignificantDigits2($specFit->photon_index, array($specFit->positive_error_photon_index, $specFit->negative_error_photon_index)); $fluxOutput = SignificantDigits2($specFit->flux, array($specFit->positive_error_flux, $specFit->negative_error_flux)); $unabsorbedFluxOutput = SignificantDigits2($specFit->unabsorbed_flux, array($specFit->positive_error_unabsorbed_flux, $specFit->negative_error_unabsorbed_flux)); echo "\t\t\t\t\n"; echo "\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; echo "\t\t\t\t\t\n"; } } } } echo "\t\t\t\t\n"; } } } //Close table and div if needed if ($additionalObs) { echo "\t\t\t
\n"; echo "\t\t\t\t\t\t

All Individual Observations

\n"; echo "\t\t\t\t\t\t$observed\n"; echo "\t\t\t\t\t\tSwift light curve for Observation ID $observationID
\n"; echo "\t\t\t\t\t\tLight Curve (txt)
\n"; echo "\t\t\t\t\t\tDetailed Light Curve (txt)
\n"; if (file_exists($hrPlotObsStandardBin)) { echo "\t\t\t\t\t\tSwift hardness ratio for Observation ID $observationID
\n"; echo "\t\t\t\t\t\tHardness Ratio (txt)\n"; } else { echo "\t\t\t\t\t\t "; } echo "
\n"; echo "\t\t\t\t\t\tSwift/XRT " . strtoupper($myModes[$m]) . " spectrum for Observation ID $observationID\n"; echo "\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; //echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t\t\n"; echo "\t\t\t\t\t\t
Statistic Type:" . $specFit->statistic_type . "
Statistic Value:" . $specFit->statistic_value . "
Degrees of Freedom:" . $specFit->degrees_of_freedom . "
NH:".$specFit->nH." (+".$specFit->positive_error_nH.", -".$specFit->negative_error_nH.")$nHOutput cm-2
Photon Index:$photonIndexOutput
Flux (0.3-10.0 keV)
(Observed)
$fluxOutput erg cm-2 s-1
Flux (0.3-10.0 keV)
(Unabsorbed)
$unabsorbedFluxOutput erg cm-2 s-1
\n"; echo "\t\t\t\t\t\t
\n\t\t
"; } } } } function Radec2vec($ra, $dec) { $ra = deg2rad($ra); $dec = deg2rad($dec); $v1 = cos($dec) * cos($ra); $v2 = cos($dec) * sin($ra); $v3 = sin($dec); return array($v1, $v2, $v3); } function DotProduct($v1, $v2) { $dotProduct = $v1[0] * $v2[0] + $v1[1] * $v2[1] + $v1[2] * $v2[2]; return $dotProduct; } function Separation($c1, $c2) { //Accepts the RA, dec of two vectors and returns the separation between them //RA and dec must be in degrees //Output is in arcminutes //Convert both to vectors $v1 = Radec2vec($c1[0], $c1[1]); $v2 = Radec2vec($c2[0], $c2[1]); return rad2deg(acos(DotProduct($v1, $v2))) * 60.; } function SignificantDigits($value, $error, $offset = 0) { $errorBase = floor(log10($error)); $meanBase = floor(log10($value)); if ((number_format($error, -1 * $errorBase) / pow(10, $errorBase)) < 2) { $errorBase--; } $error = number_format($error / pow(10, $meanBase), $meanBase - $errorBase); $value = number_format($value / pow(10, $meanBase), $meanBase - $errorBase); if ($meanBase == 0) { $output = "\$ $value \pm $error \$"; } else { $output = "\$ ($value \pm $error) \\times 10^{" . ($meanBase + $offset) . "} \$"; } return $output; /* if(!is_array($error)) $error = array($error); $errorBase = floor(log10($error)); $meanBase = floor(log10($value)); if((number_format(min($error),-1*$errorBase)/pow(10,$errorBase))<2) $errorBase--; if(count($error)<2){ $error = number_format($error[0]/pow(10,$meanBase),$meanBase-$errorBase); $errorString = " \pm $error "; } else { $error[0] = number_format($error[0]/pow(10,$meanBase),$meanBase-$errorBase); $error[1] = number_format($error[1]/pow(10,$meanBase),$meanBase-$errorBase); $errorString = "^{+".$error[0]."}_{-".$error[1]."} "; } $value = number_format($value/pow(10,$meanBase),$meanBase-$errorBase); if($meanBase==0){ $output = "\$ $value$errorString\$"; } else $output = "\$ ($value$errorString) \\times 10^{".($meanBase+$offset)."} \$"; return $output; */ } function SignificantDigits2($value, $error, $offset = 0) { if (!is_array($error)) { $error = array($error, $error); } $errorP = $error[0]; //Positive error $errorN = $error[1]; //Negative error $errorBaseP = floor(log10(abs($errorP))); $errorBaseN = floor(log10(abs($errorN))); $meanBase = floor(log10($value)); if ($errorP != 0 && (number_format($errorP, -1 * $errorBaseP) / pow(10, $errorBaseP)) < 2) { $errorBaseP--; } if ($errorN != 0 && (number_format($errorN, -1 * $errorBaseN) / pow(10, $errorBaseN)) < 2) { $errorBaseN--; } //Error if $errorN=0 // echo "delta bases P: ".$meanBase-$errorBaseP."
"; // echo "delta bases N: ".$meanBase-$errorBaseN."
"; $errorP = number_format($errorP / pow(10, $meanBase), $meanBase - $errorBaseP); $errorN = number_format($errorN / pow(10, $meanBase), $meanBase - $errorBaseN); $value = number_format($value / pow(10, $meanBase), max(array($meanBase - $errorBaseP, $meanBase - $errorBaseN))); // $valueP = number_format($value/pow(10,$meanBase),$meanBase-$errorBaseP); // $valueN = number_format($value/pow(10,$meanBase),$meanBase-$errorBaseN); // echo "value P: ".$valueP."
"; // echo "value N: ".$valueN."
"; if ($meanBase == 0) { $output = "$value (+$errorP, -$errorN)"; } else { $output = "($value (+$errorP, -$errorN)) × 10" . ($meanBase + $offset) . ""; } return $output; } function FutureObservations($username, $targetName = false, $initialDate = false, $finalDate = false, $maxObservations = false) { $monitoring = new Monitoring(); //$monitoring -> UpcomingObservations('stroh',$targetName,$initialDate,$finalDate,$maxObservations); $monitoring->UpcomingObservations('afalcone', $targetName, $initialDate, $finalDate, $maxObservations); if (isset($monitoring->observations)) { echo << END; if ($targetName !== false && $maxObservations !== false) { $nObservations = count($monitoring->observations); echo << END; } echo << END; for ($i = 0; $i < count($monitoring->observations); $i++) { $start = $monitoring->observations[$i]->start; $stop = $monitoring->observations[$i]->stop; $myTargetName = $monitoring->observations[$i]->targetName; $duration = number_format($monitoring->observations[$i]->duration / 1000., 1); if (fmod($i, 2) == 0) { echo " "; } else { echo " "; } echo <<
$start
END; } if ($targetName !== false && $maxObservations !== false) { $link = "/monitoring/futureObservations.php?targetName=" . preg_replace('/\s/', '', $targetName) . ""; echo << END; } else if ($targetName !== false) { $link = "/monitoring/futureObservations.php"; echo << END; } echo "
Next $nObservations observations
Window Start
Window Stop
Target Name
Exposure
Time (ks)
$stop
$myTargetName
$duration
"; echo "
"; } else { echo <<
No observations are currently scheduled for this source through our monitoring program, but there may be other ToO programs that have upcoming observations on this source.
END; } } function sanitizeText($text) { /* if(get_magic_quotes_gpc()) $text = stripcslashes($text);*/ /* $text = str_replace("<", "<", $text); $text = str_replace(">", ">", $text); $text = str_replace("\"", """, $text); $text = str_replace("'", "'", $text); */ //$text = $text; return $text; } function validateDate($date, $format = 'Y-m-d H:i:s') { $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) == $date; } * Created: 03/26/2001 * * TODO: * - Move all the duplicate code to a utility function * Most of the functions have the first lines of * code do the same processing. If this can be moved * into a utility function then it would reduce the * overall size of the code significantly. * * 08/22/2001 - Chris Ryan * Added the Authenticate() method submitted by Brent Matzelle * in response to the feature request #298. */ /* * PhpSMTP library for using the SMTP protocol from PHP * Copyright (C) 2001-2003 Chris Ryan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * STMP is rfc 821 compliant and implements all the rfc 821 SMTP * commands except TURN which will always return a not implemented * error. SMTP also provides some utility methods for sending mail * to an SMTP server. */ class SMTP { var $SMTP_PORT = 25; # the default SMTP PORT var $CRLF = "\r\n"; # CRLF pair var $smtp_conn; # the socket to the server var $error; # error if any on the last call var $helo_rply; # the reply the server sent to us for HELO var $do_debug; # the level of debug to perform /* * SMTP() * * Initialize the class so that the data is in a known state. */ function SMTP() { $this->smtp_conn = 0; $this->error = null; $this->helo_rply = null; $this->do_debug = 0; } /************************************************************ * CONNECTION FUNCTIONS * ***********************************************************/ /* * Connect($host, $port=0, $tval=30) * * Connect to the server specified on the port specified. * If the port is not specified use the default SMTP_PORT. * If tval is specified then a connection will try and be * established with the server for that number of seconds. * If tval is not specified the default is 30 seconds to * try on the connection. * * SMTP CODE SUCCESS: 220 * SMTP CODE FAILURE: 421 */ function Connect($host,$port=0,$tval=30) { # set the error val to null so there is no confusion $this->error = null; # make sure we are __not__ connected if($this->connected()) { # ok we are connected! what should we do? # for now we will just give an error saying we # are already connected $this->error = array("error" => "Already connected to a server"); return false; } if(empty($port)) { $port = $this->SMTP_PORT; } #connect to the smtp server $this->smtp_conn = fsockopen($host, # the host of the server $port, # the port to use $errno, # error number if any $errstr, # error message if any $tval); # give up after ? secs # verify we connected properly if(empty($this->smtp_conn)) { $this->error = array("error" => "Failed to connect to server", "errno" => $errno, "errstr" => $errstr); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF; } return false; } # sometimes the SMTP server takes a little longer to respond # so we will give it a longer timeout for the first read # I have a report that on Windows systems this doesn't # behave properly. #socket_set_timeout($this->smtp_conn, 1, 0); # get any announcement stuff $announce = $this->get_lines(); # set the timeout of any socket functions at 1/10 of a second #socket_set_timeout($this->smtp_conn, 0, 100000); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $announce; } return true; } /* * Connected() * * Returns true if connected to a server otherwise false */ function Connected() { if(!empty($this->smtp_conn)) { $sock_status = socket_get_status($this->smtp_conn); if($sock_status["eof"]) { # hmm this is an odd situation... the socket is # valid but we aren't connected anymore if($this->do_debug >= 1) { echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; } $this->Close(); return false; } return true; # everything looks good } return false; } /* * Close() * * Closes the socket and cleans up the state of the class. * It is not considered good to use this function without * first trying to use QUIT. */ function Close() { $this->error = null; # so there is no confusion $this->helo_rply = null; if(!empty($this->smtp_conn)) { # close the connection and cleanup fclose($this->smtp_conn); $this->smtp_conn = 0; } } /************************************************************** * SMTP COMMANDS * *************************************************************/ /* * Data($msg_data) * * Issues a data command and sends the msg_data to the server * finializing the mail transaction. $msg_data is the message * that is to be send with the headers. Each header needs to be * on a single line followed by a with the message headers * and the message body being seperated by and additional . * * Implements rfc 821: DATA * * SMTP CODE INTERMEDIATE: 354 * [data] * . * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 552,554,451,452 * SMTP CODE FAILURE: 451,554 * SMTP CODE ERROR : 500,501,503,421 */ function Data($msg_data) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Data() without being connected"); return false; } fputs($this->smtp_conn,"DATA" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 354) { $this->error = array("error" => "DATA command not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } # the server is ready to accept data! # according to rfc 821 we should not send more than 1000 # including the CRLF # characters on a single line so we will break the data up # into lines by \r and/or \n then if needed we will break # each of those into smaller lines to fit within the limit. # in addition we will be looking for lines that start with # a period '.' and append and additional period '.' to that # line. NOTE: this does not count towards are limit. # normalize the line breaks so we know the explode works $msg_data = str_replace("\r\n","\n",$msg_data); $msg_data = str_replace("\r","\n",$msg_data); $lines = explode("\n",$msg_data); # we need to find a good way to determine is headers are # in the msg_data or if it is a straight msg body # currently I'm assuming rfc 822 definitions of msg headers # and if the first field of the first line (':' sperated) # does not contain a space then it _should_ be a header # and we can process all lines before a blank "" line as # headers. $field = substr($lines[0],0,strpos($lines[0],":")); $in_headers = false; if(!empty($field) && !strstr($field," ")) { $in_headers = true; } $max_line_length = 980; # used below; set here for ease in change while(list(,$line) = @each($lines)) { $lines_out = null; if($line == "" && $in_headers) { $in_headers = false; } # ok we need to break this line up into several # smaller lines while(strlen($line) > $max_line_length) { $pos = strrpos(substr($line,0,$max_line_length)," "); if($pos === false) { $pos = $max_line_length; } $lines_out[] = substr($line,0,$pos); $line = substr($line,$pos + 1); # if we are processing headers we need to # add a LWSP-char to the front of the new line # rfc 822 on long msg headers if($in_headers) { $line = "\t" . $line; } } $lines_out[] = $line; # now send the lines to the server while(list(,$line_out) = @each($lines_out)) { if(!empty($line_out) && $line_out[0] == ".") { $line_out = "." . $line_out; } fputs($this->smtp_conn,$line_out . $this->CRLF); } } # ok all the message data has been sent so lets get this # over with aleady fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "DATA not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * Expand($name) * * Expand takes the name and asks the server to list all the * people who are members of the _list_. Expand will return * back and array of the result or false if an error occurs. * Each value in the array returned has the format of: * [ ] * The definition of is defined in rfc 821 * * Implements rfc 821: EXPN * * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 550 * SMTP CODE ERROR : 500,501,502,504,421 */ function Expand($name) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Expand() without being connected"); return false; } fputs($this->smtp_conn,"EXPN " . $name . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "EXPN not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } # parse the reply and place in our array to return to user $entries = explode($this->CRLF,$rply); while(list(,$l) = @each($entries)) { $list[] = substr($l,4); } return $rval; } /* * Hello($host="") * * Sends the HELO command to the smtp server. * This makes sure that we and the server are in * the same known state. * * Implements from rfc 821: HELO * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500, 501, 504, 421 */ function Hello($host="") { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Hello() without being connected"); return false; } # if a hostname for the HELO wasn't specified determine # a suitable one to send if(empty($host)) { # we need to determine some sort of appopiate default # to send to the server $host = "localhost"; } fputs($this->smtp_conn,"HELO " . $host . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "HELO not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } $this->helo_rply = $rply; return true; } /* * Help($keyword="") * * Gets help information on the keyword specified. If the keyword * is not specified then returns generic help, ussually contianing * A list of keywords that help is available on. This function * returns the results back to the user. It is up to the user to * handle the returned data. If an error occurs then false is * returned with $this->error set appropiately. * * Implements rfc 821: HELP [ ] * * SMTP CODE SUCCESS: 211,214 * SMTP CODE ERROR : 500,501,502,504,421 */ function Help($keyword="") { $this->error = null; # to avoid confusion if(!$this->connected()) { $this->error = array( "error" => "Called Help() without being connected"); return false; } $extra = ""; if(!empty($keyword)) { $extra = " " . $keyword; } fputs($this->smtp_conn,"HELP" . $extra . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 211 && $code != 214) { $this->error = array("error" => "HELP not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return $rply; } /* * Mail($from) * * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. * * Implements rfc 821: MAIL FROM: * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,421 */ function Mail($from) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Mail() without being connected"); return false; } fputs($this->smtp_conn,"MAIL FROM:" . $from . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "MAIL not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * Noop() * * Sends the command NOOP to the SMTP server. * * Implements from rfc 821: NOOP * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500, 421 */ function Noop() { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Noop() without being connected"); return false; } fputs($this->smtp_conn,"NOOP" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "NOOP not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * Quit($close_on_error=true) * * Sends the quit command to the server and then closes the socket * if there is no error or the $close_on_error argument is true. * * Implements from rfc 821: QUIT * * SMTP CODE SUCCESS: 221 * SMTP CODE ERROR : 500 */ function Quit($close_on_error=true) { $this->error = null; # so there is no confusion if(!$this->connected()) { $this->error = array( "error" => "Called Quit() without being connected"); return false; } # send the quit command to the server fputs($this->smtp_conn,"quit" . $this->CRLF); # get any good-bye messages $byemsg = $this->get_lines(); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $byemsg; } $rval = true; $e = null; $code = substr($byemsg,0,3); if($code != 221) { # use e as a tmp var cause Close will overwrite $this->error $e = array("error" => "SMTP server rejected quit command", "smtp_code" => $code, "smtp_rply" => substr($byemsg,4)); $rval = false; if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF; } } if(empty($e) || $close_on_error) { $this->Close(); } return $rval; } /* * Recipient($to) * * Sends the command RCPT to the SMTP server with the TO: argument of $to. * Returns true if the recipient was accepted false if it was rejected. * * Implements from rfc 821: RCPT TO: * * SMTP CODE SUCCESS: 250,251 * SMTP CODE FAILURE: 550,551,552,553,450,451,452 * SMTP CODE ERROR : 500,501,503,421 */ function Recipient($to) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Recipient() without being connected"); return false; } fputs($this->smtp_conn,"RCPT TO:" . $to . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250 && $code != 251) { $this->error = array("error" => "RCPT not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * Reset() * * Sends the RSET command to abort and transaction that is * currently in progress. Returns true if successful false * otherwise. * * Implements rfc 821: RSET * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500,501,504,421 */ function Reset() { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Reset() without being connected"); return false; } fputs($this->smtp_conn,"RSET" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "RSET failed", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * Send($from) * * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. This command * will send the message to the users terminal if they are logged * in. * * Implements rfc 821: SEND FROM: * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,502,421 */ function Send($from) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Send() without being connected"); return false; } fputs($this->smtp_conn,"SEND FROM:" . $from . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "SEND not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * SendAndMail($from) * * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. This command * will send the message to the users terminal if they are logged * in and send them an email. * * Implements rfc 821: SAML FROM: * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,502,421 */ function SendAndMail($from) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called SendAndMail() without being connected"); return false; } fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "SAML not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * SendOrMail($from) * * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. This command * will send the message to the users terminal if they are logged * in or mail it to them if they are not. * * Implements rfc 821: SOML FROM: * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,502,421 */ function SendOrMail($from) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called SendOrMail() without being connected"); return false; } fputs($this->smtp_conn,"SOML FROM:" . $from . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250) { $this->error = array("error" => "SOML not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } /* * Turn() * * This is an optional command for SMTP that this class does not * support. This method is here to make the RFC821 Definition * complete for this class and __may__ be implimented in the future * * Implements from rfc 821: TURN * * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 502 * SMTP CODE ERROR : 500, 503 */ function Turn() { $this->error = array("error" => "This method, TURN, of the SMTP ". "is not implemented"); if($this->do_debug >= 1) { echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF; } return false; } /* * Verify($name) * * Verifies that the name is recognized by the server. * Returns false if the name could not be verified otherwise * the response from the server is returned. * * Implements rfc 821: VRFY * * SMTP CODE SUCCESS: 250,251 * SMTP CODE FAILURE: 550,551,553 * SMTP CODE ERROR : 500,501,502,421 */ function Verify($name) { $this->error = null; # so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Verify() without being connected"); return false; } fputs($this->smtp_conn,"VRFY " . $name . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; } if($code != 250 && $code != 251) { $this->error = array("error" => "VRFY failed on name '$name'", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return $rply; } /****************************************************************** * INTERNAL FUNCTIONS * ******************************************************************/ /* * get_lines() * * __internal_use_only__: read in as many lines as possible * either before eof or socket timeout occurs on the operation. * With SMTP we can tell if we have more lines to read if the * 4th character is '-' symbol. If it is a space then we don't * need to read anything else. */ function get_lines() { $data = ""; while($str = fgets($this->smtp_conn,515)) { if($this->do_debug >= 4) { echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF; echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF; } $data .= $str; if($this->do_debug >= 4) { echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF; } # if the 4th character is a space then we are done reading # so just break the loop if(substr($str,3,1) == " ") { break; } } return $data; } /****************************************************************** * EXTENDED FUNCTIONALITY * ******************************************************************/ /* * Authenticate() * * Performs SMTP authentication. Must be run after running the * Hello() method. Returns true if successfully authenticated. * * Submitted by: "Brent R. Matzelle" */ function Authenticate($username, $password) { // Start authentication fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($code != 334) { $this->error = array("error" => "AUTH not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } // Send encoded username fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($code != 334) { $this->error = array("error" => "Username not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } // Send encoded password fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($code != 235) { $this->error = array("error" => "Password not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF; } return false; } return true; } } ?>