--- loncom/interface/loncommon.pm	2004/07/26 21:57:27	1.203
+++ loncom/interface/loncommon.pm	2005/03/02 20:35:46	1.254
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # a pile of common routines
 #
-# $Id: loncommon.pm,v 1.203 2004/07/26 21:57:27 albertel Exp $
+# $Id: loncommon.pm,v 1.254 2005/03/02 20:35:46 matthew Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -59,7 +59,6 @@ use Apache::lonnet();
 use GDBM_File;
 use POSIX qw(strftime mktime);
 use Apache::Constants qw(:common :http :methods);
-use Apache::lonmsg();
 use Apache::lonmenu();
 use Apache::lonlocal;
 use HTML::Entities;
@@ -254,6 +253,7 @@ sub browser_and_searcher_javascript {
     if (!defined($mode)) { $mode='edit'; }
     my $resurl=&lastresurl();
     return <<END;
+// <!-- BEGIN LON-CAPA Internal
     var editbrowser = null;
     function openbrowser(formname,elementname,only,omit,titleelement) {
         var url = '$resurl/?';
@@ -265,16 +265,22 @@ sub browser_and_searcher_javascript {
         url += 'form=' + formname + '&';
         if (only != null) {
             url += 'only=' + only + '&';
-        } 
+        } else {
+            url += 'only=&';
+	}
         if (omit != null) {
             url += 'omit=' + omit + '&';
-        }
+        } else {
+            url += 'omit=&';
+	}
         if (titleelement != null) {
             url += 'titleelement=' + titleelement + '&';
-        }
+        } else {
+	    url += 'titleelement=&';
+	}
         url += 'element=' + elementname + '';
         var title = 'Browser';
-        var options = 'scrollbars=1,resizable=1,menubar=0';
+        var options = 'scrollbars=1,resizable=1,menubar=1,location=1';
         options += ',width=700,height=600';
         editbrowser = open(url,title,options,'1');
         editbrowser.focus();
@@ -290,7 +296,9 @@ sub browser_and_searcher_javascript {
         url += 'form=' + formname + '&';
         if (titleelement != null) {
             url += 'titleelement=' + titleelement + '&';
-        }
+        } else {
+	    url += 'titleelement=&';
+	}
         url += 'element=' + elementname + '';
         var title = 'Search';
         var options = 'scrollbars=1,resizable=1,menubar=0';
@@ -298,6 +306,7 @@ sub browser_and_searcher_javascript {
         editsearcher = open(url,title,options,'1');
         editsearcher.focus();
     }
+// END LON-CAPA Internal -->
 END
 }
 
@@ -370,7 +379,7 @@ sub coursebrowser_javascript {
    return (<<ENDSTDBRW);
 <script type="text/javascript" language="Javascript" >
     var stdeditbrowser;
-    function opencrsbrowser(formname,uname,udom,desc) {
+    function opencrsbrowser(formname,uname,udom,desc,extra_element) {
         var url = '/adm/pickcourse?';
         var filter;
         if (filter != null) {
@@ -387,6 +396,12 @@ sub coursebrowser_javascript {
         url += 'form=' + formname + '&cnumelement='+uname+
 	                            '&cdomelement='+udom+
                                     '&cnameelement='+desc;
+        if (extra_element !=null && extra_element != '' && formname == 'rolechoice') {
+            url += '&roleelement='+extra_element;
+            if (domainfilter == null || domainfilter == '') {
+                url += '&domainfilter='+extra_element;
+            }
+        }
         var title = 'Course_Browser';
         var options = 'scrollbars=1,resizable=1,menubar=0';
         options += ',width=700,height=600';
@@ -398,9 +413,9 @@ ENDSTDBRW
 }
 
 sub selectcourse_link {
-   my ($form,$unameele,$udomele,$desc)=@_;
+   my ($form,$unameele,$udomele,$desc,$extra_element)=@_;
     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
-        '","'.$udomele.'","'.$desc.'");'."'>".&mt('Select Course')."</a>";
+        '","'.$udomele.'","'.$desc.'","'.$extra_element.'");'."'>".&mt('Select Course')."</a>";
 }
 
 =pod
@@ -483,7 +498,7 @@ sub linked_select_forms {
     my $first = "document.$formname.$firstselectname";
     # output the javascript to do the changing
     my $result = '';
-    $result.="<script>\n";
+    $result.="<script type=\"text/javascript\">\n";
     $result.="var select2data = new Object();\n";
     $" = '","';
     my $debug = '';
@@ -532,7 +547,7 @@ END
     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
     foreach my $value (sort(keys(%$hashref))) {
         $result.="    <option value=\"$value\" ";
-        $result.=" selected=\"true\" " if ($value eq $firstdefault);
+        $result.=" selected=\"selected\" " if ($value eq $firstdefault);
         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
     }
     $result .= "</select>\n";
@@ -542,7 +557,7 @@ END
     my $seconddefault = $hashref->{$firstdefault}->{'default'};
     foreach my $value (sort(keys(%select2))) {
         $result.="    <option value=\"$value\" ";        
-        $result.=" selected=\"true\" " if ($value eq $seconddefault);
+        $result.=" selected=\"selected\" " if ($value eq $seconddefault);
         $result.=">".&mt($select2{$value})."</option>\n";
     }
     $result .= "</select>\n";
@@ -611,8 +626,9 @@ sub help_open_topic {
 
     # Add the graphic
     my $title = &mt('Online Help');
+    my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
     $template .= <<"ENDTEMPLATE";
- <a href="$link" title="$title"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
+ <a href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
 ENDTEMPLATE
     if ($text ne '') { $template.='</td></tr></table>' };
     return $template;
@@ -652,6 +668,7 @@ sub help_open_menu {
     my $link='';
     my $title = &mt('Get help');
     my $origurl = $ENV{'REQUEST_URI'};
+    $origurl=~s|^/~|/priv/|;
     my $timestamp = time;
     foreach (\$color,\$function,\$topic,\$component_help,\$faq,\$bug,\$origurl) {
         $$_ = &Apache::lonnet::escape($$_);
@@ -667,28 +684,44 @@ sub help_open_menu {
     my $template;
     if ($text ne "") {
 	$template .= 
-  "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
-  "<td bgcolor='#448844'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
+  "<table bgcolor='#773311' cellspacing='1' cellpadding='1' border='0'><tr>".
+  "<td bgcolor='#886622'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
     }
+    my $html=&Apache::lonxml::xmlbegin();
+    my $helpicon=&lonhttpdurl("/adm/lonIcons/helpgateway.gif");
     $template .= <<"ENDTEMPLATE";
- <script>
-function helpMenu(caller) {
-    if (caller == 'open') {
-        newWindow =  window.open("","helpmenu","HEIGHT=$height,WIDTH=$width,resize=yes,scrollbars=yes" )
-        caller = newWindow.document
-    } else {
-        caller = this.document
-    }
-    caller.write("<html><head><title>LON-CAPA Help Menu</title><meta http-equiv='pragma' content='no-cache'></head>")
-    caller.write("<frameset rows='105,*' border='0'><frame name='bannerframe'  src='$banner_link'><frame name='bodyframe' src='$details_link'></frameset>")
-    caller.write("</html>")
-    caller.close()
-    if (caller == newWindow.document) {
-        caller.focus()
+ <script type="text/javascript">
+// <!-- BEGIN LON-CAPA Internal
+// <![CDATA[
+function helpMenu(target) {
+    var caller = this;
+    if (target == 'open') {
+        var newWindow = null;
+        try {
+            newWindow =  window.open("/adm/rat/empty.html","helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
+        }
+        catch(error) {
+            writeHelp(caller);
+            return;
+        }
+        if (newWindow) {
+            caller = newWindow;
+        }
     }
+    writeHelp(caller);
+    return;
+}
+function writeHelp(caller) {
+    caller.document.write('$html<head><title>LON-CAPA Help Menu</title><meta http-equiv="pragma" content="no-cache"></head>')
+    caller.document.write("<frameset rows='105,*' border='0'><frame name='bannerframe'  src='$banner_link'><frame name='bodyframe' src='$details_link'></frameset>")
+    caller.document.write("</html>")
+    caller.document.close()
+    caller.focus()
 }
+// ]]>
+// END LON-CAPA Internal -->
  </script>
- <a href="$link" title="$title"><image src="/adm/lonMisc/smallFAQ.gif" border="0" alt="(Help Menu)" /></a>
+ <a href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help Menu)" /></a>
 ENDTEMPLATE
     if ($component_help) {
 	if (!$text) {
@@ -743,8 +776,9 @@ sub help_open_bug {
 
     # Add the graphic
     my $title = &mt('Report a Bug');
+    my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
     $template .= <<"ENDTEMPLATE";
- <a href="$link" title="$title"><image src="/adm/lonMisc/smallBug.gif" border="0" alt="(Bug: $topic)" /></a>
+ <a href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 ENDTEMPLATE
     if ($text ne '') { $template.='</td></tr></table>' };
     return $template;
@@ -787,8 +821,9 @@ sub help_open_faq {
 
     # Add the graphic
     my $title = &mt('View the FAQ');
+    my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
     $template .= <<"ENDTEMPLATE";
- <a href="$link" title="$title"><image src="/adm/lonMisc/smallFAQ.gif" border="0" alt="(FAQ: $topic)" /></a>
+ <a href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 ENDTEMPLATE
     if ($text ne '') { $template.='</td></tr></table>' };
     return $template;
@@ -812,7 +847,7 @@ format.
 sub csv_translate {
     my $text = shift;
     $text =~ s/\"/\"\"/g;
-    $text =~ s/\n//g;
+    $text =~ s/\n/ /g;
     return $text;
 }
 
@@ -862,8 +897,9 @@ sub define_excel_formats {
     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
+    $format->{'i'}    = $workbook->add_format(italic=>1);
     $format->{'date'} = $workbook->add_format(num_format=>
-                                            'mmm d yyyy hh:mm AM/PM');
+                                            'mm/dd/yyyy hh:mm:ss');
     return $format;
 }
 
@@ -1011,7 +1047,7 @@ sub multiple_select_form {
     $output.="\n<select name='$name' size='$size' multiple='1'>";
     foreach (sort(keys(%hash))) {
         $output.='<option value="'.$_.'" ';
-        $output.='selected ' if ($selected{$_});
+        $output.='selected="selected" ' if ($selected{$_});
         $output.='>'.$hash{$_}."</option>\n";
     }
     $output.="</select>\n";
@@ -1042,7 +1078,7 @@ sub select_form {
     }
     foreach (@keys) {
         $selectform.="<option value=\"$_\" ".
-            ($_ eq $def ? 'selected' : '').
+            ($_ eq $def ? 'selected="selected" ' : '').
                 ">".&mt($hash{$_})."</option>\n";
     }
     $selectform.="</select>";
@@ -1079,7 +1115,7 @@ sub select_level_form {
     my $selectform = "<select name=\"$name\" size=\"1\">\n";
     for (my $i=0; $i<=18; $i++) {
         $selectform.="<option value=\"$i\" ".
-            ($i==$deflevel ? 'selected' : '').
+            ($i==$deflevel ? 'selected="selected" ' : '').
                 ">".&gradeleveldescription($i)."</option>\n";
     }
     $selectform.="</select>";
@@ -1109,7 +1145,7 @@ sub select_dom_form {
     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
     foreach (@domains) {
         $selectdomain.="<option value=\"$_\" ".
-            ($_ eq $defdom ? 'selected' : '').
+            ($_ eq $defdom ? 'selected="selected" ' : '').
                 ">$_</option>\n";
     }
     $selectdomain.="</select>";
@@ -1208,9 +1244,11 @@ Outputs:
 ###############################################################
 ###############################################################
 sub decode_user_agent {
+    my ($r)=@_;
     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
+    if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
     my $clientbrowser='unknown';
     my $clientversion='0';
     my $clientmathml='';
@@ -1725,21 +1763,26 @@ sub get_related_words {
 
 =over 4
 
-=item * plainname($uname,$udom)
+=item * plainname($uname,$udom,$first)
 
 Takes a users logon name and returns it as a string in
-"first middle last generation" form
+"first middle last generation" form 
+if $first is set to 'lastname' then it returns it as
+'lastname generation, firstname middlename' if their is a lastname
 
 =cut
 
 ###############################################################
 sub plainname {
-    my ($uname,$udom)=@_;
+    my ($uname,$udom,$first)=@_;
     my %names=&Apache::lonnet::get('environment',
                     ['firstname','middlename','lastname','generation'],
 					 $udom,$uname);
-    my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
-	$names{'lastname'}.' '.$names{'generation'};
+    my $name=&Apache::lonnet::format_name($names{'firstname'},
+					  $names{'middlename'},
+					  $names{'lastname'},
+					  $names{'generation'},$first);
+    $name=~s/^\s+//;
     $name=~s/\s+$//;
     $name=~s/\s+/ /g;
     if ($name !~ /\S/) { $name=$uname.'@'.$udom; }
@@ -1765,8 +1808,19 @@ if the user does not
 
 sub nickname {
     my ($uname,$udom)=@_;
-    my %names=&Apache::lonnet::get('environment',
-  ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
+    my %names;
+    if ($uname eq $ENV{'user.name'} &&
+	$udom eq $ENV{'user.domain'}) {
+	%names=('nickname'   => $ENV{'environment.nickname'}  ,
+		'firstname'  => $ENV{'environment.firstname'} ,
+		'middlename' => $ENV{'environment.middlename'},
+		'lastname'   => $ENV{'environment.lastname'}  ,
+		'generation' => $ENV{'environment.generation'});
+    } else {
+	%names=&Apache::lonnet::get('environment',
+				    ['nickname','firstname','middlename',
+				     'lastname','generation'],$udom,$uname);
+    }
     my $name=$names{'nickname'};
     if ($name) {
        $name='&quot;'.$name.'&quot;'; 
@@ -1792,11 +1846,13 @@ Gets a users screenname and returns it a
 
 sub screenname {
     my ($uname,$udom)=@_;
-    my %names=
- &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
+    if ($uname eq $ENV{'user.name'} &&
+	$udom eq $ENV{'user.domain'}) {return $ENV{'environment.screenname'};}
+    my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
     return $names{'screenname'};
 }
 
+
 # ------------------------------------------------------------- Message Wrapper
 
 sub messagewrapper {
@@ -1817,7 +1873,7 @@ sub noteswrapper {
 
 sub aboutmewrapper {
     my ($link,$username,$domain,$target)=@_;
-    return '<a href="/adm/$domain/$username/aboutme"'.
+    return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 	($target?' target="$target"':'').' title="'.&mt('View this users personal page').'">'.$link.'</a>';
 }
 
@@ -1829,9 +1885,28 @@ sub syllabuswrapper {
     if ($fontcolor) { 
         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
     }
-    return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
+    return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
+}
+
+sub track_student_link {
+    my ($linktext,$sname,$sdom,$target) = @_;
+    my $link ="/adm/trackstudent";
+    my $title = 'View recent activity';
+    if (defined($sname) && $sname !~ /^\s*$/ &&
+        defined($sdom)  && $sdom  !~ /^\s*$/) {
+        $link .= "?selected_student=$sname:$sdom";
+        $title .= ' of this student';
+    }
+    if (defined($target) && $target !~ /^\s*$/) {
+        $target = qq{target="$target"};
+    } else {
+        $target = '';
+    }
+    return qq{<a href="$link" title="$title" $target>$linktext</a>};
 }
 
+
+
 =pod
 
 =back
@@ -2226,7 +2301,7 @@ sub get_student_view {
   if (defined($moreenv)) {
       %form=(%form,%{$moreenv});
   }
-  if ($target eq 'tex') {$form{'grade_target'} = 'tex';}
+  if (defined($target)) { $form{'grade_target'} = $target; }
   $feedurl=&Apache::lonnet::clutter($feedurl);
   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
   $userview=~s/\<body[^\>]*\>//gi;
@@ -2266,7 +2341,7 @@ sub get_student_answers {
 
 =item * &submlink()
 
-Inputs: $text $uname $udom $symb
+Inputs: $text $uname $udom $symb $target
 
 Returns: A link to grades.pm such as to see the SUBM view of a student
 
@@ -2274,15 +2349,64 @@ Returns: A link to grades.pm such as to
 
 ###############################################
 sub submlink {
-    my ($text,$uname,$udom,$symb)=@_;
+    my ($text,$uname,$udom,$symb,$target)=@_;
     if (!($uname && $udom)) {
 	(my $cursymb, my $courseid,$udom,$uname)=
 	    &Apache::lonxml::whichuser($symb);
 	if (!$symb) { $symb=$cursymb; }
     }
-    if (!$symb) { $symb=&symbread(); }
-    return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
-	'&userdom='.$udom.'&command=submission">'.$text.'</a>';
+    if (!$symb) { $symb=&Apache::lonnet::symbread(); }
+    $symb=&Apache::lonnet::escape($symb);
+    if ($target) { $target="target=\"$target\""; }
+    return '<a href="/adm/grades?&command=submission&'.
+	'symb='.$symb.'&student='.$uname.
+	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
+}
+##############################################
+
+=pod
+
+=item * &pgrdlink()
+
+Inputs: $text $uname $udom $symb $target
+
+Returns: A link to grades.pm such as to see the PGRD view of a student
+
+=cut
+
+###############################################
+sub pgrdlink {
+    my $link=&submlink(@_);
+    $link=~s/(&command=submission)/$1&showgrading=yes/;
+    return $link;
+}
+##############################################
+
+=pod
+
+=item * &pprmlink()
+
+Inputs: $text $uname $udom $symb $target
+
+Returns: A link to parmset.pm such as to see the PPRM view of a
+student andn resource
+
+=cut
+
+###############################################
+sub pprmlink {
+    my ($text,$uname,$udom,$symb,$target)=@_;
+    if (!($uname && $udom)) {
+	(my $cursymb, my $courseid,$udom,$uname)=
+	    &Apache::lonxml::whichuser($symb);
+	if (!$symb) { $symb=$cursymb; }
+    }
+    if (!$symb) { $symb=&Apache::lonnet::symbread(); }
+    $symb=&Apache::lonnet::escape($symb);
+    if ($target) { $target="target=\"$target\""; }
+    return '<a href="/adm/parmset?&command=set&'.
+	'symb='.$symb.'&uname='.$uname.
+	'&udom='.$udom.'" '.$target.'>'.$text.'</a>';
 }
 ##############################################
 
@@ -2312,7 +2436,7 @@ sub maketime {
     my %th=@_;
     return POSIX::mktime(
         ($th{'seconds'},$th{'minutes'},$th{'hours'},
-         $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
+         $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 }
 
 #########################################
@@ -2383,10 +2507,8 @@ sub domainlogo {
     my $domain = &determinedomain(shift);    
      # See if there is a logo
     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
-	my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
-	if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
-        return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
-	    '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
+	my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
+        return '<img src="'.$logo.'" alt="'.$domain.'" />';
     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
         return $Apache::lonnet::domaindescription{$domain};
     } else {
@@ -2472,7 +2594,7 @@ other decorations will be returned.
 =cut
 
 sub bodytag {
-    my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
+    my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle)=@_;
     $title=&mt($title);
     $function = &get_users_function() if (!$function);
     my $img=&designparm($function.'.img',$domain);
@@ -2505,33 +2627,109 @@ sub bodytag {
     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 # construct main body tag
     my $bodytag = <<END;
-<style>
+<style type="text/css">
 h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
 a:focus { color: red; background: yellow } 
 </style>
 <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
 style="margin-top: 0px;$addstyle" $addentries>
 END
+    if ($ENV{'environment.texengine'} eq 'jsMath') {
+	$bodytag.='<script type="text/javascript">
+                     function NoFontMessage () {}
+                   </script>'."\n".
+	    '<script src="/adm/jsMath/jsMath.js"></script>'."\n";
+    }
+
     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
     if ($bodyonly) {
         return $bodytag;
     } elsif ($ENV{'browser.interface'} eq 'textual') {
 # Accessibility
+          
         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                                                       $forcereg).
                '<h1>LON-CAPA: '.$title.'</h1>';
     } elsif ($ENV{'environment.remote'} eq 'off') {
 # No Remote
-        return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
-                                                      $forcereg).
-      '<table bgcolor="'.$pgbg.'" width="100%" border="0" cellspacing="3" cellpadding="3"><tr><td bgcolor="'.$tabbg.'"><font face="Arial, Helvetica, sans-serif" size="+3" color="'.$font.'"><b>'.$title.
-'</b></font></td></tr></table>';
+	my $roleinfo=(<<ENDROLE);
+<td bgcolor="$tabbg" align="right">
+<font size="2" face="Arial, Helvetica, sans-serif">
+    $ENV{'environment.firstname'}
+    $ENV{'environment.middlename'}
+    $ENV{'environment.lastname'}
+    $ENV{'environment.generation'}
+    </font>&nbsp;
+<br />
+<font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
+<br />
+<font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;
+</td>
+ENDROLE
+        my $titleinfo = '<font face="Arial, Helvetica, sans-serif" size="+3" color="'.
+		$font.'"><b>'.$title.'</b></font>';
+        if ($customtitle) {
+            $titleinfo = $customtitle;
+        }
+
+	if ($ENV{'request.state'} eq 'construct') {
+	    my ($uname,$thisdisfn)=
+		($ENV{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
+	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
+	    $formaction=~s/\/+/\//g;
+            unless ($customtitle) {  #this is for resources; directories have customtitle, and crumbs and select recent are created in lonpubdir.pm  
+                my $parentpath = '';
+                my $lastitem = '';
+                if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
+                    $parentpath = $1;
+                    $lastitem = $2;
+                } else {
+                    $lastitem = $thisdisfn;
+                }
+	        $titleinfo = &Apache::loncommon::help_open_menu('','','','',3,'Authoring').
+                      '<font face="Arial, Helvetica, sans-serif"><b>Construction Space</b>:</font>&nbsp;'. 
+                      '<form name="dirs" method="post" action="'.$formaction
+		    .'" target="_top"><tt><b>'
+		    .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
+		    .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
+		    .'</form>'
+		    .&Apache::lonmenu::constspaceform();
+
+            }
+	    $forcereg=1;
+        }
+        my $titletable = '<table bgcolor="'.$pgbg.'" width="100%" border="0" '.
+                         'cellspacing="3" cellpadding="3">'.
+                         '<tr><td rowspan="3" bgcolor="'.$tabbg.'">'.
+                         $titleinfo.'</td>'.$roleinfo.'</tr></table>';
+        if ($ENV{'request.state'} eq 'construct') {
+            $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg,$titletable);
+	} else {
+            $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg).
+                        $titletable;
+        }
+        return $bodytag;
     }
 
 #
 # Top frame rendering, Remote is up
 #
+    my $titleinfo = '&nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>'.$title.'</b></font>';
+    if ($customtitle) {
+        $titleinfo = $customtitle;
+    }
+    #
+    # Extra info if you are the DC
+    my $dc_info = '';
+    if ($ENV{'user.adv'} && exists($ENV{'user.role.dc./'.
+                        $ENV{'course.'.$ENV{'request.course.id'}.
+                                 '.domain'}.'/'})) {
+        my $cid = $ENV{'request.course.id'};
+        $dc_info.= $cid.' '.$ENV{'course.'.$cid.'.internal.coursecode'};
+        $dc_info = '('.$dc_info.')';
+    }
+    #
     return(<<ENDBODY);
 $bodytag
 <table width="100%" cellspacing="0" border="0" cellpadding="0">
@@ -2541,7 +2739,7 @@ $upperleft</td>
 </tr>
 <tr>
 <td rowspan="3" bgcolor="$tabbg">
-&nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
+$titleinfo $dc_info
 <td bgcolor="$tabbg" align="right">
 <font size="2" face="Arial, Helvetica, sans-serif">
     $ENV{'environment.firstname'}
@@ -2561,6 +2759,40 @@ ENDBODY
 }
 
 ###############################################
+###############################################
+
+=pod
+
+=back
+
+=head1 HTTP Helpers
+
+=over 4
+
+=item * &endbodytag()
+
+Returns a uniform footer for LON-CAPA web pages.
+
+Inputs: 
+
+=over 4
+
+=back
+
+Returns: A uniform footer for LON-CAPA web pages.  
+
+=cut
+
+sub endbodytag {
+    my $endbodytag='</body>';
+    if ($ENV{'environment.texengine'} eq 'jsMath') {
+	$endbodytag='<script type="text/javascript">jsMath.Process()</script>'.
+	    "\n".$endbodytag;
+    }
+    return $endbodytag;
+}
+
+###############################################
 
 =pod
 
@@ -2589,6 +2821,61 @@ sub get_users_function {
 
 ###############################################
 
+=pod
+
+=item get_sections
+
+Determines all the sections for a course including
+sections with students and sections containing other roles.
+Incoming parameters: domain, course number, reference to 
+section hash (keys to be section/group IDs), reference to 
+array containing roles for which sections should be gathered
+(optional). If the fourth argument is undefined, sections
+are gathered for any role.
+ 
+Returns number of sections.
+
+=cut
+
+###############################################
+sub get_sections {
+    my ($cdom,$cnum,$sectioncount,$possible_roles) = @_;
+    if (!($cdom && $cnum)) { return 0; }
+    my $cid = $cdom.'_'.$cnum;
+    my $numsections = 0;
+
+    if (!defined($possible_roles) || (grep/^st$/,@$possible_roles)) {
+	my ($classlist) = &Apache::loncoursedata::get_classlist($cid,$cdom,$cnum);
+	my $sec_index = &Apache::loncoursedata::CL_SECTION();
+	my $status_index = &Apache::loncoursedata::CL_STATUS();
+	while (my ($student,$data) = each %$classlist) {
+	    my ($section,$status) = ($data->[$sec_index],
+				     $data->[$status_index]);
+	    unless ($section eq '-1' || $section =~ /^\s*$/) {
+		if (!defined($$sectioncount{$section})) { $numsections++; }
+		$$sectioncount{$section}++;
+	    }
+	}
+    }
+    my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
+    foreach my $user (sort(keys(%courseroles))) {
+	if ($user !~ /^(\w{2})/) { next; }
+	my ($role) = ($user =~ /^(\w{2})/);
+	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
+	my $section;
+	if ($role eq 'cr' &&
+	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
+	    $section=$1;
+	}
+	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
+	if (!defined($section) || $section eq '-1') { next; }
+	if (!defined($$sectioncount{$section})) { $numsections++; } 
+	$$sectioncount{$section}++;
+    }
+    return $numsections;
+}
+
+
 sub get_posted_cgi {
     my $r=shift;
 
@@ -2697,12 +2984,12 @@ returns cache-controlling header code
 =cut
 
 sub cacheheader {
-  unless ($ENV{'request.method'} eq 'GET') { return ''; }
-  my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
-  my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
+    unless ($ENV{'request.method'} eq 'GET') { return ''; }
+    my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
+    my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
-  return $output;
+    return $output;
 }
 
 =pod
@@ -2714,16 +3001,18 @@ specifies header code to not have cache
 =cut
 
 sub no_cache {
-  my ($r) = @_;
-  unless ($ENV{'request.method'} eq 'GET') { return ''; }
-  #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
-  $r->no_cache(1);
-  $r->header_out("Pragma" => "no-cache");
-  #$r->header_out("Expires" => $date);
+    my ($r) = @_;
+    if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
+	$ENV{'request.method'} ne 'GET') { return ''; }
+    my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
+    $r->no_cache(1);
+    $r->header_out("Expires" => $date);
+    $r->header_out("Pragma" => "no-cache");
 }
 
 sub content_type {
     my ($r,$type,$charset) = @_;
+    if ($ENV{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
     unless ($charset) {
 	$charset=&Apache::lonlocal::current_encoding;
     }
@@ -2861,7 +3150,12 @@ needs $ENV{'form.upfile'} and $ENV{'form
 sub upfile_record_sep {
     if ($ENV{'form.upfiletype'} eq 'xml') {
     } else {
-	return split(/\n/,$ENV{'form.upfile'});
+	my @records;
+	foreach my $line (split(/\n/,$ENV{'form.upfile'})) {
+	    if ($line=~/^\s*$/) { next; }
+	    push(@records,$line);
+	}
+	return @records;
     }
 }
 
@@ -3019,7 +3313,7 @@ sub csv_print_select_table {
 	$r->print('<option value="none"></option>');
 	foreach (sort({$a <=> $b} keys(%sone))) {
 	    $r->print('<option value="'.$_.'"'.
-                      ($_ eq $defaultcol ? ' selected ' : '').
+                      ($_ eq $defaultcol ? ' selected="selected" ' : '').
                       '>Column '.($_+1).'</option>');
 	}
 	$r->print('</select></td></tr>'."\n");
@@ -3063,7 +3357,7 @@ sub csv_samples_select_table {
 	foreach (@$d) {
 	    my ($value,$display,$defaultcol)=@{ $_ };
 	    $r->print('<option value="'.$value.'"'.
-                      ($i eq $defaultcol ? ' selected ':'').'>'.
+                      ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
                       $display.'</option>');
 	}
 	$r->print('</select></td><td>');
@@ -3194,6 +3488,9 @@ they are plotted.  If undefined, default
 =item @Values: An array of array references.  Each array reference holds data
 to be plotted in a stacked bar chart.
 
+=item If the final element of @Values is a hash reference the key/value
+pairs will be added to the graph definition.
+
 =back
 
 Returns:
@@ -3214,13 +3511,28 @@ sub DrawBarGraph {
                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   ]; 
     }
+    my $extra_settings = {};
+    if (ref($Values[-1]) eq 'HASH') {
+        $extra_settings = pop(@Values);
+    }
     #
     my $identifier = &get_cgi_id();
     my $id = 'cgi.'.$identifier;        
     if (! @Values || ref($Values[0]) ne 'ARRAY') {
         return '';
     }
+    #
+    my @Labels;
+    if (defined($labels)) {
+        @Labels = @$labels;
+    } else {
+        for (my $i=0;$i<@{$Values[0]};$i++) {
+            push (@Labels,$i+1);
+        }
+    }
+    #
     my $NumBars = scalar(@{$Values[0]});
+    if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
     my %ValuesHash;
     my $NumSets=1;
     foreach my $array (@Values) {
@@ -3230,7 +3542,15 @@ sub DrawBarGraph {
     }
     #
     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
-    if ($NumBars < 10) {
+    if ($NumBars < 3) {
+        $width = 120+$NumBars*32;
+        $xskip = 1;
+        $bar_width = 30;
+    } elsif ($NumBars < 5) {
+        $width = 120+$NumBars*20;
+        $xskip = 1;
+        $bar_width = 20;
+    } elsif ($NumBars < 10) {
         $width = 120+$NumBars*15;
         $xskip = 1;
         $bar_width = 15;
@@ -3248,15 +3568,6 @@ sub DrawBarGraph {
         $bar_width = 4;
     }
     #
-    my @Labels;
-    if (defined($labels)) {
-        @Labels = @$labels;
-    } else {
-        for (my $i=0;$i<@{$Values[0]};$i++) {
-            push (@Labels,$i+1);
-        }
-    }
-    #
     $Max = 1 if ($Max < 1);
     if ( int($Max) < $Max ) {
         $Max++;
@@ -3279,6 +3590,11 @@ sub DrawBarGraph {
     $ValuesHash{$id.'.bar_width'} = $bar_width;
     $ValuesHash{$id.'.labels'} = join(',',@Labels);
     #
+    # Deal with other parameters
+    while (my ($key,$value) = each(%$extra_settings)) {
+        $ValuesHash{$id.'.'.$key} = $value;
+    }
+    #
     &Apache::lonnet::appenv(%ValuesHash);
     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 }
@@ -3513,8 +3829,8 @@ Inputs:
 sub chartlink {
     my ($linktext, $sname, $sdomain) = @_;
     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
-        '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
-        '&chartoutputmode='.HTML::Entities::encode('html, with all links').
+        '&amp;SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
+        '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
        '">'.$linktext.'</a>';
 }
 
@@ -3648,9 +3964,48 @@ sub icon {
 		$curfext.".gif";
 	}
     }
-    return $iconname;
+    return &lonhttpdurl($iconname);
 } 
 
+sub lonhttpdurl {
+    my ($url)=@_;
+    my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
+    if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
+    return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
+}
+
+sub connection_aborted {
+    my ($r)=@_;
+    $r->print(" ");$r->rflush();
+    my $c = $r->connection;
+    return $c->aborted();
+}
+
+#    Escapes strings that may have embedded 's that will be put into
+#    strings as 'strings'.
+sub escape_single {
+    my ($input) = @_;
+    $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
+    $input =~ s/\'/\\\'/g;	# Esacpe the 's....
+    return $input;
+}
+
+#  Same as escape_single, but escape's "'s  This 
+#  can be used for  "strings"
+sub escape_double {
+    my ($input) = @_;
+    $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
+    $input =~ s/\"/\\\"/g;	# Esacpe the "s....
+    return $input;
+}
+ 
+#   Escapes the last element of a full URL.
+sub escape_url {
+    my ($url)   = @_;
+    my @urlslices = split(/\//, $url,-1);
+    my $lastitem = &Apache::lonnet::escape(pop(@urlslices));
+    return join('/',@urlslices).'/'.$lastitem;
+}
 =pod
 
 =back