Пример #1
0
/**
 * Get a new file to write an attachment to.
 * This function makes sure it doesn't overwrite other attachments,
 * preventing collisions and race conditions.
 *
 * @return filename of the tempfile only (not full path)
 * @since 1.5.2
 */
function sq_get_attach_tempfile()
{
    global $username, $attachment_dir;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    // using PHP >= 4.3.2 we can be truly atomic here
    $filemods = check_php_version(4, 3, 2) ? 'x' : 'w';
    // give up after 1000 tries
    $TMP_MAX = 1000;
    for ($try = 0; $try < $TMP_MAX; ++$try) {
        $localfilename = GenerateRandomString(32, '', 7);
        $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
        // filename collision. try again
        if (file_exists($full_localfilename)) {
            continue;
        }
        // try to open for (binary) writing
        $fp = @fopen($full_localfilename, $filemods);
        if ($fp !== FALSE) {
            // success! make sure it's not readable, close and return filename
            chmod($full_localfilename, 0600);
            fclose($fp);
            return $localfilename;
        }
    }
    // we tried 1000 times but didn't succeed.
    error_box(_("Could not open temporary file to store attachment. Contact your system administrator to resolve this issue."));
    return FALSE;
}
Пример #2
0
function getMessage_RFC822_Attachment($message, $composeMessage, $passed_id, $passed_ent_id = '', $imapConnection)
{
    global $attachments, $attachment_dir, $username, $data_dir, $uid_support;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    if (!$passed_ent_id) {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' RFC822', TRUE, $response, $readmessage, $uid_support);
    } else {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' BODY[' . $passed_ent_id . ']', TRUE, $response, $readmessage, $uid_support);
        $message = $message->parent;
    }
    if ($response == 'OK') {
        $subject = encodeHeader($message->rfc822_header->subject);
        array_shift($body_a);
        $body = implode('', $body_a) . "\r\n";
        $localfilename = GenerateRandomString(32, 'FILE', 7);
        $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
        $fp = fopen($full_localfilename, 'w');
        fwrite($fp, $body);
        fclose($fp);
        /* dirty relative dir fix */
        if (substr($attachment_dir, 0, 3) == '../') {
            $attachment_dir = substr($attachment_dir, 3);
            $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
        }
        $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
        $composeMessage->initAttachment('message/rfc822', 'email.txt', $full_localfilename);
    }
    return $composeMessage;
}
Пример #3
0
/**
 * Generates a unique file in a specific directory and
 * returns the file name (without the path).
 *
 * @param directory The directory within which to create the file
 *
 * @return mixed FALSE when a failure occurs, otherwise a string
 *               containing the filename of the file only (not
 *               its full path)
 *
 * @since 1.5.2
 *
 */
function sq_create_tempfile($directory)
{
    // give up after 1000 tries
    $maximum_tries = 1000;
    // using PHP >= 4.3.2 we can be truly atomic here
    $filemods = check_php_version(4, 3, 2) ? 'x' : 'w';
    for ($try = 0; $try < $maximum_tries; ++$try) {
        $localfilename = GenerateRandomString(32, '', 7);
        $full_localfilename = $directory . DIRECTORY_SEPARATOR . $localfilename;
        // filename collision. try again
        if (file_exists($full_localfilename)) {
            continue;
        }
        // try to open for (binary) writing
        $fp = @fopen($full_localfilename, $filemods);
        if ($fp !== FALSE) {
            // success! make sure it's not readable, close and return filename
            chmod($full_localfilename, 0600);
            fclose($fp);
            return $localfilename;
        }
    }
    // we tried as many times as we could but didn't succeed.
    return FALSE;
}
function attachSelectedMessages($msg, $imapConnection)
{
    global $username, $attachment_dir, $startMessage, $data_dir, $composesession, $uid_support, $msgs, $thread_sort_messages, $allow_server_sort, $show_num, $compose_messages;
    if (!isset($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir, $composesession);
    if ($thread_sort_messages || $allow_server_sort) {
        $start_index = 0;
    } else {
        $start_index = ($startMessage - 1) * $show_num;
    }
    $i = 0;
    $j = 0;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    while ($j < count($msg)) {
        if (isset($msg[$i])) {
            $id = $msg[$i];
            $body_a = sqimap_run_command($imapConnection, "FETCH {$id} RFC822", true, $response, $readmessage, $uid_support);
            if ($response == 'OK') {
                // fetch the subject for the message with $id from msgs.
                // is there a more efficient way to do this?
                foreach ($msgs as $k => $vals) {
                    if ($vals['ID'] == $id) {
                        $subject = $msgs[$k]['SUBJECT'];
                        break;
                    }
                }
                array_shift($body_a);
                array_pop($body_a);
                $body = implode('', $body_a);
                $body .= "\r\n";
                $localfilename = GenerateRandomString(32, 'FILE', 7);
                $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
                $fp = fopen($full_localfilename, 'wb');
                fwrite($fp, $body);
                fclose($fp);
                $composeMessage->initAttachment('message/rfc822', $subject . '.msg', $full_localfilename);
            }
            $j++;
        }
        $i++;
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    session_write_close();
    return $composesession;
}
Пример #5
0
function password_forget_pre()
{
    global $username_form_name, $password_form_name;
    global $newUsername;
    $newUsername = GenerateRandomString(10, '', 3);
    $newPassword = GenerateRandomString(10, '', 3);
    while ($newPassword == $newUsername) {
        $newPassword = GenerateRandomString(10, 3);
    }
    echo "<input type=\"hidden\" name=\"login_username\" value=\"{$newUsername}\">\n";
    echo "<input type=\"hidden\" name=\"secretkey\" value=\"{$newPassword}\">\n";
    $username_form_name = $newUsername;
    $password_form_name = $newPassword;
}
Пример #6
0
	function SearchDefault(&$result, $s, $colors, $colors2) {
		error_reporting(-1);
		ini_set('display_errors', '1');
	
		/* escape all the variables and put them back into meaningful variable names */
		foreach ($s as $key => $value) {
			if (is_scalar($value)) { $$key = mysql_real_escape_string($s[$key]); }
			else { $$key = $s[$key]; }
		}
	
		/* ---------------- regular search --------------- */
		$s_studymodality = strtolower($s_studymodality);
		$sqlstring3 = "select data_id, rating_value from ratings where rating_type = 'series' and data_modality = '$s_studymodality'";
		$result3 = MySQLQuery($sqlstring3,__FILE__,__LINE__);
		while ($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)) {
			//$ratingseriesids[] = $row3['data_id'];
			$ratingseriesid = $row3['data_id'];
			$ratings[$ratingseriesid][] = $row3['rating_value'];
		}
		?>
		<br><br>
		<form name="subjectlist" method="post" action="search.php">
		<input type="hidden" name="modality" value="<?php 
echo $s_studymodality;
?>
">
		<input type="hidden" name="action" value="submit">
		<?
		
		if (strtolower($s_studymodality) == "mr") {
			/* get the movement & SNR stats by sequence name */
			$sqlstring2 = "SELECT b.series_sequencename, max(a.move_maxx) 'maxx', min(a.move_minx) 'minx', max(a.move_maxy) 'maxy', min(a.move_miny) 'miny', max(a.move_maxz) 'maxz', min(a.move_minz) 'minz', avg(a.pv_snr) 'avgpvsnr', avg(a.io_snr) 'avgiosnr', std(a.pv_snr) 'stdpvsnr', std(a.io_snr) 'stdiosnr', min(a.pv_snr) 'minpvsnr', min(a.io_snr) 'miniosnr', max(a.pv_snr) 'maxpvsnr', max(a.io_snr) 'maxiosnr', min(a.motion_rsq) 'minmotion', max(a.motion_rsq) 'maxmotion', avg(a.motion_rsq) 'avgmotion', std(a.motion_rsq) 'stdmotion' FROM mr_qa a left join mr_series b on a.mrseries_id = b.mrseries_id where a.io_snr > 0 group by b.series_sequencename";
			//echo "$sqlstring2<br>";
			$result2 = MySQLQuery($sqlstring2,__FILE__,__LINE__);
			while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
				$sequence = $row2['series_sequencename'];
				$pstats[$sequence]['avgpvsnr'] = $row2['avgpvsnr'];
				$pstats[$sequence]['stdpvsnr'] = $row2['stdpvsnr'];
				$pstats[$sequence]['minpvsnr'] = $row2['minpvsnr'];
				$pstats[$sequence]['maxpvsnr'] = $row2['maxpvsnr'];
				$pstats[$sequence]['avgiosnr'] = $row2['avgiosnr'];
				$pstats[$sequence]['stdiosnr'] = $row2['stdiosnr'];
				$pstats[$sequence]['miniosnr'] = $row2['miniosnr'];
				$pstats[$sequence]['maxiosnr'] = $row2['maxiosnr'];
				$pstats[$sequence]['avgmotion'] = $row2['avgmotion'];
				$pstats[$sequence]['stdmotion'] = $row2['stdmotion'];
				$pstats[$sequence]['minmotion'] = $row2['minmotion'];
				$pstats[$sequence]['maxmotion'] = $row2['maxmotion'];
	
				if ($row2['stdiosnr'] != 0) {
					$pstats[$sequence]['maxstdiosnr'] = ($row2['avgiosnr'] - $row2['miniosnr'])/$row2['stdiosnr'];
				} else { $pstats[$sequence]['maxstdiosnr'] = 0; }
				if ($row2['stdpvsnr'] != 0) {
					$pstats[$sequence]['maxstdpvsnr'] = ($row2['avgpvsnr'] - $row2['minpvsnr'])/$row2['stdpvsnr'];
				} else { $pstats[$sequence]['maxstdpvsnr'] = 0; }
				if ($row2['stdmotion'] != 0) {
					$pstats[$sequence]['maxstdmotion'] = ($row2['avgmotion'] - $row2['minmotion'])/$row2['stdmotion'];
				} else { $pstats[$sequence]['maxstdmotion'] = 0; }
			}
			
			//print_r($pstats);
		}
		?>
		<? if ($s_resultorder == "table") { ?>
		<table width="100%" class="searchresultssheet">
		<? } else { ?>
		<table width="100%" class="searchresults">
		<? } ?>
			<script type="text/javascript">
			$(document).ready(function() {
				$("#seriesall").click(function() {
					var checked_status = this.checked;
					$(".allseries").find("input[type='checkbox']").each(function() {
						this.checked = checked_status;
					});
				});
			});
			</script>
		<?
		$projectids = array();
		$projectnames = array();

		/* get the users id */
		$sqlstringC = "select user_id from users where username = '******'username'] ."'";
		$resultC = MySQLQuery($sqlstringC,__FILE__,__LINE__);
		$rowC = mysql_fetch_array($resultC, MYSQL_ASSOC);
		$userid = $rowC['user_id'];
				
		/* check to see which projects this user has access to view */
		$sqlstringC = "select a.project_id 'projectid', b.project_name 'projectname' from user_project a left join projects b on a.project_id = b.project_id where a.user_id = $userid and (a.view_data = 1 or a.view_phi = 1)";
		//print "$sqlstringC<br>";
		$resultC = MySQLQuery($sqlstringC,__FILE__,__LINE__);
		while ($rowC = mysql_fetch_array($resultC, MYSQL_ASSOC)) {
			$projectids[] = $rowC['projectid'];
		}
		
		/* tell the user if there are results for projects they don't have access to */
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$projectid = $row['project_id'];
			$projectname = $row['project_name'];
			$studyid = $row['study_id'];
			$subjectid = $row['subject_id'];
			$uid = $row['uid'];

			if (!in_array($projectid, $projectids)) {
				//echo "$projectid is not in projectids<br>";
				if (!in_array($projectname, $projectnames)) {
					//echo "$projectname is not in projectnames<br>";
					$projectnames[] = $projectname;
				}
			}
			
			/* BUT: while we're in this loop, count the # of unique studies ... */
			if ((!isset($studies)) || (!in_array($studyid, $studies))) {
				$studies[] = $studyid;
			}
			/* ... and # of unique subjects */
			if ((!isset($subjects)) || (!in_array($subjectid, $subjects))) {
				$subjects[] = $subjectid;
			}
			/* also a unique list of UIDs */
			if ((!isset($uids)) || (!in_array($uid, $uids))) {
				$uids[] = $uid;
			}
		}
		
		/* get the measures, if requested */
		$measurenames = null;
		if ($s_measurelist != "") {
			$searchcriteria = ParseMeasureResultList($s_measurelist, "d.measure_name");
			
			if ($s_measurelist == "*") {
				$sqlstringD = "select a.subject_id, b.enrollment_id, c.*, d.measure_name from measures c join measurenames d on c.measurename_id = d.measurename_id left join enrollment b on c.enrollment_id = b.enrollment_id join subjects a on a.subject_id = b.subject_id where a.subject_id in (" . implode2(",", $subjects) . ")";
			}
			else {
				$sqlstringD = "select a.subject_id, b.enrollment_id, c.*, d.measure_name from measures c join measurenames d on c.measurename_id = d.measurename_id left join enrollment b on c.enrollment_id = b.enrollment_id join subjects a on a.subject_id = b.subject_id where a.subject_id in (" . implode2(",", $subjects) . ") and d.measure_name in (" . MakeSQLList($s_measurelist) . ")";
			}
			
			//PrintSQL($sqlstringD);
			$resultD = MySQLQuery($sqlstringD,__FILE__,__LINE__);
			//echo "<pre>";
			//print_r($sqlstringD);
			//echo "</pre>";
			//PrintSQLTable($resultD);
			//$i=0;
			while ($rowD = mysql_fetch_array($resultD, MYSQL_ASSOC)) {
				if ($rowD['measure_type'] == 's') {
					$measuredata[$rowD['subject_id']][$rowD['measure_name']]['value'] = $rowD['measure_valuestring'];
				}
				else {
					$measuredata[$rowD['subject_id']][$rowD['measure_name']]['value'] = $rowD['measure_valuenum'];
				}
				$measuredata[$rowD['subject_id']][$rowD['measure_name']]['notes'] = $rowD['measure_notes'];
				$measurenames[] = $rowD['measure_name'];
				//$i++;
			}
			$measurenames = array_unique($measurenames);
			natcasesort($measurenames);
			//echo "<pre>";
			//print_r($measurenames);
			//print_r($measuredata);
			//echo "</pre>";
		}
		
		/* if there was a list of UIDs or alternate UIDs, determine which were not found */
		if ($s['s_subjectuid'] != "") {
			$uidsearchlist = preg_split('/[\^,;\-\'\s\t\n\f\r]+/', $s['s_subjectuid']);
			$missinguids = array_diff($uidsearchlist,$uids);
		}
		if ($s['s_subjectaltuid'] != "") {
			$altuidsearchlist = preg_split('/[\^,;\-\'\s\t\n\f\r]+/', $s['s_subjectaltuid']);

			/* get list of UIDs from the list of alternate UIDs */
			$sqlstringX = "select altuid from subject_altuid a left join subjects b on a.subject_id = b.subject_id where a.altuid in (" . MakeSQLList($s['s_subjectaltuid']) . ")";
			$resultX = MySQLQuery($sqlstringX,__FILE__,__LINE__);
			while ($rowX = mysql_fetch_array($resultX, MYSQL_ASSOC)) {
				$altuids[] = $rowX['altuid'];
			}
			$missingaltuids = array_diff($altuidsearchlist,$altuids);
		}
		if ($s['s_subjectgroupid'] != "") {
			$subjectids = explode(',', GetIDListFromGroup($s['s_subjectgroupid']));
			$missingsubjects = array_diff($subjectids,$subjects);
			if (count($missingstudies) > 0) {
				$sqlstringY = "select uid from subjects where subject_id in (" . implode(',',$missingsubjects) . ")";
				$resultY = MySQLQuery($sqlstringY,__FILE__,__LINE__);
				while ($rowY = mysql_fetch_array($resultY, MYSQL_ASSOC)) {
					$missinguids[] = $rowY['uid'];
				}
			}
		}
		if ($s['s_studygroupid'] != "") {
			$studyids = explode(',', GetIDListFromGroup($s['s_studygroupid']));
			$missingstudies = array_diff($studyids,$studies);
			//PrintVariable($studies,'studies');
			if (count($missingstudies) > 0) {
				$sqlstringY = "select a.study_num, c.uid from studies a left join enrollment b on a.enrollment_id = b.enrollment_id left join subjects c on c.subject_id = b.subject_id where study_id in (" . implode(',',$missingstudies) . ")";
				$resultY = MySQLQuery($sqlstringY,__FILE__,__LINE__);
				while ($rowY = mysql_fetch_array($resultY, MYSQL_ASSOC)) {
					$missingstudynums[] = $rowY['uid'] . $rowY['study_num'];
				}
			}
		}
		?>
		Found <b><?php 
echo count($subjects);
?>
 subjects</b> in <b><?php 
echo count($studies);
?>
 studies</b> with <b><?php 
echo mysql_num_rows($result);
?>
 series</b> matching your query<!-- &nbsp; &nbsp; <span class="sublabel">Query took <?php 
echo number_format($querytime, 4);
?>
 sec to execute</span>-->
		<?
			if (count($missinguids) > 0) {
			?>
				<details>
				<summary style="font-size:9pt; background-color: orangered; color: white;"><?php 
echo count($missinguids);
?>
 UIDs not found</summary>
				<span style="font-size:9pt"><?php 
echo implode('<br>', $missinguids);
?>
</span>
				</details>
			<?
			}
			elseif ($uidsearchlist != '') {
			?>
				<br><span style="font-size:8pt">All UIDs found</span>
			<?
			}
			
			if (count($missingaltuids) > 0) {
			?>
				<details>
				<summary style="font-size:9pt; background-color: orangered; color: white;"><?php 
echo count($missingaltuids);
?>
 alternate UIDs not found</summary>
				<span style="font-size:9pt"><?php 
echo implode('<br>', $missingaltuids);
?>
</span>
				</details>
			<?
			}
			elseif ($altuidsearchlist != '') {
			?>
				<br><span style="font-size:8pt">All alternate UIDs found</span>
			<?
			}
			
			if (count($missingstudynums) > 0) {
			?>
				<details>
				<summary style="font-size:9pt; background-color: orangered; color: white;"><?php 
echo count($missingstudynums);
?>
 Studies not found</summary>
				<span style="font-size:9pt"><?php 
echo implode('<br>', $missingstudynums);
?>
</span>
				</details>
			<?
			}
			elseif ($uidsearchlist != '') {
			?>
				<br><span style="font-size:8pt">All UIDs found</span>
			<?
			}
		?>
		<br><br>
		<?
		if (count($projectnames) > 0) {
		?>
			<div style="border: 2px solid darkred; background-color: #FFEEEE; text-align: left; padding:5px; border-radius: 5px">
			<b>Your search results contain subjects enrolled in the following projects to which you do not have view access</b>
			<br>Contact your PI or project administrator for access
			<ul>
			<?
			natcasesort($projectnames);
			foreach ($projectnames as $projectname) {
				echo "<li>$projectname</li>\n";
			}
			?>
			</ul>
			</div>
			<?
		}
		
		/* ----- loop through the results and display them ----- */
		mysql_data_seek($result,0); /* rewind the record pointer */
		$laststudy_id = "";
		$headeradded = 0;
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			//echo "<pre>";
			//print_r($row);
			//echo "</pre>";
			
			$project_id = $row['project_id'];
			/* if the user doesn't have view access to this project, skip to the next record */
			if (($projectids == null) || (!in_array($project_id, $projectids))) {
				continue;
			}
			$enrollment_id = $row['enrollment_id'];
			$subject_id = $row['subject_id'];
			$project_name = $row['project_name'];
			$project_costcenter = $row['project_costcenter'];
			$name = $row['name'];
			$birthdate = $row['birthdate'];
			$gender = $row['gender'];
			$uid = $row['uid'];
			$subject_id = $row['subject_id'];
			$study_id = $row['study_id'];
			$study_num = $row['study_num'];
			$study_desc = $row['study_desc'];
			$study_type = $row['study_type'];
			$study_height = $row['study_height'];
			$study_weight = $row['study_weight'];
			$study_alternateid = $row['study_alternateid'];
			$study_modality = strtolower($row['study_modality']);
			$study_datetime = $row['study_datetime'];
			$study_ageatscan = $row['study_ageatscan'];
			$study_type = $row['study_type'];
			$study_operator = $row['study_operator'];
			$study_performingphysician = $row['study_performingphysician'];
			$study_site = $row['study_site'];
			$study_institution = $row['study_institution'];
			$enrollsubgroup = $row['enroll_subgroup'];

			/* get list of alternate subject UIDs */
			$altuids = GetAlternateUIDs($subject_id);
			if (count($altuids) > 0) {
				$altuidlist = implode2(",",$altuids);
			}
			else {
				$altuidlist = "";
			}
			
			/* calculate the BMI */
			if (($study_height == 0) || ($study_weight == 0)) {
				$study_bmi = 0;
			}
			else {
				$study_bmi = $study_weight / ( $study_height * $study_height);
			}

			$newstudyid = $uid . $study_num;

			/* calculate age at scan */
			if (($study_ageatscan == '') || ($study_ageatscan == 0)) {
				list($year, $month, $day) = explode("-", $birthdate);
				$d1 = mktime(0,0,0,$month,$day,$year);
				list($year, $month, $day, $extra) = explode("-", $study_datetime);
				$d2 = mktime(0,0,0,$month,$day,$year);
				$ageatscan = floor(($d2-$d1)/31536000);
			}
			else {
				$ageatscan = $study_ageatscan;
			}

			/* fix some fields */
			list($lname, $fname) = explode("^",$name);
			$name = strtoupper(substr($fname,0,1)) . strtoupper(substr($lname,0,1));
			$study_desc = str_replace("^"," ",$study_desc);
			if (($s_resultorder == "study") || ($s_resultorder == "export")) {
				$study_datetime = date("M j, Y g:ia",strtotime($study_datetime));
			}
			else {
				$study_datetime = date("Y-m-d H:i",strtotime($study_datetime));
			}

			/* gather series specific info based on modality */
			if ($study_modality == "mr") {
				$series_id = $row['mrseries_id'];
				$series_datetime = $row['series_datetime'];
				$series_desc = $row['series_desc'];
				$series_altdesc = $row['series_altdesc'];
				$sequence = $row['series_sequencename'];
				$series_num = $row['series_num'];
				$series_tr = $row['series_tr'];
				$series_spacingx = $row['series_spacingx'];
				$series_spacingy = $row['series_spacingy'];
				$series_spacingz = $row['series_spacingz'];
				$series_fieldstrength = $row['series_fieldstrength'];
				$series_notes = $row['series_notes'];
				$img_rows = $row['img_rows'];
				$img_cols = $row['img_cols'];
				$img_slices = $row['img_slices'];
				$bold_reps = $row['bold_reps'];
				$numfiles = $row['numfiles'];
				$series_size = $row['series_size'];
				$numfiles_beh = $row['numfiles_beh'];
				$beh_size = $row['beh_size'];
				$series_status = $row['series_status'];
				$is_derived = $row['is_derived'];
				$move_minx = $row['move_minx'];
				$move_miny = $row['move_miny'];
				$move_minz = $row['move_minz'];
				$move_maxx = $row['move_maxx'];
				$move_maxy = $row['move_maxy'];
				$move_maxz = $row['move_maxz'];
				$rot_maxp = $row['rot_maxp'];
				$rot_maxr = $row['rot_maxr'];
				$rot_maxy = $row['rot_maxy'];
				$rot_minp = $row['rot_minp'];
				$rot_minr = $row['rot_minr'];
				$rot_miny = $row['rot_miny'];
				$iosnr = $row['io_snr'];
				$pvsnr = $row['pv_snr'];
				$motion_rsq = $row['motion_rsq'];
				
				$thumbpath = $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/thumb.png";
				$gifthumbpath = $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/thumb.gif";
				$realignpath = $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/MotionCorrection.txt";
				
				$series_datetime = date("g:ia",strtotime($series_datetime));
				$series_size = HumanReadableFilesize($series_size);
				$beh_size = HumanReadableFilesize($beh_size);
				
				if (($sequence == "epfid2d1_64") && ($numfiles_beh < 1)) { $behcolor = "red"; } else { $behcolor = ""; }
				/* format the colors for realignment and SNR */
				$rangex = abs($move_minx) + abs($move_maxx);
				$rangey = abs($move_miny) + abs($move_maxy);
				$rangez = abs($move_minz) + abs($move_maxz);
				$rangePitch = abs($rot_minp) + abs($rot_maxp);
				$rangeRoll = abs($rot_minr) + abs($rot_maxr);
				$rangeYaw = abs($rot_miny) + abs($rot_maxy);
				
				/* calculate color based on voxel size... red (100) means more than 1 voxel displacement in that direction */
				if ($series_spacingx > 0) { $xindex = round(($rangex/$series_spacingx)*100); if ($xindex > 100) { $xindex = 100; } }
				if ($series_spacingy > 0) { $yindex = round(($rangey/$series_spacingy)*100); if ($yindex > 100) { $yindex = 100; } }
				if ($series_spacingz > 0) { $zindex = round(($rangez/$series_spacingz)*100); if ($zindex > 100) { $zindex = 100; } }

				/* get standard deviations from the mean for SNR */
				if ($pstats[$sequence]['stdiosnr'] != 0) {
					if ($iosnr > $pstats[$sequence]['avgiosnr']) {
						$stdsiosnr = 0;
					}
					else {
						$stdsiosnr = (($iosnr - $pstats[$sequence]['avgiosnr'])/$pstats[$sequence]['stdiosnr']);
					}
				}
				if ($pstats[$sequence]['stdpvsnr'] != 0) {
					if ($pvsnr > $pstats[$sequence]['avgpvsnr']) {
						$stdspvsnr = 0;
					}
					else {
						$stdspvsnr = (($pvsnr - $pstats[$sequence]['avgpvsnr'])/$pstats[$sequence]['stdpvsnr']);
					}
				}
				if ($pstats[$sequence]['stdmotion'] != 0) {
					if ($motion_rsq > $pstats[$sequence]['avgmotion']) {
						$stdsmotion = 0;
					}
					else {
						$stdsmotion = (($motion_rsq - $pstats[$sequence]['avgmotion'])/$pstats[$sequence]['stdmotion']);
					}
				}
				
				if ($pstats[$sequence]['maxstdpvsnr'] == 0) { $pvindex = 100; }
				else { $pvindex = round(($stdspvsnr/$pstats[$sequence]['maxstdpvsnr'])*100); }
				$pvindex = 100 + $pvindex;
				if ($pvindex > 100) { $pvindex = 100; }
				
				if ($pstats[$sequence]['maxstdiosnr'] == 0) { $ioindex = 100; }
				else { $ioindex = round(($stdsiosnr/$pstats[$sequence]['maxstdiosnr'])*100); }
				$ioindex = 100 + $ioindex;
				if ($ioindex > 100) { $ioindex = 100; }
				
				if ($pstats[$sequence]['maxstdmotion'] == 0) { $motionindex = 100; }
				else { $motionindex = round(($stdsmotion/$pstats[$sequence]['maxstdmotion'])*100); }
				$motionindex = 100 + $motionindex;
				if ($motionindex > 100) { $motionindex = 100; }
				
				$maxpvsnrcolor = $colors[100-$pvindex];
				$maxiosnrcolor = $colors[100-$ioindex];
				$maxmotioncolor = $colors[100-$motionindex];
				if ($pvsnr <= 0.0001) { $pvsnr = "-"; $maxpvsnrcolor = "#FFFFFF"; }
				else { $pvsnr = number_format($pvsnr,2); }
				if ($iosnr <= 0.0001) { $iosnr = "-"; $maxiosnrcolor = "#FFFFFF"; }
				else { $iosnr = number_format($iosnr,2); }
				if ($motion_rsq <= 0.0001) { $motion_rsq = "-"; $maxmotioncolor = ""; }
				else { $motion_rsq = number_format($motion_rsq,5); }
				
				/* setup movement colors */
				$maxxcolor = $colors[$xindex];
				$maxycolor = $colors[$yindex];
				$maxzcolor = $colors[$zindex];
				if ($rangex <= 0.0001) { $rangex = "-"; $maxxcolor = "#FFFFFF"; }
				else { $rangex = number_format($rangex,2); }
				if ($rangey <= 0.0001) { $rangey = "-"; $maxycolor = "#FFFFFF"; }
				else { $rangey = number_format($rangey,2); }
				if ($rangez <= 0.0001) { $rangez = "-"; $maxzcolor = "#FFFFFF"; }
				else { $rangez = number_format($rangez,2); }
				
				/* check if this is real data, or unusable data based on the ratings, and get rating counts */
				$isbadseries = false;
				$istestseries = false;
				$ratingcount2 = '';
				$hasratings = false;
				$rowcolor = '';
				if (isset($ratings)) {
					foreach ($ratings as $key => $ratingarray) {
						if ($key == $series_id) {
							$hasratings = true;
							if (in_array(5,$ratingarray)) {
								$isbadseries = true;
								//echo "IsBadSeries is true";
							}
							if (in_array(6,$ratingarray)) {
								$istestseries = true;
							}
							$ratingcount2 = count($ratingarray);
							break;
						}
					}
				}
				if ($isbadseries) { $rowcolor = "red"; }
				if ($istestseries) { $rowcolor = "#AAAAAA"; }
			}
			else {
				$series_id = $row[$study_modality . 'series_id'];
				$series_num = $row['series_num'];
				$series_datetime = $row['series_datetime'];
				$series_protocol = $row['series_protocol'];
				$series_numfiles = $row['series_numfiles'];
				$series_size = $row['series_size'];
				$series_notes = $row['series_notes'];
				
				$series_datetime = date("g:ia",strtotime($series_datetime));
				if ($series_numfiles < 1) { $series_numfiles = "-"; }
				if ($series_size > 1) { $series_size = HumanReadableFilesize($series_size); } else { $series_size = "-"; }
			}
			
			/* display study header if study */
			if ($study_id != $laststudy_id) {
				if (($s_resultorder == "study") || ($s_resultorder == "export")) {
					/* display study header */
					?>
					<script type="text/javascript">
					$(document).ready(function() {
						$("#study<?php 
echo $study_id;
?>
").click(function() {
							var checked_status = this.checked;
							$(".tr<?php 
echo $study_id;
?>
").find("input[type='checkbox']").each(function() {
								this.checked = checked_status;
							});
						});
					});
					</script>
					<tr>
						<td colspan="19">
							<br>
							<table width="100%" class="searchresultstudy">
								<tr>
									<td class="header1"><?php 
echo $name;
?>
</td>
									<td class="header1"><a href="subjects.php?id=<?php 
echo $subject_id;
?>
" class="header1"><?php 
echo $uid;
?>
</a></td>
									<td class="header3"><?php 
echo $altuidlist;
?>
</td>
									<td class="header2"><a href="studies.php?id=<?php 
echo $study_id;
?>
">Study <?php 
echo $study_num;
?>
</a> <?php 
echo $study_type;
?>
</td>
									<td class="header2"><?php 
echo $project_name;
?>
 (<?php 
echo $project_costcenter;
?>
)</td>
									<td class="header2"><?php 
echo $study_datetime;
?>
</td>
									<td class="header3"><?php 
echo $enrollsubgroup;
?>
</td>
									<td class="header3"><?php 
echo number_format($ageatscan, 1);
?>
Y</td>
									<td class="header3"><?php 
echo $gender;
?>
</td>
									<td class="header3"><?php 
echo $study_alternateid;
?>
</td>
									<td class="header3"><?php 
echo $study_type;
?>
</td>
									<td class="header3"><?php 
echo $study_site;
?>
</td>
								</tr>
							</table>
						</td>
					</tr>
					<?
				}
				/* display the series header only once */
				if ($study_modality == "mr") {
					if (($laststudy_id == "") && ($s_resultorder != "study") && ($s_resultorder != "export") && ($s_resultorder != "csv")) {
						DisplayMRSeriesHeader($s_resultorder, $measurenames);
					}
					if (($s_resultorder == "study") || ($s_resultorder == "export")) {
						DisplayMRStudyHeader($study_id, true, $measurenames);
					}
					if ($s_resultorder == "csv") {
						if (!$headeradded) {
							$header = DisplayMRStudyHeader($study_id, false, $measurenames);
							$csv .= "$header";
							if (count($measurenames) > 0) {
								foreach ($measurenames as $measurename) {
									$csv .= ",$measurename";
								}
							}
							$csv .= "\n";
						}
						$headeradded = 1;
					}
				}
				else {
					if (($laststudy_id == "") && ($s_resultorder != "study") && ($s_resultorder != "export")) {
						DisplayGenericSeriesHeader($s_resultorder);
					}
					if (($s_resultorder == "study") || ($s_resultorder == "export")) {
						DisplayGenericStudyHeader($study_id);
					}
				}
			}
			/* set the css class for the rows */
			if (($s_resultorder == "series") || ($s_resultorder == "table") || ($s_resultorder == "operations")) {
				$rowstyle = "seriesrowsmall";
			}
			else {
				$rowstyle = "seriesrow";
			}
			/* and then display the series... */
			if ($study_modality == "mr") {
				if ($s_resultorder == "csv") {
					if ($s_usealtseriesdesc) {
						$csv .= "$series_num, $series_altdesc, $uid, $gender, $ageatscan, " . implode2(' ',$altuids) . ", $newstudyid, $study_alternateid, $study_type, $study_num, $study_datetime, $study_type, $project_name($project_costcenter), $study_height, $study_weight, $study_bmi, $series_datetime, $move_minx, $move_miny, $move_minz, $move_maxx, $move_maxy, $move_maxz, $rangex, $rangey, $rangez, $rangePitch, $rangeRoll, $rangeYaw, $pvsnr, $iosnr, $img_cols, $img_rows, $numfiles, $series_size, $sequence, $series_tr, $numfiles_beh, $beh_size";
					}
					else {
						$csv .= "$series_num, $series_desc, $uid, $gender, $ageatscan, " . implode2(' ',$altuids) . ", $newstudyid, $study_alternateid, $study_type, $study_num, $study_datetime, $study_type, $project_name($project_costcenter), $study_height, $study_weight, $study_bmi, $series_datetime, $move_minx, $move_miny, $move_minz, $move_maxx, $move_maxy, $move_maxz, $rangex, $rangey, $rangez, $rangePitch, $rangeRoll, $rangeYaw, $pvsnr, $iosnr, $img_cols, $img_rows, $numfiles, $series_size, $sequence, $series_tr, $numfiles_beh, $beh_size";
					}
					if (count($measurenames) > 0) {
						foreach ($measurenames as $measure) {
							$csv .= "," . $measuredata[$subject_id][$measure]['value'];
						}
					}
					$csv .= "\n";
				}
				else {
				?>
					<tr class="tr<?php 
echo $study_id;
?>
 allseries" style="color: <?php 
echo $rowcolor;
?>
; white-space: nowrap">
						<? if ($s_resultorder != "table") { ?>
							<td class="<?php 
echo $rowstyle;
?>
"><input type="checkbox" name="seriesid[]" value="<?php 
echo $series_id;
?>
"></td>
						<? } ?>
						<td class="<?php 
echo $rowstyle;
?>
"><b><?php 
echo $series_num;
?>
</b></td>
						<td class="<?php 
echo $rowstyle;
?>
">
							<!--<a href="protocols.php?action=viewprotocol&protocol=<?php 
echo $series_desc;
?>
" rel="protocols.php?action=viewprotocol&protocol=<?php 
echo $series_desc;
?>
" class="wide cluetip-default" title="Protocol Info">-->
							<span><? if ($s_usealtseriesdesc) { echo $series_altdesc; } else { echo $series_desc; } ?></span></a>
							&nbsp;<a href="preview.php?image=<?php 
echo $thumbpath;
?>
" class="preview"><img src="images/preview.gif" border="0"></a>
							&nbsp;<a href="preview.php?image=<?php 
echo $gifthumbpath;
?>
" class="preview"><img src="images/movie.png" border="0"></a>
						</td>
						<? if (($s_resultorder == "series") || ($s_resultorder == "table") || ($s_resultorder == "operations")) { ?>
							<td class="<?php 
echo $rowstyle;
?>
"><a href="subjects.php?id=<?php 
echo $subject_id;
?>
"><tt><?php 
echo $uid;
?>
</tt></a></td>
							<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $gender;
?>
</td>
							<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo number_format($ageatscan, 1);
?>
Y</td>
							<td class="<?php 
echo $rowstyle;
?>
"><a href="subjects.php?id=<?php 
echo $subject_id;
?>
"><tt><? if (count($altuids) > 0) { echo implode2(', ',$altuids); } ?></tt></a></td>
							<td class="<?php 
echo $rowstyle;
?>
"><a href="studies.php?id=<?php 
echo $study_id;
?>
"><?php 
echo $newstudyid;
?>
</a></td>
							<td class="<?php 
echo $rowstyle;
?>
"><a href="studies.php?id=<?php 
echo $study_id;
?>
"><?php 
echo $study_alternateid;
?>
</a></td>
							<td class="<?php 
echo $rowstyle;
?>
"><a href="studies.php?id=<?php 
echo $study_id;
?>
"><?php 
echo $study_type;
?>
</a></td>
							<td class="<?php 
echo $rowstyle;
?>
"><a href="studies.php?id=<?php 
echo $study_id;
?>
"><?php 
echo $study_num;
?>
</a></td>
							<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $study_datetime;
?>
</td>
							<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_datetime;
?>
</td>
						<? } else { ?>
							<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_datetime;
?>
</td>
						<? } ?>
						<td class="<?php 
echo $rowstyle;
?>
" align="right" style="background-color: <?php 
echo $maxxcolor;
?>
;"><?php 
echo $rangex;
?>
</td>
						<td class="<?php 
echo $rowstyle;
?>
" align="right" style="background-color: <?php 
echo $maxycolor;
?>
;"><?php 
echo $rangey;
?>
</td>
						<td class="<?php 
echo $rowstyle;
?>
" align="right" style="background-color: <?php 
echo $maxzcolor;
?>
;"><?php 
echo $rangez;
?>
</td>
						<? if ($s_resultorder != "table") { ?>
						<td class="<?php 
echo $rowstyle;
?>
" style="padding: 0px 5px;">
							<a href="JavaScript:newPopup('mrseriesqa.php?id=<?php 
echo $series_id;
?>
');"><img src="images/chart.gif" border="0" title="View QA results, including movement correction"></a>
						</td>
						<td class="<?php 
echo $rowstyle;
?>
" style="padding: 0px 5px;">
							<span style="font-size:7pt"><?php 
echo $ratingcount2;
?>
</span>
							<a href="JavaScript:newPopup('ratings.php?id=<?php 
echo $series_id;
?>
&type=series&modality=mr');">
							<? if ($hasratings) { $image = "rating2.png"; } else { $image = "rating.png"; } ?>
							<img src="images/<?php 
echo $image;
?>
" border="0" title="View ratings">
							</a>
						</td>
						<td class="<?php 
echo $rowstyle;
?>
">
							<? if (trim($series_notes) != "") { ?>
							<span title="<?php 
echo $series_notes;
?>
" style="font-size:12pt">&#9998;</span>
							<? } ?>
						</td>
						<? } ?>
						<td class="<?php 
echo $rowstyle;
?>
" align="right" style="background-color: <?php 
echo $maxpvsnrcolor;
?>
;">
							<a href="stddevchart.php?h=40&w=450&min=<?php 
echo $pstats[$sequence]['minpvsnr'];
?>
&max=<?php 
echo $pstats[$sequence]['maxpvsnr'];
?>
&mean=<?php 
echo $pstats[$sequence]['avgpvsnr'];
?>
&std=<?php 
echo $pstats[$sequence]['stdpvsnr'];
?>
&i=<?php 
echo $pvsnr;
?>
&b=yes" class="preview" style="color: black; text-decoration: none"><?php 
echo $pvsnr;
?>
</a> 
						</td>
						<td class="<?php 
echo $rowstyle;
?>
" align="right" style="background-color: <?php 
echo $maxiosnrcolor;
?>
;">
							<a href="stddevchart.php?h=40&w=450&min=<?php 
echo $pstats[$sequence]['miniosnr'];
?>
&max=<?php 
echo $pstats[$sequence]['maxiosnr'];
?>
&mean=<?php 
echo $pstats[$sequence]['avgiosnr'];
?>
&std=<?php 
echo $pstats[$sequence]['stdiosnr'];
?>
&i=<?php 
echo $iosnr;
?>
&b=yes" class="preview" style="color: black; text-decoration: none"><?php 
echo $iosnr;
?>
</a>
						</td>
						<td class="<?php 
echo $rowstyle;
?>
" align="right" style="background-color: <?php 
echo $maxmotioncolor;
?>
; font-size:8pt">
							<a href="stddevchart.php?h=40&w=450&min=<?php 
echo $pstats[$sequence]['minmotion'];
?>
&max=<?php 
echo $pstats[$sequence]['maxmotion'];
?>
&mean=<?php 
echo $pstats[$sequence]['avgmotion'];
?>
&std=<?php 
echo $pstats[$sequence]['stdmotion'];
?>
&i=<?php 
echo $motion_rsq;
?>
&b=yes" class="preview" style="color: black; text-decoration: none"><?php 
echo $motion_rsq;
?>
</a>
						</td>
						<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $img_cols;
?>
&times;<?php 
echo $img_rows;
?>
</td>
						<td class="<?php 
echo $rowstyle;
?>
">
							<?php 
echo $numfiles;
?>
							<?
								if ($s_audit) {
									$files = glob($GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/*.dcm");
									//print_r($files);
									if (count($files) != $numfiles) { ?><span style="color: white; background-color: red; padding: 1px 5px; font-weight: bold"><?php 
echo count($files);
?>
</span> <? }
								}
							?>
						</td>
						<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_size;
?>
</td>
						<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $sequence;
?>
</td>
						<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_tr;
?>
</td>
						<? if ($s_resultorder != "table") { ?>
						<td class="<?php 
echo $rowstyle;
?>
" bgcolor="<?php 
echo $behcolor;
?>
"><?php 
echo $numfiles_beh;
?>
 <span class="tiny">(<?php 
echo $beh_size;
?>
)</span></td>
						<? }
							if (count($measurenames) > 0) {
								foreach ($measurenames as $measure) {
								?>
								<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $measuredata[$subject_id][$measure]['value'];
?>
</td>
								<?
								}
							}
						?>
					</tr>
					<?
				}
			}
			else {
				?>
				<tr class="tr<?php 
echo $study_id;
?>
 allseries">
					<? if ($s_resultorder != "table") { ?>
						<td class="<?php 
echo $rowstyle;
?>
"><input type="checkbox" name="seriesid[]" value="<?php 
echo $series_id;
?>
"></td>
					<? } ?>
					<td class="<?php 
echo $rowstyle;
?>
"><b><?php 
echo $series_num;
?>
</b></td>
					<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_protocol;
?>
</td>
					<? if (($s_resultorder == "series") || ($s_resultorder == "table") || ($s_resultorder == "operations")) { ?>
						<td class="<?php 
echo $rowstyle;
?>
"><tt><?php 
echo $uid;
?>
</tt></td>
						<td class="<?php 
echo $rowstyle;
?>
"><a href="subjects.php?id=<?php 
echo $subject_id;
?>
"><tt><?php 
echo implode2(', ', $altuids);
?>
</tt></a></td>
						<td class="<?php 
echo $rowstyle;
?>
"><a href="studies.php?id=<?php 
echo $study_id;
?>
"><?php 
echo $study_num;
?>
</a></td>
						<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $study_datetime;
?>
</td>
						<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_datetime;
?>
</td>
					<? } else { ?>
						<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_datetime;
?>
</td>
					<? } ?>
					<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_numfiles;
?>
</td>
					<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_size;
?>
</td>
					<td class="<?php 
echo $rowstyle;
?>
"><?php 
echo $series_notes;
?>
</td>
				</tr>
				<?
			}

			$laststudy_id = $study_id;
		}

		/* ---------- generate csv file ---------- */
		if ($s_resultorder == "csv") {
			$filename = "query" . GenerateRandomString(10) . ".csv";
			file_put_contents("/tmp/" . $filename, $csv);
			?>
			<div width="50%" align="center" style="background-color: #FAF8CC; padding: 5px;">
			Download .csv file <a href="download.php?type=file&filename=<?php 
echo "/tmp/{$filename}";
?>
"><img src="images/download16.png"></a>
			</div>
			<?
		}
		?>
		</table>
		
		<?
			/* ---------- display download/group box ---------- */
			if (($s_resultorder == "study") || ($s_resultorder == "series") || ($s_resultorder == "export")) {
				DisplayDownloadBox($s_studymodality, $s_resultorder);
			}
			elseif ($s_resultorder == "operations") {
				DisplayFileIOBox();
			}
		?>
		<br><br><br>
		<?
	}
Пример #7
0
function attachSelectedMessages($msg, $imapConnection)
{
    global $username, $attachment_dir, $startMessage, $data_dir, $composesession, $uid_support, $mailbox, $msgs, $thread_sort_messages, $allow_server_sort, $show_num, $compose_messages;
    if (!isset($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir, $composesession);
    if ($thread_sort_messages || $allow_server_sort) {
        $start_index = 0;
    } else {
        $start_index = ($startMessage - 1) * $show_num;
    }
    $i = 0;
    $j = 0;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    while ($j < count($msg)) {
        if (isset($msg[$i])) {
            $id = $msg[$i];
            $body_a = sqimap_run_command($imapConnection, "FETCH {$id} RFC822", true, $response, $readmessage, $uid_support);
            if ($response == 'OK') {
                $message = sqimap_get_message($imapConnection, $id, $mailbox);
                // fetch the subject for the message from the object
                $filename = $message->rfc822_header->subject;
                if (empty($filename)) {
                    $filename = "untitled-" . $message->entity_id;
                }
                $filename .= '.msg';
                $filename = decodeHeader($filename, false, false);
                array_shift($body_a);
                array_pop($body_a);
                $body = implode('', $body_a);
                $body .= "\r\n";
                $localfilename = GenerateRandomString(32, 'FILE', 7);
                $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
                while (file_exists($full_localfilename)) {
                    $localfilename = GenerateRandomString(32, 'FILE', 7);
                    $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
                }
                $fp = fopen($full_localfilename, 'wb');
                fwrite($fp, $body);
                fclose($fp);
                $composeMessage->initAttachment('message/rfc822', $filename, $localfilename);
            }
            $j++;
        }
        $i++;
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    session_write_close();
    return $composesession;
}
function attachSelectedMessages($imapConnection, $aMsgHeaders)
{
    global $username, $attachment_dir, $data_dir, $composesession, $compose_messages;
    if (!isset($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    foreach ($aMsgHeaders as $iUid => $aMsgHeader) {
        /**
         * Retrieve the full message
         */
        $body_a = sqimap_run_command($imapConnection, "FETCH {$iUid} RFC822", true, $response, $readmessage, TRUE);
        if ($response == 'OK') {
            $subject = isset($aMsgHeader['SUBJECT']) ? $aMsgHeader['SUBJECT'] : $iUid;
            array_shift($body_a);
            array_pop($body_a);
            $body = implode('', $body_a);
            $body .= "\r\n";
            $localfilename = GenerateRandomString(32, 'FILE', 7);
            $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
            $fp = fopen($full_localfilename, 'wb');
            fwrite($fp, $body);
            fclose($fp);
            $composeMessage->initAttachment('message/rfc822', $subject . '.msg', $full_localfilename);
        }
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    return $composesession;
}
Пример #9
0
function saveAttachedFiles($session)
{
    global $_FILES, $attachment_dir, $attachments, $username, $data_dir, $compose_messages;
    /* get out of here if no file was attached at all */
    if (!is_uploaded_file($_FILES['attachfile']['tmp_name'])) {
        return true;
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $localfilename = GenerateRandomString(32, '', 7);
    $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
    while (file_exists($full_localfilename)) {
        $localfilename = GenerateRandomString(32, '', 7);
        $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
    }
    // FIXME: we SHOULD prefer move_uploaded_file over rename because
    // m_u_f works better with restricted PHP installes (safe_mode, open_basedir)
    if (!@rename($_FILES['attachfile']['tmp_name'], $full_localfilename)) {
        if (!@move_uploaded_file($_FILES['attachfile']['tmp_name'], $full_localfilename)) {
            return true;
        }
    }
    $message = $compose_messages[$session];
    $type = strtolower($_FILES['attachfile']['type']);
    $name = $_FILES['attachfile']['name'];
    $message->initAttachment($type, $name, $full_localfilename);
    $compose_messages[$session] = $message;
    sqsession_register($compose_messages, 'compose_messages');
}
Пример #10
0
/**
 * create hashed password
 * @param string $pass plain text password
 * @param string $crypto used crypto algorithm
 * @param array $msgs array used for error messages
 * @param string $forced_salt salt that should be used during hashing.
 * Is used only when is not set to empty string. Salt should be formated
 * according to $crypto requirements.
 * @return hashed password or false.
 */
function cpw_ldap_password_hash($pass, $crypto, &$msgs, $forced_salt = '')
{
    // set default return code
    $ret = false;
    // lowercase crypto just in case
    $crypto = strtolower($crypto);
    // extra symbols used for random string in crypt salt
    // squirrelmail GenerateRandomString() adds alphanumerics with third argument = 7.
    $extra_salt_chars = './';
    // encrypt/hash password
    switch ($crypto) {
        case 'md4':
            // minimal requirement = php with mhash extension
            if (function_exists('mhash') && defined('MHASH_MD4')) {
                $ret = '{MD4}' . base64_encode(mhash(MHASH_MD4, $pass));
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'md4'), _("PHP mhash extension is missing or does not support selected crypto."));
            }
            break;
        case 'md5':
            $ret = '{MD5}' . base64_encode(pack('H*', md5($pass)));
            break;
        case 'smd5':
            // minimal requirement = mhash extension with md5 support and php 4.0.4.
            if (function_exists('mhash') && function_exists('mhash_keygen_s2k') && defined('MHASH_MD5')) {
                if ($forced_salt != '') {
                    $salt = $forced_salt;
                } else {
                    $salt = mhash_keygen_s2k(MHASH_MD5, $pass, substr(pack("h*", md5(mt_rand())), 0, 8), 4);
                }
                $ret = "{SMD5}" . base64_encode(mhash(MHASH_MD5, $pass . $salt) . $salt);
            } else {
                // use two array_push calls in order to display messages in different lines.
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'smd5'), _("PHP mhash extension is missing or does not support selected crypto."));
            }
            break;
        case 'rmd160':
            // minimal requirement = php with mhash extension
            if (function_exists('mhash') && defined('MHASH_RIPEMD160')) {
                $ret = '{RMD160}' . base64_encode(mhash(MHASH_RIPEMD160, $pass));
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'ripe-md160'), _("PHP mhash extension is missing or does not support selected crypto."));
            }
            break;
        case 'sha':
            // minimal requirement = php 4.3.0+ or php with mhash extension
            if (function_exists('sha1') && defined('MHASH_SHA1')) {
                // use php 4.3.0+ sha1 function, if it is available.
                $ret = '{SHA}' . base64_encode(pack('H*', sha1($pass)));
            } elseif (function_exists('mhash')) {
                $ret = '{SHA}' . base64_encode(mhash(MHASH_SHA1, $pass));
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'sha'), _("PHP mhash extension is missing or does not support selected crypto."));
            }
            break;
        case 'ssha':
            // minimal requirement = mhash extension and php 4.0.4
            if (function_exists('mhash') && function_exists('mhash_keygen_s2k') && defined('MHASH_SHA1')) {
                if ($forced_salt != '') {
                    $salt = $forced_salt;
                } else {
                    $salt = mhash_keygen_s2k(MHASH_SHA1, $pass, substr(pack("h*", md5(mt_rand())), 0, 8), 4);
                }
                $ret = "{SSHA}" . base64_encode(mhash(MHASH_SHA1, $pass . $salt) . $salt);
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'ssha'), _("PHP mhash extension is missing or does not support selected crypto."));
            }
            break;
        case 'crypt':
            if (defined('CRYPT_STD_DES') && CRYPT_STD_DES == 1) {
                $ret = '{CRYPT}' . crypt($pass, GenerateRandomString(2, $extra_salt_chars, 7));
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'crypt'), _("System crypt library doesn't support standard DES crypt."));
            }
            break;
        case 'md5crypt':
            // check if crypt() supports md5
            if (defined('CRYPT_MD5') && CRYPT_MD5 == 1) {
                $ret = '{CRYPT}' . crypt($pass, '$1$' . GenerateRandomString(9, $extra_salt_chars, 7));
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'md5crypt'), _("System crypt library doesn't have MD5 support."));
            }
            break;
        case 'extcrypt':
            // check if crypt() supports extended des
            if (defined('CRYPT_EXT_DES') && CRYPT_EXT_DES == 1) {
                $ret = '{CRYPT}' . crypt($pass, '_' . GenerateRandomString(8, $extra_salt_chars, 7));
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'ext_des'), _("System crypt library doesn't support extended DES crypt."));
            }
            break;
        case 'blowfish':
            // check if crypt() supports blowfish
            if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH == 1) {
                $ret = '{CRYPT}' . crypt($pass, '$2a$12$' . GenerateRandomString(13, $extra_salt_chars, 7));
            } else {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'Blowfish'), _("System crypt library doesn't have Blowfish support."));
            }
            break;
        case 'plaintext':
            // clear plain text password
            $ret = $pass;
            break;
        default:
            array_push($msgs, sprintf(_("Unsupported crypto: %s"), is_string($ldap_crypto) ? sm_encode_html_special_chars($ldap_crypto) : _("unknown")));
    }
    return $ret;
}
Пример #11
0
/**
 * Encode password
 * @param string $password plain text password
 * @param string $crypto used crypto
 * @param array $msgs error messages
 * @param string $forced_salt old password used to create password hash for verification
 * @return string hashed password. false, if hashing fails
 */
function cpw_peardb_passwd_hash($password, $crypto, &$msgs, $forced_salt = '')
{
    global $username;
    $crypto = strtolower($crypto);
    $ret = false;
    $salt = '';
    // extra symbols used for random string in crypt salt
    // squirrelmail GenerateRandomString() adds alphanumerics with third argument = 7.
    $extra_salt_chars = './';
    switch ($crypto) {
        case 'plain-md5':
            $ret = '{PLAIN-MD5}' . md5($password);
            break;
        case 'digest-md5':
            // split username into user and domain parts
            if (preg_match("/(.*)@(.*)/", $username, $match)) {
                $ret = '{DIGEST-MD5}' . md5($match[1] . ':' . $match[2] . ':' . $password);
            } else {
                array_push($msgs, _("Unable to use digest-md5 crypto."));
            }
            break;
        case 'tagged_crypt':
        case 'crypt':
            if (!defined('CRYPT_STD_DES') || CRYPT_STD_DES == 0) {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'crypt'));
                break;
            }
            if ($forced_salt == '') {
                $salt = GenerateRandomString(2, $extra_salt_chars, 7);
            } else {
                $salt = $forced_salt;
            }
            $ret = $crypto == 'tagged_crypt' ? '{crypt}' : '';
            $ret .= crypt($password, $salt);
            break;
        case 'tagged_md5crypt':
        case 'md5crypt':
            if (!defined('CRYPT_MD5') || CRYPT_MD5 == 0) {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'md5crypt'));
                break;
            }
            if ($forced_salt == '') {
                $salt = '$1$' . GenerateRandomString(9, $extra_salt_chars, 7);
            } else {
                $salt = $forced_salt;
            }
            $ret = $crypto == 'tagged_md5crypt' ? '{crypt}' : '';
            $ret .= crypt($password, $salt);
            break;
        case 'tagged_extcrypt':
        case 'extcrypt':
            if (!defined('CRYPT_EXT_DES') || CRYPT_EXT_DES == 0) {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'extcrypt'));
                break;
            }
            if ($forced_salt == '') {
                $salt = '_' . GenerateRandomString(8, $extra_salt_chars, 7);
            } else {
                $salt = $forced_salt;
            }
            $ret = $crypto == 'tagged_extcrypt' ? '{crypt}' : '';
            $ret .= crypt($password, $salt);
            break;
        case 'tagged_blowfish':
        case 'blowfish':
            if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH == 0) {
                array_push($msgs, sprintf(_("Unsupported crypto: %s"), 'blowfish'));
                break;
            }
            if ($forced_salt == '') {
                $salt = '$2a$12$' . GenerateRandomString(13, $extra_salt_chars, 7);
            } else {
                $salt = $forced_salt;
            }
            $ret = $crypto == 'tagged_blowfish' ? '{crypt}' : '';
            $ret .= crypt($password, $salt);
            break;
        case 'plain':
        case 'plaintext':
            $ret = $password;
            break;
        default:
            array_push($msgs, sprintf(_("Unsupported crypto: %s"), sm_encode_html_special_chars($crypto)));
    }
    return $ret;
}
Пример #12
0
	function ImportAssessmentForm() {
	
		$savepath = $GLOBALS['cfg']['tmpdir'] . '/' . GenerateRandomString(20);
		
		/* create the directory in which the files are stored until the import module takes them */
		mkdir($savepath, 0, true);
		chmod($savepath, 0777);
		
		echo "<ul>";
		
		/* go through all the files and save them */
		foreach ($_FILES['files']['name'] as $i => $name) {
			if (move_uploaded_file($_FILES['files']['tmp_name'][$i], "$savepath/$name")) {
				echo "<li>Received $name - " . number_format($_FILES['files']['size'][$i]) . " bytes<br>";
				chmod("$savepath/$name", 0777);
				if (ValidateAssessmentForm("$savepath/$name")) {
					echo "<br>Assessment form is valid, inserting into database<br>";
					InsertAssessmentForm("$savepath/$name");
				}
				else {
					echo "<br>Assessment form is not valid. See errors above.";
				}
			}
			else {
				echo "<br>An error occured moving " . $_FILES['files']['tmp_name'][$i] . " to [" . $_FILES['files']['error'][$i] . "]<br>";
			}
		}
		
		echo "</ul>";
	}
Пример #13
0
/**
 * Generates a security token that is then stored in
 * the user's preferences with a timestamp for later
 * verification/use.
 *
 * NOTE: The administrator can force SquirrelMail to generate
 * a new token every time one is requested (which may increase
 * obscurity through token randomness at the cost of some
 * performance) by adding the following to
 * config/config_local.php:   $do_not_use_single_token = TRUE;
 * Otherwise, only one token will be generated per user which
 * will change only after it expires or is used outside of the
 * validity period specified when calling sm_validate_security_token()
 *
 * WARNING: If the administrator has turned the token system
 *          off by setting $disable_security_tokens to TRUE in
 *          config/config.php or the configuration tool, this
 *          function will not store tokens in the user
 *          preferences (but it will still generate and return
 *          a random string).
 *
 * @param boolean $force_generate_new When TRUE, a new token will
 *                                    always be created even if current
 *                                    configuration dictates otherwise
 *                                    (OPTIONAL; default FALSE)
 *
 * @return string A security token
 *
 * @since 1.4.19 and 1.5.2
 *
 */
function sm_generate_security_token($force_generate_new = FALSE)
{
    global $data_dir, $username, $disable_security_tokens, $do_not_use_single_token;
    $max_generation_tries = 1000;
    $tokens = sm_get_user_security_tokens();
    if (!$force_generate_new && !$do_not_use_single_token && !empty($tokens)) {
        return key($tokens);
    }
    $new_token = GenerateRandomString(12, '', 7);
    $count = 0;
    while (isset($tokens[$new_token])) {
        $new_token = GenerateRandomString(12, '', 7);
        if (++$count > $max_generation_tries) {
            logout_error(_("Fatal token generation error; please contact your system administrator or the SquirrelMail Team"));
            exit;
        }
    }
    // is the token system enabled?  CAREFUL!
    //
    if (!$disable_security_tokens) {
        $tokens[$new_token] = time();
        setPref($data_dir, $username, 'security_tokens', serialize($tokens));
    }
    return $new_token;
}
Пример #14
0
 /**
  * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
  *
  * This function takes the Rfc822Header object(s) and formats them
  * into the RFC822Header string to send to the SMTP server as part
  * of the SMTP message.
  *
  * @param Rfc822Header  $rfc822_header
  * @param Rfc822Header  $reply_rfc822_header
  * @param integer      &$raw_length length of the message
  *
  * @return string $header
  */
 function prepareRFC822_Header(&$rfc822_header, $reply_rfc822_header, &$raw_length)
 {
     global $domain, $username, $encode_header_key, $edit_identity, $hide_auth_header;
     /* if server var SERVER_NAME not available, or contains
        ":" (e.g. IPv6) which is illegal in a Message-ID, use $domain */
     if (!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER) || strpos($SERVER_NAME, ':') !== FALSE) {
         $SERVER_NAME = $domain;
     }
     sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER);
     sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER);
     sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER);
     sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER);
     sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER);
     $rn = "\r\n";
     /* This creates an RFC 822 date */
     $date = date('D, j M Y H:i:s ', time()) . $this->timezone();
     /* Create a message-id */
     $message_id = 'MESSAGE ID GENERATION ERROR! PLEASE CONTACT SQUIRRELMAIL DEVELOPERS';
     if (empty($rfc822_header->message_id)) {
         $message_id = '<' . md5(GenerateRandomString(16, '', 7) . uniqid(mt_rand(), true)) . '.squirrel@' . $SERVER_NAME . '>';
     }
     /* Make an RFC822 Received: line */
     if (isset($REMOTE_HOST)) {
         $received_from = "{$REMOTE_HOST} ([{$REMOTE_ADDR}])";
     } else {
         $received_from = $REMOTE_ADDR;
     }
     if (isset($HTTP_VIA) || isset($HTTP_X_FORWARDED_FOR)) {
         if (!isset($HTTP_X_FORWARDED_FOR) || $HTTP_X_FORWARDED_FOR == '') {
             $HTTP_X_FORWARDED_FOR = 'unknown';
         }
         $received_from .= " (proxying for {$HTTP_X_FORWARDED_FOR})";
     }
     $header = array();
     /**
      * SquirrelMail header
      *
      * This Received: header provides information that allows to track
      * user and machine that was used to send email. Don't remove it
      * unless you understand all possible forging issues or your
      * webmail installation does not prevent changes in user's email address.
      * See SquirrelMail bug tracker #847107 for more details about it.
      *
      * Add hide_squirrelmail_header as a candidate for config_local.php
      * (must be defined as a constant:  define('hide_squirrelmail_header', 1);
      * to allow completely hiding SquirrelMail participation in message
      * processing; This is dangerous, especially if users can modify their
      * account information, as it makes mapping a sent message back to the
      * original sender almost impossible.
      */
     $show_sm_header = defined('hide_squirrelmail_header') ? !hide_squirrelmail_header : 1;
     // FIXME: The following headers may generate slightly differently between the message sent to the destination and that stored in the Sent folder because this code will be called before both actions.  This is not necessarily a big problem, but other headers such as Message-ID and Date are preserved between both actions
     if ($show_sm_header) {
         if (isset($encode_header_key) && trim($encode_header_key) != '') {
             // use encoded headers, if encryption key is set and not empty
             $header[] = 'X-Squirrel-UserHash: ' . OneTimePadEncrypt($username, base64_encode($encode_header_key)) . $rn;
             $header[] = 'X-Squirrel-FromHash: ' . OneTimePadEncrypt($this->ip2hex($REMOTE_ADDR), base64_encode($encode_header_key)) . $rn;
             if (isset($HTTP_X_FORWARDED_FOR)) {
                 $header[] = 'X-Squirrel-ProxyHash:' . OneTimePadEncrypt($this->ip2hex($HTTP_X_FORWARDED_FOR), base64_encode($encode_header_key)) . $rn;
             }
         } else {
             // use default received headers
             $header[] = "Received: from {$received_from}" . $rn;
             if (!isset($hide_auth_header) || !$hide_auth_header) {
                 $header[] = "        (SquirrelMail authenticated user {$username})" . $rn;
             }
             $header[] = "        by {$SERVER_NAME} with HTTP;" . $rn;
             $header[] = "        {$date}" . $rn;
         }
     }
     /* Insert the rest of the header fields */
     if (!empty($rfc822_header->message_id)) {
         $header[] = 'Message-ID: ' . $rfc822_header->message_id . $rn;
     } else {
         $header[] = 'Message-ID: ' . $message_id . $rn;
         $rfc822_header->message_id = $message_id;
     }
     if (is_object($reply_rfc822_header) && isset($reply_rfc822_header->message_id) && $reply_rfc822_header->message_id) {
         $rep_message_id = $reply_rfc822_header->message_id;
         $header[] = 'In-Reply-To: ' . $rep_message_id . $rn;
         $rfc822_header->in_reply_to = $rep_message_id;
         $references = $this->calculate_references($reply_rfc822_header);
         $header[] = 'References: ' . $references . $rn;
         $rfc822_header->references = $references;
     }
     if (!empty($rfc822_header->date) && $rfc822_header->date != -1) {
         $header[] = 'Date: ' . $rfc822_header->date . $rn;
     } else {
         $header[] = "Date: {$date}" . $rn;
         $rfc822_header->date = $date;
     }
     $header[] = 'Subject: ' . encodeHeader($rfc822_header->subject) . $rn;
     $header[] = 'From: ' . $rfc822_header->getAddr_s('from', ",{$rn} ", true) . $rn;
     // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>"
     // as delimiter
     // Do not use foldLine for that.
     // RFC2822 if from contains more then 1 address
     if (count($rfc822_header->from) > 1) {
         $header[] = 'Sender: ' . $rfc822_header->getAddr_s('sender', ',', true) . $rn;
     }
     if (count($rfc822_header->to)) {
         $header[] = 'To: ' . $rfc822_header->getAddr_s('to', ",{$rn} ", true) . $rn;
     }
     if (count($rfc822_header->cc)) {
         $header[] = 'Cc: ' . $rfc822_header->getAddr_s('cc', ",{$rn} ", true) . $rn;
     }
     if (count($rfc822_header->reply_to)) {
         $header[] = 'Reply-To: ' . $rfc822_header->getAddr_s('reply_to', ',', true) . $rn;
     }
     /* Sendmail should return true. Default = false */
     $bcc = $this->getBcc();
     if (count($rfc822_header->bcc)) {
         $s = 'Bcc: ' . $rfc822_header->getAddr_s('bcc', ",{$rn} ", true) . $rn;
         if (!$bcc) {
             $raw_length += strlen($s);
         } else {
             $header[] = $s;
         }
     }
     /* Identify SquirrelMail */
     $header[] = 'User-Agent: SquirrelMail/' . SM_VERSION . $rn;
     /* Do the MIME-stuff */
     $header[] = 'MIME-Version: 1.0' . $rn;
     $contenttype = 'Content-Type: ' . $rfc822_header->content_type->type0 . '/' . $rfc822_header->content_type->type1;
     if (count($rfc822_header->content_type->properties)) {
         foreach ($rfc822_header->content_type->properties as $k => $v) {
             if ($k && $v) {
                 $contenttype .= ';' . $k . '=' . $v;
             }
         }
     }
     $header[] = $contenttype . $rn;
     if ($encoding = $rfc822_header->encoding) {
         $header[] = 'Content-Transfer-Encoding: ' . $encoding . $rn;
     }
     if (isset($rfc822_header->dnt) && $rfc822_header->dnt) {
         $dnt = $rfc822_header->getAddr_s('dnt');
         /* Pegasus Mail */
         $header[] = 'X-Confirm-Reading-To: ' . $dnt . $rn;
         /* RFC 2298 */
         $header[] = 'Disposition-Notification-To: ' . $dnt . $rn;
     }
     if ($rfc822_header->priority) {
         switch ($rfc822_header->priority) {
             case 1:
                 $header[] = 'X-Priority: 1 (Highest)' . $rn;
                 $header[] = 'Importance: High' . $rn;
                 break;
             case 5:
                 $header[] = 'X-Priority: 5 (Lowest)' . $rn;
                 $header[] = 'Importance: Low' . $rn;
                 break;
             default:
                 break;
         }
     }
     /* Insert headers from the $more_headers array */
     if (count($rfc822_header->more_headers)) {
         reset($rfc822_header->more_headers);
         foreach ($rfc822_header->more_headers as $k => $v) {
             $header[] = $k . ': ' . $v . $rn;
         }
     }
     $cnt = count($header);
     $hdr_s = '';
     for ($i = 0; $i < $cnt; $i++) {
         $sKey = substr($header[$i], 0, strpos($header[$i], ':'));
         switch ($sKey) {
             case 'Message-ID':
             case 'In-Reply_To':
                 $hdr_s .= $header[$i];
                 break;
             case 'References':
                 $sRefs = substr($header[$i], 12);
                 $aRefs = explode(' ', $sRefs);
                 $sLine = 'References:';
                 foreach ($aRefs as $sReference) {
                     if (trim($sReference) == '') {
                         /* Don't add spaces. */
                     } elseif (strlen($sLine) + strlen($sReference) > 76) {
                         $hdr_s .= $sLine;
                         $sLine = $rn . '    ' . $sReference;
                     } else {
                         $sLine .= ' ' . $sReference;
                     }
                 }
                 $hdr_s .= $sLine;
                 break;
             case 'To':
             case 'Cc':
             case 'Bcc':
             case 'From':
                 $hdr_s .= $header[$i];
                 break;
             default:
                 $hdr_s .= $this->foldLine($header[$i], 78);
                 break;
         }
     }
     $header = $hdr_s;
     $header .= $rn;
     /* One blank line to separate header and body */
     $raw_length += strlen($header);
     return $header;
 }
Пример #15
0
	function ViewGroup($id, $measures, $columns, $groupmeasures) {
	
		$urllist['Group List'] = "groups.php";
		NavigationBar("Groups", $urllist,0,'','','','');
		
		/* get the general group information */
		$sqlstring = "select * from groups where group_id = $id";
		$result = mysql_query($sqlstring) or die("Query failed: " . mysql_error() . "<br><i>$sqlstring</i><br>");
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		$groupname = $row['group_name'];
		$grouptype = $row['group_type'];

		?>
		<script>
			$(document).ready(function()
				{
					$("#studytable").tablesorter();
				}
			); 
		</script>
		
		<div align="center"><span style="color:darkblue;font-size:15pt;font-weight:bold"><?php 
echo $groupname;
?>
</span> - <i><?php 
echo $grouptype;
?>
</i> level group</div>
		<br><br>
		<?
		/* (subject level) group statistics */
		$totalage = 0;
		$numage = 0;
		$totalweight = 0;
		$numweight = 0;
		$n = 0;
		
		//print_r(get_defined_vars());
		
		/* ------------------ subject group type ------------------- */
		if ($grouptype == "subject") {
			/* get the actual group data (subject level) */
			$sqlstring = "select a.subjectgroup_id, b.*, (datediff(now(), birthdate)/365.25) 'age' from group_data a left join subjects b on a.data_id = b.subject_id where a.group_id = $id";
			$result = mysql_query($sqlstring) or die("Query failed: " . mysql_error() . "<br><i>$sqlstring</i><br>");
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$subjectid = $row['subject_id'];
				$name = $row['name'];
				$birthdate = $row['birthdate'];
				$age = $row['age'];
				$gender = $row['gender'];
				$ethnicity1 = $row['ethnicity1'];
				$ethnicity2 = $row['ethnicity2'];
				$weight = $row['weight'];
				$handedness = $row['handedness'];
				$education = $row['education'];
				$uid = $row['uid'];
				
				/* do some demographics calculations */
				$n++;
				if ($age > 0) {
					$totalage += $age;
					$numage++;
					$ages[] = $age;
				}
				if ($weight > 0) {
					$totalweight += $weight;
					$numweight++;
					$weights[] = $weight;
				}
				$genders{$gender}++;
				$educations{$education}++;
				$ethnicity1s{$ethnicity1}++;
				$ethnicity2s{$ethnicity2}++;
				$handednesses{$handedness}++;
			}
			if ($numage > 0) { $avgage = $totalage/$numage; } else { $avgage = 0; }
			if (count($ages) > 0) { $varage = sd($ages); } else { $varage = 0; }
			if ($numweight > 0) { $avgweight = $totalweight/$numweight; } else { $avgweight = 0; }
			if (count($weights) > 0) { $varweight = sd($weights); } else { $varweight = 0; }
			
			?>
			<table>
				<tr>
					<td valign="top" style="padding-right:20px">
						<?
						DisplayDemographicsTable($n,$avgage,$varage,$genders,$ethnicity1s,$ethnicity2s,$educations,$handednesses,$avgweight,$varweight);
						?>
					</td>
				</tr>
				<tr>
					<td valign="top" style="padding-right:20px">
						<details>
						<summary>SQL</summary>
						<?php 
echo PrintSQL($sqlstring);
?>
						</details>
					</td>
				</tr>
				<tr>
					<td valign="top">
						<form action="groups.php" method="post">
						<input type="hidden" name="id" value="<?php 
echo $id;
?>
">
						<input type="hidden" name="action" value="removegroupitem">
						<table class="smallgraydisplaytable">
							<th>Initials</th>
							<th>UID</th>
							<th>Age<br><span class="tiny">current</span></th>
							<th>Sex</th>
							<th>Ethnicity 1</th>
							<th>Ethnicity 2</th>
							<th>Weight</th>
							<th>Handedness</th>
							<th>Education</th>
							<th>Alt UIDs</th>
							<th>Remove<br>from group</th>
						<?
						/* reset the result pointer to 0 to iterate through the results again */
						mysql_data_seek($result,0);
						while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
							$itemid = $row['subjectgroup_id'];
							$subjectid = $row['subject_id'];
							$name = $row['name'];
							$birthdate = $row['birthdate'];
							$age = $row['age'];
							$gender = $row['gender'];
							$ethnicity1 = $row['ethnicity1'];
							$ethnicity2 = $row['ethnicity2'];
							$weight = $row['weight'];
							$handedness = $row['handedness'];
							$education = $row['education'];
							$uid = $row['uid'];
							
							/* get list of alternate subject UIDs */
							$altuids = GetAlternateUIDs($subjectid);
							
							$parts = explode("^",$name);
							$name = substr($parts[1],0,1) . substr($parts[0],0,1);
							?>
							<tr>
								<td><?php 
echo $name;
?>
</td>
								<td><a href="subjects.php?id=<?php 
echo $subjectid;
?>
"><?php 
echo $uid;
?>
</a></td>
								<? if ($age <= 0) {$color = "red";} else {$color="black";} ?>
								<td style="color:<?php 
echo $color;
?>
"><?php 
echo number_format($age, 1);
?>
Y</td>
								<? if (!in_array(strtoupper($gender),array('M','F','O'))) {$color = "red";} else {$color="black";} ?>
								<td style="color:<?php 
echo $color;
?>
"><?php 
echo $gender;
?>
</td>
								<td><?php 
echo $ethnicitiy1;
?>
</td>
								<td><?php 
echo $ethnicitiy1;
?>
</td>
								<td><?php 
echo number_format($weight, 1);
?>
kg</td>
								<td><?php 
echo $handedness;
?>
</td>
								<td><?php 
echo $education;
?>
</td>
								<td><?php 
echo implode(', ', $altuids);
?>
</td>
								<!--<td><a href="groups.php?action=removegroupitem&itemid=<?php 
echo $itemid;
?>
&id=<?php 
echo $id;
?>
" style="color:red">X</a></td>-->
								<td><input type="checkbox" name="itemid[]" value="<?php 
echo $itemid;
?>
"></td>
							</tr>
							<?
						}
						?>
							<tr>
								<td colspan="100" align="right">
									<input type="submit" value="Remove">
									</form>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
			<?
		}
		
		/* ------------------ study group type ------------------- */
		if ($grouptype == "study") {
			$csv = "";
			
			/* get the demographics (study level) */
			$sqlstring = "select c.enroll_subgroup,d.*, (datediff(b.study_datetime, d.birthdate)/365.25) 'age' from group_data a left join studies b on a.data_id = b.study_id left join enrollment c on b.enrollment_id = c.enrollment_id left join subjects d on c.subject_id = d.subject_id where a.group_id = $id group by d.uid order by d.uid,b.study_num";
			$result = mysql_query($sqlstring) or die("Query failed: " . mysql_error() . "<br><i>$sqlstring</i><br>");
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$studyid = $row['study_id'];
				$studynum = $row['study_num'];
				$studydesc = $row['study_desc'];
				$studyalternateid = $row['study_alternateid'];
				$studymodality = $row['study_modality'];
				$studydatetime = $row['study_datetime'];
				$studyoperator = $row['study_operator'];
				$studyperformingphysician = $row['study_performingphysician'];
				$studysite = $row['study_site'];
				$studyinstitution = $row['study_institution'];
				$studynotes = $row['study_notes'];
				$subgroup = $row['enroll_subgroup'];

				$subjectid = $row['subject_id'];
				$name = $row['name'];
				$birthdate = $row['birthdate'];
				$age = $row['age'];
				$gender = $row['gender'];
				$ethnicity1 = $row['ethnicity1'];
				$ethnicity2 = $row['ethnicity2'];
				$weight = $row['weight'];
				$handedness = $row['handedness'];
				$education = $row['education'];
				$uid = $row['uid'];

				$subjectids[] = $subjectid;
				/* do some demographics calculations */
				$n++;
				if ($age > 0) {
					$totalage += $age;
					$numage++;
					$ages[] = $age;
				}
				if ($weight > 0) {
					$totalweight += $weight;
					$numweight++;
					$weights[] = $weight;
				}
				$genders{$gender}++;
				$educations{$education}++;
				$ethnicity1s{$ethnicity1}++;
				$ethnicity2s{$ethnicity2}++;
				$handednesses{$handedness}++;
			}
			if ($numage > 0) { $avgage = $totalage/$numage; } else { $avgage = 0; }
			if (count($ages) > 0) { $varage = sd($ages); } else { $varage = 0; }
			if ($numweight > 0) { $avgweight = $totalweight/$numweight; } else { $avgweight = 0; }
			if (count($weights) > 0) { $varweight = sd($weights); } else { $varweight = 0; }
			
			if ($measures == "all") {
				$sqlstringD = "select a.subject_id, b.enrollment_id, c.*, d.measure_name from measures c join measurenames d on c.measurename_id = d.measurename_id left join enrollment b on c.enrollment_id = b.enrollment_id join subjects a on a.subject_id = b.subject_id where a.subject_id in (" . implode2(",", $subjectids) . ")";
				//PrintSQL($sqlstringD);
				$resultD = MySQLQuery($sqlstringD,__FILE__,__LINE__);
				
				if ($groupmeasures == "byvalue") {
					$mnames = array('ANTDX','AVDDX','AX1Com1_Code','AX1Com2_Code','AX1Com3_Code','AX1Com4_Code','AX1Com5_Code','AX1Com6_Code','AX1Com7_Code','AX1Pri_Code','AXIIDX','BRDDX','DPNDX','DSM-Axis','DSM-Axis1','DSM-Axis2','DSM-Axis295.3','DSM-Axis304.3','DSM-AxisV71.09','DSM_IV_TR','DXGROUP_1','DX_GROUP','MiniDxn','MiniDxnFollowUp','NARDX','OBCDX','PARDX','ProbandGroup','Psychosis','relnm1','SAsubtype','SCZDX','status','SubjectType','SZTDX');
					while ($rowD = mysql_fetch_array($resultD, MYSQL_ASSOC)) {
						$subjectid = $rowD['subject_id'];
						$measurename = $rowD['measure_name'];

						if (in_array($measurename,$mnames)) {
							if ($rowD['measure_type'] == 's') {
								$value = strtolower(trim($rowD['measure_valuestring']));
							}
							else {
								$value = strtolower(trim($rowD['measure_valuenum']));
							}
							
							if (is_numeric(substr($value,0,6))) {
								//echo "$value --6--> ";
								$value = substr($value,0,6);
								//echo "$value<br>";
							}
							elseif (is_numeric(substr($value,0,5))) {
								//echo "$value --5--> ";
								$value = substr($value,0,5);
								//echo "$value<br>";
							}
							elseif (is_numeric(substr($value,0,4))) {
								$value = substr($value,0,4);
							}
							elseif (is_numeric(substr($value,0,3))) {
								$value = substr($value,0,3);
							}
							elseif (is_numeric(substr($value,1,5))) {
								$value = substr($value,1,5);
							}
							elseif (substr($value,0,3) == "xxx") {
								$value = "xxx";
							}
							
							$measuredata[$subjectid][$value] = 1;
							$measurenames[] = $value;
						}
					}
					$measurenames = array_unique($measurenames);
					natsort($measurenames);
				}
				else {
					while ($rowD = mysql_fetch_array($resultD, MYSQL_ASSOC)) {
						if ($rowD['measure_type'] == 's') {
							$measuredata[$rowD['subject_id']][$rowD['measure_name']]['value'][] = $rowD['measure_valuestring'];
						}
						else {
							$measuredata[$rowD['subject_id']][$rowD['measure_name']]['value'][] = $rowD['measure_valuenum'];
						}
						$measuredata[$rowD['subject_id']][$rowD['measure_name']]['notes'][] = $rowD['measure_notes'];
						$measurenames[] = $rowD['measure_name'];
						//$i++;
					}
					$measurenames = array_unique($measurenames);
					natcasesort($measurenames);
				}
				//PrintVariable($measurenames, 'MeasureNames');
				//PrintVariable($measuredata, 'MeasureData');
			}
			
			/* setup the CSV header */
			if ($columns == "min") {
				$csv = "UID";
			}
			else {
				$csv = "Initials,UID,AgeAtStudy,Sex,Ethnicity,Race,SubGroup,Weight,Handedness,Education,AltUIDs,StudyID,Description,AltStudyID,Modality,StudyDate,Operator,Physician,Site";
			}
			
			?>
			<table>
				<tr>
					<td valign="top" style="padding-right:20px">
						<?
						DisplayDemographicsTable($n,$avgage,$varage,$genders,$ethnicity1s,$ethnicity2s,$educations,$handednesses,$avgweight,$varweight);
						?>
					</td>
				</tr>
				<tr>
					<td valign="top" style="padding-right:20px">
						<details>
						<summary>SQL</summary>
						<?php 
echo PrintSQL($sqlstring);
?>
						</details>
					</td>
				</tr>
				<tr>
					<td valign="top">
						<a href="groups.php?action=viewgroup&id=<?php 
echo $id;
?>
&measures=all">Include measures</a><br>
						<a href="groups.php?action=viewgroup&id=<?php 
echo $id;
?>
&measures=all&columns=min">Include measures and only UID</a><br>
						<a href="groups.php?action=viewgroup&id=<?php 
echo $id;
?>
&measures=all&columns=min&groupmeasures=byvalue">Include measures and only UID and group measures by value</a>
						<br><br>
						<span class="tiny">Click columns to sort. May be slow for large tables</span>

						<form action="groups.php" method="post">
						<input type="hidden" name="id" value="<?php 
echo $id;
?>
">
						<input type="hidden" name="action" value="removegroupitem">
						
						<table id="studytable" class="tablesorter">
							<thead>
								<tr>
									<? if ($columns != "min") { ?>
									<th>Initials</th>
									<? } ?>
									<th>UID</th>
									<? if ($columns != "min") { ?>
									<th>Age<br><span class="tiny">at study</span></th>
									<th>Sex</th>
									<th>Ethnicities</th>
									<th>SubGroup</th>
									<th>Weight</th>
									<th>Handedness</th>
									<th>Education</th>
									<th>Alt UIDs</th>
									<th>Study ID</th>
									<th>Description</th>
									<th>Alternate Study ID</th>
									<th>Modality</th>
									<th>Date/time</th>
									<th>Operator</th>
									<th>Physician</th>
									<th>Site</th>
									<? } ?>
									<?
										if (count($measurenames) > 0) {
											foreach ($measurenames as $measurename) {
												echo "<th>$measurename</th>";
												$csv .= ",\"$measurename\"";
											}
										}
									?>
									<th>Remove<br>from group</th>
								</tr>
							</thead>
							<tbody>
						<?

						/* reset the result pointer to 0 to iterate through the results again */
						$sqlstring = "select a.subjectgroup_id, c.enroll_subgroup, b.*, d.*, (datediff(b.study_datetime, d.birthdate)/365.25) 'age' from group_data a left join studies b on a.data_id = b.study_id left join enrollment c on b.enrollment_id = c.enrollment_id left join subjects d on c.subject_id = d.subject_id where a.group_id = $id order by d.uid,b.study_num";
						$result = mysql_query($sqlstring) or die("Query failed: " . mysql_error() . "<br><i>$sqlstring</i><br>");
						//mysql_data_seek($result,0);
						while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
							$studyid = $row['study_id'];
							$studynum = $row['study_num'];
							$studydesc = $row['study_desc'];
							$studyalternateid = $row['study_alternateid'];
							$studymodality = $row['study_modality'];
							$studydatetime = $row['study_datetime'];
							$studyoperator = $row['study_operator'];
							$studyperformingphysician = $row['study_performingphysician'];
							$studysite = $row['study_site'];
							$studyinstitution = $row['study_institution'];
							$studynotes = $row['study_notes'];
							$subgroup = $row['enroll_subgroup'];
							
							$itemid = $row['subjectgroup_id'];
							$subjectid = $row['subject_id'];
							$name = $row['name'];
							$birthdate = $row['birthdate'];
							$age = $row['age'];
							$gender = $row['gender'];
							$ethnicity1 = $row['ethnicity1'];
							$ethnicity2 = $row['ethnicity2'];
							$weight = $row['weight'];
							$handedness = $row['handedness'];
							$education = $row['education'];
							$uid = $row['uid'];

							/* get list of alternate subject UIDs */
							$altuids = GetAlternateUIDs($subjectid);
							
							$parts = explode("^",$name);
							$name = substr($parts[1],0,1) . substr($parts[0],0,1);
							
							if ($columns == "min") {
								$csv .= "\n\"$uid\"";
							}
							else {
								$csv .= "\n\"$name\",\"$uid\",\"$age\",\"$gender\",\"$ethnicity1\",\"$ethnicity2\",\"$subgroup\",\"$weight\",\"$handedness\",\"$education\",\"" . implode2(', ',$altuids) . "\",\"$uid$studynum\",\"$studydesc\",\"$studyalternateid\",\"$studymodality\",\"$studydatetime\",\"$studyoperator\",\"$studyperformingphysician\",\"$studysite\"";
							}
							?>
							<tr>
								<? if ($columns != "min") { ?>
								<td><?php 
echo $name;
?>
</td>
								<? } ?>
								<td><a href="subjects.php?id=<?php 
echo $subjectid;
?>
"><?php 
echo $uid;
?>
</a></td>
								<? if ($columns != "min") { ?>
								<? if ($age <= 0) {$color = "red";} else {$color="black";} ?>
								<td style="color:<?php 
echo $color;
?>
"><?php 
echo number_format($age, 1);
?>
Y</td>
								<? if (!in_array(strtoupper($gender),array('M','F','O'))) {$color = "red";} else {$color="black";} ?>
								<td style="color:<?php 
echo $color;
?>
"><?php 
echo $gender;
?>
</td>
								<td style="font-size:8pt"><?php 
echo $ethnicity1;
?>
 <?php 
echo $ethnicity2;
?>
</td>
								<td style="font-size:8pt"><?php 
echo $subgroup;
?>
</td>
								<? if ($weight <= 0) {$color = "red";} else {$color="black";} ?>
								<td style="color:<?php 
echo $color;
?>
"><?php 
echo number_format($weight, 1);
?>
kg</td>
								<td><?php 
echo $handedness;
?>
</td>
								<td><?php 
echo $education;
?>
</td>
								<td style="font-size:8pt"><?php 
echo implode2(', ', $altuids);
?>
</td>
								<td><a href="studies.php?id=<?php 
echo $studyid;
?>
"><?php 
echo $uid;
echo $studynum;
?>
</a></td>
								<td style="font-size:8pt"><?php 
echo $studydesc;
?>
</td>
								<td><?php 
echo $studyalternateid;
?>
</td>
								<td><?php 
echo $studymodality;
?>
</td>
								<td><?php 
echo $studydatetime;
?>
</td>
								<td><?php 
echo $studyoperator;
?>
</td>
								<td><?php 
echo $studyperformingphysician;
?>
</td>
								<td style="font-size:8pt"><?php 
echo $studysite;
?>
</td>
								<? } ?>
								<?
									if (count($measurenames) > 0) {
										if ($groupmeasures == "byvalue") {
											foreach ($measurenames as $measurename) {
												$csv .= ",\"" . $measuredata[$subjectid][$measurename] . "\"";
											?>
											<td class="seriesrow">
												<?
													if (isset($measuredata[$subjectid][$measurename])) {
														echo $measuredata[$subjectid][$measurename];
													}
												?>
											</td>
											<?
											}
										}
										else {
											foreach ($measurenames as $measure) {
												$csv .= ",\"" . $measuredata[$subjectid][$measure]['value'] . "\"";
												?>
												<td class="seriesrow">
													<?
														if (isset($measuredata[$subjectid][$measure]['value'])) {
															foreach ($measuredata[$subjectid][$measure]['value'] as $value) {
																echo "$value<br>";
															}
														}
													?>
												</td>
												<?
											}
										}
									}
								?>
								<!--<td><a href="groups.php?action=removegroupitem&itemid=<?php 
echo $itemid;
?>
&id=<?php 
echo $id;
?>
" style="color:red">X</a></td>-->
								<td><input type="checkbox" name="itemid[]" value="<?php 
echo $itemid;
?>
"></td>
							</tr>
							<?
						}
						?>
							<tr>
								<td colspan="100" align="right">
									<input type="submit" value="Remove">
									</form>
								</td>
							</tr>
							</tbody>
						</table>
					</td>
				</tr>
			</table>
			<?
			
				/* ---------- generate csv file ---------- */
				$filename = $groupname . "_" . GenerateRandomString(10) . ".csv";
				file_put_contents("/tmp/" . $filename, $csv);
				?>
				<div width="50%" align="center" style="background-color: #FAF8CC; padding: 5px;">
				Download .csv file <a href="download.php?type=file&filename=<?php 
echo "/tmp/{$filename}";
?>
"><img src="images/download16.png"></a>
				</div>
				<?
		}
		
		/* ------------------ series group type ------------------- */
		if ($grouptype == "series") {
			/* get a distinct list of modalities... then get a list of series for each modality */
			$sqlstring = "select distinct(modality) from group_data where group_id = $id order by modality";
			$result = mysql_query($sqlstring) or die("Query failed: " . mysql_error() . "<br><i>$sqlstring</i><br>");
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$modalities[] = $row['modality'];
			}
			
			foreach ($modalities as $modality) {
				$modality = strtolower($modality);
				/* get the demographics (series level) */
				$sqlstring = "select b.*,c.enroll_subgroup, e.*, (datediff(b.series_datetime, e.birthdate)/365.25) 'age' from group_data a left join ".$modality."_series b on a.data_id = b.".$modality."series_id left join studies c on b.study_id = c.study_id left join enrollment d on c.enrollment_id = d.enrollment_id left join subjects e on d.subject_id = e.subject_id where a.group_id = 3 and a.modality = '".$modality."' and e.subject_id is not null group by e.uid";
				$result = mysql_query($sqlstring) or die("Query failed: " . mysql_error() . "<br><i>$sqlstring</i><br>");
				while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
					$studyid = $row['study_id'];
					$studynum = $row['study_num'];
					$studydesc = $row['study_desc'];
					$studyalternateid = $row['study_alternateid'];
					$studymodality = $row['study_modality'];
					$studydatetime = $row['study_datetime'];
					$studyoperator = $row['study_operator'];
					$studyperformingphysician = $row['study_performingphysician'];
					$studysite = $row['study_site'];
					$studyinstitution = $row['study_institution'];
					$studynotes = $row['study_notes'];

					$subgroup = $row['enroll_subgroup'];
					
					$subjectid = $row['subject_id'];
					$name = $row['name'];
					$birthdate = $row['birthdate'];
					$age = $row['age'];
					$gender = $row['gender'];
					$ethnicity1 = $row['ethnicity1'];
					$ethnicity2 = $row['ethnicity2'];
					$weight = $row['weight'];
					$handedness = $row['handedness'];
					$education = $row['education'];
					$uid = $row['uid'];
					
					/* do some demographics calculations */
					$n++;
					if ($age > 0) {
						$totalage += $age;
						$numage++;
						$ages[] = $age;
					}
					if ($weight > 0) {
						$totalweight += $weight;
						$numweight++;
						$weights[] = $weight;
					}
					$genders{$gender}++;
					$educations{$education}++;
					$ethnicity1s{$ethnicity1}++;
					$ethnicity2s{$ethnicity2}++;
					$handednesses{$handedness}++;
				}
			}
			/* calculate some stats */
			if ($numage > 0) { $avgage = $totalage/$numage; } else { $avgage = 0; }
			if (count($ages) > 0) { $varage = sd($ages); } else { $varage = 0; }
			if ($numweight > 0) { $avgweight = $totalweight/$numweight; } else { $avgweight = 0; }
			if (count($weights) > 0) { $varweight = sd($weights); } else { $varweight = 0; }
			
			?>
			<table>
				<tr>
					<td valign="top" style="padding-right:20px">
						<?
						DisplayDemographicsTable($n,$avgage,$varage,$genders,$ethnicity1s,$ethnicity2s,$educations,$handednesses,$avgweight,$varweight);
						?>
					</td>
					<td valign="top" style="padding-right:20px">
						<details>
						<summary>SQL</summary>
						<?php 
echo PrintSQL($sqlstring);
?>
						</details>
					</td>
					<td valign="top">
						<table class="smallgraydisplaytable">
							<th>Initials</th>
							<th>UID</th>
							<th>Age<br><span class="tiny">at study</span></th>
							<th>Sex</th>
							<th>Ethnicities</th>
							<th>SubGroup</th>
							<th>Weight</th>
							<th>Handedness</th>
							<th>Education</th>
							<th>Alt UIDs</th>
							<th>Study ID</th>
							<th>Description/Protocol</th>
							<th>Modality</th>
							<th>Date/time</th>
							<th>Series #</th>
							<th>Remove<br>from group</th>
						<?
						/* get a distinct list of modalities... then get a list of series for each modality */
						
						/* reset the result pointer to 0 to iterate through the results again */
						foreach ($modalities as $modality) {
							$modality = strtolower($modality);
							/* get the demographics (series level) */
							$sqlstring = "select b.*, c.study_num, e.*, (datediff(b.series_datetime, e.birthdate)/365.25) 'age' from group_data a left join ".$modality."_series b on a.data_id = b.".$modality."series_id left join studies c on b.study_id = c.study_id left join enrollment d on c.enrollment_id = d.enrollment_id left join subjects e on d.subject_id = e.subject_id where a.group_id = 3 and a.modality = '".$modality."' and e.subject_id is not null";
							//print "[$sqlstring]<br>";
							$result = mysql_query($sqlstring) or die("Query failed: " . mysql_error() . "<br><i>$sqlstring</i><br>");
							mysql_data_seek($result,0);
							while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
								$seriesdesc = $row['series_desc'];
								$seriesprotocol = $row['series_protocol'];
								$seriesdatetime = $row['series_datetime'];
								$seriesnum = $row['series_num'];
								$studynum = $row['study_num'];
								$seriesmodality = strtoupper($modality);
								
								$itemid = $row['subjectgroup_id'];
								$subjectid = $row['subject_id'];
								$name = $row['name'];
								$birthdate = $row['birthdate'];
								$age = $row['age'];
								$gender = $row['gender'];
								$ethnicity1 = $row['ethnicity1'];
								$ethnicity2 = $row['ethnicity2'];
								$weight = $row['weight'];
								$handedness = $row['handedness'];
								$education = $row['education'];
								$uid = $row['uid'];

								/* get list of alternate subject UIDs */
								$altuids = GetAlternateUIDs($subjectid);
								
								$parts = explode("^",$name);
								$name = substr($parts[1],0,1) . substr($parts[0],0,1);
								?>
								<tr>
									<td><?php 
echo $name;
?>
</td>
									<td><a href="subjects.php?id=<?php 
echo $subjectid;
?>
"><?php 
echo $uid;
?>
</a></td>
									<? if ($age <= 0) {$color = "red";} else {$color="black";} ?>
									<td style="color:<?php 
echo $color;
?>
"><?php 
echo number_format($age, 1);
?>
Y</td>
									<? if (!in_array(strtoupper($gender),array('M','F','O'))) {$color = "red";} else {$color="black";} ?>
									<td style="color:<?php 
echo $color;
?>
"><?php 
echo $gender;
?>
</td>
									<td style="font-size:8pt"><?php 
echo $ethnicitiy1;
?>
 <?php 
echo $ethnicitiy1;
?>
</td>
									<td style="font-size:8pt"><?php 
echo $subgroup;
?>
</td>
									<? if ($weight <= 0) {$color = "red";} else {$color="black";} ?>
									<td style="color:<?php 
echo $color;
?>
"><?php 
echo number_format($weight, 1);
?>
kg</td>
									<td><?php 
echo $handedness;
?>
</td>
									<td><?php 
echo $education;
?>
</td>
									<td style="font-size:8pt"><?php 
echo implode2(', ', $altuids);
?>
</td>
									<td><a href="studies.php?id=<?php 
echo $studyid;
?>
"><?php 
echo $uid;
echo $studynum;
?>
</a></td>
									<td style="font-size:8pt"><?php 
echo $seriesdesc;
?>
 <?php 
echo $seriesprotocol;
?>
</td>
									<td><?php 
echo $seriesmodality;
?>
</td>
									<td style="font-size:8pt"><?php 
echo $seriesdatetime;
?>
</td>
									<td><?php 
echo $seriesnum;
?>
</td>
									<td><a href="groups.php?action=removegroupitem&itemid=<?php 
echo $itemid;
?>
&id=<?php 
echo $id;
?>
" style="color:red">X</a></td>
								</tr>
								<?
							}
						}
						?>
						</table>
					</td>
				</tr>
			</table>
			<?
		}
	}
Пример #16
0
	function DisplayCTSeries($id, $study_num, $uid, $audit, $fix) {

		/* get the subject information */
		$sqlstring = "select * from subjects a left join enrollment b on a.subject_id = b.subject_id left join studies c on b.enrollment_id = c.enrollment_id where c.study_id = $id";
		$result = MySQLQuery($sqlstring, __FILE__, __LINE__);
		if (mysql_num_rows($result) > 0) {
			$row = mysql_fetch_array($result, MYSQL_ASSOC);
			$dbsubjectname = $row['name'];
			$dbsubjectdob = $row['birthdate'];
			$dbsubjectsex = $row['gender'];
			$dbstudydatetime = $row['study_datetime'];
		}
		else {
			echo "$sqlstring<br>";
		}
	
		?>
		<!--<a href="studies.php?id=<?$id?>&action=addseries&modality=CT">Add Series</a>-->
		<style type="text/css">
            .edit_inline { background-color: lightyellow; padding-left: 2pt; padding-right: 2pt; }
            .edit_textarea { background-color: lightyellow; }
			textarea.inplace_field { background-color: white; font-family: courier new; font-size: 8pt; border: 1pt solid gray; width: 800px;  }
			input.inplace_field { background-color: white; font-size: 8pt; border: 1pt solid gray; width: 200px;  }
		</style>
		
		<span class="smallnote"><b>Upload file(s) by clicking the button or drag-and-drop (Firefox and Chrome only)</b><br>
		DICOM files will only be associated with the study under which they were originally run... If you upload files from a different study, they won't show up here.</span>
		<br><br>
		<div id="file-uploader-demo1">		
			<noscript>			
				<p>Please enable JavaScript to use file uploader.</p>
				<!-- or put a simple form for upload here -->
			</noscript>         
		</div>
		<br>
		<table class="smalldisplaytable" width="100%">
			<thead>
				<tr>
					<th>Series</th>
					<th>Desc</th>
					<th>Protocol</th>
					<th>Time</th>
					<th>Notes</th>
					<th>Contrast</th>
					<th>Body part</th>
					<th>Options</th>
					<th>KVP</th>
					<th>Collection Dia</th>
					<th>Contrast Route</th>
					<th>Rotation Dir</th>
					<th>Exposure</th>
					<th>Tube current</th>
					<th>Filter type</th>
					<th>Power</th>
					<th>Kernel</th>
					<th>Spacing</th>
					<th>Image size</th>
					<th># files</th>
					<th>Size</th>
				</tr>
			</thead>
			<tbody>
				<?
					$sqlstring = "select * from ct_series where study_id = $id order by series_num";
					$result = MySQLQuery($sqlstring, __FILE__, __LINE__);
					while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
						$ctseries_id = $row['ctseries_id'];
						$series_datetime = date('g:ia',strtotime($row['series_datetime']));
						$series_desc = $row['series_desc'];
						$protocol = $row['series_protocol'];
						$sequence = $row['series_sequencename'];
						$series_num = $row['series_num'];
						$series_contrastbolusagent = $row['series_contrastbolusagent'];
						$series_bodypartexamined = $row['series_bodypartexamined'];
						$series_scanoptions = $row['series_scanoptions'];
						$series_kvp = $row['series_kvp'];
						$series_datacollectiondiameter = $row['series_datacollectiondiameter'];
						$series_contrastbolusroute = $row['series_contrastbolusroute'];
						$series_rotationdirection = $row['series_rotationdirection'];
						$series_exposuretime = $row['series_exposuretime'];
						$series_xraytubecurrent = $row['series_xraytubecurrent'];
						$series_filtertype = $row['series_filtertype'];
						$series_generatorpower = $row['series_generatorpower'];
						$series_convolutionkernel = $row['series_convolutionkernel'];
						$series_spacingx = $row['series_spacingx'];
						$series_spacingy = $row['series_spacingy'];
						$series_spacingz = $row['series_spacingz'];
						$img_rows = $row['series_imgrows'];
						$img_cols = $row['series_imgcols'];
						$img_slices = $row['series_imgslices'];
						$numfiles = $row['numfiles'];
						$series_size = $row['series_size'];
						$series_status = $row['series_status'];
						$series_notes = $row['series_notes'];
						$data_type = $row['data_type'];
						$lastupdate = $row['lastupdate'];
						
						if ( (preg_match("/epfid2d1/i",$sequence)) && ($numfiles_beh < 1)) { $behcolor = "red"; } else { $behcolor = ""; }
						if ($numfiles_beh < 1) { $numfiles_beh = "-"; }

						$thumbpath = $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/thumb.png";
						$realignpath = $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/MotionCorrection.txt";

						/* --- audit the dicom files --- */
						if ($audit) {
							$dicoms = glob($GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/*.dcm");
							//print_r($dicoms);
							$dcmcount = count($dicoms);
							$dupes = null;
							if ($dcmcount > 0) {
								//$filename = $dicoms[0];
								$mergeddcms = null;
								foreach ($dicoms as $dcmfile) {
									$dicom = Nanodicom::factory($dcmfile, 'simple');
									$dicom->parse(array(array(0x0010, 0x0010), array(0x0010, 0x0030), array(0x0010, 0x0040), array(0x0018, 0x1030), array(0x0008, 0x103E), array(0x0010, 0x0020), array(0x0020, 0x0012), array(0x0020, 0x0013), array(0x0008, 0x0020), array(0x0008, 0x0030), array(0x0008, 0x0032)));
									$dicom->profiler_diff('parse');
									$filesubjectname = trim($dicom->value(0x0010, 0x0010));
									$filesubjectdob = trim($dicom->value(0x0010, 0x0030));
									$filesubjectsex = trim($dicom->value(0x0010, 0x0040));
									$fileprotocol = trim($dicom->value(0x0018, 0x1030));
									$fileseriesdesc = trim($dicom->value(0x0008, 0x103E));
									$fileseriesnum = trim($dicom->value(0x0020, 0x0011));
									$filescanid = trim($dicom->value(0x0010, 0x0020));
									$fileinstancenumber = trim($dicom->value(0x0020, 0x0013));
									$fileslicenumber = trim($dicom->value(0x0020, 0x0012));
									$fileacquisitiontime = trim($dicom->value(0x0008, 0x0032));
									$filestudydate = trim($dicom->value(0x0008, 0x0020));
									$filestudytime = trim($dicom->value(0x0008, 0x0030));
									unset($dicom);
									
									//echo "<pre>$fileprotocol, $protocol -- $fileslicenumber, $fileinstancenumber - [$filestudydate $filestudytime] - [$dbstudydatetime]</pre><br>";
									$filestudydatetime = $filestudydate . substr($filestudytime,0,6);
									$dbstudydatetime = str_replace(array(":","-"," "),"",$dbstudydatetime);
									$dbsubjectdob = str_replace(array(":","-"," "),"",$dbsubjectdob);
									if (
										($fileprotocol != $protocol) ||
										($dbsubjectname != $filesubjectname) ||
										($dbsubjectdob != $filesubjectdob) ||
										($dbsubjectsex != $filesubjectsex) ||
										($series_num != $fileseriesnum) ||
										($filestudydatetime != $dbstudydatetime)
										)
										{
										
										if ($fileprotocol != $protocol) {
											//echo "Protocol does not match (File: $fileprotocol DB: $protocol)<br>";
											//echo "files don't match DB<br>";
											$errantdcms[]{'filename'} = $dcmfile;
											$errantdcms[]{'error'} = "Protocol does not match (File: $fileprotocol DB: $protocol)";
										}
										if (strcasecmp($dbsubjectname,$filesubjectname) != 0) {
											if (($dbsubjectname == "") && ($filesubjectname) != "") {
												//echo "Patient name does not match (File: $filesubjectname DB: $dbsubjectname)<br>";
												$errantdcms[]{'filename'} = $dcmfile;
												$errantdcms[]{'error'} = "Patient name does not match (File: $filesubjectname DB: $dbsubjectname)";
											}
											elseif (($filesubjectname == "") && ($dbsubjectname) != "") {
												//echo "Patient name does not match (File: $filesubjectname DB: $dbsubjectname)<br>";
												$errantdcms[]{'filename'} = $dcmfile;
												$errantdcms[]{'error'} = "Patient name does not match (File: $filesubjectname DB: $dbsubjectname)";
											}
											else {
												if ((stristr($dbsubjectname, $filesubjectname) === false) && (stristr($filesubjectname, $dbsubjectname) === false)) {
													//echo "Patient name does not match (File: $filesubjectname DB: $dbsubjectname)<br>";
													$errantdcms[]{'filename'} = $dcmfile;
													$errantdcms[]{'error'} = "Patient name does not match (File: $filesubjectname DB: $dbsubjectname)";
												}
											}
										}
										
										if ($dbsubjectdob != $filesubjectdob) {
											//echo "Patient DOB does not match (File: $filesubjectdob DB: $dbsubjectdob)<br>";
											$errantdcms[]{'filename'} = $dcmfile;
											$errantdcms[]{'error'} = "Patient DOB does not match (File: $filesubjectdob DB: $dbsubjectdob)";
										}
										if ($dbsubjectsex != $filesubjectsex) {
											//echo "Patient sex does not match (File: $filesubjectsex DB: $dbsubjectsex)<br>";
											$errantdcms[]{'filename'} = $dcmfile;
											$errantdcms[]{'error'} = "Patient sex does not match (File: $filesubjectsex DB: $dbsubjectsex)";
										}
										if ($series_num != $fileseriesnum) {
											//echo "Series number does not match (File: $fileseriesnum DB: $series_num)<br>";
											$errantdcms[]{'filename'} = $dcmfile;
											$errantdcms[]{'error'} = "Series number does not match (File: $fileseriesnum DB: $series_num)";
										}
										if ($filestudydatetime != $dbstudydatetime) {
											//echo "Study datetime does not match (File: $filestudydatetime DB: $dbstudydatetime)<br>";
											$errantdcms[]{'filename'} = $dcmfile;
											$errantdcms[]{'error'} = "Study datetime does not match (File: $filestudydatetime DB: $dbstudydatetime)";
										}
										
									}
									//$mergeddcms{$filesubjectname}{$filesubjectdob}{$filesubjectsex}{$filestudydate}{$filestudytime}{$fileseriesnum}{$fileslicenumber}{$fileinstancenumber} = $dcmfile;
									$mergeddcms{$filesubjectname}{$filesubjectdob}{$filesubjectsex}{$filestudydate}{$filestudytime}{$fileseriesnum}{$fileslicenumber}{$fileinstancenumber}{$fileacquisitiontime}++;
									if ($mergeddcms{$filesubjectname}{$filesubjectdob}{$filesubjectsex}{$filestudydate}{$filestudytime}{$fileseriesnum}{$fileslicenumber}{$fileinstancenumber}{$fileacquisitiontime} > 1) {
										/* check the MD5 hash to see if the files really are the same */
										//$hash1 = md5_file(
										echo "Series $fileseriesnum contains duplicate files<br>";
										$dupes[$series_num] = 1;
										
										if ($fix) {
											/* move the duplicate file to the dicom/extra directory */
											if (!file_exists($GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/duplicates")) {
												mkdir($GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/duplicates");
											}
											echo "Moving [$dcmfile] -> [" . $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/duplicates/" . GenerateRandomString(20) . ".dcm]<br>";
											rename($dcmfile, $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/duplicates/" . GenerateRandomString(20) . ".dcm");
										}
									}
								}
							}
							echo "<pre>";
							//print_r($mergeddcms);
							print_r($errantdcms);
							echo "</pre>";
							
							/* move the errant files */
							if ($fix) {
								for($i=0;$i<count($errantdcms);$i++) {
									echo "Moving [$errantdcms[$i]{'filename'}] -> [" . $GLOBALS['dicomincomingpath'] . "/" . GenerateRandomString(20) . ".dcm]<br>";
									rename($errantdcms[$i]{'filename'},$GLOBALS['dicomincomingpath'] . "/" . GenerateRandomString(20) . ".dcm");
								}
							
								/* rename the files in the directory */
								$dicoms = glob($GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/*.dcm");
								//print_r($dicoms);
								$dcmcount = count($dicoms);
								if ($dcmcount > 0) {
									$dcmsize = 0;
									foreach ($dicoms as $dcmfile) {
										$dicom = Nanodicom::factory($dcmfile, 'simple');
										$dicom->parse(array(array(0x0010, 0x0010), array(0x0010, 0x0030), array(0x0010, 0x0040), array(0x0018, 0x1030), array(0x0008, 0x103E), array(0x0010, 0x0020), array(0x0020, 0x0012), array(0x0020, 0x0013), array(0x0008, 0x0020), array(0x0008, 0x0030), array(0x0008, 0x0032)));
										$dicom->profiler_diff('parse');
										$fileseriesnum = trim($dicom->value(0x0020, 0x0011));
										$fileinstancenumber = trim($dicom->value(0x0020, 0x0013));
										$fileslicenumber = trim($dicom->value(0x0020, 0x0012));
										$fileacquisitiontime = trim($dicom->value(0x0008, 0x0032));
										unset($dicom);
										
										$dcmsize += filesize($dcmfile);
										
										$newdcmfile = $GLOBALS['cfg']['archivedir'] . "/$uid/$study_num/$series_num/dicom/$uid" . "_$study_num" . "_$series_num" . "_" . sprintf("%05d",$fileslicenumber) . "_" . sprintf("%05d",$fileinstancenumber) . "_$fileacquisitiontime.dcm";
										//if (file_exists($newdcmfile)) {
											/* some DTI files are weird, so we'll append the aquisition time */
										//}
										echo "$dcmfile --> $newdcmfile<br>";
										rename($dcmfile, $newdcmfile);
									}
									
									/* update the database with the new info */
									$sqlstring5 = "update ct_series set series_size = $dcmsize, numfiles = $dcmcount where ctseries_id = $ctseries_id";
									$result5 = MySQLQuery($sqlstring5, __FILE__, __LINE__);
								}
							}
						}
						
						?>
						<script type="text/javascript">
							$(document).ready(function(){
								$(".edit_inline<? echo $ctseries_id; ?>").editInPlace({
									url: "series_inlineupdate.php",
									params: "action=editinplace&modality=CT&id=<? echo $ctseries_id; ?>",
									default_text: "<i style='color:#AAAAAA'>Add notes...</i>",
									bg_over: "white",
									bg_out: "lightyellow",
								});
							});
						</script>
						<tr>
							<td><?php 
echo $series_num;
?>
							<?
								if ($dupes[$series_num] == 1) {
									?><span style="color: white; background-color: red; padding: 1px 5px; font-weight: bold; font-size: 8pt">Contains duplicates</span> <?
								}
							?>
							</td>
							<td><?php 
echo $series_desc;
?>
</td>
							<td><?php 
echo $protocol;
?>
 <a href="preview.php?image=<?php 
echo $thumbpath;
?>
" class="preview"><img src="images/preview.gif" border="0"></a></td>
							<td><?php 
echo $series_datetime;
?>
</td>
							<td><span id="series_notes" class="edit_inline<? echo $ctseries_id; ?>" style="background-color: lightyellow; padding: 1px 3px; font-size: 8pt;"><? echo $series_notes; ?></span></td>
							<td><?php 
echo $series_contrastbolusagent;
?>
</td>
							<td><?php 
echo $series_bodypartexamined;
?>
</td>
							<td><?php 
echo $series_scanoptions;
?>
</td>
							<td><?php 
echo $series_kvp;
?>
<span class="tiny">V</span></td>
							<td><?php 
echo $series_datacollectiondiameter;
?>
<span class="tiny">mm</span></td>
							<td><?php 
echo $series_contrastbolusroute;
?>
</td>
							<td><?php 
echo $series_rotationdirection;
?>
</td>
							<td><?php 
echo $series_exposuretime;
?>
<span class="tiny">ms</span></td>
							<td><?php 
echo $series_xraytubecurrent;
?>
<span class="tiny">mA</span></td>
							<td><?php 
echo $series_filtertype;
?>
</td>
							<td><?php 
echo $series_generatorpower;
?>
<span class="tiny">V</span></td>
							<td><?php 
echo $series_convolutionkernel;
?>
</td>
							<td><?php 
echo number_format($series_spacingx, 1);
?>
 &times; <?php 
echo number_format($series_spacingy, 1);
?>
 &times; <?php 
echo number_format($series_spacingz, 1);
?>
</td>
							<td><?php 
echo $img_cols;
?>
 &times; <?php 
echo $img_rows;
?>
 &times; <?php 
echo $img_slices;
?>
</td>
							<td>
								<?php 
echo $numfiles;
?>
								<? if (($dcmcount != $numfiles) && ($audit)) { ?><span style="color: white; background-color: red; padding: 1px 5px; font-weight: bold"><?php 
echo $dcmcount;
?>
</span> <? } ?>
							</td>
							<td nowrap><?php 
echo HumanReadableFilesize($series_size);
?>
 <a href="download.php?modality=ct&type=dicom&seriesid=<?php 
echo $ctseries_id;
?>
" border="0"><img src="images/download16.png" title="Download <?php 
echo $data_type;
?>
 data"></a></td>
						</tr>
						<?
					}
				?>
			</tbody>
		</table>
		<?
	}
Пример #17
0
	function DrawScatterPlot($w,$h,$x,$y,$c) {

		$axisindent = 40;
		$numticks = 5;
		$ticklength = 8;
		
		/* create the canvas */
		$im = imagecreatetruecolor($w,$h);
		imageantialias($im, true);
		
		/* set background to white */
		$bg = imagecolorallocate($im, 255, 255, 255);
		imagefilledrectangle($im, 0,0,$w,$h,$bg);

		
		/* determine x and y scales based on data */
		$x = explode(",", $x);
		$y = explode(",", $y);
		$c = explode(",", $c);
		$xrange = max($x);
		$yrange = max($y);
		$draww = $w - $axisindent;
		$drawh = $h - $axisindent;
		$xscale = $draww/$xrange;
		$yscale = $drawh/$yrange;
		
		//echo "Scales: $xscale, $yscale";
		/* draw the dots */
		for ($i=0; $i<count($x); $i++) {
			$xp = $x[$i]*$xscale + $axisindent;
			$yp = $h-($y[$i]*$yscale + $axisindent);

			$color = imagecolorallocatealpha($im, hexdec(substr($c[$i],0,2)), hexdec(substr($c[$i],2,2)), hexdec(substr($c[$i],4,2)), 100);
			//echo "Plotting $i: ($xp,$yp) $color<br>\n";
			imagefilledellipse($im,$xp,$yp,6,6,$color);
		}
		
		/* setup text color */
		$fontsize = 2;
		$txtcolor = imagecolorallocate($im,0,0,0);
		$linecolor = imagecolorallocate($im,180,180,180);
		$txtheight = imagefontheight($fontsize);
		$txtwidth = imagefontwidth($fontsize);

		/* draw the axis lines */
		imageline($im,$axisindent,$h-$axisindent,$w,$h-$axisindent,$linecolor); // x
		imageline($im,$axisindent,$h-$axisindent,$axisindent,0,$linecolor); // y
		
		/* draw tick lines */
		$xtickspacing = ($w-$axisindent)/$numticks;
		$ytickspacing = ($h-$axisindent)/$numticks;
		for ($i=0;$i<=$numticks;$i++) {
			/* y ticks */
			$x1 = ($i*$xtickspacing)+$axisindent;
			$x2 = ($i*$xtickspacing)+$axisindent;
			$y1 = $h-$axisindent;
			$y2 = $h-$axisindent+$ticklength;
			imageline($im, $x1, $y1, $x2, $y2,$linecolor);
			
			/* x axis values */
			$str = number_format(($i*$xtickspacing)/$xscale, 1);
			$x1 = $axisindent+($i*$xtickspacing-($txtwidth*strlen($str))/2);
			$y1 = $h-$axisindent+$ticklength+2;
			imagestring($im, $fontsize, $x1, $y1,$str,$txtcolor);

			/* y ticks */
			$y1 = $h-(($i*$ytickspacing)+$axisindent);
			$y2 = $h-(($i*$ytickspacing)+$axisindent);
			$x1 = $axisindent-$ticklength;
			$x2 = $axisindent;
			imageline($im, $x1, $y1, $x2, $y2,$linecolor);
			
			/* y axis values */
			$str = number_format(($i*$ytickspacing)/$yscale, 1);
			$x1 = $axisindent-($txtwidth*strlen($str))-($ticklength+2);
			$y1 = ($numticks-$i)*$ytickspacing-$txtheight/2;
			imagestring($im, $fontsize, $x1, $y1, $str, $txtcolor);
		}

		/* draw axis labels */
		$fontsize = 5;
		$txtcolor = imagecolorallocate($im,0,0,0);
		$txtheight = imagefontheight($fontsize);
		$txtwidth = imagefontwidth($fontsize);
		
		$str = "Years";
		$x1 = $axisindent + ($w-$axisindent)/2 - (($txtwidth*strlen($str))/2);
		$y1 = ($h-$axisindent/2);
		imagestring($im, $fontsize, $x1, $y1, $str, $txtcolor);
		
		$str = "mm";
		$y1 = ($h-$axisindent)/2 - ($txtheight/2);
		$x1 = $axisindent/2 - ($txtwidth*strlen($str)/2);
		imagestring($im, $fontsize, $x1, $y1, $str, $txtcolor);
		
		$filename = "/tmp/" . GenerateRandomString(10) . ".png";
		imagepng($im, $filename);
		chmod($filename, 0777);
		imagedestroy($im);
		
		return $filename;
	}
Пример #18
0
function ResetPassword($email)
{
    $email = mysql_real_escape_string($email);
    $safetoemail = 0;
    $securimage = new Securimage();
    if ($securimage->check($_POST['captcha_code']) == false) {
        // or you can use the following code if there is no validation or you do not know how
        ResetPasswordForm("CAPTCHA code entered was incorrect");
    }
    if (trim($email) == "") {
        ResetPasswordForm("Email was blank");
    }
    /* check if the username or email address is already in the users table */
    $sqlstring = "select count(*) 'count' from users where username = '******' or user_email = '{$email}'";
    //echo "$sqlstring<br>";
    $result = MySQLQuery($sqlstring, __FILE__, __LINE__);
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    $count = $row['count'];
    //echo "Count [$count]<br>";
    if ($count > 0) {
        $safetoemail = 1;
    } else {
        /* check if the username or email address is already in the users_pending table */
        $sqlstring = "select count(*) 'count' from users where username = '******' or user_email = '{$email}'";
        //echo "$sqlstring<br>";
        $result = MySQLQuery($sqlstring, __FILE__, __LINE__);
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        $count = $row['count'];
        //echo "Count [$count]<br>";
        if ($count > 0) {
            ?>
This email address was used to sign up for an account, but has not been activated<?php 
        } else {
            ?>
This email address is not valid in this system<?php 
            return 0;
        }
    }
    $newpass = GenerateRandomString(10);
    /* send a password reset email */
    $body = "Your password has been temporarily reset to '{$newpass}'. Please login to " . $GLOBALS['cfg']['siteurl'] . " and change your password";
    /* send the email */
    if (!SendGmail($email, 'NiDB password reset', $body, 0)) {
        echo "System error. Unable to send email!";
        //$sqlstring = "delete from users_pending where user_id = $rowid";
        //$result = MySQLQuery($sqlstring, __FILE__, __LINE__);
    } else {
        $sqlstring = "update users set password = sha1('{$newpass}') where user_email = '{$email}'";
        $result = MySQLQuery($sqlstring, __FILE__, __LINE__);
        echo "Email sent to '{$email}'. Check it and get back to me";
    }
}