File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.677: download - view: text, annotated - select for diffs
Thu Sep 4 21:04:00 2008 UTC (15 years, 9 months ago) by riegler
Branches: MAIN
CVS tags: HEAD
added style for img.stift

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.677 2008/09/04 21:04:00 riegler Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use HTML::Entities;
   65: use Apache::lonhtmlcommon();
   66: use Apache::loncoursedata();
   67: use Apache::lontexconvert();
   68: use Apache::lonclonecourse();
   69: use LONCAPA qw(:DEFAULT :match);
   70: use DateTime::TimeZone;
   71: 
   72: # ---------------------------------------------- Designs
   73: use vars qw(%defaultdesign);
   74: 
   75: my $readit;
   76: 
   77: 
   78: ##
   79: ## Global Variables
   80: ##
   81: 
   82: 
   83: # ----------------------------------------------- SSI with retries:
   84: #
   85: 
   86: =pod
   87: 
   88: =head1 Server Side include with retries:
   89: 
   90: =over 4
   91: 
   92: =item * &ssi_with_retries(resource,retries form)
   93: 
   94: Performs an ssi with some number of retries.  Retries continue either
   95: until the result is ok or until the retry count supplied by the
   96: caller is exhausted.  
   97: 
   98: Inputs:
   99: 
  100: =over 4
  101: 
  102: resource   - Identifies the resource to insert.
  103: 
  104: retries    - Count of the number of retries allowed.
  105: 
  106: form       - Hash that identifies the rendering options.
  107: 
  108: =back
  109: 
  110: Returns:
  111: 
  112: =over 4
  113: 
  114: content    - The content of the response.  If retries were exhausted this is empty.
  115: 
  116: response   - The response from the last attempt (which may or may not have been successful.
  117: 
  118: =back
  119: 
  120: =back
  121: 
  122: =cut
  123: 
  124: sub ssi_with_retries {
  125:     my ($resource, $retries, %form) = @_;
  126: 
  127: 
  128:     my $ok = 0;			# True if we got a good response.
  129:     my $content;
  130:     my $response;
  131: 
  132:     # Try to get the ssi done. within the retries count:
  133: 
  134:     do {
  135: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  136: 	$ok      = $response->is_success;
  137:         if (!$ok) {
  138:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  139:         }
  140: 	$retries--;
  141:     } while (!$ok && ($retries > 0));
  142: 
  143:     if (!$ok) {
  144: 	$content = '';		# On error return an empty content.
  145:     }
  146:     return ($content, $response);
  147: 
  148: }
  149: 
  150: 
  151: 
  152: # ----------------------------------------------- Filetypes/Languages/Copyright
  153: my %language;
  154: my %supported_language;
  155: my %cprtag;
  156: my %scprtag;
  157: my %fe; my %fd; my %fm;
  158: my %category_extensions;
  159: 
  160: # ---------------------------------------------- Thesaurus variables
  161: #
  162: # %Keywords:
  163: #      A hash used by &keyword to determine if a word is considered a keyword.
  164: # $thesaurus_db_file 
  165: #      Scalar containing the full path to the thesaurus database.
  166: 
  167: my %Keywords;
  168: my $thesaurus_db_file;
  169: 
  170: #
  171: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  172: # thesaurus.tab, and filecategories.tab.
  173: #
  174: BEGIN {
  175:     # Variable initialization
  176:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  177:     #
  178:     unless ($readit) {
  179: # ------------------------------------------------------------------- languages
  180:     {
  181:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  182:                                    '/language.tab';
  183:         if ( open(my $fh,"<$langtabfile") ) {
  184:             while (my $line = <$fh>) {
  185:                 next if ($line=~/^\#/);
  186:                 chomp($line);
  187:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  188:                 $language{$key}=$val.' - '.$enc;
  189:                 if ($sup) {
  190:                     $supported_language{$key}=$sup;
  191:                 }
  192:             }
  193:             close($fh);
  194:         }
  195:     }
  196: # ------------------------------------------------------------------ copyrights
  197:     {
  198:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  199:                                   '/copyright.tab';
  200:         if ( open (my $fh,"<$copyrightfile") ) {
  201:             while (my $line = <$fh>) {
  202:                 next if ($line=~/^\#/);
  203:                 chomp($line);
  204:                 my ($key,$val)=(split(/\s+/,$line,2));
  205:                 $cprtag{$key}=$val;
  206:             }
  207:             close($fh);
  208:         }
  209:     }
  210: # ----------------------------------------------------------- source copyrights
  211:     {
  212:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  213:                                   '/source_copyright.tab';
  214:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  215:             while (my $line = <$fh>) {
  216:                 next if ($line =~ /^\#/);
  217:                 chomp($line);
  218:                 my ($key,$val)=(split(/\s+/,$line,2));
  219:                 $scprtag{$key}=$val;
  220:             }
  221:             close($fh);
  222:         }
  223:     }
  224: 
  225: # -------------------------------------------------------------- default domain designs
  226:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  227:     my $designfile = $designdir.'/default.tab';
  228:     if ( open (my $fh,"<$designfile") ) {
  229:         while (my $line = <$fh>) {
  230:             next if ($line =~ /^\#/);
  231:             chomp($line);
  232:             my ($key,$val)=(split(/\=/,$line));
  233:             if ($val) { $defaultdesign{$key}=$val; }
  234:         }
  235:         close($fh);
  236:     }
  237: 
  238: # ------------------------------------------------------------- file categories
  239:     {
  240:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  241:                                   '/filecategories.tab';
  242:         if ( open (my $fh,"<$categoryfile") ) {
  243: 	    while (my $line = <$fh>) {
  244: 		next if ($line =~ /^\#/);
  245: 		chomp($line);
  246:                 my ($extension,$category)=(split(/\s+/,$line,2));
  247:                 push @{$category_extensions{lc($category)}},$extension;
  248:             }
  249:             close($fh);
  250:         }
  251: 
  252:     }
  253: # ------------------------------------------------------------------ file types
  254:     {
  255:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  256:                '/filetypes.tab';
  257:         if ( open (my $fh,"<$typesfile") ) {
  258:             while (my $line = <$fh>) {
  259: 		next if ($line =~ /^\#/);
  260: 		chomp($line);
  261:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  262:                 if ($descr ne '') {
  263:                     $fe{$ending}=lc($emb);
  264:                     $fd{$ending}=$descr;
  265:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  266:                 }
  267:             }
  268:             close($fh);
  269:         }
  270:     }
  271:     &Apache::lonnet::logthis(
  272:               "<font color=yellow>INFO: Read file types</font>");
  273:     $readit=1;
  274:     }  # end of unless($readit) 
  275:     
  276: }
  277: 
  278: ###############################################################
  279: ##           HTML and Javascript Helper Functions            ##
  280: ###############################################################
  281: 
  282: =pod 
  283: 
  284: =head1 HTML and Javascript Functions
  285: 
  286: =over 4
  287: 
  288: =item * &browser_and_searcher_javascript()
  289: 
  290: X<browsing, javascript>X<searching, javascript>Returns a string
  291: containing javascript with two functions, C<openbrowser> and
  292: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  293: tags.
  294: 
  295: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  296: 
  297: inputs: formname, elementname, only, omit
  298: 
  299: formname and elementname indicate the name of the html form and name of
  300: the element that the results of the browsing selection are to be placed in. 
  301: 
  302: Specifying 'only' will restrict the browser to displaying only files
  303: with the given extension.  Can be a comma separated list.
  304: 
  305: Specifying 'omit' will restrict the browser to NOT displaying files
  306: with the given extension.  Can be a comma separated list.
  307: 
  308: =item * &opensearcher(formname,elementname) [javascript]
  309: 
  310: Inputs: formname, elementname
  311: 
  312: formname and elementname specify the name of the html form and the name
  313: of the element the selection from the search results will be placed in.
  314: 
  315: =cut
  316: 
  317: sub browser_and_searcher_javascript {
  318:     my ($mode)=@_;
  319:     if (!defined($mode)) { $mode='edit'; }
  320:     my $resurl=&escape_single(&lastresurl());
  321:     return <<END;
  322: // <!-- BEGIN LON-CAPA Internal
  323:     var editbrowser = null;
  324:     function openbrowser(formname,elementname,only,omit,titleelement) {
  325:         var url = '$resurl/?';
  326:         if (editbrowser == null) {
  327:             url += 'launch=1&';
  328:         }
  329:         url += 'catalogmode=interactive&';
  330:         url += 'mode=$mode&';
  331:         url += 'inhibitmenu=yes&';
  332:         url += 'form=' + formname + '&';
  333:         if (only != null) {
  334:             url += 'only=' + only + '&';
  335:         } else {
  336:             url += 'only=&';
  337: 	}
  338:         if (omit != null) {
  339:             url += 'omit=' + omit + '&';
  340:         } else {
  341:             url += 'omit=&';
  342: 	}
  343:         if (titleelement != null) {
  344:             url += 'titleelement=' + titleelement + '&';
  345:         } else {
  346: 	    url += 'titleelement=&';
  347: 	}
  348:         url += 'element=' + elementname + '';
  349:         var title = 'Browser';
  350:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  351:         options += ',width=700,height=600';
  352:         editbrowser = open(url,title,options,'1');
  353:         editbrowser.focus();
  354:     }
  355:     var editsearcher;
  356:     function opensearcher(formname,elementname,titleelement) {
  357:         var url = '/adm/searchcat?';
  358:         if (editsearcher == null) {
  359:             url += 'launch=1&';
  360:         }
  361:         url += 'catalogmode=interactive&';
  362:         url += 'mode=$mode&';
  363:         url += 'form=' + formname + '&';
  364:         if (titleelement != null) {
  365:             url += 'titleelement=' + titleelement + '&';
  366:         } else {
  367: 	    url += 'titleelement=&';
  368: 	}
  369:         url += 'element=' + elementname + '';
  370:         var title = 'Search';
  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  372:         options += ',width=700,height=600';
  373:         editsearcher = open(url,title,options,'1');
  374:         editsearcher.focus();
  375:     }
  376: // END LON-CAPA Internal -->
  377: END
  378: }
  379: 
  380: sub lastresurl {
  381:     if ($env{'environment.lastresurl'}) {
  382: 	return $env{'environment.lastresurl'}
  383:     } else {
  384: 	return '/res';
  385:     }
  386: }
  387: 
  388: sub storeresurl {
  389:     my $resurl=&Apache::lonnet::clutter(shift);
  390:     unless ($resurl=~/^\/res/) { return 0; }
  391:     $resurl=~s/\/$//;
  392:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  393:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  394:     return 1;
  395: }
  396: 
  397: sub studentbrowser_javascript {
  398:    unless (
  399:             (($env{'request.course.id'}) && 
  400:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  401: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  402: 					  '/'.$env{'request.course.sec'})
  403: 	      ))
  404:          || ($env{'request.role'}=~/^(au|dc|su)/)
  405:           ) { return ''; }  
  406:    return (<<'ENDSTDBRW');
  407: <script type="text/javascript" language="Javascript" >
  408:     var stdeditbrowser;
  409:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
  410:         var url = '/adm/pickstudent?';
  411:         var filter;
  412: 	if (!ignorefilter) {
  413: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  414: 	}
  415:         if (filter != null) {
  416:            if (filter != '') {
  417:                url += 'filter='+filter+'&';
  418: 	   }
  419:         }
  420:         url += 'form=' + formname + '&unameelement='+uname+
  421:                                     '&udomelement='+udom;
  422: 	if (roleflag) { url+="&roles=1"; }
  423:         var title = 'Student_Browser';
  424:         var options = 'scrollbars=1,resizable=1,menubar=0';
  425:         options += ',width=700,height=600';
  426:         stdeditbrowser = open(url,title,options,'1');
  427:         stdeditbrowser.focus();
  428:     }
  429: </script>
  430: ENDSTDBRW
  431: }
  432: 
  433: sub selectstudent_link {
  434:    my ($form,$unameele,$udomele)=@_;
  435:    if ($env{'request.course.id'}) {  
  436:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  437: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  438: 					'/'.$env{'request.course.sec'})) {
  439: 	   return '';
  440:        }
  441:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  442:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  443:    }
  444:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  445:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  446:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  447:    }
  448:    return '';
  449: }
  450: 
  451: sub authorbrowser_javascript {
  452:     return <<"ENDAUTHORBRW";
  453: <script type="text/javascript">
  454: var stdeditbrowser;
  455: 
  456: function openauthorbrowser(formname,udom) {
  457:     var url = '/adm/pickauthor?';
  458:     url += 'form='+formname+'&roledom='+udom;
  459:     var title = 'Author_Browser';
  460:     var options = 'scrollbars=1,resizable=1,menubar=0';
  461:     options += ',width=700,height=600';
  462:     stdeditbrowser = open(url,title,options,'1');
  463:     stdeditbrowser.focus();
  464: }
  465: 
  466: </script>
  467: ENDAUTHORBRW
  468: }
  469: 
  470: sub coursebrowser_javascript {
  471:     my ($domainfilter,$sec_element,$formname)=@_;
  472:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
  473:    my $output = '
  474: <script type="text/javascript">
  475:     var stdeditbrowser;'."\n";
  476:    $output .= <<"ENDSTDBRW";
  477:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  478:         var url = '/adm/pickcourse?';
  479:         var domainfilter = '';
  480:         var formid = getFormIdByName(formname);
  481:         if (formid > -1) {
  482:             var domid = getIndexByName(formid,udom);
  483:             if (domid > -1) {
  484:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  485:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  486:                 }
  487:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  488:                     domainfilter=document.forms[formid].elements[domid].value;
  489:                 }
  490:             }
  491:         }
  492:         if (domainfilter != null) {
  493:            if (domainfilter != '') {
  494:                url += 'domainfilter='+domainfilter+'&';
  495: 	   }
  496:         }
  497:         url += 'form=' + formname + '&cnumelement='+uname+
  498: 	                            '&cdomelement='+udom+
  499:                                     '&cnameelement='+desc;
  500:         if (extra_element !=null && extra_element != '') {
  501:             if (formname == 'rolechoice' || formname == 'studentform') {
  502:                 url += '&roleelement='+extra_element;
  503:                 if (domainfilter == null || domainfilter == '') {
  504:                     url += '&domainfilter='+extra_element;
  505:                 }
  506:             }
  507:             else {
  508:                 if (formname == 'portform') {
  509:                     url += '&setroles='+extra_element;
  510:                 }
  511:             }     
  512:         }
  513:         if (multflag !=null && multflag != '') {
  514:             url += '&multiple='+multflag;
  515:         }
  516:         if (crstype == 'Course/Group') {
  517:             if (formname == 'cu') {
  518:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  519:                 if (crstype == "") {
  520:                     alert("$crs_or_grp_alert");
  521:                     return;
  522:                 }
  523:             }
  524:         }
  525:         if (crstype !=null && crstype != '') {
  526:             url += '&type='+crstype;
  527:         }
  528:         var title = 'Course_Browser';
  529:         var options = 'scrollbars=1,resizable=1,menubar=0';
  530:         options += ',width=700,height=600';
  531:         stdeditbrowser = open(url,title,options,'1');
  532:         stdeditbrowser.focus();
  533:     }
  534: 
  535:     function getFormIdByName(formname) {
  536:         for (var i=0;i<document.forms.length;i++) {
  537:             if (document.forms[i].name == formname) {
  538:                 return i;
  539:             }
  540:         }
  541:         return -1; 
  542:     }
  543: 
  544:     function getIndexByName(formid,item) {
  545:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  546:             if (document.forms[formid].elements[i].name == item) {
  547:                 return i;
  548:             }
  549:         }
  550:         return -1;
  551:     }
  552: ENDSTDBRW
  553:     if ($sec_element ne '') {
  554:         $output .= &setsec_javascript($sec_element,$formname);
  555:     }
  556:     $output .= '
  557: </script>';
  558:     return $output;
  559: }
  560: 
  561: sub setsec_javascript {
  562:     my ($sec_element,$formname) = @_;
  563:     my $setsections = qq|
  564: function setSect(sectionlist) {
  565:     var sectionsArray = new Array();
  566:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  567:         sectionsArray = sectionlist.split(",");
  568:     }
  569:     var numSections = sectionsArray.length;
  570:     document.$formname.$sec_element.length = 0;
  571:     if (numSections == 0) {
  572:         document.$formname.$sec_element.multiple=false;
  573:         document.$formname.$sec_element.size=1;
  574:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  575:     } else {
  576:         if (numSections == 1) {
  577:             document.$formname.$sec_element.multiple=false;
  578:             document.$formname.$sec_element.size=1;
  579:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  580:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  581:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  582:         } else {
  583:             for (var i=0; i<numSections; i++) {
  584:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  585:             }
  586:             document.$formname.$sec_element.multiple=true
  587:             if (numSections < 3) {
  588:                 document.$formname.$sec_element.size=numSections;
  589:             } else {
  590:                 document.$formname.$sec_element.size=3;
  591:             }
  592:             document.$formname.$sec_element.options[0].selected = false
  593:         }
  594:     }
  595: }
  596: |;
  597:     return $setsections;
  598: }
  599: 
  600: 
  601: sub selectcourse_link {
  602:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  603:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  604:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
  605: }
  606: 
  607: sub selectauthor_link {
  608:    my ($form,$udom)=@_;
  609:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  610:           &mt('Select Author').'</a>';
  611: }
  612: 
  613: sub check_uncheck_jscript {
  614:     my $jscript = <<"ENDSCRT";
  615: function checkAll(field) {
  616:     if (field.length > 0) {
  617:         for (i = 0; i < field.length; i++) {
  618:             field[i].checked = true ;
  619:         }
  620:     } else {
  621:         field.checked = true
  622:     }
  623: }
  624:  
  625: function uncheckAll(field) {
  626:     if (field.length > 0) {
  627:         for (i = 0; i < field.length; i++) {
  628:             field[i].checked = false ;
  629:         }
  630:     } else {
  631:         field.checked = false ;
  632:     }
  633: }
  634: ENDSCRT
  635:     return $jscript;
  636: }
  637: 
  638: sub select_timezone {
  639:    my ($name,$selected,$onchange,$includeempty)=@_;
  640:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  641:    if ($includeempty) {
  642:        $output .= '<option value=""';
  643:        if (($selected eq '') || ($selected eq 'local')) {
  644:            $output .= ' selected="selected" ';
  645:        }
  646:        $output .= '> </option>';
  647:    }
  648:    my @timezones = DateTime::TimeZone->all_names;
  649:    foreach my $tzone (@timezones) {
  650:        $output.= '<option value="'.$tzone.'"';
  651:        if ($tzone eq $selected) {
  652:            $output.=' selected="selected"';
  653:        }
  654:        $output.=">$tzone</option>\n";
  655:    }
  656:    $output.="</select>";
  657:    return $output;
  658: }
  659: 
  660: =pod
  661: 
  662: =item * &linked_select_forms(...)
  663: 
  664: linked_select_forms returns a string containing a <script></script> block
  665: and html for two <select> menus.  The select menus will be linked in that
  666: changing the value of the first menu will result in new values being placed
  667: in the second menu.  The values in the select menu will appear in alphabetical
  668: order unless a defined order is provided.
  669: 
  670: linked_select_forms takes the following ordered inputs:
  671: 
  672: =over 4
  673: 
  674: =item * $formname, the name of the <form> tag
  675: 
  676: =item * $middletext, the text which appears between the <select> tags
  677: 
  678: =item * $firstdefault, the default value for the first menu
  679: 
  680: =item * $firstselectname, the name of the first <select> tag
  681: 
  682: =item * $secondselectname, the name of the second <select> tag
  683: 
  684: =item * $hashref, a reference to a hash containing the data for the menus.
  685: 
  686: =item * $menuorder, the order of values in the first menu
  687: 
  688: =back 
  689: 
  690: Below is an example of such a hash.  Only the 'text', 'default', and 
  691: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  692: values for the first select menu.  The text that coincides with the 
  693: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  694: and text for the second menu are given in the hash pointed to by 
  695: $menu{$choice1}->{'select2'}.  
  696: 
  697:  my %menu = ( A1 => { text =>"Choice A1" ,
  698:                        default => "B3",
  699:                        select2 => { 
  700:                            B1 => "Choice B1",
  701:                            B2 => "Choice B2",
  702:                            B3 => "Choice B3",
  703:                            B4 => "Choice B4"
  704:                            },
  705:                        order => ['B4','B3','B1','B2'],
  706:                    },
  707:                A2 => { text =>"Choice A2" ,
  708:                        default => "C2",
  709:                        select2 => { 
  710:                            C1 => "Choice C1",
  711:                            C2 => "Choice C2",
  712:                            C3 => "Choice C3"
  713:                            },
  714:                        order => ['C2','C1','C3'],
  715:                    },
  716:                A3 => { text =>"Choice A3" ,
  717:                        default => "D6",
  718:                        select2 => { 
  719:                            D1 => "Choice D1",
  720:                            D2 => "Choice D2",
  721:                            D3 => "Choice D3",
  722:                            D4 => "Choice D4",
  723:                            D5 => "Choice D5",
  724:                            D6 => "Choice D6",
  725:                            D7 => "Choice D7"
  726:                            },
  727:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  728:                    }
  729:                );
  730: 
  731: =cut
  732: 
  733: sub linked_select_forms {
  734:     my ($formname,
  735:         $middletext,
  736:         $firstdefault,
  737:         $firstselectname,
  738:         $secondselectname, 
  739:         $hashref,
  740:         $menuorder,
  741:         ) = @_;
  742:     my $second = "document.$formname.$secondselectname";
  743:     my $first = "document.$formname.$firstselectname";
  744:     # output the javascript to do the changing
  745:     my $result = '';
  746:     $result.="<script type=\"text/javascript\">\n";
  747:     $result.="var select2data = new Object();\n";
  748:     $" = '","';
  749:     my $debug = '';
  750:     foreach my $s1 (sort(keys(%$hashref))) {
  751:         $result.="select2data.d_$s1 = new Object();\n";        
  752:         $result.="select2data.d_$s1.def = new String('".
  753:             $hashref->{$s1}->{'default'}."');\n";
  754:         $result.="select2data.d_$s1.values = new Array(";
  755:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  756:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  757:             @s2values = @{$hashref->{$s1}->{'order'}};
  758:         }
  759:         $result.="\"@s2values\");\n";
  760:         $result.="select2data.d_$s1.texts = new Array(";        
  761:         my @s2texts;
  762:         foreach my $value (@s2values) {
  763:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  764:         }
  765:         $result.="\"@s2texts\");\n";
  766:     }
  767:     $"=' ';
  768:     $result.= <<"END";
  769: 
  770: function select1_changed() {
  771:     // Determine new choice
  772:     var newvalue = "d_" + $first.value;
  773:     // update select2
  774:     var values     = select2data[newvalue].values;
  775:     var texts      = select2data[newvalue].texts;
  776:     var select2def = select2data[newvalue].def;
  777:     var i;
  778:     // out with the old
  779:     for (i = 0; i < $second.options.length; i++) {
  780:         $second.options[i] = null;
  781:     }
  782:     // in with the nuclear
  783:     for (i=0;i<values.length; i++) {
  784:         $second.options[i] = new Option(values[i]);
  785:         $second.options[i].value = values[i];
  786:         $second.options[i].text = texts[i];
  787:         if (values[i] == select2def) {
  788:             $second.options[i].selected = true;
  789:         }
  790:     }
  791: }
  792: </script>
  793: END
  794:     # output the initial values for the selection lists
  795:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  796:     my @order = sort(keys(%{$hashref}));
  797:     if (ref($menuorder) eq 'ARRAY') {
  798:         @order = @{$menuorder};
  799:     }
  800:     foreach my $value (@order) {
  801:         $result.="    <option value=\"$value\" ";
  802:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  803:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  804:     }
  805:     $result .= "</select>\n";
  806:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  807:     $result .= $middletext;
  808:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  809:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  810:     
  811:     my @secondorder = sort(keys(%select2));
  812:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  813:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  814:     }
  815:     foreach my $value (@secondorder) {
  816:         $result.="    <option value=\"$value\" ";        
  817:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  818:         $result.=">".&mt($select2{$value})."</option>\n";
  819:     }
  820:     $result .= "</select>\n";
  821:     #    return $debug;
  822:     return $result;
  823: }   #  end of sub linked_select_forms {
  824: 
  825: =pod
  826: 
  827: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  828: 
  829: Returns a string corresponding to an HTML link to the given help
  830: $topic, where $topic corresponds to the name of a .tex file in
  831: /home/httpd/html/adm/help/tex, with underscores replaced by
  832: spaces. 
  833: 
  834: $text will optionally be linked to the same topic, allowing you to
  835: link text in addition to the graphic. If you do not want to link
  836: text, but wish to specify one of the later parameters, pass an
  837: empty string. 
  838: 
  839: $stayOnPage is a value that will be interpreted as a boolean. If true,
  840: the link will not open a new window. If false, the link will open
  841: a new window using Javascript. (Default is false.) 
  842: 
  843: $width and $height are optional numerical parameters that will
  844: override the width and height of the popped up window, which may
  845: be useful for certain help topics with big pictures included. 
  846: 
  847: =cut
  848: 
  849: sub help_open_topic {
  850:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  851:     $text = "" if (not defined $text);
  852:     $stayOnPage = 0 if (not defined $stayOnPage);
  853:     if ($env{'browser.interface'} eq 'textual') {
  854: 	$stayOnPage=1;
  855:     }
  856:     $width = 350 if (not defined $width);
  857:     $height = 400 if (not defined $height);
  858:     my $filename = $topic;
  859:     $filename =~ s/ /_/g;
  860: 
  861:     my $template = "";
  862:     my $link;
  863:     
  864:     $topic=~s/\W/\_/g;
  865: 
  866:     if (!$stayOnPage) {
  867: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  868:     } else {
  869: 	$link = "/adm/help/${filename}.hlp";
  870:     }
  871: 
  872:     # Add the text
  873:     if ($text ne "") {
  874: 	$template .= 
  875:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  876:             "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  877:     }
  878: 
  879:     # Add the graphic
  880:     my $title = &mt('Online Help');
  881:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  882:     $template .= <<"ENDTEMPLATE";
  883:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  884: ENDTEMPLATE
  885:     if ($text ne '') { $template.='</td></tr></table>' };
  886:     return $template;
  887: 
  888: }
  889: 
  890: # This is a quicky function for Latex cheatsheet editing, since it 
  891: # appears in at least four places
  892: sub helpLatexCheatsheet {
  893:     my $other = shift;
  894:     my $addOther = '';
  895:     if ($other) {
  896: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  897: 						       undef, undef, 600) .
  898: 							   '</td><td>';
  899:     }
  900:     return '<table><tr><td>'.
  901: 	$addOther .
  902: 	&Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
  903: 					    undef,undef,600)
  904: 	.'</td><td>'.
  905: 	&Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
  906: 					    undef,undef,600)
  907: 	.'</td><td>'.
  908: 	&Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
  909: 	                                    undef,undef,600)
  910: 	.'</td></tr></table>';
  911: }
  912: 
  913: sub general_help {
  914:     my $helptopic='Student_Intro';
  915:     if ($env{'request.role'}=~/^(ca|au)/) {
  916: 	$helptopic='Authoring_Intro';
  917:     } elsif ($env{'request.role'}=~/^cc/) {
  918: 	$helptopic='Course_Coordination_Intro';
  919:     } elsif ($env{'request.role'}=~/^dc/) {
  920:         $helptopic='Domain_Coordination_Intro';
  921:     }
  922:     return $helptopic;
  923: }
  924: 
  925: sub update_help_link {
  926:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  927:     my $origurl = $ENV{'REQUEST_URI'};
  928:     $origurl=~s|^/~|/priv/|;
  929:     my $timestamp = time;
  930:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  931:         $$datum = &escape($$datum);
  932:     }
  933: 
  934:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
  935:     my $output .= <<"ENDOUTPUT";
  936: <script type="text/javascript">
  937: banner_link = '$banner_link';
  938: </script>
  939: ENDOUTPUT
  940:     return $output;
  941: }
  942: 
  943: # now just updates the help link and generates a blue icon
  944: sub help_open_menu {
  945:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
  946: 	= @_;    
  947:     $stayOnPage = 0 if (not defined $stayOnPage);
  948:     # only use pop-up help (stayOnPage == 0)
  949:     # if environment.remote is on (using remote control UI)
  950:     if ($env{'browser.interface'} eq 'textual' ||
  951:     	$env{'environment.remote'} eq 'off' ) {
  952:         $stayOnPage=1;
  953:     }
  954:     my $output;
  955:     if ($component_help) {
  956: 	if (!$text) {
  957: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
  958: 				       $width,$height);
  959: 	} else {
  960: 	    my $help_text;
  961: 	    $help_text=&unescape($topic);
  962: 	    $output='<table><tr><td>'.
  963: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  964: 				 $width,$height).'</td></tr></table>';
  965: 	}
  966:     }
  967:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
  968:     return $output.$banner_link;
  969: }
  970: 
  971: sub top_nav_help {
  972:     my ($text) = @_;
  973:     $text = &mt($text);
  974:     my $stay_on_page = 
  975: 	($env{'browser.interface'}  eq 'textual' ||
  976: 	 $env{'environment.remote'} eq 'off' );
  977:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
  978: 	                     : "javascript:helpMenu('open')";
  979:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
  980: 
  981:     my $title = &mt('Get help');
  982: 
  983:     return <<"END";
  984: $banner_link
  985:  <a href="$link" title="$title">$text</a>
  986: END
  987: }
  988: 
  989: sub help_menu_js {
  990:     my ($text) = @_;
  991: 
  992:     my $stayOnPage = 
  993: 	($env{'browser.interface'}  eq 'textual' ||
  994: 	 $env{'environment.remote'} eq 'off' );
  995: 
  996:     my $width = 620;
  997:     my $height = 600;
  998:     my $helptopic=&general_help();
  999:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1000:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1001:     my $start_page =
 1002:         &Apache::loncommon::start_page('Help Menu', undef,
 1003: 				       {'frameset'    => 1,
 1004: 					'js_ready'    => 1,
 1005: 					'add_entries' => {
 1006: 					    'border' => '0',
 1007: 					    'rows'   => "110,*",},});
 1008:     my $end_page =
 1009:         &Apache::loncommon::end_page({'frameset' => 1,
 1010: 				      'js_ready' => 1,});
 1011: 
 1012:     my $template .= <<"ENDTEMPLATE";
 1013: <script type="text/javascript">
 1014: // <!-- BEGIN LON-CAPA Internal
 1015: // <![CDATA[
 1016: var banner_link = '';
 1017: function helpMenu(target) {
 1018:     var caller = this;
 1019:     if (target == 'open') {
 1020:         var newWindow = null;
 1021:         try {
 1022:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1023:         }
 1024:         catch(error) {
 1025:             writeHelp(caller);
 1026:             return;
 1027:         }
 1028:         if (newWindow) {
 1029:             caller = newWindow;
 1030:         }
 1031:     }
 1032:     writeHelp(caller);
 1033:     return;
 1034: }
 1035: function writeHelp(caller) {
 1036:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1037:     caller.document.close()
 1038:     caller.focus()
 1039: }
 1040: // ]]>
 1041: // END LON-CAPA Internal -->
 1042: </script>
 1043: ENDTEMPLATE
 1044:     return $template;
 1045: }
 1046: 
 1047: sub help_open_bug {
 1048:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1049:     unless ($env{'user.adv'}) { return ''; }
 1050:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1051:     $text = "" if (not defined $text);
 1052:     $stayOnPage = 0 if (not defined $stayOnPage);
 1053:     if ($env{'browser.interface'} eq 'textual' ||
 1054: 	$env{'environment.remote'} eq 'off' ) {
 1055: 	$stayOnPage=1;
 1056:     }
 1057:     $width = 600 if (not defined $width);
 1058:     $height = 600 if (not defined $height);
 1059: 
 1060:     $topic=~s/\W+/\+/g;
 1061:     my $link='';
 1062:     my $template='';
 1063:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1064: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1065:     if (!$stayOnPage)
 1066:     {
 1067: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1068:     }
 1069:     else
 1070:     {
 1071: 	$link = $url;
 1072:     }
 1073:     # Add the text
 1074:     if ($text ne "")
 1075:     {
 1076: 	$template .= 
 1077:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1078:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1079:     }
 1080: 
 1081:     # Add the graphic
 1082:     my $title = &mt('Report a Bug');
 1083:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1084:     $template .= <<"ENDTEMPLATE";
 1085:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1086: ENDTEMPLATE
 1087:     if ($text ne '') { $template.='</td></tr></table>' };
 1088:     return $template;
 1089: 
 1090: }
 1091: 
 1092: sub help_open_faq {
 1093:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1094:     unless ($env{'user.adv'}) { return ''; }
 1095:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1096:     $text = "" if (not defined $text);
 1097:     $stayOnPage = 0 if (not defined $stayOnPage);
 1098:     if ($env{'browser.interface'} eq 'textual' ||
 1099: 	$env{'environment.remote'} eq 'off' ) {
 1100: 	$stayOnPage=1;
 1101:     }
 1102:     $width = 350 if (not defined $width);
 1103:     $height = 400 if (not defined $height);
 1104: 
 1105:     $topic=~s/\W+/\+/g;
 1106:     my $link='';
 1107:     my $template='';
 1108:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1109:     if (!$stayOnPage)
 1110:     {
 1111: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1112:     }
 1113:     else
 1114:     {
 1115: 	$link = $url;
 1116:     }
 1117: 
 1118:     # Add the text
 1119:     if ($text ne "")
 1120:     {
 1121: 	$template .= 
 1122:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1123:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1124:     }
 1125: 
 1126:     # Add the graphic
 1127:     my $title = &mt('View the FAQ');
 1128:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1129:     $template .= <<"ENDTEMPLATE";
 1130:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1131: ENDTEMPLATE
 1132:     if ($text ne '') { $template.='</td></tr></table>' };
 1133:     return $template;
 1134: 
 1135: }
 1136: 
 1137: ###############################################################
 1138: ###############################################################
 1139: 
 1140: =pod
 1141: 
 1142: =item * &change_content_javascript():
 1143: 
 1144: This and the next function allow you to create small sections of an
 1145: otherwise static HTML page that you can update on the fly with
 1146: Javascript, even in Netscape 4.
 1147: 
 1148: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1149: must be written to the HTML page once. It will prove the Javascript
 1150: function "change(name, content)". Calling the change function with the
 1151: name of the section 
 1152: you want to update, matching the name passed to C<changable_area>, and
 1153: the new content you want to put in there, will put the content into
 1154: that area.
 1155: 
 1156: B<Note>: Netscape 4 only reserves enough space for the changable area
 1157: to contain room for the original contents. You need to "make space"
 1158: for whatever changes you wish to make, and be B<sure> to check your
 1159: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1160: it's adequate for updating a one-line status display, but little more.
 1161: This script will set the space to 100% width, so you only need to
 1162: worry about height in Netscape 4.
 1163: 
 1164: Modern browsers are much less limiting, and if you can commit to the
 1165: user not using Netscape 4, this feature may be used freely with
 1166: pretty much any HTML.
 1167: 
 1168: =cut
 1169: 
 1170: sub change_content_javascript {
 1171:     # If we're on Netscape 4, we need to use Layer-based code
 1172:     if ($env{'browser.type'} eq 'netscape' &&
 1173: 	$env{'browser.version'} =~ /^4\./) {
 1174: 	return (<<NETSCAPE4);
 1175: 	function change(name, content) {
 1176: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1177: 	    doc.open();
 1178: 	    doc.write(content);
 1179: 	    doc.close();
 1180: 	}
 1181: NETSCAPE4
 1182:     } else {
 1183: 	# Otherwise, we need to use semi-standards-compliant code
 1184: 	# (technically, "innerHTML" isn't standard but the equivalent
 1185: 	# is really scary, and every useful browser supports it
 1186: 	return (<<DOMBASED);
 1187: 	function change(name, content) {
 1188: 	    element = document.getElementById(name);
 1189: 	    element.innerHTML = content;
 1190: 	}
 1191: DOMBASED
 1192:     }
 1193: }
 1194: 
 1195: =pod
 1196: 
 1197: =item * &changable_area($name,$origContent):
 1198: 
 1199: This provides a "changable area" that can be modified on the fly via
 1200: the Javascript code provided in C<change_content_javascript>. $name is
 1201: the name you will use to reference the area later; do not repeat the
 1202: same name on a given HTML page more then once. $origContent is what
 1203: the area will originally contain, which can be left blank.
 1204: 
 1205: =cut
 1206: 
 1207: sub changable_area {
 1208:     my ($name, $origContent) = @_;
 1209: 
 1210:     if ($env{'browser.type'} eq 'netscape' &&
 1211: 	$env{'browser.version'} =~ /^4\./) {
 1212: 	# If this is netscape 4, we need to use the Layer tag
 1213: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1214:     } else {
 1215: 	return "<span id='$name'>$origContent</span>";
 1216:     }
 1217: }
 1218: 
 1219: =pod
 1220: 
 1221: =item * &viewport_geometry_js 
 1222: 
 1223: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1224: 
 1225: =cut
 1226: 
 1227: 
 1228: sub viewport_geometry_js { 
 1229:     return <<"GEOMETRY";
 1230: var Geometry = {};
 1231: function init_geometry() {
 1232:     if (Geometry.init) { return };
 1233:     Geometry.init=1;
 1234:     if (window.innerHeight) {
 1235:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1236:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1237:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1238:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1239:     }
 1240:     else if (document.documentElement && document.documentElement.clientHeight) {
 1241:         Geometry.getViewportHeight =
 1242:             function() { return document.documentElement.clientHeight; };
 1243:         Geometry.getViewportWidth =
 1244:             function() { return document.documentElement.clientWidth; };
 1245: 
 1246:         Geometry.getHorizontalScroll =
 1247:             function() { return document.documentElement.scrollLeft; };
 1248:         Geometry.getVerticalScroll =
 1249:             function() { return document.documentElement.scrollTop; };
 1250:     }
 1251:     else if (document.body.clientHeight) {
 1252:         Geometry.getViewportHeight =
 1253:             function() { return document.body.clientHeight; };
 1254:         Geometry.getViewportWidth =
 1255:             function() { return document.body.clientWidth; };
 1256:         Geometry.getHorizontalScroll =
 1257:             function() { return document.body.scrollLeft; };
 1258:         Geometry.getVerticalScroll =
 1259:             function() { return document.body.scrollTop; };
 1260:     }
 1261: }
 1262: 
 1263: GEOMETRY
 1264: }
 1265: 
 1266: =pod
 1267: 
 1268: =item * &viewport_size_js()
 1269: 
 1270: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1271: 
 1272: =cut
 1273: 
 1274: sub viewport_size_js {
 1275:     my $geometry = &viewport_geometry_js();
 1276:     return <<"DIMS";
 1277: 
 1278: $geometry
 1279: 
 1280: function getViewportDims(width,height) {
 1281:     init_geometry();
 1282:     width.value = Geometry.getViewportWidth();
 1283:     height.value = Geometry.getViewportHeight();
 1284:     return;
 1285: }
 1286: 
 1287: DIMS
 1288: }
 1289: 
 1290: =pod
 1291: 
 1292: =item * &resize_textarea_js()
 1293: 
 1294: emits the needed javascript to resize a textarea to be as big as possible
 1295: 
 1296: creates a function resize_textrea that takes two IDs first should be
 1297: the id of the element to resize, second should be the id of a div that
 1298: surrounds everything that comes after the textarea, this routine needs
 1299: to be attached to the <body> for the onload and onresize events.
 1300: 
 1301: =back
 1302: 
 1303: =cut
 1304: 
 1305: sub resize_textarea_js {
 1306:     my $geometry = &viewport_geometry_js();
 1307:     return <<"RESIZE";
 1308:     <script type="text/javascript">
 1309: $geometry
 1310: 
 1311: function getX(element) {
 1312:     var x = 0;
 1313:     while (element) {
 1314: 	x += element.offsetLeft;
 1315: 	element = element.offsetParent;
 1316:     }
 1317:     return x;
 1318: }
 1319: function getY(element) {
 1320:     var y = 0;
 1321:     while (element) {
 1322: 	y += element.offsetTop;
 1323: 	element = element.offsetParent;
 1324:     }
 1325:     return y;
 1326: }
 1327: 
 1328: 
 1329: function resize_textarea(textarea_id,bottom_id) {
 1330:     init_geometry();
 1331:     var textarea        = document.getElementById(textarea_id);
 1332:     //alert(textarea);
 1333: 
 1334:     var textarea_top    = getY(textarea);
 1335:     var textarea_height = textarea.offsetHeight;
 1336:     var bottom          = document.getElementById(bottom_id);
 1337:     var bottom_top      = getY(bottom);
 1338:     var bottom_height   = bottom.offsetHeight;
 1339:     var window_height   = Geometry.getViewportHeight();
 1340:     var fudge           = 23;
 1341:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1342:     if (new_height < 300) {
 1343: 	new_height = 300;
 1344:     }
 1345:     textarea.style.height=new_height+'px';
 1346: }
 1347: </script>
 1348: RESIZE
 1349: 
 1350: }
 1351: 
 1352: =pod
 1353: 
 1354: =head1 Excel and CSV file utility routines
 1355: 
 1356: =over 4
 1357: 
 1358: =cut
 1359: 
 1360: ###############################################################
 1361: ###############################################################
 1362: 
 1363: =pod
 1364: 
 1365: =item * &csv_translate($text) 
 1366: 
 1367: Translate $text to allow it to be output as a 'comma separated values' 
 1368: format.
 1369: 
 1370: =cut
 1371: 
 1372: ###############################################################
 1373: ###############################################################
 1374: sub csv_translate {
 1375:     my $text = shift;
 1376:     $text =~ s/\"/\"\"/g;
 1377:     $text =~ s/\n/ /g;
 1378:     return $text;
 1379: }
 1380: 
 1381: ###############################################################
 1382: ###############################################################
 1383: 
 1384: =pod
 1385: 
 1386: =item * &define_excel_formats()
 1387: 
 1388: Define some commonly used Excel cell formats.
 1389: 
 1390: Currently supported formats:
 1391: 
 1392: =over 4
 1393: 
 1394: =item header
 1395: 
 1396: =item bold
 1397: 
 1398: =item h1
 1399: 
 1400: =item h2
 1401: 
 1402: =item h3
 1403: 
 1404: =item h4
 1405: 
 1406: =item i
 1407: 
 1408: =item date
 1409: 
 1410: =back
 1411: 
 1412: Inputs: $workbook
 1413: 
 1414: Returns: $format, a hash reference.
 1415: 
 1416: =cut
 1417: 
 1418: ###############################################################
 1419: ###############################################################
 1420: sub define_excel_formats {
 1421:     my ($workbook) = @_;
 1422:     my $format;
 1423:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1424:                                                 bottom    => 1,
 1425:                                                 align     => 'center');
 1426:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1427:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1428:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1429:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1430:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1431:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1432:     $format->{'date'} = $workbook->add_format(num_format=>
 1433:                                             'mm/dd/yyyy hh:mm:ss');
 1434:     return $format;
 1435: }
 1436: 
 1437: ###############################################################
 1438: ###############################################################
 1439: 
 1440: =pod
 1441: 
 1442: =item * &create_workbook()
 1443: 
 1444: Create an Excel worksheet.  If it fails, output message on the
 1445: request object and return undefs.
 1446: 
 1447: Inputs: Apache request object
 1448: 
 1449: Returns (undef) on failure, 
 1450:     Excel worksheet object, scalar with filename, and formats 
 1451:     from &Apache::loncommon::define_excel_formats on success
 1452: 
 1453: =cut
 1454: 
 1455: ###############################################################
 1456: ###############################################################
 1457: sub create_workbook {
 1458:     my ($r) = @_;
 1459:         #
 1460:     # Create the excel spreadsheet
 1461:     my $filename = '/prtspool/'.
 1462:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1463:         time.'_'.rand(1000000000).'.xls';
 1464:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1465:     if (! defined($workbook)) {
 1466:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1467:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1468:                             "This error has been logged.  ".
 1469:                             "Please alert your LON-CAPA administrator").
 1470:                   '</p>');
 1471:         return (undef);
 1472:     }
 1473:     #
 1474:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1475:     #
 1476:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1477:     return ($workbook,$filename,$format);
 1478: }
 1479: 
 1480: ###############################################################
 1481: ###############################################################
 1482: 
 1483: =pod
 1484: 
 1485: =item * &create_text_file()
 1486: 
 1487: Create a file to write to and eventually make available to the user.
 1488: If file creation fails, outputs an error message on the request object and 
 1489: return undefs.
 1490: 
 1491: Inputs: Apache request object, and file suffix
 1492: 
 1493: Returns (undef) on failure, 
 1494:     Filehandle and filename on success.
 1495: 
 1496: =cut
 1497: 
 1498: ###############################################################
 1499: ###############################################################
 1500: sub create_text_file {
 1501:     my ($r,$suffix) = @_;
 1502:     if (! defined($suffix)) { $suffix = 'txt'; };
 1503:     my $fh;
 1504:     my $filename = '/prtspool/'.
 1505:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1506:         time.'_'.rand(1000000000).'.'.$suffix;
 1507:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1508:     if (! defined($fh)) {
 1509:         $r->log_error("Couldn't open $filename for output $!");
 1510:         $r->print("Problems occured in creating the output file.  ".
 1511:                   "This error has been logged.  ".
 1512:                   "Please alert your LON-CAPA administrator.");
 1513:     }
 1514:     return ($fh,$filename)
 1515: }
 1516: 
 1517: 
 1518: =pod 
 1519: 
 1520: =back
 1521: 
 1522: =cut
 1523: 
 1524: ###############################################################
 1525: ##        Home server <option> list generating code          ##
 1526: ###############################################################
 1527: 
 1528: # ------------------------------------------
 1529: 
 1530: sub domain_select {
 1531:     my ($name,$value,$multiple)=@_;
 1532:     my %domains=map { 
 1533: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1534:     } &Apache::lonnet::all_domains();
 1535:     if ($multiple) {
 1536: 	$domains{''}=&mt('Any domain');
 1537: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1538: 	return &multiple_select_form($name,$value,4,\%domains);
 1539:     } else {
 1540: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1541: 	return &select_form($name,$value,%domains);
 1542:     }
 1543: }
 1544: 
 1545: #-------------------------------------------
 1546: 
 1547: =pod
 1548: 
 1549: =head1 Routines for form select boxes
 1550: 
 1551: =over 4
 1552: 
 1553: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1554: 
 1555: Returns a string containing a <select> element int multiple mode
 1556: 
 1557: 
 1558: Args:
 1559:   $name - name of the <select> element
 1560:   $value - scalar or array ref of values that should already be selected
 1561:   $size - number of rows long the select element is
 1562:   $hash - the elements should be 'option' => 'shown text'
 1563:           (shown text should already have been &mt())
 1564:   $order - (optional) array ref of the order to show the elements in
 1565: 
 1566: =cut
 1567: 
 1568: #-------------------------------------------
 1569: sub multiple_select_form {
 1570:     my ($name,$value,$size,$hash,$order)=@_;
 1571:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1572:     my $output='';
 1573:     if (! defined($size)) {
 1574:         $size = 4;
 1575:         if (scalar(keys(%$hash))<4) {
 1576:             $size = scalar(keys(%$hash));
 1577:         }
 1578:     }
 1579:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1580:     my @order;
 1581:     if (ref($order) eq 'ARRAY')  {
 1582:         @order = @{$order};
 1583:     } else {
 1584:         @order = sort(keys(%$hash));
 1585:     }
 1586:     if (exists($$hash{'select_form_order'})) {
 1587:         @order = @{$$hash{'select_form_order'}};
 1588:     }
 1589:         
 1590:     foreach my $key (@order) {
 1591:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1592:         $output.='selected="selected" ' if ($selected{$key});
 1593:         $output.='>'.$hash->{$key}."</option>\n";
 1594:     }
 1595:     $output.="</select>\n";
 1596:     return $output;
 1597: }
 1598: 
 1599: #-------------------------------------------
 1600: 
 1601: =pod
 1602: 
 1603: =item * &select_form($defdom,$name,%hash)
 1604: 
 1605: Returns a string containing a <select name='$name' size='1'> form to 
 1606: allow a user to select options from a hash option_name => displayed text.  
 1607: See lonrights.pm for an example invocation and use.
 1608: 
 1609: =cut
 1610: 
 1611: #-------------------------------------------
 1612: sub select_form {
 1613:     my ($def,$name,%hash) = @_;
 1614:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1615:     my @keys;
 1616:     if (exists($hash{'select_form_order'})) {
 1617: 	@keys=@{$hash{'select_form_order'}};
 1618:     } else {
 1619: 	@keys=sort(keys(%hash));
 1620:     }
 1621:     foreach my $key (@keys) {
 1622:         $selectform.=
 1623: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1624:             ($key eq $def ? 'selected="selected" ' : '').
 1625:                 ">".&mt($hash{$key})."</option>\n";
 1626:     }
 1627:     $selectform.="</select>";
 1628:     return $selectform;
 1629: }
 1630: 
 1631: # For display filters
 1632: 
 1633: sub display_filter {
 1634:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1635:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1636:     return '<nobr><label>'.&mt('Records [_1]',
 1637: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1638: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1639: 	   '</label></nobr> <nobr>'.
 1640:            &mt('Filter [_1]',
 1641: 	   &select_form($env{'form.displayfilter'},
 1642: 			'displayfilter',
 1643: 			('currentfolder' => 'Current folder/page',
 1644: 			 'containing' => 'Containing phrase',
 1645: 			 'none' => 'None'))).
 1646: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
 1647: }
 1648: 
 1649: sub gradeleveldescription {
 1650:     my $gradelevel=shift;
 1651:     my %gradelevels=(0 => 'Not specified',
 1652: 		     1 => 'Grade 1',
 1653: 		     2 => 'Grade 2',
 1654: 		     3 => 'Grade 3',
 1655: 		     4 => 'Grade 4',
 1656: 		     5 => 'Grade 5',
 1657: 		     6 => 'Grade 6',
 1658: 		     7 => 'Grade 7',
 1659: 		     8 => 'Grade 8',
 1660: 		     9 => 'Grade 9',
 1661: 		     10 => 'Grade 10',
 1662: 		     11 => 'Grade 11',
 1663: 		     12 => 'Grade 12',
 1664: 		     13 => 'Grade 13',
 1665: 		     14 => '100 Level',
 1666: 		     15 => '200 Level',
 1667: 		     16 => '300 Level',
 1668: 		     17 => '400 Level',
 1669: 		     18 => 'Graduate Level');
 1670:     return &mt($gradelevels{$gradelevel});
 1671: }
 1672: 
 1673: sub select_level_form {
 1674:     my ($deflevel,$name)=@_;
 1675:     unless ($deflevel) { $deflevel=0; }
 1676:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1677:     for (my $i=0; $i<=18; $i++) {
 1678:         $selectform.="<option value=\"$i\" ".
 1679:             ($i==$deflevel ? 'selected="selected" ' : '').
 1680:                 ">".&gradeleveldescription($i)."</option>\n";
 1681:     }
 1682:     $selectform.="</select>";
 1683:     return $selectform;
 1684: }
 1685: 
 1686: #-------------------------------------------
 1687: 
 1688: =pod
 1689: 
 1690: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
 1691: 
 1692: Returns a string containing a <select name='$name' size='1'> form to 
 1693: allow a user to select the domain to preform an operation in.  
 1694: See loncreateuser.pm for an example invocation and use.
 1695: 
 1696: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1697: selected");
 1698: 
 1699: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
 1700: 
 1701: =cut
 1702: 
 1703: #-------------------------------------------
 1704: sub select_dom_form {
 1705:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
 1706:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1707:     if ($includeempty) { @domains=('',@domains); }
 1708:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1709:     foreach my $dom (@domains) {
 1710:         $selectdomain.="<option value=\"$dom\" ".
 1711:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1712:         if ($showdomdesc) {
 1713:             if ($dom ne '') {
 1714:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1715:                 if ($domdesc ne '') {
 1716:                     $selectdomain .= ' ('.$domdesc.')';
 1717:                 }
 1718:             } 
 1719:         }
 1720:         $selectdomain .= "</option>\n";
 1721:     }
 1722:     $selectdomain.="</select>";
 1723:     return $selectdomain;
 1724: }
 1725: 
 1726: #-------------------------------------------
 1727: 
 1728: =pod
 1729: 
 1730: =item * &home_server_form_item($domain,$name,$defaultflag)
 1731: 
 1732: input: 4 arguments (two required, two optional) - 
 1733:     $domain - domain of new user
 1734:     $name - name of form element
 1735:     $default - Value of 'default' causes a default item to be first 
 1736:                             option, and selected by default. 
 1737:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1738:                             if 1 server found, or default, if 0 found.
 1739: output: returns 2 items: 
 1740: (a) form element which contains either:
 1741:    (i) <select name="$name">
 1742:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1743:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1744:        </select>
 1745:        form item if there are multiple library servers in $domain, or
 1746:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1747:        if there is only one library server in $domain.
 1748: 
 1749: (b) number of library servers found.
 1750: 
 1751: See loncreateuser.pm for example of use.
 1752: 
 1753: =cut
 1754: 
 1755: #-------------------------------------------
 1756: sub home_server_form_item {
 1757:     my ($domain,$name,$default,$hide) = @_;
 1758:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1759:     my $result;
 1760:     my $numlib = keys(%servers);
 1761:     if ($numlib > 1) {
 1762:         $result .= '<select name="'.$name.'" />'."\n";
 1763:         if ($default) {
 1764:             $result .= '<option value="default" selected>'.&mt('default').
 1765:                        '</option>'."\n";
 1766:         }
 1767:         foreach my $hostid (sort(keys(%servers))) {
 1768:             $result.= '<option value="'.$hostid.'">'.
 1769: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1770:         }
 1771:         $result .= '</select>'."\n";
 1772:     } elsif ($numlib == 1) {
 1773:         my $hostid;
 1774:         foreach my $item (keys(%servers)) {
 1775:             $hostid = $item;
 1776:         }
 1777:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1778:                    $hostid.'" />';
 1779:                    if (!$hide) {
 1780:                        $result .= $hostid.' '.$servers{$hostid};
 1781:                    }
 1782:                    $result .= "\n";
 1783:     } elsif ($default) {
 1784:         $result .= '<input type="hidden" name="'.$name.
 1785:                    '" value="default" />';
 1786:                    if (!$hide) {
 1787:                        $result .= &mt('default');
 1788:                    }
 1789:                    $result .= "\n";
 1790:     }
 1791:     return ($result,$numlib);
 1792: }
 1793: 
 1794: =pod
 1795: 
 1796: =back 
 1797: 
 1798: =cut
 1799: 
 1800: ###############################################################
 1801: ##                  Decoding User Agent                      ##
 1802: ###############################################################
 1803: 
 1804: =pod
 1805: 
 1806: =head1 Decoding the User Agent
 1807: 
 1808: =over 4
 1809: 
 1810: =item * &decode_user_agent()
 1811: 
 1812: Inputs: $r
 1813: 
 1814: Outputs:
 1815: 
 1816: =over 4
 1817: 
 1818: =item * $httpbrowser
 1819: 
 1820: =item * $clientbrowser
 1821: 
 1822: =item * $clientversion
 1823: 
 1824: =item * $clientmathml
 1825: 
 1826: =item * $clientunicode
 1827: 
 1828: =item * $clientos
 1829: 
 1830: =back
 1831: 
 1832: =back 
 1833: 
 1834: =cut
 1835: 
 1836: ###############################################################
 1837: ###############################################################
 1838: sub decode_user_agent {
 1839:     my ($r)=@_;
 1840:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1841:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1842:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1843:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1844:     my $clientbrowser='unknown';
 1845:     my $clientversion='0';
 1846:     my $clientmathml='';
 1847:     my $clientunicode='0';
 1848:     for (my $i=0;$i<=$#browsertype;$i++) {
 1849:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1850: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1851: 	    $clientbrowser=$bname;
 1852:             $httpbrowser=~/$vreg/i;
 1853: 	    $clientversion=$1;
 1854:             $clientmathml=($clientversion>=$minv);
 1855:             $clientunicode=($clientversion>=$univ);
 1856: 	}
 1857:     }
 1858:     my $clientos='unknown';
 1859:     if (($httpbrowser=~/linux/i) ||
 1860:         ($httpbrowser=~/unix/i) ||
 1861:         ($httpbrowser=~/ux/i) ||
 1862:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1863:     if (($httpbrowser=~/vax/i) ||
 1864:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1865:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1866:     if (($httpbrowser=~/mac/i) ||
 1867:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1868:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1869:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1870:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1871:             $clientunicode,$clientos,);
 1872: }
 1873: 
 1874: ###############################################################
 1875: ##    Authentication changing form generation subroutines    ##
 1876: ###############################################################
 1877: ##
 1878: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1879: ## hash, and have reasonable default values.
 1880: ##
 1881: ##    formname = the name given in the <form> tag.
 1882: #-------------------------------------------
 1883: 
 1884: =pod
 1885: 
 1886: =head1 Authentication Routines
 1887: 
 1888: =over 4
 1889: 
 1890: =item * &authform_xxxxxx()
 1891: 
 1892: The authform_xxxxxx subroutines provide javascript and html forms which 
 1893: handle some of the conveniences required for authentication forms.  
 1894: This is not an optimal method, but it works.  
 1895: 
 1896: =over 4
 1897: 
 1898: =item * authform_header
 1899: 
 1900: =item * authform_authorwarning
 1901: 
 1902: =item * authform_nochange
 1903: 
 1904: =item * authform_kerberos
 1905: 
 1906: =item * authform_internal
 1907: 
 1908: =item * authform_filesystem
 1909: 
 1910: =back
 1911: 
 1912: See loncreateuser.pm for invocation and use examples.
 1913: 
 1914: =cut
 1915: 
 1916: #-------------------------------------------
 1917: sub authform_header{  
 1918:     my %in = (
 1919:         formname => 'cu',
 1920:         kerb_def_dom => '',
 1921:         @_,
 1922:     );
 1923:     $in{'formname'} = 'document.' . $in{'formname'};
 1924:     my $result='';
 1925: 
 1926: #---------------------------------------------- Code for upper case translation
 1927:     my $Javascript_toUpperCase;
 1928:     unless ($in{kerb_def_dom}) {
 1929:         $Javascript_toUpperCase =<<"END";
 1930:         switch (choice) {
 1931:            case 'krb': currentform.elements[choicearg].value =
 1932:                currentform.elements[choicearg].value.toUpperCase();
 1933:                break;
 1934:            default:
 1935:         }
 1936: END
 1937:     } else {
 1938:         $Javascript_toUpperCase = "";
 1939:     }
 1940: 
 1941:     my $radioval = "'nochange'";
 1942:     if (defined($in{'curr_authtype'})) {
 1943:         if ($in{'curr_authtype'} ne '') {
 1944:             $radioval = "'".$in{'curr_authtype'}."arg'";
 1945:         }
 1946:     }
 1947:     my $argfield = 'null';
 1948:     if (defined($in{'mode'})) {
 1949:         if ($in{'mode'} eq 'modifycourse')  {
 1950:             if (defined($in{'curr_autharg'})) {
 1951:                 if ($in{'curr_autharg'} ne '') {
 1952:                     $argfield = "'$in{'curr_autharg'}'";
 1953:                 }
 1954:             }
 1955:         }
 1956:     }
 1957: 
 1958:     $result.=<<"END";
 1959: var current = new Object();
 1960: current.radiovalue = $radioval;
 1961: current.argfield = $argfield;
 1962: 
 1963: function changed_radio(choice,currentform) {
 1964:     var choicearg = choice + 'arg';
 1965:     // If a radio button in changed, we need to change the argfield
 1966:     if (current.radiovalue != choice) {
 1967:         current.radiovalue = choice;
 1968:         if (current.argfield != null) {
 1969:             currentform.elements[current.argfield].value = '';
 1970:         }
 1971:         if (choice == 'nochange') {
 1972:             current.argfield = null;
 1973:         } else {
 1974:             current.argfield = choicearg;
 1975:             switch(choice) {
 1976:                 case 'krb': 
 1977:                     currentform.elements[current.argfield].value = 
 1978:                         "$in{'kerb_def_dom'}";
 1979:                 break;
 1980:               default:
 1981:                 break;
 1982:             }
 1983:         }
 1984:     }
 1985:     return;
 1986: }
 1987: 
 1988: function changed_text(choice,currentform) {
 1989:     var choicearg = choice + 'arg';
 1990:     if (currentform.elements[choicearg].value !='') {
 1991:         $Javascript_toUpperCase
 1992:         // clear old field
 1993:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1994:             currentform.elements[current.argfield].value = '';
 1995:         }
 1996:         current.argfield = choicearg;
 1997:     }
 1998:     set_auth_radio_buttons(choice,currentform);
 1999:     return;
 2000: }
 2001: 
 2002: function set_auth_radio_buttons(newvalue,currentform) {
 2003:     var i=0;
 2004:     while (i < currentform.login.length) {
 2005:         if (currentform.login[i].value == newvalue) { break; }
 2006:         i++;
 2007:     }
 2008:     if (i == currentform.login.length) {
 2009:         return;
 2010:     }
 2011:     current.radiovalue = newvalue;
 2012:     currentform.login[i].checked = true;
 2013:     return;
 2014: }
 2015: END
 2016:     return $result;
 2017: }
 2018: 
 2019: sub authform_authorwarning{
 2020:     my $result='';
 2021:     $result='<i>'.
 2022:         &mt('As a general rule, only authors or co-authors should be '.
 2023:             'filesystem authenticated '.
 2024:             '(which allows access to the server filesystem).')."</i>\n";
 2025:     return $result;
 2026: }
 2027: 
 2028: sub authform_nochange{  
 2029:     my %in = (
 2030:               formname => 'document.cu',
 2031:               kerb_def_dom => 'MSU.EDU',
 2032:               @_,
 2033:           );
 2034:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2035:     my $result;
 2036:     if (keys(%can_assign) == 0) {
 2037:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2038:     } else {
 2039:         $result = '<label>'.&mt('[_1] Do not change login data',
 2040:                   '<input type="radio" name="login" value="nochange" '.
 2041:                   'checked="checked" onclick="'.
 2042:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2043: 	    '</label>';
 2044:     }
 2045:     return $result;
 2046: }
 2047: 
 2048: sub authform_kerberos {
 2049:     my %in = (
 2050:               formname => 'document.cu',
 2051:               kerb_def_dom => 'MSU.EDU',
 2052:               kerb_def_auth => 'krb4',
 2053:               @_,
 2054:               );
 2055:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2056:         $autharg,$jscall);
 2057:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2058:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2059:        $check5 = ' checked="on"';
 2060:     } else {
 2061:        $check4 = ' checked="on"';
 2062:     }
 2063:     $krbarg = $in{'kerb_def_dom'};
 2064:     if (defined($in{'curr_authtype'})) {
 2065:         if ($in{'curr_authtype'} eq 'krb') {
 2066:             $krbcheck = ' checked="on"';
 2067:             if (defined($in{'mode'})) {
 2068:                 if ($in{'mode'} eq 'modifyuser') {
 2069:                     $krbcheck = '';
 2070:                 }
 2071:             }
 2072:             if (defined($in{'curr_kerb_ver'})) {
 2073:                 if ($in{'curr_krb_ver'} eq '5') {
 2074:                     $check5 = ' checked="on"';
 2075:                     $check4 = '';
 2076:                 } else {
 2077:                     $check4 = ' checked="on"';
 2078:                     $check5 = '';
 2079:                 }
 2080:             }
 2081:             if (defined($in{'curr_autharg'})) {
 2082:                 $krbarg = $in{'curr_autharg'};
 2083:             }
 2084:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2085:                 if (defined($in{'curr_autharg'})) {
 2086:                     $result = 
 2087:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2088:         $in{'curr_autharg'},$krbver);
 2089:                 } else {
 2090:                     $result =
 2091:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2092:                 }
 2093:                 return $result; 
 2094:             }
 2095:         }
 2096:     } else {
 2097:         if ($authnum == 1) {
 2098:             $authtype = '<input type="hidden" name="login" value="krb">';
 2099:         }
 2100:     }
 2101:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2102:         return;
 2103:     } elsif ($authtype eq '') {
 2104:         if (defined($in{'mode'})) {
 2105:             if ($in{'mode'} eq 'modifycourse') {
 2106:                 if ($authnum == 1) {
 2107:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2108:                 }
 2109:             }
 2110:         }
 2111:     }
 2112:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2113:     if ($authtype eq '') {
 2114:         $authtype = '<input type="radio" name="login" value="krb" '.
 2115:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2116:                     $krbcheck.' />';
 2117:     }
 2118:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2119:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2120:          $in{'curr_authtype'} eq 'krb5') ||
 2121:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2122:          $in{'curr_authtype'} eq 'krb4')) {
 2123:         $result .= &mt
 2124:         ('[_1] Kerberos authenticated with domain [_2] '.
 2125:          '[_3] Version 4 [_4] Version 5 [_5]',
 2126:          '<label>'.$authtype,
 2127:          '</label><input type="text" size="10" name="krbarg" '.
 2128:              'value="'.$krbarg.'" '.
 2129:              'onchange="'.$jscall.'" />',
 2130:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2131:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2132: 	 '</label>');
 2133:     } elsif ($can_assign{'krb4'}) {
 2134:         $result .= &mt
 2135:         ('[_1] Kerberos authenticated with domain [_2] '.
 2136:          '[_3] Version 4 [_4]',
 2137:          '<label>'.$authtype,
 2138:          '</label><input type="text" size="10" name="krbarg" '.
 2139:              'value="'.$krbarg.'" '.
 2140:              'onchange="'.$jscall.'" />',
 2141:          '<label><input type="hidden" name="krbver" value="4" />',
 2142:          '</label>');
 2143:     } elsif ($can_assign{'krb5'}) {
 2144:         $result .= &mt
 2145:         ('[_1] Kerberos authenticated with domain [_2] '.
 2146:          '[_3] Version 5 [_4]',
 2147:          '<label>'.$authtype,
 2148:          '</label><input type="text" size="10" name="krbarg" '.
 2149:              'value="'.$krbarg.'" '.
 2150:              'onchange="'.$jscall.'" />',
 2151:          '<label><input type="hidden" name="krbver" value="5" />',
 2152:          '</label>');
 2153:     }
 2154:     return $result;
 2155: }
 2156: 
 2157: sub authform_internal{  
 2158:     my %in = (
 2159:                 formname => 'document.cu',
 2160:                 kerb_def_dom => 'MSU.EDU',
 2161:                 @_,
 2162:                 );
 2163:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2164:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2165:     if (defined($in{'curr_authtype'})) {
 2166:         if ($in{'curr_authtype'} eq 'int') {
 2167:             if ($can_assign{'int'}) {
 2168:                 $intcheck = 'checked="on" ';
 2169:                 if (defined($in{'mode'})) {
 2170:                     if ($in{'mode'} eq 'modifyuser') {
 2171:                         $intcheck = '';
 2172:                     }
 2173:                 }
 2174:                 if (defined($in{'curr_autharg'})) {
 2175:                     $intarg = $in{'curr_autharg'};
 2176:                 }
 2177:             } else {
 2178:                 $result = &mt('Currently internally authenticated.');
 2179:                 return $result;
 2180:             }
 2181:         }
 2182:     } else {
 2183:         if ($authnum == 1) {
 2184:             $authtype = '<input type="hidden" name="login" value="int">';
 2185:         }
 2186:     }
 2187:     if (!$can_assign{'int'}) {
 2188:         return;
 2189:     } elsif ($authtype eq '') {
 2190:         if (defined($in{'mode'})) {
 2191:             if ($in{'mode'} eq 'modifycourse') {
 2192:                 if ($authnum == 1) {
 2193:                     $authtype = '<input type="hidden" name="login" value="int">';
 2194:                 }
 2195:             }
 2196:         }
 2197:     }
 2198:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2199:     if ($authtype eq '') {
 2200:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2201:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2202:     }
 2203:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2204:                $intarg.'" onchange="'.$jscall.'" />';
 2205:     $result = &mt
 2206:         ('[_1] Internally authenticated (with initial password [_2])',
 2207:          '<label>'.$authtype,'</label>'.$autharg);
 2208:     $result.="<label><input type=\"checkbox\" name=\"visible\" onClick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 2209:     return $result;
 2210: }
 2211: 
 2212: sub authform_local{  
 2213:     my %in = (
 2214:               formname => 'document.cu',
 2215:               kerb_def_dom => 'MSU.EDU',
 2216:               @_,
 2217:               );
 2218:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2219:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2220:     if (defined($in{'curr_authtype'})) {
 2221:         if ($in{'curr_authtype'} eq 'loc') {
 2222:             if ($can_assign{'loc'}) {
 2223:                 $loccheck = 'checked="on" ';
 2224:                 if (defined($in{'mode'})) {
 2225:                     if ($in{'mode'} eq 'modifyuser') {
 2226:                         $loccheck = '';
 2227:                     }
 2228:                 }
 2229:                 if (defined($in{'curr_autharg'})) {
 2230:                     $locarg = $in{'curr_autharg'};
 2231:                 }
 2232:             } else {
 2233:                 $result = &mt('Currently using local (institutional) authentication.');
 2234:                 return $result;
 2235:             }
 2236:         }
 2237:     } else {
 2238:         if ($authnum == 1) {
 2239:             $authtype = '<input type="hidden" name="login" value="loc">';
 2240:         }
 2241:     }
 2242:     if (!$can_assign{'loc'}) {
 2243:         return;
 2244:     } elsif ($authtype eq '') {
 2245:         if (defined($in{'mode'})) {
 2246:             if ($in{'mode'} eq 'modifycourse') {
 2247:                 if ($authnum == 1) {
 2248:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2249:                 }
 2250:             }
 2251:         }
 2252:     }
 2253:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2254:     if ($authtype eq '') {
 2255:         $authtype = '<input type="radio" name="login" value="loc" '.
 2256:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2257:                     $jscall.'" />';
 2258:     }
 2259:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2260:                $locarg.'" onchange="'.$jscall.'" />';
 2261:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2262:                   '<label>'.$authtype,'</label>'.$autharg);
 2263:     return $result;
 2264: }
 2265: 
 2266: sub authform_filesystem{  
 2267:     my %in = (
 2268:               formname => 'document.cu',
 2269:               kerb_def_dom => 'MSU.EDU',
 2270:               @_,
 2271:               );
 2272:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2273:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2274:     if (defined($in{'curr_authtype'})) {
 2275:         if ($in{'curr_authtype'} eq 'fsys') {
 2276:             if ($can_assign{'fsys'}) {
 2277:                 $fsyscheck = 'checked="on" ';
 2278:                 if (defined($in{'mode'})) {
 2279:                     if ($in{'mode'} eq 'modifyuser') {
 2280:                         $fsyscheck = '';
 2281:                     }
 2282:                 }
 2283:             } else {
 2284:                 $result = &mt('Currently Filesystem Authenticated.');
 2285:                 return $result;
 2286:             }           
 2287:         }
 2288:     } else {
 2289:         if ($authnum == 1) {
 2290:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2291:         }
 2292:     }
 2293:     if (!$can_assign{'fsys'}) {
 2294:         return;
 2295:     } elsif ($authtype eq '') {
 2296:         if (defined($in{'mode'})) {
 2297:             if ($in{'mode'} eq 'modifycourse') {
 2298:                 if ($authnum == 1) {
 2299:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2300:                 }
 2301:             }
 2302:         }
 2303:     }
 2304:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2305:     if ($authtype eq '') {
 2306:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2307:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2308:                     $jscall.'" />';
 2309:     }
 2310:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2311:                ' onchange="'.$jscall.'" />';
 2312:     $result = &mt
 2313:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2314:          '<label><input type="radio" name="login" value="fsys" '.
 2315:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2316:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2317:                   'onchange="'.$jscall.'" />');
 2318:     return $result;
 2319: }
 2320: 
 2321: sub get_assignable_auth {
 2322:     my ($dom) = @_;
 2323:     if ($dom eq '') {
 2324:         $dom = $env{'request.role.domain'};
 2325:     }
 2326:     my %can_assign = (
 2327:                           krb4 => 1,
 2328:                           krb5 => 1,
 2329:                           int  => 1,
 2330:                           loc  => 1,
 2331:                      );
 2332:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2333:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2334:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2335:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2336:             my $context;
 2337:             if ($env{'request.role'} =~ /^au/) {
 2338:                 $context = 'author';
 2339:             } elsif ($env{'request.role'} =~ /^dc/) {
 2340:                 $context = 'domain';
 2341:             } elsif ($env{'request.course.id'}) {
 2342:                 $context = 'course';
 2343:             }
 2344:             if ($context) {
 2345:                 if (ref($authhash->{$context}) eq 'HASH') {
 2346:                    %can_assign = %{$authhash->{$context}}; 
 2347:                 }
 2348:             }
 2349:         }
 2350:     }
 2351:     my $authnum = 0;
 2352:     foreach my $key (keys(%can_assign)) {
 2353:         if ($can_assign{$key}) {
 2354:             $authnum ++;
 2355:         }
 2356:     }
 2357:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2358:         $authnum --;
 2359:     }
 2360:     return ($authnum,%can_assign);
 2361: }
 2362: 
 2363: ###############################################################
 2364: ##    Get Kerberos Defaults for Domain                 ##
 2365: ###############################################################
 2366: ##
 2367: ## Returns default kerberos version and an associated argument
 2368: ## as listed in file domain.tab. If not listed, provides
 2369: ## appropriate default domain and kerberos version.
 2370: ##
 2371: #-------------------------------------------
 2372: 
 2373: =pod
 2374: 
 2375: =item * &get_kerberos_defaults()
 2376: 
 2377: get_kerberos_defaults($target_domain) returns the default kerberos
 2378: version and domain. If not found, it defaults to version 4 and the 
 2379: domain of the server.
 2380: 
 2381: =over 4
 2382: 
 2383: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2384: 
 2385: =back
 2386: 
 2387: =back
 2388: 
 2389: =cut
 2390: 
 2391: #-------------------------------------------
 2392: sub get_kerberos_defaults {
 2393:     my $domain=shift;
 2394:     my ($krbdef,$krbdefdom);
 2395:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2396:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2397:         $krbdef = $domdefaults{'auth_def'};
 2398:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2399:     } else {
 2400:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2401:         my $krbdefdom=$1;
 2402:         $krbdefdom=~tr/a-z/A-Z/;
 2403:         $krbdef = "krb4";
 2404:     }
 2405:     return ($krbdef,$krbdefdom);
 2406: }
 2407: 
 2408: 
 2409: ###############################################################
 2410: ##                Thesaurus Functions                        ##
 2411: ###############################################################
 2412: 
 2413: =pod
 2414: 
 2415: =head1 Thesaurus Functions
 2416: 
 2417: =over 4
 2418: 
 2419: =item * &initialize_keywords()
 2420: 
 2421: Initializes the package variable %Keywords if it is empty.  Uses the
 2422: package variable $thesaurus_db_file.
 2423: 
 2424: =cut
 2425: 
 2426: ###################################################
 2427: 
 2428: sub initialize_keywords {
 2429:     return 1 if (scalar keys(%Keywords));
 2430:     # If we are here, %Keywords is empty, so fill it up
 2431:     #   Make sure the file we need exists...
 2432:     if (! -e $thesaurus_db_file) {
 2433:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2434:                                  " failed because it does not exist");
 2435:         return 0;
 2436:     }
 2437:     #   Set up the hash as a database
 2438:     my %thesaurus_db;
 2439:     if (! tie(%thesaurus_db,'GDBM_File',
 2440:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2441:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2442:                                  $thesaurus_db_file);
 2443:         return 0;
 2444:     } 
 2445:     #  Get the average number of appearances of a word.
 2446:     my $avecount = $thesaurus_db{'average.count'};
 2447:     #  Put keywords (those that appear > average) into %Keywords
 2448:     while (my ($word,$data)=each (%thesaurus_db)) {
 2449:         my ($count,undef) = split /:/,$data;
 2450:         $Keywords{$word}++ if ($count > $avecount);
 2451:     }
 2452:     untie %thesaurus_db;
 2453:     # Remove special values from %Keywords.
 2454:     foreach my $value ('total.count','average.count') {
 2455:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2456:   }
 2457:     return 1;
 2458: }
 2459: 
 2460: ###################################################
 2461: 
 2462: =pod
 2463: 
 2464: =item * &keyword($word)
 2465: 
 2466: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2467: than the average number of times in the thesaurus database.  Calls 
 2468: &initialize_keywords
 2469: 
 2470: =cut
 2471: 
 2472: ###################################################
 2473: 
 2474: sub keyword {
 2475:     return if (!&initialize_keywords());
 2476:     my $word=lc(shift());
 2477:     $word=~s/\W//g;
 2478:     return exists($Keywords{$word});
 2479: }
 2480: 
 2481: ###############################################################
 2482: 
 2483: =pod 
 2484: 
 2485: =item * &get_related_words()
 2486: 
 2487: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2488: an array of words.  If the keyword is not in the thesaurus, an empty array
 2489: will be returned.  The order of the words returned is determined by the
 2490: database which holds them.
 2491: 
 2492: Uses global $thesaurus_db_file.
 2493: 
 2494: =cut
 2495: 
 2496: ###############################################################
 2497: sub get_related_words {
 2498:     my $keyword = shift;
 2499:     my %thesaurus_db;
 2500:     if (! -e $thesaurus_db_file) {
 2501:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2502:                                  "failed because the file does not exist");
 2503:         return ();
 2504:     }
 2505:     if (! tie(%thesaurus_db,'GDBM_File',
 2506:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2507:         return ();
 2508:     } 
 2509:     my @Words=();
 2510:     my $count=0;
 2511:     if (exists($thesaurus_db{$keyword})) {
 2512: 	# The first element is the number of times
 2513: 	# the word appears.  We do not need it now.
 2514: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2515: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2516: 	my $threshold=$mostfrequentcount/10;
 2517:         foreach my $possibleword (@RelatedWords) {
 2518:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2519:             if ($wordcount>$threshold) {
 2520: 		push(@Words,$word);
 2521:                 $count++;
 2522:                 if ($count>10) { last; }
 2523: 	    }
 2524:         }
 2525:     }
 2526:     untie %thesaurus_db;
 2527:     return @Words;
 2528: }
 2529: 
 2530: =pod
 2531: 
 2532: =back
 2533: 
 2534: =cut
 2535: 
 2536: # -------------------------------------------------------------- Plaintext name
 2537: =pod
 2538: 
 2539: =head1 User Name Functions
 2540: 
 2541: =over 4
 2542: 
 2543: =item * &plainname($uname,$udom,$first)
 2544: 
 2545: Takes a users logon name and returns it as a string in
 2546: "first middle last generation" form 
 2547: if $first is set to 'lastname' then it returns it as
 2548: 'lastname generation, firstname middlename' if their is a lastname
 2549: 
 2550: =cut
 2551: 
 2552: 
 2553: ###############################################################
 2554: sub plainname {
 2555:     my ($uname,$udom,$first)=@_;
 2556:     return if (!defined($uname) || !defined($udom));
 2557:     my %names=&getnames($uname,$udom);
 2558:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2559: 					  $names{'middlename'},
 2560: 					  $names{'lastname'},
 2561: 					  $names{'generation'},$first);
 2562:     $name=~s/^\s+//;
 2563:     $name=~s/\s+$//;
 2564:     $name=~s/\s+/ /g;
 2565:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2566:     return $name;
 2567: }
 2568: 
 2569: # -------------------------------------------------------------------- Nickname
 2570: =pod
 2571: 
 2572: =item * &nickname($uname,$udom)
 2573: 
 2574: Gets a users name and returns it as a string as
 2575: 
 2576: "&quot;nickname&quot;"
 2577: 
 2578: if the user has a nickname or
 2579: 
 2580: "first middle last generation"
 2581: 
 2582: if the user does not
 2583: 
 2584: =cut
 2585: 
 2586: sub nickname {
 2587:     my ($uname,$udom)=@_;
 2588:     return if (!defined($uname) || !defined($udom));
 2589:     my %names=&getnames($uname,$udom);
 2590:     my $name=$names{'nickname'};
 2591:     if ($name) {
 2592:        $name='&quot;'.$name.'&quot;'; 
 2593:     } else {
 2594:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2595: 	     $names{'lastname'}.' '.$names{'generation'};
 2596:        $name=~s/\s+$//;
 2597:        $name=~s/\s+/ /g;
 2598:     }
 2599:     return $name;
 2600: }
 2601: 
 2602: sub getnames {
 2603:     my ($uname,$udom)=@_;
 2604:     return if (!defined($uname) || !defined($udom));
 2605:     if ($udom eq 'public' && $uname eq 'public') {
 2606: 	return ('lastname' => &mt('Public'));
 2607:     }
 2608:     my $id=$uname.':'.$udom;
 2609:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2610:     if ($cached) {
 2611: 	return %{$names};
 2612:     } else {
 2613: 	my %loadnames=&Apache::lonnet::get('environment',
 2614:                     ['firstname','middlename','lastname','generation','nickname'],
 2615: 					 $udom,$uname);
 2616: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2617: 	return %loadnames;
 2618:     }
 2619: }
 2620: 
 2621: # -------------------------------------------------------------------- getemails
 2622: 
 2623: =pod
 2624: 
 2625: =item * &getemails($uname,$udom)
 2626: 
 2627: Gets a user's email information and returns it as a hash with keys:
 2628: notification, critnotification, permanentemail
 2629: 
 2630: For notification and critnotification, values are comma-separated lists 
 2631: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2632:  
 2633: 
 2634: =cut
 2635: 
 2636: 
 2637: sub getemails {
 2638:     my ($uname,$udom)=@_;
 2639:     if ($udom eq 'public' && $uname eq 'public') {
 2640: 	return;
 2641:     }
 2642:     if (!$udom) { $udom=$env{'user.domain'}; }
 2643:     if (!$uname) { $uname=$env{'user.name'}; }
 2644:     my $id=$uname.':'.$udom;
 2645:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2646:     if ($cached) {
 2647: 	return %{$names};
 2648:     } else {
 2649: 	my %loadnames=&Apache::lonnet::get('environment',
 2650:                     			   ['notification','critnotification',
 2651: 					    'permanentemail'],
 2652: 					   $udom,$uname);
 2653: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2654: 	return %loadnames;
 2655:     }
 2656: }
 2657: 
 2658: sub flush_email_cache {
 2659:     my ($uname,$udom)=@_;
 2660:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2661:     if (!$uname) { $uname=$env{'user.name'};   }
 2662:     return if ($udom eq 'public' && $uname eq 'public');
 2663:     my $id=$uname.':'.$udom;
 2664:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2665: }
 2666: 
 2667: # ------------------------------------------------------------------ Screenname
 2668: 
 2669: =pod
 2670: 
 2671: =item * &screenname($uname,$udom)
 2672: 
 2673: Gets a users screenname and returns it as a string
 2674: 
 2675: =cut
 2676: 
 2677: sub screenname {
 2678:     my ($uname,$udom)=@_;
 2679:     if ($uname eq $env{'user.name'} &&
 2680: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2681:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2682:     return $names{'screenname'};
 2683: }
 2684: 
 2685: 
 2686: # ------------------------------------------------------------- Message Wrapper
 2687: 
 2688: sub messagewrapper {
 2689:     my ($link,$username,$domain,$subject,$text)=@_;
 2690:     return 
 2691:         '<a href="/adm/email?compose=individual&amp;'.
 2692:         'recname='.$username.'&amp;recdom='.$domain.
 2693: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2694:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2695: }
 2696: # --------------------------------------------------------------- Notes Wrapper
 2697: 
 2698: sub noteswrapper {
 2699:     my ($link,$un,$do)=@_;
 2700:     return 
 2701: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2702: }
 2703: # ------------------------------------------------------------- Aboutme Wrapper
 2704: 
 2705: sub aboutmewrapper {
 2706:     my ($link,$username,$domain,$target)=@_;
 2707:     if (!defined($username)  && !defined($domain)) {
 2708:         return;
 2709:     }
 2710:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2711: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2712: }
 2713: 
 2714: # ------------------------------------------------------------ Syllabus Wrapper
 2715: 
 2716: 
 2717: sub syllabuswrapper {
 2718:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2719:     if ($fontcolor) { 
 2720:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2721:     }
 2722:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2723: }
 2724: 
 2725: sub track_student_link {
 2726:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2727:     my $link ="/adm/trackstudent?";
 2728:     my $title = 'View recent activity';
 2729:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2730:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2731:         $link .= "selected_student=$sname:$sdom";
 2732:         $title .= ' of this student';
 2733:     } 
 2734:     if (defined($target) && $target !~ /^\s*$/) {
 2735:         $target = qq{target="$target"};
 2736:     } else {
 2737:         $target = '';
 2738:     }
 2739:     if ($start) { $link.='&amp;start='.$start; }
 2740:     $title = &mt($title);
 2741:     $linktext = &mt($linktext);
 2742:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2743: 	&help_open_topic('View_recent_activity');
 2744: }
 2745: 
 2746: # ===================================================== Display a student photo
 2747: 
 2748: 
 2749: sub student_image_tag {
 2750:     my ($domain,$user)=@_;
 2751:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2752:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2753: 	return '<img src="'.$imgsrc.'" align="right" />';
 2754:     } else {
 2755: 	return '';
 2756:     }
 2757: }
 2758: 
 2759: =pod
 2760: 
 2761: =back
 2762: 
 2763: =head1 Access .tab File Data
 2764: 
 2765: =over 4
 2766: 
 2767: =item * &languageids() 
 2768: 
 2769: returns list of all language ids
 2770: 
 2771: =cut
 2772: 
 2773: sub languageids {
 2774:     return sort(keys(%language));
 2775: }
 2776: 
 2777: =pod
 2778: 
 2779: =item * &languagedescription() 
 2780: 
 2781: returns description of a specified language id
 2782: 
 2783: =cut
 2784: 
 2785: sub languagedescription {
 2786:     my $code=shift;
 2787:     return  ($supported_language{$code}?'* ':'').
 2788:             $language{$code}.
 2789: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2790: }
 2791: 
 2792: sub plainlanguagedescription {
 2793:     my $code=shift;
 2794:     return $language{$code};
 2795: }
 2796: 
 2797: sub supportedlanguagecode {
 2798:     my $code=shift;
 2799:     return $supported_language{$code};
 2800: }
 2801: 
 2802: =pod
 2803: 
 2804: =item * &copyrightids() 
 2805: 
 2806: returns list of all copyrights
 2807: 
 2808: =cut
 2809: 
 2810: sub copyrightids {
 2811:     return sort(keys(%cprtag));
 2812: }
 2813: 
 2814: =pod
 2815: 
 2816: =item * &copyrightdescription() 
 2817: 
 2818: returns description of a specified copyright id
 2819: 
 2820: =cut
 2821: 
 2822: sub copyrightdescription {
 2823:     return &mt($cprtag{shift(@_)});
 2824: }
 2825: 
 2826: =pod
 2827: 
 2828: =item * &source_copyrightids() 
 2829: 
 2830: returns list of all source copyrights
 2831: 
 2832: =cut
 2833: 
 2834: sub source_copyrightids {
 2835:     return sort(keys(%scprtag));
 2836: }
 2837: 
 2838: =pod
 2839: 
 2840: =item * &source_copyrightdescription() 
 2841: 
 2842: returns description of a specified source copyright id
 2843: 
 2844: =cut
 2845: 
 2846: sub source_copyrightdescription {
 2847:     return &mt($scprtag{shift(@_)});
 2848: }
 2849: 
 2850: =pod
 2851: 
 2852: =item * &filecategories() 
 2853: 
 2854: returns list of all file categories
 2855: 
 2856: =cut
 2857: 
 2858: sub filecategories {
 2859:     return sort(keys(%category_extensions));
 2860: }
 2861: 
 2862: =pod
 2863: 
 2864: =item * &filecategorytypes() 
 2865: 
 2866: returns list of file types belonging to a given file
 2867: category
 2868: 
 2869: =cut
 2870: 
 2871: sub filecategorytypes {
 2872:     my ($cat) = @_;
 2873:     return @{$category_extensions{lc($cat)}};
 2874: }
 2875: 
 2876: =pod
 2877: 
 2878: =item * &fileembstyle() 
 2879: 
 2880: returns embedding style for a specified file type
 2881: 
 2882: =cut
 2883: 
 2884: sub fileembstyle {
 2885:     return $fe{lc(shift(@_))};
 2886: }
 2887: 
 2888: sub filemimetype {
 2889:     return $fm{lc(shift(@_))};
 2890: }
 2891: 
 2892: 
 2893: sub filecategoryselect {
 2894:     my ($name,$value)=@_;
 2895:     return &select_form($value,$name,
 2896: 			'' => &mt('Any category'),
 2897: 			map { $_,$_ } sort(keys(%category_extensions)));
 2898: }
 2899: 
 2900: =pod
 2901: 
 2902: =item * &filedescription() 
 2903: 
 2904: returns description for a specified file type
 2905: 
 2906: =cut
 2907: 
 2908: sub filedescription {
 2909:     my $file_description = $fd{lc(shift())};
 2910:     $file_description =~ s:([\[\]]):~$1:g;
 2911:     return &mt($file_description);
 2912: }
 2913: 
 2914: =pod
 2915: 
 2916: =item * &filedescriptionex() 
 2917: 
 2918: returns description for a specified file type with
 2919: extra formatting
 2920: 
 2921: =cut
 2922: 
 2923: sub filedescriptionex {
 2924:     my $ex=shift;
 2925:     my $file_description = $fd{lc($ex)};
 2926:     $file_description =~ s:([\[\]]):~$1:g;
 2927:     return '.'.$ex.' '.&mt($file_description);
 2928: }
 2929: 
 2930: # End of .tab access
 2931: =pod
 2932: 
 2933: =back
 2934: 
 2935: =cut
 2936: 
 2937: # ------------------------------------------------------------------ File Types
 2938: sub fileextensions {
 2939:     return sort(keys(%fe));
 2940: }
 2941: 
 2942: # ----------------------------------------------------------- Display Languages
 2943: # returns a hash with all desired display languages
 2944: #
 2945: 
 2946: sub display_languages {
 2947:     my %languages=();
 2948:     foreach my $lang (&preferred_languages()) {
 2949: 	$languages{$lang}=1;
 2950:     }
 2951:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2952:     if ($env{'form.displaylanguage'}) {
 2953: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2954: 	    $languages{$lang}=1;
 2955:         }
 2956:     }
 2957:     return %languages;
 2958: }
 2959: 
 2960: sub preferred_languages {
 2961:     my @languages=();
 2962:     if (($env{'request.role.adv'}) && ($env{'form.languages'})) {
 2963:         @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$env{'form.languages'}));
 2964:     }
 2965:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2966: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2967: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2968:     }
 2969: 
 2970:     if ($env{'environment.languages'}) {
 2971: 	@languages=(@languages,
 2972: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
 2973:     }
 2974:     my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
 2975:     if ($browser) {
 2976: 	my @browser = 
 2977: 	    map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
 2978: 	push(@languages,@browser);
 2979:     }
 2980: 
 2981:     foreach my $domtype ($env{'user.domain'},$env{'request.role.domain'},
 2982:                          $Apache::lonnet::perlvar{'lonDefDomain'}) {
 2983:         if ($domtype ne '') {
 2984:             my %domdefs = &Apache::lonnet::get_domain_defaults($domtype);
 2985:             if ($domdefs{'lang_def'} ne '') {
 2986:                 push(@languages,$domdefs{'lang_def'});
 2987:             }
 2988:         }
 2989:     }
 2990: # turn "en-ca" into "en-ca,en"
 2991:     my @genlanguages;
 2992:     foreach my $lang (@languages) {
 2993: 	unless ($lang=~/\w/) { next; }
 2994: 	push(@genlanguages,$lang);
 2995: 	if ($lang=~/(\-|\_)/) {
 2996: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
 2997: 	}
 2998:     }
 2999:     #uniqueify the languages list
 3000:     my %count;
 3001:     @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
 3002:     return @genlanguages;
 3003: }
 3004: 
 3005: sub languages {
 3006:     my ($possible_langs) = @_;
 3007:     my @preferred_langs = &preferred_languages();
 3008:     if (!ref($possible_langs)) {
 3009: 	if( wantarray ) {
 3010: 	    return @preferred_langs;
 3011: 	} else {
 3012: 	    return $preferred_langs[0];
 3013: 	}
 3014:     }
 3015:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3016:     my @preferred_possibilities;
 3017:     foreach my $preferred_lang (@preferred_langs) {
 3018: 	if (exists($possibilities{$preferred_lang})) {
 3019: 	    push(@preferred_possibilities, $preferred_lang);
 3020: 	}
 3021:     }
 3022:     if( wantarray ) {
 3023: 	return @preferred_possibilities;
 3024:     }
 3025:     return $preferred_possibilities[0];
 3026: }
 3027: 
 3028: ###############################################################
 3029: ##               Student Answer Attempts                     ##
 3030: ###############################################################
 3031: 
 3032: =pod
 3033: 
 3034: =head1 Alternate Problem Views
 3035: 
 3036: =over 4
 3037: 
 3038: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3039:     $getattempt, $regexp, $gradesub)
 3040: 
 3041: Return string with previous attempt on problem. Arguments:
 3042: 
 3043: =over 4
 3044: 
 3045: =item * $symb: Problem, including path
 3046: 
 3047: =item * $username: username of the desired student
 3048: 
 3049: =item * $domain: domain of the desired student
 3050: 
 3051: =item * $course: Course ID
 3052: 
 3053: =item * $getattempt: Leave blank for all attempts, otherwise put
 3054:     something
 3055: 
 3056: =item * $regexp: if string matches this regexp, the string will be
 3057:     sent to $gradesub
 3058: 
 3059: =item * $gradesub: routine that processes the string if it matches $regexp
 3060: 
 3061: =back
 3062: 
 3063: The output string is a table containing all desired attempts, if any.
 3064: 
 3065: =cut
 3066: 
 3067: sub get_previous_attempt {
 3068:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3069:   my $prevattempts='';
 3070:   no strict 'refs';
 3071:   if ($symb) {
 3072:     my (%returnhash)=
 3073:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3074:     if ($returnhash{'version'}) {
 3075:       my %lasthash=();
 3076:       my $version;
 3077:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3078:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3079: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3080:         }
 3081:       }
 3082:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3083:       $prevattempts.='<th>'.&mt('History').'</th>';
 3084:       foreach my $key (sort(keys(%lasthash))) {
 3085: 	my ($ign,@parts) = split(/\./,$key);
 3086: 	if ($#parts > 0) {
 3087: 	  my $data=$parts[-1];
 3088: 	  pop(@parts);
 3089: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3090: 	} else {
 3091: 	  if ($#parts == 0) {
 3092: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3093: 	  } else {
 3094: 	    $prevattempts.='<th>'.$ign.'</th>';
 3095: 	  }
 3096: 	}
 3097:       }
 3098:       $prevattempts.=&end_data_table_header_row();
 3099:       if ($getattempt eq '') {
 3100: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3101: 	  $prevattempts.=&start_data_table_row().
 3102: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3103: 	    foreach my $key (sort(keys(%lasthash))) {
 3104: 		my $value = &format_previous_attempt_value($key,
 3105: 							   $returnhash{$version.':'.$key});
 3106: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3107: 	    }
 3108: 	  $prevattempts.=&end_data_table_row();
 3109: 	 }
 3110:       }
 3111:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3112:       foreach my $key (sort(keys(%lasthash))) {
 3113: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3114: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3115: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3116:       }
 3117:       $prevattempts.= &end_data_table_row().&end_data_table();
 3118:     } else {
 3119:       $prevattempts=
 3120: 	  &start_data_table().&start_data_table_row().
 3121: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3122: 	  &end_data_table_row().&end_data_table();
 3123:     }
 3124:   } else {
 3125:     $prevattempts=
 3126: 	  &start_data_table().&start_data_table_row().
 3127: 	  '<td>'.&mt('No data.').'</td>'.
 3128: 	  &end_data_table_row().&end_data_table();
 3129:   }
 3130: }
 3131: 
 3132: sub format_previous_attempt_value {
 3133:     my ($key,$value) = @_;
 3134:     if ($key =~ /timestamp/) {
 3135: 	$value = &Apache::lonlocal::locallocaltime($value);
 3136:     } elsif (ref($value) eq 'ARRAY') {
 3137: 	$value = '('.join(', ', @{ $value }).')';
 3138:     } else {
 3139: 	$value = &unescape($value);
 3140:     }
 3141:     return $value;
 3142: }
 3143: 
 3144: 
 3145: sub relative_to_absolute {
 3146:     my ($url,$output)=@_;
 3147:     my $parser=HTML::TokeParser->new(\$output);
 3148:     my $token;
 3149:     my $thisdir=$url;
 3150:     my @rlinks=();
 3151:     while ($token=$parser->get_token) {
 3152: 	if ($token->[0] eq 'S') {
 3153: 	    if ($token->[1] eq 'a') {
 3154: 		if ($token->[2]->{'href'}) {
 3155: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3156: 		}
 3157: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3158: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3159: 	    } elsif ($token->[1] eq 'base') {
 3160: 		$thisdir=$token->[2]->{'href'};
 3161: 	    }
 3162: 	}
 3163:     }
 3164:     $thisdir=~s-/[^/]*$--;
 3165:     foreach my $link (@rlinks) {
 3166: 	unless (($link=~/^http:\/\//i) ||
 3167: 		($link=~/^\//) ||
 3168: 		($link=~/^javascript:/i) ||
 3169: 		($link=~/^mailto:/i) ||
 3170: 		($link=~/^\#/)) {
 3171: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3172: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3173: 	}
 3174:     }
 3175: # -------------------------------------------------- Deal with Applet codebases
 3176:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3177:     return $output;
 3178: }
 3179: 
 3180: =pod
 3181: 
 3182: =item * &get_student_view()
 3183: 
 3184: show a snapshot of what student was looking at
 3185: 
 3186: =cut
 3187: 
 3188: sub get_student_view {
 3189:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3190:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3191:   my (%form);
 3192:   my @elements=('symb','courseid','domain','username');
 3193:   foreach my $element (@elements) {
 3194:       $form{'grade_'.$element}=eval '$'.$element #'
 3195:   }
 3196:   if (defined($moreenv)) {
 3197:       %form=(%form,%{$moreenv});
 3198:   }
 3199:   if (defined($target)) { $form{'grade_target'} = $target; }
 3200:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3201:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3202:   $userview=~s/\<body[^\>]*\>//gi;
 3203:   $userview=~s/\<\/body\>//gi;
 3204:   $userview=~s/\<html\>//gi;
 3205:   $userview=~s/\<\/html\>//gi;
 3206:   $userview=~s/\<head\>//gi;
 3207:   $userview=~s/\<\/head\>//gi;
 3208:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3209:   $userview=&relative_to_absolute($feedurl,$userview);
 3210:   if (wantarray) {
 3211:      return ($userview,$response);
 3212:   } else {
 3213:      return $userview;
 3214:   }
 3215: }
 3216: 
 3217: sub get_student_view_with_retries {
 3218:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3219: 
 3220:     my $ok = 0;                 # True if we got a good response.
 3221:     my $content;
 3222:     my $response;
 3223: 
 3224:     # Try to get the student_view done. within the retries count:
 3225:     
 3226:     do {
 3227:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3228:          $ok      = $response->is_success;
 3229:          if (!$ok) {
 3230:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3231:          }
 3232:          $retries--;
 3233:     } while (!$ok && ($retries > 0));
 3234:     
 3235:     if (!$ok) {
 3236:        $content = '';          # On error return an empty content.
 3237:     }
 3238:     if (wantarray) {
 3239:        return ($content, $response);
 3240:     } else {
 3241:        return $content;
 3242:     }
 3243: }
 3244: 
 3245: =pod
 3246: 
 3247: =item * &get_student_answers() 
 3248: 
 3249: show a snapshot of how student was answering problem
 3250: 
 3251: =cut
 3252: 
 3253: sub get_student_answers {
 3254:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3255:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3256:   my (%moreenv);
 3257:   my @elements=('symb','courseid','domain','username');
 3258:   foreach my $element (@elements) {
 3259:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3260:   }
 3261:   $moreenv{'grade_target'}='answer';
 3262:   %moreenv=(%form,%moreenv);
 3263:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3264:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3265:   return $userview;
 3266: }
 3267: 
 3268: =pod
 3269: 
 3270: =item * &submlink()
 3271: 
 3272: Inputs: $text $uname $udom $symb $target
 3273: 
 3274: Returns: A link to grades.pm such as to see the SUBM view of a student
 3275: 
 3276: =cut
 3277: 
 3278: ###############################################
 3279: sub submlink {
 3280:     my ($text,$uname,$udom,$symb,$target)=@_;
 3281:     if (!($uname && $udom)) {
 3282: 	(my $cursymb, my $courseid,$udom,$uname)=
 3283: 	    &Apache::lonnet::whichuser($symb);
 3284: 	if (!$symb) { $symb=$cursymb; }
 3285:     }
 3286:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3287:     $symb=&escape($symb);
 3288:     if ($target) { $target="target=\"$target\""; }
 3289:     return '<a href="/adm/grades?&command=submission&'.
 3290: 	'symb='.$symb.'&student='.$uname.
 3291: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3292: }
 3293: ##############################################
 3294: 
 3295: =pod
 3296: 
 3297: =item * &pgrdlink()
 3298: 
 3299: Inputs: $text $uname $udom $symb $target
 3300: 
 3301: Returns: A link to grades.pm such as to see the PGRD view of a student
 3302: 
 3303: =cut
 3304: 
 3305: ###############################################
 3306: sub pgrdlink {
 3307:     my $link=&submlink(@_);
 3308:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3309:     return $link;
 3310: }
 3311: ##############################################
 3312: 
 3313: =pod
 3314: 
 3315: =item * &pprmlink()
 3316: 
 3317: Inputs: $text $uname $udom $symb $target
 3318: 
 3319: Returns: A link to parmset.pm such as to see the PPRM view of a
 3320: student and a specific resource
 3321: 
 3322: =cut
 3323: 
 3324: ###############################################
 3325: sub pprmlink {
 3326:     my ($text,$uname,$udom,$symb,$target)=@_;
 3327:     if (!($uname && $udom)) {
 3328: 	(my $cursymb, my $courseid,$udom,$uname)=
 3329: 	    &Apache::lonnet::whichuser($symb);
 3330: 	if (!$symb) { $symb=$cursymb; }
 3331:     }
 3332:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3333:     $symb=&escape($symb);
 3334:     if ($target) { $target="target=\"$target\""; }
 3335:     return '<a href="/adm/parmset?command=set&amp;'.
 3336: 	'symb='.$symb.'&amp;uname='.$uname.
 3337: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3338: }
 3339: ##############################################
 3340: 
 3341: =pod
 3342: 
 3343: =back
 3344: 
 3345: =cut
 3346: 
 3347: ###############################################
 3348: 
 3349: 
 3350: sub timehash {
 3351:     my @ltime=localtime(shift);
 3352:     return ( 'seconds' => $ltime[0],
 3353:              'minutes' => $ltime[1],
 3354:              'hours'   => $ltime[2],
 3355:              'day'     => $ltime[3],
 3356:              'month'   => $ltime[4]+1,
 3357:              'year'    => $ltime[5]+1900,
 3358:              'weekday' => $ltime[6],
 3359:              'dayyear' => $ltime[7]+1,
 3360:              'dlsav'   => $ltime[8] );
 3361: }
 3362: 
 3363: sub utc_string {
 3364:     my ($date)=@_;
 3365:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3366: }
 3367: 
 3368: sub maketime {
 3369:     my %th=@_;
 3370:     return POSIX::mktime(
 3371:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3372:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3373: }
 3374: 
 3375: #########################################
 3376: 
 3377: sub findallcourses {
 3378:     my ($roles,$uname,$udom) = @_;
 3379:     my %roles;
 3380:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3381:     my %courses;
 3382:     my $now=time;
 3383:     if (!defined($uname)) {
 3384:         $uname = $env{'user.name'};
 3385:     }
 3386:     if (!defined($udom)) {
 3387:         $udom = $env{'user.domain'};
 3388:     }
 3389:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3390:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3391:         if (!%roles) {
 3392:             %roles = (
 3393:                        cc => 1,
 3394:                        in => 1,
 3395:                        ep => 1,
 3396:                        ta => 1,
 3397:                        cr => 1,
 3398:                        st => 1,
 3399:              );
 3400:         }
 3401:         foreach my $entry (keys(%roleshash)) {
 3402:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3403:             if ($trole =~ /^cr/) { 
 3404:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3405:             } else {
 3406:                 next if (!exists($roles{$trole}));
 3407:             }
 3408:             if ($tend) {
 3409:                 next if ($tend < $now);
 3410:             }
 3411:             if ($tstart) {
 3412:                 next if ($tstart > $now);
 3413:             }
 3414:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3415:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3416:             if ($secpart eq '') {
 3417:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3418:                 $sec = 'none';
 3419:                 $realsec = '';
 3420:             } else {
 3421:                 $cnum = $cnumpart;
 3422:                 ($sec,$role) = split(/_/,$secpart);
 3423:                 $realsec = $sec;
 3424:             }
 3425:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3426:         }
 3427:     } else {
 3428:         foreach my $key (keys(%env)) {
 3429: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3430:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3431: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3432: 	        next if ($role eq 'ca' || $role eq 'aa');
 3433: 	        next if (%roles && !exists($roles{$role}));
 3434: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3435:                 my $active=1;
 3436:                 if ($starttime) {
 3437: 		    if ($now<$starttime) { $active=0; }
 3438:                 }
 3439:                 if ($endtime) {
 3440:                     if ($now>$endtime) { $active=0; }
 3441:                 }
 3442:                 if ($active) {
 3443:                     if ($sec eq '') {
 3444:                         $sec = 'none';
 3445:                     }
 3446:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3447:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3448:                 }
 3449:             }
 3450:         }
 3451:     }
 3452:     return %courses;
 3453: }
 3454: 
 3455: ###############################################
 3456: 
 3457: sub blockcheck {
 3458:     my ($setters,$activity,$uname,$udom) = @_;
 3459: 
 3460:     if (!defined($udom)) {
 3461:         $udom = $env{'user.domain'};
 3462:     }
 3463:     if (!defined($uname)) {
 3464:         $uname = $env{'user.name'};
 3465:     }
 3466: 
 3467:     # If uname and udom are for a course, check for blocks in the course.
 3468: 
 3469:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3470:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3471:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3472:         return ($startblock,$endblock);
 3473:     }
 3474: 
 3475:     my $startblock = 0;
 3476:     my $endblock = 0;
 3477:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3478: 
 3479:     # If uname is for a user, and activity is course-specific, i.e.,
 3480:     # boards, chat or groups, check for blocking in current course only.
 3481: 
 3482:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3483:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3484:         foreach my $key (keys(%live_courses)) {
 3485:             if ($key ne $env{'request.course.id'}) {
 3486:                 delete($live_courses{$key});
 3487:             }
 3488:         }
 3489:     }
 3490: 
 3491:     my $otheruser = 0;
 3492:     my %own_courses;
 3493:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3494:         # Resource belongs to user other than current user.
 3495:         $otheruser = 1;
 3496:         # Gather courses for current user
 3497:         %own_courses = 
 3498:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3499:     }
 3500: 
 3501:     # Gather active course roles - course coordinator, instructor, 
 3502:     # exam proctor, ta, student, or custom role.
 3503: 
 3504:     foreach my $course (keys(%live_courses)) {
 3505:         my ($cdom,$cnum);
 3506:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3507:             $cdom = $env{'course.'.$course.'.domain'};
 3508:             $cnum = $env{'course.'.$course.'.num'};
 3509:         } else {
 3510:             ($cdom,$cnum) = split(/_/,$course); 
 3511:         }
 3512:         my $no_ownblock = 0;
 3513:         my $no_userblock = 0;
 3514:         if ($otheruser && $activity ne 'com') {
 3515:             # Check if current user has 'evb' priv for this
 3516:             if (defined($own_courses{$course})) {
 3517:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3518:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3519:                     if ($sec ne 'none') {
 3520:                         $checkrole .= '/'.$sec;
 3521:                     }
 3522:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3523:                         $no_ownblock = 1;
 3524:                         last;
 3525:                     }
 3526:                 }
 3527:             }
 3528:             # if they have 'evb' priv and are currently not playing student
 3529:             next if (($no_ownblock) &&
 3530:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3531:         }
 3532:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3533:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3534:             if ($sec ne 'none') {
 3535:                 $checkrole .= '/'.$sec;
 3536:             }
 3537:             if ($otheruser) {
 3538:                 # Resource belongs to user other than current user.
 3539:                 # Assemble privs for that user, and check for 'evb' priv.
 3540:                 my ($trole,$tdom,$tnum,$tsec);
 3541:                 my $entry = $live_courses{$course}{$sec};
 3542:                 if ($entry =~ /^cr/) {
 3543:                     ($trole,$tdom,$tnum,$tsec) = 
 3544:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3545:                 } else {
 3546:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3547:                 }
 3548:                 my ($spec,$area,$trest,%allroles,%userroles);
 3549:                 $area = '/'.$tdom.'/'.$tnum;
 3550:                 $trest = $tnum;
 3551:                 if ($tsec ne '') {
 3552:                     $area .= '/'.$tsec;
 3553:                     $trest .= '/'.$tsec;
 3554:                 }
 3555:                 $spec = $trole.'.'.$area;
 3556:                 if ($trole =~ /^cr/) {
 3557:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3558:                                                       $tdom,$spec,$trest,$area);
 3559:                 } else {
 3560:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3561:                                                        $tdom,$spec,$trest,$area);
 3562:                 }
 3563:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3564:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3565:                     if ($1) {
 3566:                         $no_userblock = 1;
 3567:                         last;
 3568:                     }
 3569:                 }
 3570:             } else {
 3571:                 # Resource belongs to current user
 3572:                 # Check for 'evb' priv via lonnet::allowed().
 3573:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3574:                     $no_ownblock = 1;
 3575:                     last;
 3576:                 }
 3577:             }
 3578:         }
 3579:         # if they have the evb priv and are currently not playing student
 3580:         next if (($no_ownblock) &&
 3581:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3582:         next if ($no_userblock);
 3583: 
 3584:         # Retrieve blocking times and identity of blocker for course
 3585:         # of specified user, unless user has 'evb' privilege.
 3586:         
 3587:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3588:         if (($start != 0) && 
 3589:             (($startblock == 0) || ($startblock > $start))) {
 3590:             $startblock = $start;
 3591:         }
 3592:         if (($end != 0)  &&
 3593:             (($endblock == 0) || ($endblock < $end))) {
 3594:             $endblock = $end;
 3595:         }
 3596:     }
 3597:     return ($startblock,$endblock);
 3598: }
 3599: 
 3600: sub get_blocks {
 3601:     my ($setters,$activity,$cdom,$cnum) = @_;
 3602:     my $startblock = 0;
 3603:     my $endblock = 0;
 3604:     my $course = $cdom.'_'.$cnum;
 3605:     $setters->{$course} = {};
 3606:     $setters->{$course}{'staff'} = [];
 3607:     $setters->{$course}{'times'} = [];
 3608:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3609:     foreach my $record (keys(%records)) {
 3610:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3611:         if ($start <= time && $end >= time) {
 3612:             my ($staff_name,$staff_dom,$title,$blocks) =
 3613:                 &parse_block_record($records{$record});
 3614:             if ($blocks->{$activity} eq 'on') {
 3615:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3616:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3617:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3618:                     $startblock = $start;
 3619:                 }
 3620:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3621:                     $endblock = $end;
 3622:                 }
 3623:             }
 3624:         }
 3625:     }
 3626:     return ($startblock,$endblock);
 3627: }
 3628: 
 3629: sub parse_block_record {
 3630:     my ($record) = @_;
 3631:     my ($setuname,$setudom,$title,$blocks);
 3632:     if (ref($record) eq 'HASH') {
 3633:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3634:         $title = &unescape($record->{'event'});
 3635:         $blocks = $record->{'blocks'};
 3636:     } else {
 3637:         my @data = split(/:/,$record,3);
 3638:         if (scalar(@data) eq 2) {
 3639:             $title = $data[1];
 3640:             ($setuname,$setudom) = split(/@/,$data[0]);
 3641:         } else {
 3642:             ($setuname,$setudom,$title) = @data;
 3643:         }
 3644:         $blocks = { 'com' => 'on' };
 3645:     }
 3646:     return ($setuname,$setudom,$title,$blocks);
 3647: }
 3648: 
 3649: sub build_block_table {
 3650:     my ($startblock,$endblock,$setters) = @_;
 3651:     my %lt = &Apache::lonlocal::texthash(
 3652:         'cacb' => 'Currently active communication blocks',
 3653:         'cour' => 'Course',
 3654:         'dura' => 'Duration',
 3655:         'blse' => 'Block set by'
 3656:     );
 3657:     my $output;
 3658:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3659:     $output .= &start_data_table();
 3660:     $output .= '
 3661: <tr>
 3662:  <th>'.$lt{'cour'}.'</th>
 3663:  <th>'.$lt{'dura'}.'</th>
 3664:  <th>'.$lt{'blse'}.'</th>
 3665: </tr>
 3666: ';
 3667:     foreach my $course (keys(%{$setters})) {
 3668:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3669:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3670:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3671:             my $fullname = &plainname($uname,$udom);
 3672:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3673:                 && $env{'user.name'} ne 'public' 
 3674:                 && $env{'user.domain'} ne 'public') {
 3675:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3676:             }
 3677:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3678:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3679:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3680:             $output .= &Apache::loncommon::start_data_table_row().
 3681:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3682:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3683:                        '<td>'.$fullname.'</td>'.
 3684:                         &Apache::loncommon::end_data_table_row();
 3685:         }
 3686:     }
 3687:     $output .= &end_data_table();
 3688: }
 3689: 
 3690: sub blocking_status {
 3691:     my ($activity,$uname,$udom) = @_;
 3692:     my %setters;
 3693:     my ($blocked,$output,$ownitem,$is_course);
 3694:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3695:     if ($startblock && $endblock) {
 3696:         $blocked = 1;
 3697:         if (wantarray) {
 3698:             my $category;
 3699:             if ($activity eq 'boards') {
 3700:                 $category = 'Discussion posts in this course';
 3701:             } elsif ($activity eq 'blogs') {
 3702:                 $category = 'Blogs';
 3703:             } elsif ($activity eq 'port') {
 3704:                 if (defined($uname) && defined($udom)) {
 3705:                     if ($uname eq $env{'user.name'} &&
 3706:                         $udom eq $env{'user.domain'}) {
 3707:                         $ownitem = 1;
 3708:                     }
 3709:                 }
 3710:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3711:                 if ($ownitem) { 
 3712:                     $category = 'Your portfolio files';  
 3713:                 } elsif ($is_course) {
 3714:                     my $coursedesc;
 3715:                     foreach my $course (keys(%setters)) {
 3716:                         my %courseinfo =
 3717:                              &Apache::lonnet::coursedescription($course);
 3718:                         $coursedesc = $courseinfo{'description'};
 3719:                     }
 3720:                     $category = "Group files in the course '$coursedesc'";
 3721:                 } else {
 3722:                     $category = 'Portfolio files belonging to ';
 3723:                     if ($env{'user.name'} eq 'public' && 
 3724:                         $env{'user.domain'} eq 'public') {
 3725:                         $category .= &plainname($uname,$udom);
 3726:                     } else {
 3727:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3728:                     }
 3729:                 }
 3730:             } elsif ($activity eq 'groups') {
 3731:                 $category = 'Groups in this course';
 3732:             }
 3733:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3734:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3735:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3736:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3737:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3738:             }
 3739:         }
 3740:     }
 3741:     if (wantarray) {
 3742:         return ($blocked,$output);
 3743:     } else {
 3744:         return $blocked;
 3745:     }
 3746: }
 3747: 
 3748: ###############################################
 3749: 
 3750: =pod
 3751: 
 3752: =head1 Domain Template Functions
 3753: 
 3754: =over 4
 3755: 
 3756: =item * &determinedomain()
 3757: 
 3758: Inputs: $domain (usually will be undef)
 3759: 
 3760: Returns: Determines which domain should be used for designs
 3761: 
 3762: =cut
 3763: 
 3764: ###############################################
 3765: sub determinedomain {
 3766:     my $domain=shift;
 3767:     if (! $domain) {
 3768:         # Determine domain if we have not been given one
 3769:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3770:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3771:         if ($env{'request.role.domain'}) { 
 3772:             $domain=$env{'request.role.domain'}; 
 3773:         }
 3774:     }
 3775:     return $domain;
 3776: }
 3777: ###############################################
 3778: 
 3779: sub devalidate_domconfig_cache {
 3780:     my ($udom)=@_;
 3781:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3782: }
 3783: 
 3784: # ---------------------- Get domain configuration for a domain
 3785: sub get_domainconf {
 3786:     my ($udom) = @_;
 3787:     my $cachetime=1800;
 3788:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3789:     if (defined($cached)) { return %{$result}; }
 3790: 
 3791:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3792: 					     ['login','rolecolors'],$udom);
 3793:     my (%designhash,%legacy);
 3794:     if (keys(%domconfig) > 0) {
 3795:         if (ref($domconfig{'login'}) eq 'HASH') {
 3796:             if (keys(%{$domconfig{'login'}})) {
 3797:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3798:                     $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3799:                 }
 3800:             } else {
 3801:                 $legacy{'login'} = 1;
 3802:             }
 3803:         } else {
 3804:             $legacy{'login'} = 1;
 3805:         }
 3806:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3807:             if (keys(%{$domconfig{'rolecolors'}})) {
 3808:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3809:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3810:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3811:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3812:                         }
 3813:                     }
 3814:                 }
 3815:             } else {
 3816:                 $legacy{'rolecolors'} = 1;
 3817:             }
 3818:         } else {
 3819:             $legacy{'rolecolors'} = 1;
 3820:         }
 3821:         if (keys(%legacy) > 0) {
 3822:             my %legacyhash = &get_legacy_domconf($udom);
 3823:             foreach my $item (keys(%legacyhash)) {
 3824:                 if ($item =~ /^\Q$udom\E\.login/) {
 3825:                     if ($legacy{'login'}) { 
 3826:                         $designhash{$item} = $legacyhash{$item};
 3827:                     }
 3828:                 } else {
 3829:                     if ($legacy{'rolecolors'}) {
 3830:                         $designhash{$item} = $legacyhash{$item};
 3831:                     }
 3832:                 }
 3833:             }
 3834:         }
 3835:     } else {
 3836:         %designhash = &get_legacy_domconf($udom); 
 3837:     }
 3838:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 3839: 				  $cachetime);
 3840:     return %designhash;
 3841: }
 3842: 
 3843: sub get_legacy_domconf {
 3844:     my ($udom) = @_;
 3845:     my %legacyhash;
 3846:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 3847:     my $designfile =  $designdir.'/'.$udom.'.tab';
 3848:     if (-e $designfile) {
 3849:         if ( open (my $fh,"<$designfile") ) {
 3850:             while (my $line = <$fh>) {
 3851:                 next if ($line =~ /^\#/);
 3852:                 chomp($line);
 3853:                 my ($key,$val)=(split(/\=/,$line));
 3854:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 3855:             }
 3856:             close($fh);
 3857:         }
 3858:     }
 3859:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 3860:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 3861:     }
 3862:     return %legacyhash;
 3863: }
 3864: 
 3865: =pod
 3866: 
 3867: =item * &domainlogo()
 3868: 
 3869: Inputs: $domain (usually will be undef)
 3870: 
 3871: Returns: A link to a domain logo, if the domain logo exists.
 3872: If the domain logo does not exist, a description of the domain.
 3873: 
 3874: =cut
 3875: 
 3876: ###############################################
 3877: sub domainlogo {
 3878:     my $domain = &determinedomain(shift);
 3879:     my %designhash = &get_domainconf($domain);    
 3880:     # See if there is a logo
 3881:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 3882:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 3883:         if ($imgsrc =~ m{^/(adm|res)/}) {
 3884: 	    if ($imgsrc =~ m{^/res/}) {
 3885: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 3886: 		&Apache::lonnet::repcopy($local_name);
 3887: 	    }
 3888: 	   $imgsrc = &lonhttpdurl($imgsrc);
 3889:         } 
 3890:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 3891:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 3892:         return &Apache::lonnet::domain($domain,'description');
 3893:     } else {
 3894:         return '';
 3895:     }
 3896: }
 3897: ##############################################
 3898: 
 3899: =pod
 3900: 
 3901: =item * &designparm()
 3902: 
 3903: Inputs: $which parameter; $domain (usually will be undef)
 3904: 
 3905: Returns: value of designparamter $which
 3906: 
 3907: =cut
 3908: 
 3909: 
 3910: ##############################################
 3911: sub designparm {
 3912:     my ($which,$domain)=@_;
 3913:     if ($env{'browser.blackwhite'} eq 'on') {
 3914: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 3915: 	    return '#000000';
 3916: 	}
 3917: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 3918: 	    return '#FFFFFF';
 3919: 	}
 3920: 	if ($which=~/\.tabbg$/) {
 3921: 	    return '#CCCCCC';
 3922: 	}
 3923:     }
 3924:     if (exists($env{'environment.color.'.$which})) {
 3925: 	return $env{'environment.color.'.$which};
 3926:     }
 3927:     $domain=&determinedomain($domain);
 3928:     my %domdesign = &get_domainconf($domain);
 3929:     my $output;
 3930:     if ($domdesign{$domain.'.'.$which} ne '') {
 3931: 	$output = $domdesign{$domain.'.'.$which};
 3932:     } else {
 3933:         $output = $defaultdesign{$which};
 3934:     }
 3935:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 3936:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 3937:         if ($output =~ m{^/(adm|res)/}) {
 3938: 	    if ($output =~ m{^/res/}) {
 3939: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 3940: 		&Apache::lonnet::repcopy($local_name);
 3941: 	    }
 3942:             $output = &lonhttpdurl($output);
 3943:         }
 3944:     }
 3945:     return $output;
 3946: }
 3947: 
 3948: ###############################################
 3949: ###############################################
 3950: 
 3951: =pod
 3952: 
 3953: =back
 3954: 
 3955: =head1 HTML Helpers
 3956: 
 3957: =over 4
 3958: 
 3959: =item * &bodytag()
 3960: 
 3961: Returns a uniform header for LON-CAPA web pages.
 3962: 
 3963: Inputs: 
 3964: 
 3965: =over 4
 3966: 
 3967: =item * $title, A title to be displayed on the page.
 3968: 
 3969: =item * $function, the current role (can be undef).
 3970: 
 3971: =item * $addentries, extra parameters for the <body> tag.
 3972: 
 3973: =item * $bodyonly, if defined, only return the <body> tag.
 3974: 
 3975: =item * $domain, if defined, force a given domain.
 3976: 
 3977: =item * $forcereg, if page should register as content page (relevant for 
 3978:             text interface only)
 3979: 
 3980: =item * $customtitle, alternate text to use instead of $title
 3981:                       in the title box that appears, this text
 3982:                       is not auto translated like the $title is
 3983: 
 3984: =item * $notopbar, if true, keep the 'what is this' info but remove the
 3985:                    navigational links
 3986: 
 3987: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 3988: 
 3989: =item * $notitle, if true keep the nav controls, but remove the title bar
 3990: 
 3991: =item * $no_inline_link, if true and in remote mode, don't show the 
 3992:          'Switch To Inline Menu' link
 3993: 
 3994: =item * $args, optional argument valid values are
 3995:             no_auto_mt_title -> prevents &mt()ing the title arg
 3996:             inherit_jsmath -> when creating popup window in a page,
 3997:                               should it have jsmath forced on by the
 3998:                               current page
 3999: 
 4000: =back
 4001: 
 4002: Returns: A uniform header for LON-CAPA web pages.  
 4003: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4004: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4005: other decorations will be returned.
 4006: 
 4007: =cut
 4008: 
 4009: sub bodytag {
 4010:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4011: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4012: 
 4013:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4014: 
 4015:     $function = &get_users_function() if (!$function);
 4016:     my $img =    &designparm($function.'.img',$domain);
 4017:     my $font =   &designparm($function.'.font',$domain);
 4018:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4019: 
 4020:     my %design = ( 'style'   => 'margin-top: 0px',
 4021: 		   'bgcolor' => $pgbg,
 4022: 		   'text'    => $font,
 4023:                    'alink'   => &designparm($function.'.alink',$domain),
 4024: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4025: 		   'link'    => &designparm($function.'.link',$domain),);
 4026:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4027: 
 4028:  # role and realm
 4029:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4030:     if ($role  eq 'ca') {
 4031:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4032:         $realm = &plainname($rname,$rdom);
 4033:     } 
 4034: # realm
 4035:     if ($env{'request.course.id'}) {
 4036:         if ($env{'request.role'} !~ /^cr/) {
 4037:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4038:         }
 4039: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4040:     } else {
 4041:         $role = &Apache::lonnet::plaintext($role);
 4042:     }
 4043: 
 4044:     if (!$realm) { $realm='&nbsp;'; }
 4045: # Set messages
 4046:     my $messages=&domainlogo($domain);
 4047: 
 4048:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4049: 
 4050: # construct main body tag
 4051:     my $bodytag = "<body $extra_body_attr>".
 4052: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4053: 
 4054:     if ($bodyonly) {
 4055:         return $bodytag;
 4056:     } elsif ($env{'browser.interface'} eq 'textual') {
 4057: # Accessibility
 4058:           
 4059: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4060: 	if (!$notitle) {
 4061: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4062: 	}
 4063: 	return $bodytag;
 4064:     }
 4065: 
 4066:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4067:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4068: 	undef($role);
 4069:     } else {
 4070: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4071:     }
 4072:     
 4073:     my $roleinfo=(<<ENDROLE);
 4074: <td class="LC_title_bar_who">
 4075: <div class="LC_title_bar_name">
 4076:     $name
 4077:     &nbsp;
 4078: </div>
 4079: <div class="LC_title_bar_role">
 4080: $role&nbsp;
 4081: </div>
 4082: <div class="LC_title_bar_realm">
 4083: $realm&nbsp;
 4084: </div>
 4085: </td>
 4086: ENDROLE
 4087: 
 4088:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4089:     if ($customtitle) {
 4090:         $titleinfo = $customtitle;
 4091:     }
 4092:     #
 4093:     # Extra info if you are the DC
 4094:     my $dc_info = '';
 4095:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4096:                         $env{'course.'.$env{'request.course.id'}.
 4097:                                  '.domain'}.'/'})) {
 4098:         my $cid = $env{'request.course.id'};
 4099:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4100:         $dc_info =~ s/\s+$//;
 4101:         $dc_info = '('.$dc_info.')';
 4102:     }
 4103: 
 4104:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4105:         # No Remote
 4106: 	if ($env{'request.state'} eq 'construct') {
 4107: 	    $forcereg=1;
 4108: 	}
 4109: 
 4110: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4111: 	    # this is for resources; directories have customtitle, and crumbs
 4112:             # and select recent are created in lonpubdir.pm  
 4113: 	    my ($uname,$thisdisfn)=
 4114: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4115: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4116: 	    $formaction=~s/\/+/\//g;
 4117: 
 4118: 	    my $parentpath = '';
 4119: 	    my $lastitem = '';
 4120: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4121: 		$parentpath = $1;
 4122: 		$lastitem = $2;
 4123: 	    } else {
 4124: 		$lastitem = $thisdisfn;
 4125: 	    }
 4126: 	    $titleinfo = 
 4127: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4128: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4129: 		.'<form name="dirs" method="post" action="'.$formaction
 4130: 		.'" target="_top"><tt><b>'
 4131: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 4132: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4133: 		.'</form>'
 4134: 		.&Apache::lonmenu::constspaceform();
 4135:         }
 4136: 
 4137:         my $titletable;
 4138: 	if (!$notitle) {
 4139: 	    $titletable =
 4140: 		'<table id="LC_title_bar">'.
 4141:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4142: 			 '</tr></table>';
 4143: 	}
 4144: 	if ($notopbar) {
 4145: 	    $bodytag .= $titletable;
 4146: 	} else {
 4147: 	    if ($env{'request.state'} eq 'construct') {
 4148:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4149: 							  $titletable);
 4150:             } else {
 4151:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4152: 		    $titletable;
 4153:             }
 4154:         }
 4155:         return $bodytag;
 4156:     }
 4157: 
 4158: #
 4159: # Top frame rendering, Remote is up
 4160: #
 4161: 
 4162:     my $imgsrc = $img;
 4163:     if ($img =~ /^\/adm/) {
 4164:         $imgsrc = &lonhttpdurl($img);
 4165:     }
 4166:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4167: 
 4168:     # Explicit link to get inline menu
 4169:     my $menu= ($no_inline_link?''
 4170: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4171:     #
 4172:     if ($notitle) {
 4173: 	return $bodytag;
 4174:     }
 4175:     return(<<ENDBODY);
 4176: $bodytag
 4177: <table id="LC_title_bar" class="LC_with_remote">
 4178: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4179:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4180: </tr>
 4181: <tr><td>$titleinfo $dc_info $menu</td>
 4182: $roleinfo
 4183: </tr>
 4184: </table>
 4185: ENDBODY
 4186: }
 4187: 
 4188: sub make_attr_string {
 4189:     my ($register,$attr_ref) = @_;
 4190: 
 4191:     if ($attr_ref && !ref($attr_ref)) {
 4192: 	die("addentries Must be a hash ref ".
 4193: 	    join(':',caller(1))." ".
 4194: 	    join(':',caller(0))." ");
 4195:     }
 4196: 
 4197:     if ($register) {
 4198: 	my ($on_load,$on_unload);
 4199: 	foreach my $key (keys(%{$attr_ref})) {
 4200: 	    if      (lc($key) eq 'onload') {
 4201: 		$on_load.=$attr_ref->{$key}.';';
 4202: 		delete($attr_ref->{$key});
 4203: 
 4204: 	    } elsif (lc($key) eq 'onunload') {
 4205: 		$on_unload.=$attr_ref->{$key}.';';
 4206: 		delete($attr_ref->{$key});
 4207: 	    }
 4208: 	}
 4209: 	$attr_ref->{'onload'}  =
 4210: 	    &Apache::lonmenu::loadevents().  $on_load;
 4211: 	$attr_ref->{'onunload'}=
 4212: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4213:     }
 4214: 
 4215: # Accessibility font enhance
 4216:     if ($env{'browser.fontenhance'} eq 'on') {
 4217: 	my $style;
 4218: 	foreach my $key (keys(%{$attr_ref})) {
 4219: 	    if (lc($key) eq 'style') {
 4220: 		$style.=$attr_ref->{$key}.';';
 4221: 		delete($attr_ref->{$key});
 4222: 	    }
 4223: 	}
 4224: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4225:     }
 4226: 
 4227:     if ($env{'browser.blackwhite'} eq 'on') {
 4228: 	delete($attr_ref->{'font'});
 4229: 	delete($attr_ref->{'link'});
 4230: 	delete($attr_ref->{'alink'});
 4231: 	delete($attr_ref->{'vlink'});
 4232: 	delete($attr_ref->{'bgcolor'});
 4233: 	delete($attr_ref->{'background'});
 4234:     }
 4235: 
 4236:     my $attr_string;
 4237:     foreach my $attr (keys(%$attr_ref)) {
 4238: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4239:     }
 4240:     return $attr_string;
 4241: }
 4242: 
 4243: 
 4244: ###############################################
 4245: ###############################################
 4246: 
 4247: =pod
 4248: 
 4249: =item * &endbodytag()
 4250: 
 4251: Returns a uniform footer for LON-CAPA web pages.
 4252: 
 4253: Inputs: 1 - optional reference to an args hash
 4254: If in the hash, key for noredirectlink has a value which evaluates to true,
 4255: a 'Continue' link is not displayed if the page contains an
 4256: internal redirect in the <head></head> section,
 4257: i.e., $env{'internal.head.redirect'} exists   
 4258: 
 4259: =cut
 4260: 
 4261: sub endbodytag {
 4262:     my ($args) = @_;
 4263:     my $endbodytag='</body>';
 4264:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4265:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4266:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4267: 	    $endbodytag=
 4268: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4269: 	        &mt('Continue').'</a>'.
 4270: 	        $endbodytag;
 4271:         }
 4272:     }
 4273:     return $endbodytag;
 4274: }
 4275: 
 4276: =pod
 4277: 
 4278: =item * &standard_css()
 4279: 
 4280: Returns a style sheet
 4281: 
 4282: Inputs: (all optional)
 4283:             domain         -> force to color decorate a page for a specific
 4284:                                domain
 4285:             function       -> force usage of a specific rolish color scheme
 4286:             bgcolor        -> override the default page bgcolor
 4287: 
 4288: =cut
 4289: 
 4290: sub standard_css {
 4291:     my ($function,$domain,$bgcolor) = @_;
 4292:     $function  = &get_users_function() if (!$function);
 4293:     my $img    = &designparm($function.'.img',   $domain);
 4294:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4295:     my $font   = &designparm($function.'.font',  $domain);
 4296:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4297:     my $pgbg_or_bgcolor =
 4298: 	         $bgcolor ||
 4299: 	         &designparm($function.'.pgbg',  $domain);
 4300:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4301:     my $alink  = &designparm($function.'.alink', $domain);
 4302:     my $vlink  = &designparm($function.'.vlink', $domain);
 4303:     my $link   = &designparm($function.'.link',  $domain);
 4304: 
 4305:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4306:     my $mono                 = 'monospace';
 4307:     my $data_table_head      = $tabbg;
 4308:     my $data_table_light     = '#EEEEEE';
 4309:     my $data_table_dark      = '#DDDDDD';
 4310:     my $data_table_darker    = '#CCCCCC';
 4311:     my $data_table_highlight = '#FFFF00';
 4312:     my $mail_new             = '#FFBB77';
 4313:     my $mail_new_hover       = '#DD9955';
 4314:     my $mail_read            = '#BBBB77';
 4315:     my $mail_read_hover      = '#999944';
 4316:     my $mail_replied         = '#AAAA88';
 4317:     my $mail_replied_hover   = '#888855';
 4318:     my $mail_other           = '#99BBBB';
 4319:     my $mail_other_hover     = '#669999';
 4320:     my $table_header         = '#DDDDDD';
 4321:     my $feedback_link_bg     = '#BBBBBB';
 4322: 
 4323:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4324: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4325: 	                                                 : '0px 3px 0px 4px';
 4326: 
 4327: 
 4328:     return <<END;
 4329: h1, h2, h3, th { font-family: $sans }
 4330: a:focus { color: red; background: yellow } 
 4331: table.thinborder,
 4332: 
 4333: table.thinborder tr th {
 4334:   border-style: solid;
 4335:   border-width: 1px;
 4336:   background: $tabbg;
 4337: }
 4338: table.thinborder tr td {
 4339:   border-style: solid;
 4340:   border-width: 1px
 4341: }
 4342: 
 4343: form, .inline { display: inline; }
 4344: .center { text-align: center; }
 4345: .LC_filename {font-family: $mono; white-space:pre;}
 4346: .LC_error {
 4347:   color: red;
 4348:   font-size: larger;
 4349: }
 4350: .LC_warning,
 4351: .LC_diff_removed {
 4352:   color: red;
 4353: }
 4354: 
 4355: .LC_info,
 4356: .LC_success,
 4357: .LC_diff_added {
 4358:   color: green;
 4359: }
 4360: .LC_unknown {
 4361:   color: yellow;
 4362: }
 4363: 
 4364: .LC_icon {
 4365:   border: 0px;
 4366: }
 4367: .LC_indexer_icon {
 4368:   border: 0px;
 4369:   height: 22px;
 4370: }
 4371: .LC_docs_spacer {
 4372:   width: 25px;
 4373:   height: 1px;
 4374:   border: 0px;
 4375: }
 4376: 
 4377: .LC_internal_info {
 4378:   color: #999;
 4379: }
 4380: 
 4381: table.LC_pastsubmission {
 4382:   border: 1px solid black;
 4383:   margin: 2px;
 4384: }
 4385: 
 4386: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4387:   width: 100%;
 4388:   background: $pgbg;
 4389:   border: 2px;
 4390:   border-collapse: separate;
 4391:   padding: 0px;
 4392: }
 4393: 
 4394: table#LC_title_bar, table.LC_breadcrumbs, 
 4395: table#LC_title_bar.LC_with_remote {
 4396:   width: 100%;
 4397:   border-color: $pgbg;
 4398:   border-style: solid;
 4399:   border-width: $border;
 4400: 
 4401:   background: $pgbg;
 4402:   font-family: $sans;
 4403:   border-collapse: collapse;
 4404:   padding: 0px;
 4405: }
 4406: 
 4407: table.LC_docs_path {
 4408:   width: 100%;
 4409:   border: 0;
 4410:   background: $pgbg;
 4411:   font-family: $sans;
 4412:   border-collapse: collapse;
 4413:   padding: 0px;
 4414: }
 4415: 
 4416: table#LC_title_bar td {
 4417:   background: $tabbg;
 4418: }
 4419: table#LC_title_bar td.LC_title_bar_who {
 4420:   background: $tabbg;
 4421:   color: $font;
 4422:   font: small $sans;
 4423:   text-align: right;
 4424: }
 4425: span.LC_metadata {
 4426:     font-family: $sans;
 4427: }
 4428: span.LC_title_bar_title {
 4429:   font: bold x-large $sans;
 4430: }
 4431: table#LC_title_bar td.LC_title_bar_domain_logo {
 4432:   background: $sidebg;
 4433:   text-align: right;
 4434:   padding: 0px;
 4435: }
 4436: table#LC_title_bar td.LC_title_bar_role_logo {
 4437:   background: $sidebg;
 4438:   padding: 0px;
 4439: }
 4440: 
 4441: table#LC_menubuttons_mainmenu {
 4442:   width: 100%;
 4443:   border: 0px;
 4444:   border-spacing: 1px;
 4445:   padding: 0px 1px;
 4446:   margin: 0px;
 4447:   border-collapse: separate;
 4448: }
 4449: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4450:   border: 0px;
 4451: }
 4452: table#LC_top_nav td {
 4453:   background: $tabbg;
 4454:   border: 0px;
 4455:   font-size: small;
 4456: }
 4457: table#LC_top_nav td a, div#LC_top_nav a {
 4458:   color: $font;
 4459:   font-family: $sans;
 4460: }
 4461: table#LC_top_nav td.LC_top_nav_logo {
 4462:   background: $tabbg;
 4463:   text-align: left;
 4464:   white-space: nowrap;
 4465:   width: 31px;
 4466: }
 4467: table#LC_top_nav td.LC_top_nav_logo img {
 4468:   border: 0px;
 4469:   vertical-align: bottom;
 4470: }
 4471: table#LC_top_nav td.LC_top_nav_exit,
 4472: table#LC_top_nav td.LC_top_nav_help {
 4473:   width: 2.0em;
 4474: }
 4475: table#LC_top_nav td.LC_top_nav_login {
 4476:   width: 4.0em;
 4477:   text-align: center;
 4478: }
 4479: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4480:   background: $tabbg;
 4481:   color: $font;
 4482:   font-family: $sans;
 4483:   font-size: smaller;
 4484: }
 4485: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4486: table.LC_docs_path td.LC_docs_path_component {
 4487:   background: $tabbg;
 4488:   color: $font;
 4489:   font-family: $sans;
 4490:   font-size: larger;
 4491:   text-align: right;
 4492: }
 4493: td.LC_table_cell_checkbox {
 4494:   text-align: center;
 4495: }
 4496: 
 4497: table#LC_mainmenu td.LC_mainmenu_column {
 4498:     vertical-align: top;
 4499: }
 4500: 
 4501: .LC_menubuttons_inline_text {
 4502:   color: $font;
 4503:   font-family: $sans;
 4504:   font-size: smaller;
 4505: }
 4506: 
 4507: .LC_menubuttons_link {
 4508:   text-decoration: none;
 4509: }
 4510: 
 4511: .LC_menubuttons_category {
 4512:   color: $font;
 4513:   background: $pgbg;
 4514:   font-family: $sans;
 4515:   font-size: larger;
 4516:   font-weight: bold;
 4517: }
 4518: 
 4519: td.LC_menubuttons_text {
 4520:   width: 90%;
 4521:   color: $font;
 4522:   font-family: $sans;
 4523: }
 4524: 
 4525: td.LC_menubuttons_img {
 4526: }
 4527: 
 4528: .LC_current_location {
 4529:   font-family: $sans;
 4530:   background: $tabbg;
 4531: }
 4532: .LC_new_mail {
 4533:   font-family: $sans;
 4534:   background: $tabbg;
 4535:   font-weight: bold;
 4536: }
 4537: 
 4538: .LC_rolesmenu_is {
 4539:   font-family: $sans;
 4540: }
 4541: 
 4542: .LC_rolesmenu_selected {
 4543:   font-family: $sans;
 4544: }
 4545: 
 4546: .LC_rolesmenu_future {
 4547:   font-family: $sans;
 4548: }
 4549: 
 4550: 
 4551: .LC_rolesmenu_will {
 4552:   font-family: $sans;
 4553: }
 4554: 
 4555: .LC_rolesmenu_will_not {
 4556:   font-family: $sans;
 4557: }
 4558: 
 4559: .LC_rolesmenu_expired {
 4560:   font-family: $sans;
 4561: }
 4562: 
 4563: .LC_rolesinfo {
 4564:   font-family: $sans;
 4565: }
 4566: 
 4567: .LC_dropadd_labeltext {
 4568:   font-family: $sans;
 4569:   text-align: right;
 4570: }
 4571: 
 4572: .LC_preferences_labeltext {
 4573:   font-family: $sans;
 4574:   text-align: right;
 4575: }
 4576: 
 4577: .LC_roleslog_note {
 4578:   font-size: smaller;
 4579: }
 4580: 
 4581: table.LC_aboutme_port {
 4582:   border: 0px;
 4583:   border-collapse: collapse;
 4584:   border-spacing: 0px;
 4585: }
 4586: table.LC_data_table, table.LC_mail_list {
 4587:   border: 1px solid #000000;
 4588:   border-collapse: separate;
 4589:   border-spacing: 1px;
 4590:   background: $pgbg;
 4591: }
 4592: .LC_data_table_dense {
 4593:   font-size: small;
 4594: }
 4595: table.LC_nested_outer {
 4596:   border: 1px solid #000000;
 4597:   border-collapse: collapse;
 4598:   border-spacing: 0px;
 4599:   width: 100%;
 4600: }
 4601: table.LC_nested {
 4602:   border: 0px;
 4603:   border-collapse: collapse;
 4604:   border-spacing: 0px;
 4605:   width: 100%;
 4606: }
 4607: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4608: table.LC_prior_tries tr th {
 4609:   font-weight: bold;
 4610:   background-color: $data_table_head;
 4611:   font-size: smaller;
 4612: }
 4613: table.LC_data_table tr.LC_odd_row > td, 
 4614: table.LC_aboutme_port tr td {
 4615:   background-color: $data_table_light;
 4616:   padding: 2px;
 4617: }
 4618: table.LC_data_table tr.LC_even_row > td,
 4619: table.LC_aboutme_port tr.LC_even_row td {
 4620:   background-color: $data_table_dark;
 4621: }
 4622: table.LC_data_table tr.LC_data_table_highlight td {
 4623:   background-color: $data_table_darker;
 4624: }
 4625: table.LC_data_table tr td.LC_leftcol_header {
 4626:   background-color: $data_table_head;
 4627:   font-weight: bold;
 4628: }
 4629: table.LC_data_table tr.LC_empty_row td,
 4630: table.LC_nested tr.LC_empty_row td {
 4631:   background-color: #FFFFFF;
 4632:   font-weight: bold;
 4633:   font-style: italic;
 4634:   text-align: center;
 4635:   padding: 8px;
 4636: }
 4637: table.LC_nested tr.LC_empty_row td {
 4638:   padding: 4ex
 4639: }
 4640: table.LC_nested_outer tr th {
 4641:   font-weight: bold;
 4642:   background-color: $data_table_head;
 4643:   font-size: smaller;
 4644:   border-bottom: 1px solid #000000;
 4645: }
 4646: table.LC_nested_outer tr td.LC_subheader {
 4647:   background-color: $data_table_head;
 4648:   font-weight: bold;
 4649:   font-size: small;
 4650:   border-bottom: 1px solid #000000;
 4651:   text-align: right;
 4652: }
 4653: table.LC_nested tr.LC_info_row td {
 4654:   background-color: #CCC;
 4655:   font-weight: bold;
 4656:   font-size: small;
 4657:   text-align: center;
 4658: }
 4659: table.LC_nested tr.LC_info_row td.LC_left_item,
 4660: table.LC_nested_outer tr th.LC_left_item {
 4661:   text-align: left;
 4662: }
 4663: table.LC_nested td {
 4664:   background-color: #FFF;
 4665:   font-size: small;
 4666: }
 4667: table.LC_nested_outer tr th.LC_right_item,
 4668: table.LC_nested tr.LC_info_row td.LC_right_item,
 4669: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4670: table.LC_nested tr td.LC_right_item {
 4671:   text-align: right;
 4672: }
 4673: 
 4674: table.LC_nested tr.LC_odd_row td {
 4675:   background-color: #EEE;
 4676: }
 4677: 
 4678: table.LC_createuser {
 4679: }
 4680: 
 4681: table.LC_createuser tr.LC_section_row td {
 4682:   font-size: smaller;
 4683: }
 4684: 
 4685: table.LC_createuser tr.LC_info_row td  {
 4686:   background-color: #CCC;
 4687:   font-weight: bold;
 4688:   text-align: center;
 4689: }
 4690: 
 4691: table.LC_calendar {
 4692:   border: 1px solid #000000;
 4693:   border-collapse: collapse;
 4694: }
 4695: table.LC_calendar_pickdate {
 4696:   font-size: xx-small;
 4697: }
 4698: table.LC_calendar tr td {
 4699:   border: 1px solid #000000;
 4700:   vertical-align: top;
 4701: }
 4702: table.LC_calendar tr td.LC_calendar_day_empty {
 4703:   background-color: $data_table_dark;
 4704: }
 4705: table.LC_calendar tr td.LC_calendar_day_current {
 4706:   background-color: $data_table_highlight;
 4707: }
 4708: 
 4709: table.LC_mail_list tr.LC_mail_new {
 4710:   background-color: $mail_new;
 4711: }
 4712: table.LC_mail_list tr.LC_mail_new:hover {
 4713:   background-color: $mail_new_hover;
 4714: }
 4715: table.LC_mail_list tr.LC_mail_read {
 4716:   background-color: $mail_read;
 4717: }
 4718: table.LC_mail_list tr.LC_mail_read:hover {
 4719:   background-color: $mail_read_hover;
 4720: }
 4721: table.LC_mail_list tr.LC_mail_replied {
 4722:   background-color: $mail_replied;
 4723: }
 4724: table.LC_mail_list tr.LC_mail_replied:hover {
 4725:   background-color: $mail_replied_hover;
 4726: }
 4727: table.LC_mail_list tr.LC_mail_other {
 4728:   background-color: $mail_other;
 4729: }
 4730: table.LC_mail_list tr.LC_mail_other:hover {
 4731:   background-color: $mail_other_hover;
 4732: }
 4733: table.LC_mail_list tr.LC_mail_even {
 4734: }
 4735: table.LC_mail_list tr.LC_mail_odd {
 4736: }
 4737: 
 4738: 
 4739: table#LC_portfolio_actions {
 4740:   width: auto;
 4741:   background: $pgbg;
 4742:   border: 0px;
 4743:   border-spacing: 2px 2px;
 4744:   padding: 0px;
 4745:   margin: 0px;
 4746:   border-collapse: separate;
 4747: }
 4748: table#LC_portfolio_actions td.LC_label {
 4749:   background: $tabbg;
 4750:   text-align: right;
 4751: }
 4752: table#LC_portfolio_actions td.LC_value {
 4753:   background: $tabbg;
 4754: }
 4755: 
 4756: table#LC_cstr_controls {
 4757:   width: 100%;
 4758:   border-collapse: collapse;
 4759: }
 4760: table#LC_cstr_controls tr td {
 4761:   border: 4px solid $pgbg;
 4762:   padding: 4px;
 4763:   text-align: center;
 4764:   background: $tabbg;
 4765: }
 4766: table#LC_cstr_controls tr th {
 4767:   border: 4px solid $pgbg;
 4768:   background: $table_header;
 4769:   text-align: center;
 4770:   font-family: $sans;
 4771:   font-size: smaller;
 4772: }
 4773: 
 4774: table#LC_browser {
 4775:  
 4776: }
 4777: table#LC_browser tr th {
 4778:   background: $table_header;
 4779: }
 4780: table#LC_browser tr td {
 4781:   padding: 2px;
 4782: }
 4783: table#LC_browser tr.LC_browser_file,
 4784: table#LC_browser tr.LC_browser_file_published {
 4785:   background: #CCFF88;
 4786: }
 4787: table#LC_browser tr.LC_browser_file_locked,
 4788: table#LC_browser tr.LC_browser_file_unpublished {
 4789:   background: #FFAA99;
 4790: }
 4791: table#LC_browser tr.LC_browser_file_obsolete {
 4792:   background: #AAAAAA;
 4793: }
 4794: table#LC_browser tr.LC_browser_file_modified,
 4795: table#LC_browser tr.LC_browser_file_metamodified {
 4796:   background: #FFFF77;
 4797: }
 4798: table#LC_browser tr.LC_browser_folder {
 4799:   background: #CCCCFF;
 4800: }
 4801: span.LC_current_location {
 4802:   font-size: x-large;
 4803:   background: $pgbg;
 4804: }
 4805: 
 4806: span.LC_parm_menu_item {
 4807:   font-size: larger;
 4808:   font-family: $sans;
 4809: }
 4810: span.LC_parm_scope_all {
 4811:   color: red;
 4812: }
 4813: span.LC_parm_scope_folder {
 4814:   color: green;
 4815: }
 4816: span.LC_parm_scope_resource {
 4817:   color: orange;
 4818: }
 4819: span.LC_parm_part {
 4820:   color: blue;
 4821: }
 4822: span.LC_parm_folder, span.LC_parm_symb {
 4823:   font-size: x-small;
 4824:   font-family: $mono;
 4825:   color: #AAAAAA;
 4826: }
 4827: 
 4828: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4829: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 4830:   border: 1px solid black;
 4831:   border-collapse: collapse;
 4832: }
 4833: table.LC_parm_overview_restrictions td {
 4834:   border-width: 1px 4px 1px 4px;
 4835:   border-style: solid;
 4836:   border-color: $pgbg;
 4837:   text-align: center;
 4838: }
 4839: table.LC_parm_overview_restrictions th {
 4840:   background: $tabbg;
 4841:   border-width: 1px 4px 1px 4px;
 4842:   border-style: solid;
 4843:   border-color: $pgbg;
 4844: }
 4845: table#LC_helpmenu {
 4846:   border: 0px;
 4847:   height: 55px;
 4848:   border-spacing: 0px;
 4849: }
 4850: 
 4851: table#LC_helpmenu fieldset legend {
 4852:   font-size: larger;
 4853:   font-weight: bold;
 4854: }
 4855: table#LC_helpmenu_links {
 4856:   width: 100%;
 4857:   border: 1px solid black;
 4858:   background: $pgbg;
 4859:   padding: 0px;
 4860:   border-spacing: 1px;
 4861: }
 4862: table#LC_helpmenu_links tr td {
 4863:   padding: 1px;
 4864:   background: $tabbg;
 4865:   text-align: center;
 4866:   font-weight: bold;
 4867: }
 4868: 
 4869: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 4870: table#LC_helpmenu_links a:active {
 4871:   text-decoration: none;
 4872:   color: $font;
 4873: }
 4874: table#LC_helpmenu_links a:hover {
 4875:   text-decoration: underline;
 4876:   color: $vlink;
 4877: }
 4878: 
 4879: .LC_chrt_popup_exists {
 4880:   border: 1px solid #339933;
 4881:   margin: -1px;
 4882: }
 4883: .LC_chrt_popup_up {
 4884:   border: 1px solid yellow;
 4885:   margin: -1px;
 4886: }
 4887: .LC_chrt_popup {
 4888:   border: 1px solid #8888FF;
 4889:   background: #CCCCFF;
 4890: }
 4891: table.LC_pick_box {
 4892:   border-collapse: separate;
 4893:   background: white;
 4894:   border: 1px solid black;
 4895:   border-spacing: 1px;
 4896: }
 4897: table.LC_pick_box td.LC_pick_box_title {
 4898:   background: $tabbg;
 4899:   font-weight: bold;
 4900:   text-align: right;
 4901:   width: 184px;
 4902:   padding: 8px;
 4903: }
 4904: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 4905:   background: $tabbg;
 4906:   font-weight: bold;
 4907:   text-align: right;
 4908:   width: 350px;
 4909:   padding: 8px;
 4910: }
 4911: 
 4912: table.LC_pick_box td.LC_pick_box_value {
 4913:   text-align: left;
 4914:   padding: 8px;
 4915: }
 4916: table.LC_pick_box td.LC_pick_box_select {
 4917:   text-align: left;
 4918:   padding: 8px;
 4919: }
 4920: table.LC_pick_box td.LC_pick_box_separator {
 4921:   padding: 0px;
 4922:   height: 1px;
 4923:   background: black;
 4924: }
 4925: table.LC_pick_box td.LC_pick_box_submit {
 4926:   text-align: right;
 4927: }
 4928: table.LC_pick_box td.LC_evenrow_value {
 4929:   text-align: left;
 4930:   padding: 8px;
 4931:   background-color: $data_table_light;
 4932: }
 4933: table.LC_pick_box td.LC_oddrow_value {
 4934:   text-align: left;
 4935:   padding: 8px;
 4936:   background-color: $data_table_light;
 4937: }
 4938: table.LC_helpform_receipt {
 4939:   width: 620px;
 4940:   border-collapse: separate;
 4941:   background: white;
 4942:   border: 1px solid black;
 4943:   border-spacing: 1px;
 4944: }
 4945: table.LC_helpform_receipt td.LC_pick_box_title {
 4946:   background: $tabbg;
 4947:   font-weight: bold;
 4948:   text-align: right;
 4949:   width: 184px;
 4950:   padding: 8px;
 4951: }
 4952: table.LC_helpform_receipt td.LC_evenrow_value {
 4953:   text-align: left;
 4954:   padding: 8px;
 4955:   background-color: $data_table_light;
 4956: }
 4957: table.LC_helpform_receipt td.LC_oddrow_value {
 4958:   text-align: left;
 4959:   padding: 8px;
 4960:   background-color: $data_table_light;
 4961: }
 4962: table.LC_helpform_receipt td.LC_pick_box_separator {
 4963:   padding: 0px;
 4964:   height: 1px;
 4965:   background: black;
 4966: }
 4967: span.LC_helpform_receipt_cat {
 4968:   font-weight: bold;
 4969: }
 4970: table.LC_group_priv_box {
 4971:   background: white;
 4972:   border: 1px solid black;
 4973:   border-spacing: 1px;
 4974: }
 4975: table.LC_group_priv_box td.LC_pick_box_title {
 4976:   background: $tabbg;
 4977:   font-weight: bold;
 4978:   text-align: right;
 4979:   width: 184px;
 4980: }
 4981: table.LC_group_priv_box td.LC_groups_fixed {
 4982:   background: $data_table_light;
 4983:   text-align: center;
 4984: }
 4985: table.LC_group_priv_box td.LC_groups_optional {
 4986:   background: $data_table_dark;
 4987:   text-align: center;
 4988: }
 4989: table.LC_group_priv_box td.LC_groups_functionality {
 4990:   background: $data_table_darker;
 4991:   text-align: center;
 4992:   font-weight: bold;
 4993: }
 4994: table.LC_group_priv td {
 4995:   text-align: left;
 4996:   padding: 0px;
 4997: }
 4998: 
 4999: table.LC_notify_front_page {
 5000:   background: white;
 5001:   border: 1px solid black;
 5002:   padding: 8px;
 5003: }
 5004: table.LC_notify_front_page td {
 5005:   padding: 8px;
 5006: }
 5007: .LC_navbuttons {
 5008:   margin: 2ex 0ex 2ex 0ex;
 5009: }
 5010: .LC_topic_bar {
 5011:   font-family: $sans;
 5012:   font-weight: bold;
 5013:   width: 100%;
 5014:   background: $tabbg;
 5015:   vertical-align: middle;
 5016:   margin: 2ex 0ex 2ex 0ex;
 5017: }
 5018: .LC_topic_bar span {
 5019:   vertical-align: middle;
 5020: }
 5021: .LC_topic_bar img {
 5022:   vertical-align: bottom;
 5023: }
 5024: table.LC_course_group_status {
 5025:   margin: 20px;
 5026: }
 5027: table.LC_status_selector td {
 5028:   vertical-align: top;
 5029:   text-align: center;
 5030:   padding: 4px;
 5031: }
 5032: table.LC_descriptive_input td.LC_description {
 5033:   vertical-align: top;
 5034:   text-align: right;
 5035:   font-weight: bold;
 5036: }
 5037: div.LC_feedback_link {
 5038:   clear: both;
 5039:   background: white;
 5040:   width: 100%;  
 5041: }
 5042: span.LC_feedback_link {
 5043:   background: $feedback_link_bg;
 5044:   font-size: larger;
 5045: }
 5046: span.LC_message_link {
 5047:   background: $feedback_link_bg;
 5048:   font-size: larger;
 5049:   position: absolute;
 5050:   right: 1em;
 5051: }
 5052: 
 5053: table.LC_prior_tries {
 5054:   border: 1px solid #000000;
 5055:   border-collapse: separate;
 5056:   border-spacing: 1px;
 5057: }
 5058: 
 5059: table.LC_prior_tries td {
 5060:   padding: 2px;
 5061: }
 5062: 
 5063: .LC_answer_correct {
 5064:   background: #AAFFAA;
 5065:   color: black;
 5066: }
 5067: .LC_answer_charged_try {
 5068:   background: #FFAAAA ! important;
 5069:   color: black;
 5070: }
 5071: .LC_answer_not_charged_try, 
 5072: .LC_answer_no_grade,
 5073: .LC_answer_late {
 5074:   background: #FFFFAA;
 5075:   color: black;
 5076: }
 5077: .LC_answer_previous {
 5078:   background: #AAAAFF;
 5079:   color: black;
 5080: }
 5081: .LC_answer_no_message {
 5082:   background: #FFFFFF;
 5083:   color: black;
 5084: }
 5085: .LC_answer_unknown {
 5086:   background: orange;
 5087:   color: black;
 5088: }
 5089: 
 5090: 
 5091: span.LC_prior_numerical,
 5092: span.LC_prior_string,
 5093: span.LC_prior_custom,
 5094: span.LC_prior_reaction,
 5095: span.LC_prior_math {
 5096:   font-family: monospace;
 5097:   white-space: pre;
 5098: }
 5099: 
 5100: span.LC_prior_string {
 5101:   font-family: monospace;
 5102:   white-space: pre;
 5103: }
 5104: 
 5105: table.LC_prior_option {
 5106:   width: 100%;
 5107:   border-collapse: collapse;
 5108: }
 5109: table.LC_prior_rank, table.LC_prior_match {
 5110:   border-collapse: collapse;
 5111: }
 5112: table.LC_prior_option tr td,
 5113: table.LC_prior_rank tr td,
 5114: table.LC_prior_match tr td {
 5115:   border: 1px solid #000000;
 5116: }
 5117: 
 5118: span.LC_nobreak {
 5119:   white-space: nowrap;
 5120: }
 5121: 
 5122: span.LC_cusr_emph {
 5123:   font-style: italic;
 5124: }
 5125: 
 5126: span.LC_cusr_subheading {
 5127:   font-weight: normal;
 5128:   font-size: 85%;
 5129: }
 5130: 
 5131: table.LC_docs_documents {
 5132:   background: #BBBBBB;
 5133:   border-width: 0px;
 5134:   border-collapse: collapse;
 5135: }
 5136: 
 5137: table.LC_docs_documents td.LC_docs_document {
 5138:   border: 2px solid black;
 5139:   padding: 4px;
 5140: }
 5141: 
 5142: .LC_docs_course_commands div {
 5143:   float: left;
 5144:   border: 4px solid #AAAAAA;
 5145:   padding: 4px;
 5146:   background: #DDDDCC;
 5147: }
 5148: 
 5149: .LC_docs_entry_move {
 5150:   border: 0px;
 5151:   border-collapse: collapse;
 5152: }
 5153: 
 5154: .LC_docs_entry_move td {
 5155:   border: 2px solid #BBBBBB;
 5156:   background: #DDDDDD;
 5157: }
 5158: 
 5159: .LC_docs_editor td.LC_docs_entry_commands {
 5160:   background: #DDDDDD;
 5161:   font-size: x-small;
 5162: }
 5163: .LC_docs_copy {
 5164:   color: #000099;
 5165: }
 5166: .LC_docs_cut {
 5167:   color: #550044;
 5168: }
 5169: .LC_docs_rename {
 5170:   color: #009900;
 5171: }
 5172: .LC_docs_remove {
 5173:   color: #990000;
 5174: }
 5175: 
 5176: .LC_docs_reinit_warn,
 5177: .LC_docs_ext_edit {
 5178:   font-size: x-small;
 5179: }
 5180: 
 5181: .LC_docs_editor td.LC_docs_entry_title,
 5182: .LC_docs_editor td.LC_docs_entry_icon {
 5183:   background: #FFFFBB;
 5184: }
 5185: .LC_docs_editor td.LC_docs_entry_parameter {
 5186:   background: #BBBBFF;
 5187:   font-size: x-small;
 5188:   white-space: nowrap;
 5189: }
 5190: 
 5191: table.LC_docs_adddocs td,
 5192: table.LC_docs_adddocs th {
 5193:   border: 1px solid #BBBBBB;
 5194:   padding: 4px;
 5195:   background: #DDDDDD;
 5196: }
 5197: 
 5198: table.LC_sty_begin {
 5199:   background: #BBFFBB;
 5200: }
 5201: table.LC_sty_end {
 5202:   background: #FFBBBB;
 5203: }
 5204: 
 5205: table.LC_double_column {
 5206:   border-width: 0px;
 5207:   border-collapse: collapse;
 5208:   width: 100%;
 5209:   padding: 2px;
 5210: }
 5211: 
 5212: table.LC_double_column tr td.LC_left_col {
 5213:   top: 2px;
 5214:   left: 2px;
 5215:   width: 47%;
 5216:   vertical-align: top;
 5217: }
 5218: 
 5219: table.LC_double_column tr td.LC_right_col {
 5220:   top: 2px;
 5221:   right: 2px; 
 5222:   width: 47%;
 5223:   vertical-align: top;
 5224: }
 5225: 
 5226: span.LC_role_level {
 5227:   font-weight: bold;
 5228: }
 5229: 
 5230: div.LC_left_float {
 5231:   float: left;
 5232:   padding-right: 5%;
 5233:   padding-bottom: 4px;
 5234: }
 5235: 
 5236: div.LC_clear_float_header {
 5237:   padding-bottom: 2px;
 5238: }
 5239: 
 5240: div.LC_clear_float_footer {
 5241:   padding-top: 10px;
 5242:   clear: both;
 5243: }
 5244: 
 5245: 
 5246: div.LC_grade_select_mode {
 5247:   font-family: $sans;
 5248: }
 5249: div.LC_grade_select_mode div div {
 5250:   margin: 5px;
 5251: }
 5252: div.LC_grade_select_mode_selector {
 5253:   margin: 5px;
 5254:   float: left;
 5255: }
 5256: div.LC_grade_select_mode_selector_header {
 5257:   font: bold medium $sans;
 5258: }
 5259: div.LC_grade_select_mode_type {
 5260:   clear: left;
 5261: }
 5262: 
 5263: div.LC_grade_show_user {
 5264:   margin-top: 20px;
 5265:   border: 1px solid black;
 5266: }
 5267: div.LC_grade_user_name {
 5268:   background: #DDDDEE;
 5269:   border-bottom: 1px solid black;
 5270:   font: bold large $sans;
 5271: }
 5272: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5273:   background: #DDEEDD;
 5274: }
 5275: 
 5276: div.LC_grade_show_problem,
 5277: div.LC_grade_submissions,
 5278: div.LC_grade_message_center,
 5279: div.LC_grade_info_links,
 5280: div.LC_grade_assign {
 5281:   margin: 5px;
 5282:   width: 99%;
 5283:   background: #FFFFFF;
 5284: }
 5285: div.LC_grade_show_problem_header,
 5286: div.LC_grade_submissions_header,
 5287: div.LC_grade_message_center_header,
 5288: div.LC_grade_assign_header {
 5289:   font: bold large $sans;
 5290: }
 5291: div.LC_grade_show_problem_problem,
 5292: div.LC_grade_submissions_body,
 5293: div.LC_grade_message_center_body,
 5294: div.LC_grade_assign_body {
 5295:   border: 1px solid black;
 5296:   width: 99%;
 5297:   background: #FFFFFF;
 5298: }
 5299: span.LC_grade_check_note {
 5300:   font: normal medium $sans;
 5301:   display: inline;
 5302:   position: absolute;
 5303:   right: 1em;
 5304: }
 5305: 
 5306: table.LC_scantron_action {
 5307:   width: 100%;
 5308: }
 5309: table.LC_scantron_action tr th {
 5310:   font: normal bold $sans;
 5311: }
 5312: 
 5313: div.LC_edit_problem_header, 
 5314: div.LC_edit_problem_footer {
 5315:   font: normal medium $sans;
 5316:   margin: 2px;
 5317: }
 5318: div.LC_edit_problem_header,
 5319: div.LC_edit_problem_header div,
 5320: div.LC_edit_problem_footer,
 5321: div.LC_edit_problem_footer div,
 5322: div.LC_edit_problem_editxml_header,
 5323: div.LC_edit_problem_editxml_header div {
 5324:   margin-top: 5px;
 5325: }
 5326: div.LC_edit_problem_header_edit_row {
 5327:   background: $tabbg;
 5328:   padding: 3px;
 5329:   margin-bottom: 5px;
 5330: }
 5331: div.LC_edit_problem_header_title {
 5332:   font: larger bold $sans;
 5333:   background: $tabbg;
 5334:   padding: 3px;
 5335: }
 5336: table.LC_edit_problem_header_title {
 5337:   font: larger bold $sans;
 5338:   width: 100%;
 5339:   border-color: $pgbg;
 5340:   border-style: solid;
 5341:   border-width: $border;
 5342: 
 5343:   background: $tabbg;
 5344:   border-collapse: collapse;
 5345:   padding: 0px
 5346: }
 5347: 
 5348: div.LC_edit_problem_discards {
 5349:   float: left;
 5350:   padding-bottom: 5px;
 5351: }
 5352: div.LC_edit_problem_saves {
 5353:   float: right;
 5354:   padding-bottom: 5px;
 5355: }
 5356: hr.LC_edit_problem_divide {
 5357:   clear: both;
 5358:   color: $tabbg;
 5359:   background-color: $tabbg;
 5360:   height: 3px;
 5361:   border: 0px;
 5362: }
 5363: a.stift{
 5364:   border:none;
 5365: }
 5366: END
 5367: }
 5368: 
 5369: =pod
 5370: 
 5371: =item * &headtag()
 5372: 
 5373: Returns a uniform footer for LON-CAPA web pages.
 5374: 
 5375: Inputs: $title - optional title for the head
 5376:         $head_extra - optional extra HTML to put inside the <head>
 5377:         $args - optional arguments
 5378:             force_register - if is true call registerurl so the remote is 
 5379:                              informed
 5380:             redirect       -> array ref of
 5381:                                    1- seconds before redirect occurs
 5382:                                    2- url to redirect to
 5383:                                    3- whether the side effect should occur
 5384:                            (side effect of setting 
 5385:                                $env{'internal.head.redirect'} to the url 
 5386:                                redirected too)
 5387:             domain         -> force to color decorate a page for a specific
 5388:                                domain
 5389:             function       -> force usage of a specific rolish color scheme
 5390:             bgcolor        -> override the default page bgcolor
 5391:             no_auto_mt_title
 5392:                            -> prevent &mt()ing the title arg
 5393: 
 5394: =cut
 5395: 
 5396: sub headtag {
 5397:     my ($title,$head_extra,$args) = @_;
 5398:     
 5399:     my $function = $args->{'function'} || &get_users_function();
 5400:     my $domain   = $args->{'domain'}   || &determinedomain();
 5401:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5402:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5403: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5404: 		   #time(),
 5405: 		   $env{'environment.color.timestamp'},
 5406: 		   $function,$domain,$bgcolor);
 5407: 
 5408:     $url = '/adm/css/'.&escape($url).'.css';
 5409: 
 5410:     my $result =
 5411: 	'<head>'.
 5412: 	&font_settings();
 5413: 
 5414:     if (!$args->{'frameset'}) {
 5415: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5416:     }
 5417:     if ($args->{'force_register'}) {
 5418: 	$result .= &Apache::lonmenu::registerurl(1);
 5419:     }
 5420:     if (!$args->{'no_nav_bar'} 
 5421: 	&& !$args->{'only_body'}
 5422: 	&& !$args->{'frameset'}) {
 5423: 	$result .= &help_menu_js();
 5424:     }
 5425: 
 5426:     if (ref($args->{'redirect'})) {
 5427: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5428: 	$url = &Apache::lonenc::check_encrypt($url);
 5429: 	if (!$inhibit_continue) {
 5430: 	    $env{'internal.head.redirect'} = $url;
 5431: 	}
 5432: 	$result.=<<ADDMETA
 5433: <meta http-equiv="pragma" content="no-cache" />
 5434: <meta http-equiv="Refresh" content="$time; url=$url" />
 5435: ADDMETA
 5436:     }
 5437:     if (!defined($title)) {
 5438: 	$title = 'The LearningOnline Network with CAPA';
 5439:     }
 5440:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5441:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5442: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5443: 	.$head_extra;
 5444:     return $result;
 5445: }
 5446: 
 5447: =pod
 5448: 
 5449: =item * &font_settings()
 5450: 
 5451: Returns neccessary <meta> to set the proper encoding
 5452: 
 5453: Inputs: none
 5454: 
 5455: =cut
 5456: 
 5457: sub font_settings {
 5458:     my $headerstring='';
 5459:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5460: 	$headerstring.=
 5461: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5462:     }
 5463:     return $headerstring;
 5464: }
 5465: 
 5466: =pod
 5467: 
 5468: =item * &xml_begin()
 5469: 
 5470: Returns the needed doctype and <html>
 5471: 
 5472: Inputs: none
 5473: 
 5474: =cut
 5475: 
 5476: sub xml_begin {
 5477:     my $output='';
 5478: 
 5479:     if ($env{'internal.start_page'}==1) {
 5480: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5481:     }
 5482: 
 5483:     if ($env{'browser.mathml'}) {
 5484: 	$output='<?xml version="1.0"?>'
 5485:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5486: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5487:             
 5488: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
 5489: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
 5490:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5491: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5492:     } else {
 5493: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 5494:     }
 5495:     return $output;
 5496: }
 5497: 
 5498: =pod
 5499: 
 5500: =item * &endheadtag()
 5501: 
 5502: Returns a uniform </head> for LON-CAPA web pages.
 5503: 
 5504: Inputs: none
 5505: 
 5506: =cut
 5507: 
 5508: sub endheadtag {
 5509:     return '</head>';
 5510: }
 5511: 
 5512: =pod
 5513: 
 5514: =item * &head()
 5515: 
 5516: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5517: 
 5518: Inputs:
 5519: 
 5520: =over 4
 5521: 
 5522: $title - optional title for the page
 5523: 
 5524: $head_extra - optional extra HTML to put inside the <head>
 5525: 
 5526: =back
 5527: 
 5528: =cut
 5529: 
 5530: sub head {
 5531:     my ($title,$head_extra,$args) = @_;
 5532:     return &headtag($title,$head_extra,$args).&endheadtag();
 5533: }
 5534: 
 5535: =pod
 5536: 
 5537: =item * &start_page()
 5538: 
 5539: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5540: 
 5541: Inputs:
 5542: 
 5543: =over 4
 5544: 
 5545: $title - optional title for the page
 5546: 
 5547: $head_extra - optional extra HTML to incude inside the <head>
 5548: 
 5549: $args - additional optional args supported are:
 5550: 
 5551: =over 8
 5552: 
 5553:              only_body      -> is true will set &bodytag() onlybodytag
 5554:                                     arg on
 5555:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5556:              add_entries    -> additional attributes to add to the  <body>
 5557:              domain         -> force to color decorate a page for a 
 5558:                                     specific domain
 5559:              function       -> force usage of a specific rolish color
 5560:                                     scheme
 5561:              redirect       -> see &headtag()
 5562:              bgcolor        -> override the default page bg color
 5563:              js_ready       -> return a string ready for being used in 
 5564:                                     a javascript writeln
 5565:              html_encode    -> return a string ready for being used in 
 5566:                                     a html attribute
 5567:              force_register -> if is true will turn on the &bodytag()
 5568:                                     $forcereg arg
 5569:              body_title     -> alternate text to use instead of $title
 5570:                                     in the title box that appears, this text
 5571:                                     is not auto translated like the $title is
 5572:              frameset       -> if true will start with a <frameset>
 5573:                                     rather than <body>
 5574:              no_title       -> if true the title bar won't be shown
 5575:              skip_phases    -> hash ref of 
 5576:                                     head -> skip the <html><head> generation
 5577:                                     body -> skip all <body> generation
 5578:              no_inline_link -> if true and in remote mode, don't show the 
 5579:                                     'Switch To Inline Menu' link
 5580:              no_auto_mt_title -> prevent &mt()ing the title arg
 5581:              inherit_jsmath -> when creating popup window in a page,
 5582:                                     should it have jsmath forced on by the
 5583:                                     current page
 5584: 
 5585: =back
 5586: 
 5587: =back
 5588: 
 5589: =cut
 5590: 
 5591: sub start_page {
 5592:     my ($title,$head_extra,$args) = @_;
 5593:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5594:     my %head_args;
 5595:     foreach my $arg ('redirect','force_register','domain','function',
 5596: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5597: 		     'no_auto_mt_title') {
 5598: 	if (defined($args->{$arg})) {
 5599: 	    $head_args{$arg} = $args->{$arg};
 5600: 	}
 5601:     }
 5602: 
 5603:     $env{'internal.start_page'}++;
 5604:     my $result;
 5605:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 5606: 	$result.=
 5607: 	    &xml_begin().
 5608: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 5609:     }
 5610:     
 5611:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 5612: 	if ($args->{'frameset'}) {
 5613: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 5614: 						$args->{'add_entries'});
 5615: 	    $result .= "\n<frameset $attr_string>\n";
 5616: 	} else {
 5617: 	    $result .=
 5618: 		&bodytag($title, 
 5619: 			 $args->{'function'},       $args->{'add_entries'},
 5620: 			 $args->{'only_body'},      $args->{'domain'},
 5621: 			 $args->{'force_register'}, $args->{'body_title'},
 5622: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 5623: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 5624: 			 $args);
 5625: 	}
 5626:     }
 5627: 
 5628:     if ($args->{'js_ready'}) {
 5629: 	$result = &js_ready($result);
 5630:     }
 5631:     if ($args->{'html_encode'}) {
 5632: 	$result = &html_encode($result);
 5633:     }
 5634:     return $result;
 5635: }
 5636: 
 5637: 
 5638: =pod
 5639: 
 5640: =item * &head()
 5641: 
 5642: Returns a complete </body></html> section for LON-CAPA web pages.
 5643: 
 5644: Inputs:         $args - additional optional args supported are:
 5645:                  js_ready     -> return a string ready for being used in 
 5646:                                  a javascript writeln
 5647:                  html_encode  -> return a string ready for being used in 
 5648:                                  a html attribute
 5649:                  frameset     -> if true will start with a <frameset>
 5650:                                  rather than <body>
 5651:                  dicsussion   -> if true will get discussion from
 5652:                                   lonxml::xmlend
 5653:                                  (you can pass the target and parser arguments
 5654:                                   through optional 'target' and 'parser' args
 5655:                                   to this routine)
 5656: 
 5657: =cut
 5658: 
 5659: sub end_page {
 5660:     my ($args) = @_;
 5661:     $env{'internal.end_page'}++;
 5662:     my $result;
 5663:     if ($args->{'discussion'}) {
 5664: 	my ($target,$parser);
 5665: 	if (ref($args->{'discussion'})) {
 5666: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 5667: 				$args->{'discussion'}{'parser'});
 5668: 	}
 5669: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 5670:     }
 5671: 
 5672:     if ($args->{'frameset'}) {
 5673: 	$result .= '</frameset>';
 5674:     } else {
 5675: 	$result .= &endbodytag($args);
 5676:     }
 5677:     $result .= "\n</html>";
 5678: 
 5679:     if ($args->{'js_ready'}) {
 5680: 	$result = &js_ready($result);
 5681:     }
 5682: 
 5683:     if ($args->{'html_encode'}) {
 5684: 	$result = &html_encode($result);
 5685:     }
 5686: 
 5687:     return $result;
 5688: }
 5689: 
 5690: sub html_encode {
 5691:     my ($result) = @_;
 5692: 
 5693:     $result = &HTML::Entities::encode($result,'<>&"');
 5694:     
 5695:     return $result;
 5696: }
 5697: sub js_ready {
 5698:     my ($result) = @_;
 5699: 
 5700:     $result =~ s/[\n\r]/ /xmsg;
 5701:     $result =~ s/\\/\\\\/xmsg;
 5702:     $result =~ s/'/\\'/xmsg;
 5703:     $result =~ s{</}{<\\/}xmsg;
 5704:     
 5705:     return $result;
 5706: }
 5707: 
 5708: sub validate_page {
 5709:     if (  exists($env{'internal.start_page'})
 5710: 	  &&     $env{'internal.start_page'} > 1) {
 5711: 	&Apache::lonnet::logthis('start_page called multiple times '.
 5712: 				 $env{'internal.start_page'}.' '.
 5713: 				 $ENV{'request.filename'});
 5714:     }
 5715:     if (  exists($env{'internal.end_page'})
 5716: 	  &&     $env{'internal.end_page'} > 1) {
 5717: 	&Apache::lonnet::logthis('end_page called multiple times '.
 5718: 				 $env{'internal.end_page'}.' '.
 5719: 				 $env{'request.filename'});
 5720:     }
 5721:     if (     exists($env{'internal.start_page'})
 5722: 	&& ! exists($env{'internal.end_page'})) {
 5723: 	&Apache::lonnet::logthis('start_page called without end_page '.
 5724: 				 $env{'request.filename'});
 5725:     }
 5726:     if (   ! exists($env{'internal.start_page'})
 5727: 	&&   exists($env{'internal.end_page'})) {
 5728: 	&Apache::lonnet::logthis('end_page called without start_page'.
 5729: 				 $env{'request.filename'});
 5730:     }
 5731: }
 5732: 
 5733: sub simple_error_page {
 5734:     my ($r,$title,$msg) = @_;
 5735:     my $page =
 5736: 	&Apache::loncommon::start_page($title).
 5737: 	&mt($msg).
 5738: 	&Apache::loncommon::end_page();
 5739:     if (ref($r)) {
 5740: 	$r->print($page);
 5741: 	return;
 5742:     }
 5743:     return $page;
 5744: }
 5745: 
 5746: {
 5747:     my @row_count;
 5748:     sub start_data_table {
 5749: 	my ($add_class) = @_;
 5750: 	my $css_class = (join(' ','LC_data_table',$add_class));
 5751: 	unshift(@row_count,0);
 5752: 	return '<table class="'.$css_class.'">'."\n";
 5753:     }
 5754: 
 5755:     sub end_data_table {
 5756: 	shift(@row_count);
 5757: 	return '</table>'."\n";;
 5758:     }
 5759: 
 5760:     sub start_data_table_row {
 5761: 	my ($add_class) = @_;
 5762: 	$row_count[0]++;
 5763: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5764: 	$css_class = (join(' ',$css_class,$add_class));
 5765: 	return  '<tr class="'.$css_class.'">'."\n";;
 5766:     }
 5767:     
 5768:     sub continue_data_table_row {
 5769: 	my ($add_class) = @_;
 5770: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5771: 	$css_class = (join(' ',$css_class,$add_class));
 5772: 	return  '<tr class="'.$css_class.'">'."\n";;
 5773:     }
 5774: 
 5775:     sub end_data_table_row {
 5776: 	return '</tr>'."\n";;
 5777:     }
 5778: 
 5779:     sub start_data_table_empty_row {
 5780: 	$row_count[0]++;
 5781: 	return  '<tr class="LC_empty_row" >'."\n";;
 5782:     }
 5783: 
 5784:     sub end_data_table_empty_row {
 5785: 	return '</tr>'."\n";;
 5786:     }
 5787: 
 5788:     sub start_data_table_header_row {
 5789: 	return  '<tr class="LC_header_row">'."\n";;
 5790:     }
 5791: 
 5792:     sub end_data_table_header_row {
 5793: 	return '</tr>'."\n";;
 5794:     }
 5795: }
 5796: 
 5797: =pod
 5798: 
 5799: =item * &inhibit_menu_check($arg)
 5800: 
 5801: Checks for a inhibitmenu state and generates output to preserve it
 5802: 
 5803: Inputs:         $arg - can be any of
 5804:                      - undef - in which case the return value is a string 
 5805:                                to add  into arguments list of a uri
 5806:                      - 'input' - in which case the return value is a HTML
 5807:                                  <form> <input> field of type hidden to
 5808:                                  preserve the value
 5809:                      - a url - in which case the return value is the url with
 5810:                                the neccesary cgi args added to preserve the
 5811:                                inhibitmenu state
 5812:                      - a ref to a url - no return value, but the string is
 5813:                                         updated to include the neccessary cgi
 5814:                                         args to preserve the inhibitmenu state
 5815: 
 5816: =cut
 5817: 
 5818: sub inhibit_menu_check {
 5819:     my ($arg) = @_;
 5820:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5821:     if ($arg eq 'input') {
 5822: 	if ($env{'form.inhibitmenu'}) {
 5823: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 5824: 	} else {
 5825: 	    return
 5826: 	}
 5827:     }
 5828:     if ($env{'form.inhibitmenu'}) {
 5829: 	if (ref($arg)) {
 5830: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5831: 	} elsif ($arg eq '') {
 5832: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 5833: 	} else {
 5834: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5835: 	}
 5836:     }
 5837:     if (!ref($arg)) {
 5838: 	return $arg;
 5839:     }
 5840: }
 5841: 
 5842: ###############################################
 5843: 
 5844: =pod
 5845: 
 5846: =back
 5847: 
 5848: =head1 User Information Routines
 5849: 
 5850: =over 4
 5851: 
 5852: =item * &get_users_function()
 5853: 
 5854: Used by &bodytag to determine the current users primary role.
 5855: Returns either 'student','coordinator','admin', or 'author'.
 5856: 
 5857: =cut
 5858: 
 5859: ###############################################
 5860: sub get_users_function {
 5861:     my $function = 'student';
 5862:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 5863:         $function='coordinator';
 5864:     }
 5865:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 5866:         $function='admin';
 5867:     }
 5868:     if (($env{'request.role'}=~/^(au|ca)/) ||
 5869:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 5870:         $function='author';
 5871:     }
 5872:     return $function;
 5873: }
 5874: 
 5875: ###############################################
 5876: 
 5877: =pod
 5878: 
 5879: =item * &check_user_status()
 5880: 
 5881: Determines current status of supplied role for a
 5882: specific user. Roles can be active, previous or future.
 5883: 
 5884: Inputs: 
 5885: user's domain, user's username, course's domain,
 5886: course's number, optional section ID.
 5887: 
 5888: Outputs:
 5889: role status: active, previous or future. 
 5890: 
 5891: =cut
 5892: 
 5893: sub check_user_status {
 5894:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 5895:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 5896:     my @uroles = keys %userinfo;
 5897:     my $srchstr;
 5898:     my $active_chk = 'none';
 5899:     my $now = time;
 5900:     if (@uroles > 0) {
 5901:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 5902:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 5903:         } else {
 5904:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 5905:         }
 5906:         if (grep/^\Q$srchstr\E$/,@uroles) {
 5907:             my $role_end = 0;
 5908:             my $role_start = 0;
 5909:             $active_chk = 'active';
 5910:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 5911:                 $role_end = $1;
 5912:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 5913:                     $role_start = $1;
 5914:                 }
 5915:             }
 5916:             if ($role_start > 0) {
 5917:                 if ($now < $role_start) {
 5918:                     $active_chk = 'future';
 5919:                 }
 5920:             }
 5921:             if ($role_end > 0) {
 5922:                 if ($now > $role_end) {
 5923:                     $active_chk = 'previous';
 5924:                 }
 5925:             }
 5926:         }
 5927:     }
 5928:     return $active_chk;
 5929: }
 5930: 
 5931: ###############################################
 5932: 
 5933: =pod
 5934: 
 5935: =item * &get_sections()
 5936: 
 5937: Determines all the sections for a course including
 5938: sections with students and sections containing other roles.
 5939: Incoming parameters: 
 5940: 
 5941: 1. domain
 5942: 2. course number 
 5943: 3. reference to array containing roles for which sections should 
 5944: be gathered (optional).
 5945: 4. reference to array containing status types for which sections 
 5946: should be gathered (optional).
 5947: 
 5948: If the third argument is undefined, sections are gathered for any role. 
 5949: If the fourth argument is undefined, sections are gathered for any status.
 5950: Permissible values are 'active' or 'future' or 'previous'.
 5951:  
 5952: Returns section hash (keys are section IDs, values are
 5953: number of users in each section), subject to the
 5954: optional roles filter, optional status filter 
 5955: 
 5956: =cut
 5957: 
 5958: ###############################################
 5959: sub get_sections {
 5960:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 5961:     if (!defined($cdom) || !defined($cnum)) {
 5962:         my $cid =  $env{'request.course.id'};
 5963: 
 5964: 	return if (!defined($cid));
 5965: 
 5966:         $cdom = $env{'course.'.$cid.'.domain'};
 5967:         $cnum = $env{'course.'.$cid.'.num'};
 5968:     }
 5969: 
 5970:     my %sectioncount;
 5971:     my $now = time;
 5972: 
 5973:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 5974: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 5975: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 5976: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 5977:         my $start_index = &Apache::loncoursedata::CL_START();
 5978:         my $end_index = &Apache::loncoursedata::CL_END();
 5979:         my $status;
 5980: 	while (my ($student,$data) = each(%$classlist)) {
 5981: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 5982: 				                     $data->[$status_index],
 5983:                                                      $data->[$start_index],
 5984:                                                      $data->[$end_index]);
 5985:             if ($stu_status eq 'Active') {
 5986:                 $status = 'active';
 5987:             } elsif ($end < $now) {
 5988:                 $status = 'previous';
 5989:             } elsif ($start > $now) {
 5990:                 $status = 'future';
 5991:             } 
 5992: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 5993:                 if ((!defined($possible_status)) || (($status ne '') && 
 5994:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 5995: 		    $sectioncount{$section}++;
 5996:                 }
 5997: 	    }
 5998: 	}
 5999:     }
 6000:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6001:     foreach my $user (sort(keys(%courseroles))) {
 6002: 	if ($user !~ /^(\w{2})/) { next; }
 6003: 	my ($role) = ($user =~ /^(\w{2})/);
 6004: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6005: 	my ($section,$status);
 6006: 	if ($role eq 'cr' &&
 6007: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6008: 	    $section=$1;
 6009: 	}
 6010: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6011: 	if (!defined($section) || $section eq '-1') { next; }
 6012:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6013:         if ($end == -1 && $start == -1) {
 6014:             next; #deleted role
 6015:         }
 6016:         if (!defined($possible_status)) { 
 6017:             $sectioncount{$section}++;
 6018:         } else {
 6019:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6020:                 $status = 'active';
 6021:             } elsif ($end < $now) {
 6022:                 $status = 'future';
 6023:             } elsif ($start > $now) {
 6024:                 $status = 'previous';
 6025:             }
 6026:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6027:                 $sectioncount{$section}++;
 6028:             }
 6029:         }
 6030:     }
 6031:     return %sectioncount;
 6032: }
 6033: 
 6034: ###############################################
 6035: 
 6036: =pod
 6037: 
 6038: =item * &get_course_users()
 6039: 
 6040: Retrieves usernames:domains for users in the specified course
 6041: with specific role(s), and access status. 
 6042: 
 6043: Incoming parameters:
 6044: 1. course domain
 6045: 2. course number
 6046: 3. access status: users must have - either active, 
 6047: previous, future, or all.
 6048: 4. reference to array of permissible roles
 6049: 5. reference to array of section restrictions (optional)
 6050: 6. reference to results object (hash of hashes).
 6051: 7. reference to optional userdata hash
 6052: 8. reference to optional statushash
 6053: 9. flag if privileged users (except those set to unhide in
 6054:    course settings) should be excluded    
 6055: Keys of top level results hash are roles.
 6056: Keys of inner hashes are username:domain, with 
 6057: values set to access type.
 6058: Optional userdata hash returns an array with arguments in the 
 6059: same order as loncoursedata::get_classlist() for student data.
 6060: 
 6061: Optional statushash returns
 6062: 
 6063: Entries for end, start, section and status are blank because
 6064: of the possibility of multiple values for non-student roles.
 6065: 
 6066: =cut
 6067: 
 6068: ###############################################
 6069: 
 6070: sub get_course_users {
 6071:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6072:     my %idx = ();
 6073:     my %seclists;
 6074: 
 6075:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6076:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6077:     $idx{end} = &Apache::loncoursedata::CL_END();
 6078:     $idx{start} = &Apache::loncoursedata::CL_START();
 6079:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6080:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6081:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6082:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6083: 
 6084:     if (grep(/^st$/,@{$roles})) {
 6085:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6086:         my $now = time;
 6087:         foreach my $student (keys(%{$classlist})) {
 6088:             my $match = 0;
 6089:             my $secmatch = 0;
 6090:             my $section = $$classlist{$student}[$idx{section}];
 6091:             my $status = $$classlist{$student}[$idx{status}];
 6092:             if ($section eq '') {
 6093:                 $section = 'none';
 6094:             }
 6095:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6096:                 if (grep(/^all$/,@{$sections})) {
 6097:                     $secmatch = 1;
 6098:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6099:                     if (grep(/^none$/,@{$sections})) {
 6100:                         $secmatch = 1;
 6101:                     }
 6102:                 } else {  
 6103: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6104: 		        $secmatch = 1;
 6105:                     }
 6106: 		}
 6107:                 if (!$secmatch) {
 6108:                     next;
 6109:                 }
 6110:             }
 6111:             if (defined($$types{'active'})) {
 6112:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6113:                     push(@{$$users{st}{$student}},'active');
 6114:                     $match = 1;
 6115:                 }
 6116:             }
 6117:             if (defined($$types{'previous'})) {
 6118:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6119:                     push(@{$$users{st}{$student}},'previous');
 6120:                     $match = 1;
 6121:                 }
 6122:             }
 6123:             if (defined($$types{'future'})) {
 6124:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6125:                     push(@{$$users{st}{$student}},'future');
 6126:                     $match = 1;
 6127:                 }
 6128:             }
 6129:             if ($match) {
 6130:                 push(@{$seclists{$student}},$section);
 6131:                 if (ref($userdata) eq 'HASH') {
 6132:                     $$userdata{$student} = $$classlist{$student};
 6133:                 }
 6134:                 if (ref($statushash) eq 'HASH') {
 6135:                     $statushash->{$student}{'st'}{$section} = $status;
 6136:                 }
 6137:             }
 6138:         }
 6139:     }
 6140:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6141:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6142:         my $now = time;
 6143:         my %displaystatus = ( previous => 'Expired',
 6144:                               active   => 'Active',
 6145:                               future   => 'Future',
 6146:                             );
 6147:         my %nothide;
 6148:         if ($hidepriv) {
 6149:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6150:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6151:                 if ($user !~ /:/) {
 6152:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6153:                 } else {
 6154:                     $nothide{$user} = 1;
 6155:                 }
 6156:             }
 6157:         }
 6158:         foreach my $person (sort(keys(%coursepersonnel))) {
 6159:             my $match = 0;
 6160:             my $secmatch = 0;
 6161:             my $status;
 6162:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6163:             $user =~ s/:$//;
 6164:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6165:             if ($end == -1 || $start == -1) {
 6166:                 next;
 6167:             }
 6168:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6169:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6170:                 my ($uname,$udom) = split(/:/,$user);
 6171:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6172:                     if (grep(/^all$/,@{$sections})) {
 6173:                         $secmatch = 1;
 6174:                     } elsif ($usec eq '') {
 6175:                         if (grep(/^none$/,@{$sections})) {
 6176:                             $secmatch = 1;
 6177:                         }
 6178:                     } else {
 6179:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6180:                             $secmatch = 1;
 6181:                         }
 6182:                     }
 6183:                     if (!$secmatch) {
 6184:                         next;
 6185:                     }
 6186:                 }
 6187:                 if ($usec eq '') {
 6188:                     $usec = 'none';
 6189:                 }
 6190:                 if ($uname ne '' && $udom ne '') {
 6191:                     if ($hidepriv) {
 6192:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6193:                             (!$nothide{$uname.':'.$udom})) {
 6194:                             next;
 6195:                         }
 6196:                     }
 6197:                     if ($end > 0 && $end < $now) {
 6198:                         $status = 'previous';
 6199:                     } elsif ($start > $now) {
 6200:                         $status = 'future';
 6201:                     } else {
 6202:                         $status = 'active';
 6203:                     }
 6204:                     foreach my $type (keys(%{$types})) { 
 6205:                         if ($status eq $type) {
 6206:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6207:                                 push(@{$$users{$role}{$user}},$type);
 6208:                             }
 6209:                             $match = 1;
 6210:                         }
 6211:                     }
 6212:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6213:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6214: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6215:                         }
 6216:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6217:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6218:                         }
 6219:                         if (ref($statushash) eq 'HASH') {
 6220:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6221:                         }
 6222:                     }
 6223:                 }
 6224:             }
 6225:         }
 6226:         if (grep(/^ow$/,@{$roles})) {
 6227:             if ((defined($cdom)) && (defined($cnum))) {
 6228:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6229:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6230:                     my $owner = $csettings{'internal.courseowner'};
 6231:                     next if ($owner eq '');
 6232:                     my ($ownername,$ownerdom);
 6233:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6234:                         $ownername = $1;
 6235:                         $ownerdom = $2;
 6236:                     } else {
 6237:                         $ownername = $owner;
 6238:                         $ownerdom = $cdom;
 6239:                         $owner = $ownername.':'.$ownerdom;
 6240:                     }
 6241:                     @{$$users{'ow'}{$owner}} = 'any';
 6242:                     if (defined($userdata) && 
 6243: 			!exists($$userdata{$owner})) {
 6244: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6245:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6246:                             push(@{$seclists{$owner}},'none');
 6247:                         }
 6248:                         if (ref($statushash) eq 'HASH') {
 6249:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6250:                         }
 6251: 		    }
 6252:                 }
 6253:             }
 6254:         }
 6255:         foreach my $user (keys(%seclists)) {
 6256:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6257:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6258:         }
 6259:     }
 6260:     return;
 6261: }
 6262: 
 6263: sub get_user_info {
 6264:     my ($udom,$uname,$idx,$userdata) = @_;
 6265:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6266: 	&plainname($uname,$udom,'lastname');
 6267:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6268:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6269:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6270:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6271:     return;
 6272: }
 6273: 
 6274: ###############################################
 6275: 
 6276: =pod
 6277: 
 6278: =item * &get_user_quota()
 6279: 
 6280: Retrieves quota assigned for storage of portfolio files for a user  
 6281: 
 6282: Incoming parameters:
 6283: 1. user's username
 6284: 2. user's domain
 6285: 
 6286: Returns:
 6287: 1. Disk quota (in Mb) assigned to student.
 6288: 2. (Optional) Type of setting: custom or default
 6289:    (individually assigned or default for user's 
 6290:    institutional status).
 6291: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6292:    or student - types as defined in localenroll::inst_usertypes 
 6293:    for user's domain, which determines default quota for user.
 6294: 4. (Optional) - Default quota which would apply to the user.
 6295: 
 6296: If a value has been stored in the user's environment, 
 6297: it will return that, otherwise it returns the maximal default
 6298: defined for the user's instituional status(es) in the domain.
 6299: 
 6300: =cut
 6301: 
 6302: ###############################################
 6303: 
 6304: 
 6305: sub get_user_quota {
 6306:     my ($uname,$udom) = @_;
 6307:     my ($quota,$quotatype,$settingstatus,$defquota);
 6308:     if (!defined($udom)) {
 6309:         $udom = $env{'user.domain'};
 6310:     }
 6311:     if (!defined($uname)) {
 6312:         $uname = $env{'user.name'};
 6313:     }
 6314:     if (($udom eq '' || $uname eq '') ||
 6315:         ($udom eq 'public') && ($uname eq 'public')) {
 6316:         $quota = 0;
 6317:         $quotatype = 'default';
 6318:         $defquota = 0; 
 6319:     } else {
 6320:         my $inststatus;
 6321:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6322:             $quota = $env{'environment.portfolioquota'};
 6323:             $inststatus = $env{'environment.inststatus'};
 6324:         } else {
 6325:             my %userenv = 
 6326:                 &Apache::lonnet::get('environment',['portfolioquota',
 6327:                                      'inststatus'],$udom,$uname);
 6328:             my ($tmp) = keys(%userenv);
 6329:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6330:                 $quota = $userenv{'portfolioquota'};
 6331:                 $inststatus = $userenv{'inststatus'};
 6332:             } else {
 6333:                 undef(%userenv);
 6334:             }
 6335:         }
 6336:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6337:         if ($quota eq '') {
 6338:             $quota = $defquota;
 6339:             $quotatype = 'default';
 6340:         } else {
 6341:             $quotatype = 'custom';
 6342:         }
 6343:     }
 6344:     if (wantarray) {
 6345:         return ($quota,$quotatype,$settingstatus,$defquota);
 6346:     } else {
 6347:         return $quota;
 6348:     }
 6349: }
 6350: 
 6351: ###############################################
 6352: 
 6353: =pod
 6354: 
 6355: =item * &default_quota()
 6356: 
 6357: Retrieves default quota assigned for storage of user portfolio files,
 6358: given an (optional) user's institutional status.
 6359: 
 6360: Incoming parameters:
 6361: 1. domain
 6362: 2. (Optional) institutional status(es).  This is a : separated list of 
 6363:    status types (e.g., faculty, staff, student etc.)
 6364:    which apply to the user for whom the default is being retrieved.
 6365:    If the institutional status string in undefined, the domain
 6366:    default quota will be returned. 
 6367: 
 6368: Returns:
 6369: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6370: 2. (Optional) institutional type which determined the value of the
 6371:    default quota.
 6372: 
 6373: If a value has been stored in the domain's configuration db,
 6374: it will return that, otherwise it returns 20 (for backwards 
 6375: compatibility with domains which have not set up a configuration
 6376: db file; the original statically defined portfolio quota was 20 Mb). 
 6377: 
 6378: If the user's status includes multiple types (e.g., staff and student),
 6379: the largest default quota which applies to the user determines the
 6380: default quota returned.
 6381: 
 6382: =cut
 6383: 
 6384: ###############################################
 6385: 
 6386: 
 6387: sub default_quota {
 6388:     my ($udom,$inststatus) = @_;
 6389:     my ($defquota,$settingstatus);
 6390:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6391:                                             ['quotas'],$udom);
 6392:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6393:         if ($inststatus ne '') {
 6394:             my @statuses = split(/:/,$inststatus);
 6395:             foreach my $item (@statuses) {
 6396:                 if ($quotahash{'quotas'}{$item} ne '') {
 6397:                     if ($defquota eq '') {
 6398:                         $defquota = $quotahash{'quotas'}{$item};
 6399:                         $settingstatus = $item;
 6400:                     } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6401:                         $defquota = $quotahash{'quotas'}{$item};
 6402:                         $settingstatus = $item;
 6403:                     }
 6404:                 }
 6405:             }
 6406:         }
 6407:         if ($defquota eq '') {
 6408:             $defquota = $quotahash{'quotas'}{'default'};
 6409:             $settingstatus = 'default';
 6410:         }
 6411:     } else {
 6412:         $settingstatus = 'default';
 6413:         $defquota = 20;
 6414:     }
 6415:     if (wantarray) {
 6416:         return ($defquota,$settingstatus);
 6417:     } else {
 6418:         return $defquota;
 6419:     }
 6420: }
 6421: 
 6422: sub get_secgrprole_info {
 6423:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6424:     my %sections_count = &get_sections($cdom,$cnum);
 6425:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6426:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6427:     my @groups = sort(keys(%curr_groups));
 6428:     my $allroles = [];
 6429:     my $rolehash;
 6430:     my $accesshash = {
 6431:                      active => 'Currently has access',
 6432:                      future => 'Will have future access',
 6433:                      previous => 'Previously had access',
 6434:                   };
 6435:     if ($needroles) {
 6436:         $rolehash = {'all' => 'all'};
 6437:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6438: 	if (&Apache::lonnet::error(%user_roles)) {
 6439: 	    undef(%user_roles);
 6440: 	}
 6441:         foreach my $item (keys(%user_roles)) {
 6442:             my ($role)=split(/\:/,$item,2);
 6443:             if ($role eq 'cr') { next; }
 6444:             if ($role =~ /^cr/) {
 6445:                 $$rolehash{$role} = (split('/',$role))[3];
 6446:             } else {
 6447:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6448:             }
 6449:         }
 6450:         foreach my $key (sort(keys(%{$rolehash}))) {
 6451:             push(@{$allroles},$key);
 6452:         }
 6453:         push (@{$allroles},'st');
 6454:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6455:     }
 6456:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6457: }
 6458: 
 6459: sub user_picker {
 6460:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6461:     my $currdom = $dom;
 6462:     my %curr_selected = (
 6463:                         srchin => 'dom',
 6464:                         srchby => 'lastname',
 6465:                       );
 6466:     my $srchterm;
 6467:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6468:         if ($srch->{'srchby'} ne '') {
 6469:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6470:         }
 6471:         if ($srch->{'srchin'} ne '') {
 6472:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6473:         }
 6474:         if ($srch->{'srchtype'} ne '') {
 6475:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6476:         }
 6477:         if ($srch->{'srchdomain'} ne '') {
 6478:             $currdom = $srch->{'srchdomain'};
 6479:         }
 6480:         $srchterm = $srch->{'srchterm'};
 6481:     }
 6482:     my %lt=&Apache::lonlocal::texthash(
 6483:                     'usr'       => 'Search criteria',
 6484:                     'doma'      => 'Domain/institution to search',
 6485:                     'uname'     => 'username',
 6486:                     'lastname'  => 'last name',
 6487:                     'lastfirst' => 'last name, first name',
 6488:                     'crs'       => 'in this course',
 6489:                     'dom'       => 'in selected LON-CAPA domain', 
 6490:                     'alc'       => 'all LON-CAPA',
 6491:                     'instd'     => 'in institutional directory for selected domain',
 6492:                     'exact'     => 'is',
 6493:                     'contains'  => 'contains',
 6494:                     'begins'    => 'begins with',
 6495:                     'youm'      => "You must include some text to search for.",
 6496:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6497:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6498:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6499:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6500:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6501:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6502:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6503:                                        );
 6504:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6505:     my $srchinsel = ' <select name="srchin">';
 6506: 
 6507:     my @srchins = ('crs','dom','alc','instd');
 6508: 
 6509:     foreach my $option (@srchins) {
 6510:         # FIXME 'alc' option unavailable until 
 6511:         #       loncreateuser::print_user_query_page()
 6512:         #       has been completed.
 6513:         next if ($option eq 'alc');
 6514:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6515:         if ($curr_selected{'srchin'} eq $option) {
 6516:             $srchinsel .= ' 
 6517:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6518:         } else {
 6519:             $srchinsel .= '
 6520:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6521:         }
 6522:     }
 6523:     $srchinsel .= "\n  </select>\n";
 6524: 
 6525:     my $srchbysel =  ' <select name="srchby">';
 6526:     foreach my $option ('lastname','lastfirst','uname') {
 6527:         if ($curr_selected{'srchby'} eq $option) {
 6528:             $srchbysel .= '
 6529:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6530:         } else {
 6531:             $srchbysel .= '
 6532:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6533:          }
 6534:     }
 6535:     $srchbysel .= "\n  </select>\n";
 6536: 
 6537:     my $srchtypesel = ' <select name="srchtype">';
 6538:     foreach my $option ('begins','contains','exact') {
 6539:         if ($curr_selected{'srchtype'} eq $option) {
 6540:             $srchtypesel .= '
 6541:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6542:         } else {
 6543:             $srchtypesel .= '
 6544:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6545:         }
 6546:     }
 6547:     $srchtypesel .= "\n  </select>\n";
 6548: 
 6549:     my ($newuserscript,$new_user_create);
 6550: 
 6551:     if ($forcenewuser) {
 6552:         if (ref($srch) eq 'HASH') {
 6553:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 6554:                 if ($cancreate) {
 6555:                     $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
 6556:                 } else {
 6557:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6558:                     my %usertypetext = (
 6559:                         official   => 'institutional',
 6560:                         unofficial => 'non-institutional',
 6561:                     );
 6562:                     $new_user_create = '<br /><span class="LC_warning">'.&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.&mt('Contact the <a[_1]>helpdesk</a> for assistance.',$helplink).'</span><br /><br />';
 6563:                 }
 6564:             }
 6565:         }
 6566: 
 6567:         $newuserscript = <<"ENDSCRIPT";
 6568: 
 6569: function setSearch(createnew,callingForm) {
 6570:     if (createnew == 1) {
 6571:         for (var i=0; i<callingForm.srchby.length; i++) {
 6572:             if (callingForm.srchby.options[i].value == 'uname') {
 6573:                 callingForm.srchby.selectedIndex = i;
 6574:             }
 6575:         }
 6576:         for (var i=0; i<callingForm.srchin.length; i++) {
 6577:             if ( callingForm.srchin.options[i].value == 'dom') {
 6578: 		callingForm.srchin.selectedIndex = i;
 6579:             }
 6580:         }
 6581:         for (var i=0; i<callingForm.srchtype.length; i++) {
 6582:             if (callingForm.srchtype.options[i].value == 'exact') {
 6583:                 callingForm.srchtype.selectedIndex = i;
 6584:             }
 6585:         }
 6586:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 6587:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 6588:                 callingForm.srchdomain.selectedIndex = i;
 6589:             }
 6590:         }
 6591:     }
 6592: }
 6593: ENDSCRIPT
 6594: 
 6595:     }
 6596: 
 6597:     my $output = <<"END_BLOCK";
 6598: <script type="text/javascript">
 6599: function validateEntry(callingForm) {
 6600: 
 6601:     var checkok = 1;
 6602:     var srchin;
 6603:     for (var i=0; i<callingForm.srchin.length; i++) {
 6604: 	if ( callingForm.srchin[i].checked ) {
 6605: 	    srchin = callingForm.srchin[i].value;
 6606: 	}
 6607:     }
 6608: 
 6609:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 6610:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 6611:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 6612:     var srchterm =  callingForm.srchterm.value;
 6613:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 6614:     var msg = "";
 6615: 
 6616:     if (srchterm == "") {
 6617:         checkok = 0;
 6618:         msg += "$lt{'youm'}\\n";
 6619:     }
 6620: 
 6621:     if (srchtype== 'begins') {
 6622:         if (srchterm.length < 2) {
 6623:             checkok = 0;
 6624:             msg += "$lt{'thte'}\\n";
 6625:         }
 6626:     }
 6627: 
 6628:     if (srchtype== 'contains') {
 6629:         if (srchterm.length < 3) {
 6630:             checkok = 0;
 6631:             msg += "$lt{'thet'}\\n";
 6632:         }
 6633:     }
 6634:     if (srchin == 'instd') {
 6635:         if (srchdomain == '') {
 6636:             checkok = 0;
 6637:             msg += "$lt{'yomc'}\\n";
 6638:         }
 6639:     }
 6640:     if (srchin == 'dom') {
 6641:         if (srchdomain == '') {
 6642:             checkok = 0;
 6643:             msg += "$lt{'ymcd'}\\n";
 6644:         }
 6645:     }
 6646:     if (srchby == 'lastfirst') {
 6647:         if (srchterm.indexOf(",") == -1) {
 6648:             checkok = 0;
 6649:             msg += "$lt{'whus'}\\n";
 6650:         }
 6651:         if (srchterm.indexOf(",") == srchterm.length -1) {
 6652:             checkok = 0;
 6653:             msg += "$lt{'whse'}\\n";
 6654:         }
 6655:     }
 6656:     if (checkok == 0) {
 6657:         alert("$lt{'thfo'}\\n"+msg);
 6658:         return;
 6659:     }
 6660:     if (checkok == 1) {
 6661:         callingForm.submit();
 6662:     }
 6663: }
 6664: 
 6665: $newuserscript
 6666: 
 6667: </script>
 6668: 
 6669: $new_user_create
 6670: 
 6671: <table>
 6672:  <tr>
 6673:   <td>$lt{'doma'}:</td>
 6674:   <td>$domform</td>
 6675:   </td>
 6676:  </tr>
 6677:  <tr>
 6678:   <td>$lt{'usr'}:</td>
 6679:   <td>$srchbysel
 6680:       $srchtypesel 
 6681:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 6682:       $srchinsel 
 6683:   </td>
 6684:  </tr>
 6685: </table>
 6686: <br />
 6687: END_BLOCK
 6688: 
 6689:     return $output;
 6690: }
 6691: 
 6692: sub user_rule_check {
 6693:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 6694:     my $response;
 6695:     if (ref($usershash) eq 'HASH') {
 6696:         foreach my $user (keys(%{$usershash})) {
 6697:             my ($uname,$udom) = split(/:/,$user);
 6698:             next if ($udom eq '' || $uname eq '');
 6699:             my ($id,$newuser);
 6700:             if (ref($usershash->{$user}) eq 'HASH') {
 6701:                 $newuser = $usershash->{$user}->{'newuser'};
 6702:                 $id = $usershash->{$user}->{'id'};
 6703:             }
 6704:             my $inst_response;
 6705:             if (ref($checks) eq 'HASH') {
 6706:                 if (defined($checks->{'username'})) {
 6707:                     ($inst_response,%{$inst_results->{$user}}) = 
 6708:                         &Apache::lonnet::get_instuser($udom,$uname);
 6709:                 } elsif (defined($checks->{'id'})) {
 6710:                     ($inst_response,%{$inst_results->{$user}}) =
 6711:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 6712:                 }
 6713:             } else {
 6714:                 ($inst_response,%{$inst_results->{$user}}) =
 6715:                     &Apache::lonnet::get_instuser($udom,$uname);
 6716:                 return;
 6717:             }
 6718:             if (!$got_rules->{$udom}) {
 6719:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 6720:                                                   ['usercreation'],$udom);
 6721:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6722:                     foreach my $item ('username','id') {
 6723:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 6724:                             $$curr_rules{$udom}{$item} = 
 6725:                                 $domconfig{'usercreation'}{$item.'_rule'};
 6726:                         }
 6727:                     }
 6728:                 }
 6729:                 $got_rules->{$udom} = 1;  
 6730:             }
 6731:             foreach my $item (keys(%{$checks})) {
 6732:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 6733:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 6734:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 6735:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 6736:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 6737:                                 if ($rule_check{$rule}) {
 6738:                                     $$rulematch{$user}{$item} = $rule;
 6739:                                     if ($inst_response eq 'ok') {
 6740:                                         if (ref($inst_results) eq 'HASH') {
 6741:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 6742:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 6743:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 6744:                                                 }
 6745:                                             }
 6746:                                         }
 6747:                                     }
 6748:                                     last;
 6749:                                 }
 6750:                             }
 6751:                         }
 6752:                     }
 6753:                 }
 6754:             }
 6755:         }
 6756:     }
 6757:     return;
 6758: }
 6759: 
 6760: sub user_rule_formats {
 6761:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 6762:     my %text = ( 
 6763:                  'username' => 'Usernames',
 6764:                  'id'       => 'IDs',
 6765:                );
 6766:     my $output;
 6767:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 6768:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 6769:         if (@{$ruleorder} > 0) {
 6770:             $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
 6771:             foreach my $rule (@{$ruleorder}) {
 6772:                 if (ref($curr_rules) eq 'ARRAY') {
 6773:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 6774:                         if (ref($rules->{$rule}) eq 'HASH') {
 6775:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 6776:                                         $rules->{$rule}{'desc'}.'</li>';
 6777:                         }
 6778:                     }
 6779:                 }
 6780:             }
 6781:             $output .= '</ul>';
 6782:         }
 6783:     }
 6784:     return $output;
 6785: }
 6786: 
 6787: sub instrule_disallow_msg {
 6788:     my ($checkitem,$domdesc,$count,$mode) = @_;
 6789:     my $response;
 6790:     my %text = (
 6791:                   item   => 'username',
 6792:                   items  => 'usernames',
 6793:                   match  => 'matches',
 6794:                   do     => 'does',
 6795:                   action => 'a username',
 6796:                   one    => 'one',
 6797:                );
 6798:     if ($count > 1) {
 6799:         $text{'item'} = 'usernames';
 6800:         $text{'match'} ='match';
 6801:         $text{'do'} = 'do';
 6802:         $text{'action'} = 'usernames',
 6803:         $text{'one'} = 'ones';
 6804:     }
 6805:     if ($checkitem eq 'id') {
 6806:         $text{'items'} = 'IDs';
 6807:         $text{'item'} = 'ID';
 6808:         $text{'action'} = 'an ID';
 6809:         if ($count > 1) {
 6810:             $text{'item'} = 'IDs';
 6811:             $text{'action'} = 'IDs';
 6812:         }
 6813:     }
 6814:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
 6815:     if ($mode eq 'upload') {
 6816:         if ($checkitem eq 'username') {
 6817:             $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 6818:         } elsif ($checkitem eq 'id') {
 6819:             $response .= &mt("Either upload a file which includes $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
 6820:         }
 6821:     } elsif ($mode eq 'selfcreate') {
 6822:         if ($checkitem eq 'id') {
 6823:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
 6824:         }
 6825:     } else {
 6826:         if ($checkitem eq 'username') {
 6827:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 6828:         } elsif ($checkitem eq 'id') {
 6829:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
 6830:         }
 6831:     }
 6832:     return $response;
 6833: }
 6834: 
 6835: sub personal_data_fieldtitles {
 6836:     my %fieldtitles = &Apache::lonlocal::texthash (
 6837:                         id => 'Student/Employee ID',
 6838:                         permanentemail => 'E-mail address',
 6839:                         lastname => 'Last Name',
 6840:                         firstname => 'First Name',
 6841:                         middlename => 'Middle Name',
 6842:                         generation => 'Generation',
 6843:                         gen => 'Generation',
 6844:                    );
 6845:     return %fieldtitles;
 6846: }
 6847: 
 6848: sub sorted_inst_types {
 6849:     my ($dom) = @_;
 6850:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 6851:     my $othertitle = &mt('All users');
 6852:     if ($env{'request.course.id'}) {
 6853:         $othertitle  = &mt('Any users');
 6854:     }
 6855:     my @types;
 6856:     if (ref($order) eq 'ARRAY') {
 6857:         @types = @{$order};
 6858:     }
 6859:     if (@types == 0) {
 6860:         if (ref($usertypes) eq 'HASH') {
 6861:             @types = sort(keys(%{$usertypes}));
 6862:         }
 6863:     }
 6864:     if (keys(%{$usertypes}) > 0) {
 6865:         $othertitle = &mt('Other users');
 6866:     }
 6867:     return ($othertitle,$usertypes,\@types);
 6868: }
 6869: 
 6870: sub get_institutional_codes {
 6871:     my ($settings,$allcourses,$LC_code) = @_;
 6872: # Get complete list of course sections to update
 6873:     my @currsections = ();
 6874:     my @currxlists = ();
 6875:     my $coursecode = $$settings{'internal.coursecode'};
 6876: 
 6877:     if ($$settings{'internal.sectionnums'} ne '') {
 6878:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 6879:     }
 6880: 
 6881:     if ($$settings{'internal.crosslistings'} ne '') {
 6882:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 6883:     }
 6884: 
 6885:     if (@currxlists > 0) {
 6886:         foreach (@currxlists) {
 6887:             if (m/^([^:]+):(\w*)$/) {
 6888:                 unless (grep/^$1$/,@{$allcourses}) {
 6889:                     push @{$allcourses},$1;
 6890:                     $$LC_code{$1} = $2;
 6891:                 }
 6892:             }
 6893:         }
 6894:     }
 6895:  
 6896:     if (@currsections > 0) {
 6897:         foreach (@currsections) {
 6898:             if (m/^(\w+):(\w*)$/) {
 6899:                 my $sec = $coursecode.$1;
 6900:                 my $lc_sec = $2;
 6901:                 unless (grep/^$sec$/,@{$allcourses}) {
 6902:                     push @{$allcourses},$sec;
 6903:                     $$LC_code{$sec} = $lc_sec;
 6904:                 }
 6905:             }
 6906:         }
 6907:     }
 6908:     return;
 6909: }
 6910: 
 6911: =pod
 6912: 
 6913: =back
 6914: 
 6915: =head1 HTTP Helpers
 6916: 
 6917: =over 4
 6918: 
 6919: =item * &get_unprocessed_cgi($query,$possible_names)
 6920: 
 6921: Modify the %env hash to contain unprocessed CGI form parameters held in
 6922: $query.  The parameters listed in $possible_names (an array reference),
 6923: will be set in $env{'form.name'} if they do not already exist.
 6924: 
 6925: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 6926: $possible_names is an ref to an array of form element names.  As an example:
 6927: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 6928: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 6929: 
 6930: =cut
 6931: 
 6932: sub get_unprocessed_cgi {
 6933:   my ($query,$possible_names)= @_;
 6934:   # $Apache::lonxml::debug=1;
 6935:   foreach my $pair (split(/&/,$query)) {
 6936:     my ($name, $value) = split(/=/,$pair);
 6937:     $name = &unescape($name);
 6938:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 6939:       $value =~ tr/+/ /;
 6940:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 6941:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 6942:     }
 6943:   }
 6944: }
 6945: 
 6946: =pod
 6947: 
 6948: =item * &cacheheader() 
 6949: 
 6950: returns cache-controlling header code
 6951: 
 6952: =cut
 6953: 
 6954: sub cacheheader {
 6955:     unless ($env{'request.method'} eq 'GET') { return ''; }
 6956:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 6957:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 6958:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 6959:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 6960:     return $output;
 6961: }
 6962: 
 6963: =pod
 6964: 
 6965: =item * &no_cache($r) 
 6966: 
 6967: specifies header code to not have cache
 6968: 
 6969: =cut
 6970: 
 6971: sub no_cache {
 6972:     my ($r) = @_;
 6973:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 6974: 	$env{'request.method'} ne 'GET') { return ''; }
 6975:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 6976:     $r->no_cache(1);
 6977:     $r->header_out("Expires" => $date);
 6978:     $r->header_out("Pragma" => "no-cache");
 6979: }
 6980: 
 6981: sub content_type {
 6982:     my ($r,$type,$charset) = @_;
 6983:     if ($r) {
 6984: 	#  Note that printout.pl calls this with undef for $r.
 6985: 	&no_cache($r);
 6986:     }
 6987:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 6988:     unless ($charset) {
 6989: 	$charset=&Apache::lonlocal::current_encoding;
 6990:     }
 6991:     if ($charset) { $type.='; charset='.$charset; }
 6992:     if ($r) {
 6993: 	$r->content_type($type);
 6994:     } else {
 6995: 	print("Content-type: $type\n\n");
 6996:     }
 6997: }
 6998: 
 6999: =pod
 7000: 
 7001: =item * &add_to_env($name,$value) 
 7002: 
 7003: adds $name to the %env hash with value
 7004: $value, if $name already exists, the entry is converted to an array
 7005: reference and $value is added to the array.
 7006: 
 7007: =cut
 7008: 
 7009: sub add_to_env {
 7010:   my ($name,$value)=@_;
 7011:   if (defined($env{$name})) {
 7012:     if (ref($env{$name})) {
 7013:       #already have multiple values
 7014:       push(@{ $env{$name} },$value);
 7015:     } else {
 7016:       #first time seeing multiple values, convert hash entry to an arrayref
 7017:       my $first=$env{$name};
 7018:       undef($env{$name});
 7019:       push(@{ $env{$name} },$first,$value);
 7020:     }
 7021:   } else {
 7022:     $env{$name}=$value;
 7023:   }
 7024: }
 7025: 
 7026: =pod
 7027: 
 7028: =item * &get_env_multiple($name) 
 7029: 
 7030: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7031: values may be defined and end up as an array ref.
 7032: 
 7033: returns an array of values
 7034: 
 7035: =cut
 7036: 
 7037: sub get_env_multiple {
 7038:     my ($name) = @_;
 7039:     my @values;
 7040:     if (defined($env{$name})) {
 7041:         # exists is it an array
 7042:         if (ref($env{$name})) {
 7043:             @values=@{ $env{$name} };
 7044:         } else {
 7045:             $values[0]=$env{$name};
 7046:         }
 7047:     }
 7048:     return(@values);
 7049: }
 7050: 
 7051: sub ask_for_embedded_content {
 7052:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7053:     my $upload_output = '
 7054:    <form name="upload_embedded" action="'.$actionurl.'"
 7055:                   method="post" enctype="multipart/form-data">';
 7056:     $upload_output .= $state;
 7057:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7058: 
 7059:     my $num = 0;
 7060:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7061:         $upload_output .= &start_data_table_row().
 7062:             '<td>'.$embed_file.'</td><td>';
 7063:         if ($args->{'ignore_remote_references'}
 7064:             && $embed_file =~ m{^\w+://}) {
 7065:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7066:         } elsif ($args->{'error_on_invalid_names'}
 7067:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7068: 
 7069:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7070: 
 7071:         } else {
 7072:             $upload_output .='
 7073:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7074:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7075:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7076:             $upload_output .=
 7077:                 "\n\t\t".
 7078:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7079:                 $attrib.'" />';
 7080:             if (exists($$codebase{$embed_file})) {
 7081:                 $upload_output .=
 7082:                     "\n\t\t".
 7083:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7084:                     &escape($$codebase{$embed_file}).'" />';
 7085:             }
 7086:         }
 7087:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7088:         $num++;
 7089:     }
 7090:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7091:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7092:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7093:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7094:    </form>';
 7095:     return $upload_output;
 7096: }
 7097: 
 7098: sub upload_embedded {
 7099:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7100:         $current_disk_usage) = @_;
 7101:     my $output;
 7102:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7103:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7104:         my $orig_uploaded_filename =
 7105:             $env{'form.embedded_item_'.$i.'.filename'};
 7106: 
 7107:         $env{'form.embedded_orig_'.$i} =
 7108:             &unescape($env{'form.embedded_orig_'.$i});
 7109:         my ($path,$fname) =
 7110:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7111:         # no path, whole string is fname
 7112:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7113: 
 7114:         $path = $env{'form.currentpath'}.$path;
 7115:         $fname = &Apache::lonnet::clean_filename($fname);
 7116:         # See if there is anything left
 7117:         next if ($fname eq '');
 7118: 
 7119:         # Check if file already exists as a file or directory.
 7120:         my ($state,$msg);
 7121:         if ($context eq 'portfolio') {
 7122:             my $port_path = $dirpath;
 7123:             if ($group ne '') {
 7124:                 $port_path = "groups/$group/$port_path";
 7125:             }
 7126:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7127:                                               $dir_root,$port_path,$disk_quota,
 7128:                                               $current_disk_usage,$uname,$udom);
 7129:             if ($state eq 'will_exceed_quota'
 7130:                 || $state eq 'file_locked'
 7131:                 || $state eq 'file_exists' ) {
 7132:                 $output .= $msg;
 7133:                 next;
 7134:             }
 7135:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7136:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7137:             if ($state eq 'exists') {
 7138:                 $output .= $msg;
 7139:                 next;
 7140:             }
 7141:         }
 7142:         # Check if extension is valid
 7143:         if (($fname =~ /\.(\w+)$/) &&
 7144:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7145:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7146:             next;
 7147:         } elsif (($fname =~ /\.(\w+)$/) &&
 7148:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7149:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7150:             next;
 7151:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7152:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7153:             next;
 7154:         }
 7155: 
 7156:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7157:         if ($context eq 'portfolio') {
 7158:             my $result=
 7159:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7160:                                                 $dirpath.$path);
 7161:             if ($result !~ m|^/uploaded/|) {
 7162:                 $output .= '<span class="LC_error">'
 7163:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7164:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7165:                       .'</span><br />';
 7166:                 next;
 7167:             } else {
 7168:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7169:                            $path.$fname.'</span>').'</p>';     
 7170:             }
 7171:         } else {
 7172: # Save the file
 7173:             my $target = $env{'form.embedded_item_'.$i};
 7174:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7175:             my $dest = $fullpath.$fname;
 7176:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7177:             my @parts=split(/\//,$fullpath);
 7178:             my $count;
 7179:             my $filepath = $dir_root;
 7180:             for ($count=4;$count<=$#parts;$count++) {
 7181:                 $filepath .= "/$parts[$count]";
 7182:                 if ((-e $filepath)!=1) {
 7183:                     mkdir($filepath,0770);
 7184:                 }
 7185:             }
 7186:             my $fh;
 7187:             if (!open($fh,'>'.$dest)) {
 7188:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7189:                 $output .= '<span class="LC_error">'.
 7190:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7191:                            '</span><br />';
 7192:             } else {
 7193:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7194:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7195:                     $output .= '<span class="LC_error">'.
 7196:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7197:                               '</span><br />';
 7198:                 } else {
 7199:                     if ($context eq 'testbank') {
 7200:                         $output .= &mt('Embedded file uploaded successfully:').
 7201:                                    '&nbsp;<a href="'.$url.'">'.
 7202:                                    $orig_uploaded_filename.'</a><br />';
 7203:                     } else {
 7204:                         $output .= '<font size="+2">'.
 7205:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7206:                                    $orig_uploaded_filename.'</a>').'</font><br />';
 7207:                     }
 7208:                 }
 7209:                 close($fh);
 7210:             }
 7211:         }
 7212:     }
 7213:     return $output;
 7214: }
 7215: 
 7216: sub check_for_existing {
 7217:     my ($path,$fname,$element) = @_;
 7218:     my ($state,$msg);
 7219:     if (-d $path.'/'.$fname) {
 7220:         $state = 'exists';
 7221:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7222:     } elsif (-e $path.'/'.$fname) {
 7223:         $state = 'exists';
 7224:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7225:     }
 7226:     if ($state eq 'exists') {
 7227:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7228:     }
 7229:     return ($state,$msg);
 7230: }
 7231: 
 7232: sub check_for_upload {
 7233:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7234:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7235:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7236:     my $getpropath = 1;
 7237:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7238:                                             $getpropath);
 7239:     my $found_file = 0;
 7240:     my $locked_file = 0;
 7241:     foreach my $line (@dir_list) {
 7242:         my ($file_name)=split(/\&/,$line,2);
 7243:         if ($file_name eq $fname){
 7244:             $file_name = $path.$file_name;
 7245:             if ($group ne '') {
 7246:                 $file_name = $group.$file_name;
 7247:             }
 7248:             $found_file = 1;
 7249:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7250:                 $locked_file = 1;
 7251:             }
 7252:         }
 7253:     }
 7254:     if (($current_disk_usage + $filesize) > $disk_quota){
 7255:         my $msg = '<span class="LC_error">'.
 7256:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7257:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7258:         return ('will_exceed_quota',$msg);
 7259:     } elsif ($found_file) {
 7260:         if ($locked_file) {
 7261:             my $msg = '<span class="LC_error">';
 7262:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
 7263:             $msg .= '</span><br />';
 7264:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7265:             return ('file_locked',$msg);
 7266:         } else {
 7267:             my $msg = '<span class="LC_error">';
 7268:             $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 7269:             $msg .= '</span>';
 7270:             $msg .= '<br />';
 7271:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7272:             return ('file_exists',$msg);
 7273:         }
 7274:     }
 7275: }
 7276: 
 7277: 
 7278: =pod
 7279: 
 7280: =back
 7281: 
 7282: =head1 CSV Upload/Handling functions
 7283: 
 7284: =over 4
 7285: 
 7286: =item * &upfile_store($r)
 7287: 
 7288: Store uploaded file, $r should be the HTTP Request object,
 7289: needs $env{'form.upfile'}
 7290: returns $datatoken to be put into hidden field
 7291: 
 7292: =cut
 7293: 
 7294: sub upfile_store {
 7295:     my $r=shift;
 7296:     $env{'form.upfile'}=~s/\r/\n/gs;
 7297:     $env{'form.upfile'}=~s/\f/\n/gs;
 7298:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7299:     $env{'form.upfile'}=~s/\n+$//gs;
 7300: 
 7301:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7302: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7303:     {
 7304:         my $datafile = $r->dir_config('lonDaemons').
 7305:                            '/tmp/'.$datatoken.'.tmp';
 7306:         if ( open(my $fh,">$datafile") ) {
 7307:             print $fh $env{'form.upfile'};
 7308:             close($fh);
 7309:         }
 7310:     }
 7311:     return $datatoken;
 7312: }
 7313: 
 7314: =pod
 7315: 
 7316: =item * &load_tmp_file($r)
 7317: 
 7318: Load uploaded file from tmp, $r should be the HTTP Request object,
 7319: needs $env{'form.datatoken'},
 7320: sets $env{'form.upfile'} to the contents of the file
 7321: 
 7322: =cut
 7323: 
 7324: sub load_tmp_file {
 7325:     my $r=shift;
 7326:     my @studentdata=();
 7327:     {
 7328:         my $studentfile = $r->dir_config('lonDaemons').
 7329:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7330:         if ( open(my $fh,"<$studentfile") ) {
 7331:             @studentdata=<$fh>;
 7332:             close($fh);
 7333:         }
 7334:     }
 7335:     $env{'form.upfile'}=join('',@studentdata);
 7336: }
 7337: 
 7338: =pod
 7339: 
 7340: =item * &upfile_record_sep()
 7341: 
 7342: Separate uploaded file into records
 7343: returns array of records,
 7344: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7345: 
 7346: =cut
 7347: 
 7348: sub upfile_record_sep {
 7349:     if ($env{'form.upfiletype'} eq 'xml') {
 7350:     } else {
 7351: 	my @records;
 7352: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7353: 	    if ($line=~/^\s*$/) { next; }
 7354: 	    push(@records,$line);
 7355: 	}
 7356: 	return @records;
 7357:     }
 7358: }
 7359: 
 7360: =pod
 7361: 
 7362: =item * &record_sep($record)
 7363: 
 7364: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7365: 
 7366: =cut
 7367: 
 7368: sub takeleft {
 7369:     my $index=shift;
 7370:     return substr('0000'.$index,-4,4);
 7371: }
 7372: 
 7373: sub record_sep {
 7374:     my $record=shift;
 7375:     my %components=();
 7376:     if ($env{'form.upfiletype'} eq 'xml') {
 7377:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7378:         my $i=0;
 7379:         foreach my $field (split(/\s+/,$record)) {
 7380:             $field=~s/^(\"|\')//;
 7381:             $field=~s/(\"|\')$//;
 7382:             $components{&takeleft($i)}=$field;
 7383:             $i++;
 7384:         }
 7385:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7386:         my $i=0;
 7387:         foreach my $field (split(/\t/,$record)) {
 7388:             $field=~s/^(\"|\')//;
 7389:             $field=~s/(\"|\')$//;
 7390:             $components{&takeleft($i)}=$field;
 7391:             $i++;
 7392:         }
 7393:     } else {
 7394:         my $separator=',';
 7395:         if ($env{'form.upfiletype'} eq 'semisv') {
 7396:             $separator=';';
 7397:         }
 7398:         my $i=0;
 7399: # the character we are looking for to indicate the end of a quote or a record 
 7400:         my $looking_for=$separator;
 7401: # do not add the characters to the fields
 7402:         my $ignore=0;
 7403: # we just encountered a separator (or the beginning of the record)
 7404:         my $just_found_separator=1;
 7405: # store the field we are working on here
 7406:         my $field='';
 7407: # work our way through all characters in record
 7408:         foreach my $character ($record=~/(.)/g) {
 7409:             if ($character eq $looking_for) {
 7410:                if ($character ne $separator) {
 7411: # Found the end of a quote, again looking for separator
 7412:                   $looking_for=$separator;
 7413:                   $ignore=1;
 7414:                } else {
 7415: # Found a separator, store away what we got
 7416:                   $components{&takeleft($i)}=$field;
 7417: 	          $i++;
 7418:                   $just_found_separator=1;
 7419:                   $ignore=0;
 7420:                   $field='';
 7421:                }
 7422:                next;
 7423:             }
 7424: # single or double quotation marks after a separator indicate beginning of a quote
 7425: # we are now looking for the end of the quote and need to ignore separators
 7426:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7427:                $looking_for=$character;
 7428:                next;
 7429:             }
 7430: # ignore would be true after we reached the end of a quote
 7431:             if ($ignore) { next; }
 7432:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7433:             $field.=$character;
 7434:             $just_found_separator=0; 
 7435:         }
 7436: # catch the very last entry, since we never encountered the separator
 7437:         $components{&takeleft($i)}=$field;
 7438:     }
 7439:     return %components;
 7440: }
 7441: 
 7442: ######################################################
 7443: ######################################################
 7444: 
 7445: =pod
 7446: 
 7447: =item * &upfile_select_html()
 7448: 
 7449: Return HTML code to select a file from the users machine and specify 
 7450: the file type.
 7451: 
 7452: =cut
 7453: 
 7454: ######################################################
 7455: ######################################################
 7456: sub upfile_select_html {
 7457:     my %Types = (
 7458:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7459:                  semisv => &mt('Semicolon separated values'),
 7460:                  space => &mt('Space separated'),
 7461:                  tab   => &mt('Tabulator separated'),
 7462: #                 xml   => &mt('HTML/XML'),
 7463:                  );
 7464:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7465:         '<br />Type: <select name="upfiletype">';
 7466:     foreach my $type (sort(keys(%Types))) {
 7467:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7468:     }
 7469:     $Str .= "</select>\n";
 7470:     return $Str;
 7471: }
 7472: 
 7473: sub get_samples {
 7474:     my ($records,$toget) = @_;
 7475:     my @samples=({});
 7476:     my $got=0;
 7477:     foreach my $rec (@$records) {
 7478: 	my %temp = &record_sep($rec);
 7479: 	if (! grep(/\S/, values(%temp))) { next; }
 7480: 	if (%temp) {
 7481: 	    $samples[$got]=\%temp;
 7482: 	    $got++;
 7483: 	    if ($got == $toget) { last; }
 7484: 	}
 7485:     }
 7486:     return \@samples;
 7487: }
 7488: 
 7489: ######################################################
 7490: ######################################################
 7491: 
 7492: =pod
 7493: 
 7494: =item * &csv_print_samples($r,$records)
 7495: 
 7496: Prints a table of sample values from each column uploaded $r is an
 7497: Apache Request ref, $records is an arrayref from
 7498: &Apache::loncommon::upfile_record_sep
 7499: 
 7500: =cut
 7501: 
 7502: ######################################################
 7503: ######################################################
 7504: sub csv_print_samples {
 7505:     my ($r,$records) = @_;
 7506:     my $samples = &get_samples($records,5);
 7507: 
 7508:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 7509:               &start_data_table_header_row());
 7510:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 7511:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 7512:     $r->print(&end_data_table_header_row());
 7513:     foreach my $hash (@$samples) {
 7514: 	$r->print(&start_data_table_row());
 7515: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7516: 	    $r->print('<td>');
 7517: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 7518: 	    $r->print('</td>');
 7519: 	}
 7520: 	$r->print(&end_data_table_row());
 7521:     }
 7522:     $r->print(&end_data_table().'<br />'."\n");
 7523: }
 7524: 
 7525: ######################################################
 7526: ######################################################
 7527: 
 7528: =pod
 7529: 
 7530: =item * &csv_print_select_table($r,$records,$d)
 7531: 
 7532: Prints a table to create associations between values and table columns.
 7533: 
 7534: $r is an Apache Request ref,
 7535: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7536: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 7537: 
 7538: =cut
 7539: 
 7540: ######################################################
 7541: ######################################################
 7542: sub csv_print_select_table {
 7543:     my ($r,$records,$d) = @_;
 7544:     my $i=0;
 7545:     my $samples = &get_samples($records,1);
 7546:     $r->print(&mt('Associate columns with student attributes.')."\n".
 7547: 	      &start_data_table().&start_data_table_header_row().
 7548:               '<th>'.&mt('Attribute').'</th>'.
 7549:               '<th>'.&mt('Column').'</th>'.
 7550:               &end_data_table_header_row()."\n");
 7551:     foreach my $array_ref (@$d) {
 7552: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 7553: 	$r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
 7554: 
 7555: 	$r->print('<td><select name=f'.$i.
 7556: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7557: 	$r->print('<option value="none"></option>');
 7558: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7559: 	    $r->print('<option value="'.$sample.'"'.
 7560:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 7561:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 7562: 	}
 7563: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 7564: 	$i++;
 7565:     }
 7566:     $r->print(&end_data_table());
 7567:     $i--;
 7568:     return $i;
 7569: }
 7570: 
 7571: ######################################################
 7572: ######################################################
 7573: 
 7574: =pod
 7575: 
 7576: =item * &csv_samples_select_table($r,$records,$d)
 7577: 
 7578: Prints a table of sample values from the upload and can make associate samples to internal names.
 7579: 
 7580: $r is an Apache Request ref,
 7581: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7582: $d is an array of 2 element arrays (internal name, displayed name)
 7583: 
 7584: =cut
 7585: 
 7586: ######################################################
 7587: ######################################################
 7588: sub csv_samples_select_table {
 7589:     my ($r,$records,$d) = @_;
 7590:     my $i=0;
 7591:     #
 7592:     my $max_samples = 5;
 7593:     my $samples = &get_samples($records,$max_samples);
 7594:     $r->print(&start_data_table().
 7595:               &start_data_table_header_row().'<th>'.
 7596:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 7597:               &end_data_table_header_row());
 7598: 
 7599:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 7600: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 7601: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7602: 	foreach my $option (@$d) {
 7603: 	    my ($value,$display,$defaultcol)=@{ $option };
 7604: 	    $r->print('<option value="'.$value.'"'.
 7605:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 7606:                       $display.'</option>');
 7607: 	}
 7608: 	$r->print('</select></td><td>');
 7609: 	foreach my $line (0..($max_samples-1)) {
 7610: 	    if (defined($samples->[$line]{$key})) { 
 7611: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 7612: 	    }
 7613: 	}
 7614: 	$r->print('</td>'.&end_data_table_row());
 7615: 	$i++;
 7616:     }
 7617:     $r->print(&end_data_table());
 7618:     $i--;
 7619:     return($i);
 7620: }
 7621: 
 7622: ######################################################
 7623: ######################################################
 7624: 
 7625: =pod
 7626: 
 7627: =item * &clean_excel_name($name)
 7628: 
 7629: Returns a replacement for $name which does not contain any illegal characters.
 7630: 
 7631: =cut
 7632: 
 7633: ######################################################
 7634: ######################################################
 7635: sub clean_excel_name {
 7636:     my ($name) = @_;
 7637:     $name =~ s/[:\*\?\/\\]//g;
 7638:     if (length($name) > 31) {
 7639:         $name = substr($name,0,31);
 7640:     }
 7641:     return $name;
 7642: }
 7643: 
 7644: =pod
 7645: 
 7646: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 7647: 
 7648: Returns either 1 or undef
 7649: 
 7650: 1 if the part is to be hidden, undef if it is to be shown
 7651: 
 7652: Arguments are:
 7653: 
 7654: $id the id of the part to be checked
 7655: $symb, optional the symb of the resource to check
 7656: $udom, optional the domain of the user to check for
 7657: $uname, optional the username of the user to check for
 7658: 
 7659: =cut
 7660: 
 7661: sub check_if_partid_hidden {
 7662:     my ($id,$symb,$udom,$uname) = @_;
 7663:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 7664: 					 $symb,$udom,$uname);
 7665:     my $truth=1;
 7666:     #if the string starts with !, then the list is the list to show not hide
 7667:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 7668:     my @hiddenlist=split(/,/,$hiddenparts);
 7669:     foreach my $checkid (@hiddenlist) {
 7670: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 7671:     }
 7672:     return !$truth;
 7673: }
 7674: 
 7675: 
 7676: ############################################################
 7677: ############################################################
 7678: 
 7679: =pod
 7680: 
 7681: =back 
 7682: 
 7683: =head1 cgi-bin script and graphing routines
 7684: 
 7685: =over 4
 7686: 
 7687: =item * &get_cgi_id()
 7688: 
 7689: Inputs: none
 7690: 
 7691: Returns an id which can be used to pass environment variables
 7692: to various cgi-bin scripts.  These environment variables will
 7693: be removed from the users environment after a given time by
 7694: the routine &Apache::lonnet::transfer_profile_to_env.
 7695: 
 7696: =cut
 7697: 
 7698: ############################################################
 7699: ############################################################
 7700: my $uniq=0;
 7701: sub get_cgi_id {
 7702:     $uniq=($uniq+1)%100000;
 7703:     return (time.'_'.$$.'_'.$uniq);
 7704: }
 7705: 
 7706: ############################################################
 7707: ############################################################
 7708: 
 7709: =pod
 7710: 
 7711: =item * &DrawBarGraph()
 7712: 
 7713: Facilitates the plotting of data in a (stacked) bar graph.
 7714: Puts plot definition data into the users environment in order for 
 7715: graph.png to plot it.  Returns an <img> tag for the plot.
 7716: The bars on the plot are labeled '1','2',...,'n'.
 7717: 
 7718: Inputs:
 7719: 
 7720: =over 4
 7721: 
 7722: =item $Title: string, the title of the plot
 7723: 
 7724: =item $xlabel: string, text describing the X-axis of the plot
 7725: 
 7726: =item $ylabel: string, text describing the Y-axis of the plot
 7727: 
 7728: =item $Max: scalar, the maximum Y value to use in the plot
 7729: If $Max is < any data point, the graph will not be rendered.
 7730: 
 7731: =item $colors: array ref holding the colors to be used for the data sets when
 7732: they are plotted.  If undefined, default values will be used.
 7733: 
 7734: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 7735: 
 7736: =item @Values: An array of array references.  Each array reference holds data
 7737: to be plotted in a stacked bar chart.
 7738: 
 7739: =item If the final element of @Values is a hash reference the key/value
 7740: pairs will be added to the graph definition.
 7741: 
 7742: =back
 7743: 
 7744: Returns:
 7745: 
 7746: An <img> tag which references graph.png and the appropriate identifying
 7747: information for the plot.
 7748: 
 7749: =cut
 7750: 
 7751: ############################################################
 7752: ############################################################
 7753: sub DrawBarGraph {
 7754:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 7755:     #
 7756:     if (! defined($colors)) {
 7757:         $colors = ['#33ff00', 
 7758:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 7759:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 7760:                   ]; 
 7761:     }
 7762:     my $extra_settings = {};
 7763:     if (ref($Values[-1]) eq 'HASH') {
 7764:         $extra_settings = pop(@Values);
 7765:     }
 7766:     #
 7767:     my $identifier = &get_cgi_id();
 7768:     my $id = 'cgi.'.$identifier;        
 7769:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 7770:         return '';
 7771:     }
 7772:     #
 7773:     my @Labels;
 7774:     if (defined($labels)) {
 7775:         @Labels = @$labels;
 7776:     } else {
 7777:         for (my $i=0;$i<@{$Values[0]};$i++) {
 7778:             push (@Labels,$i+1);
 7779:         }
 7780:     }
 7781:     #
 7782:     my $NumBars = scalar(@{$Values[0]});
 7783:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 7784:     my %ValuesHash;
 7785:     my $NumSets=1;
 7786:     foreach my $array (@Values) {
 7787:         next if (! ref($array));
 7788:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 7789:             join(',',@$array);
 7790:     }
 7791:     #
 7792:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 7793:     if ($NumBars < 3) {
 7794:         $width = 120+$NumBars*32;
 7795:         $xskip = 1;
 7796:         $bar_width = 30;
 7797:     } elsif ($NumBars < 5) {
 7798:         $width = 120+$NumBars*20;
 7799:         $xskip = 1;
 7800:         $bar_width = 20;
 7801:     } elsif ($NumBars < 10) {
 7802:         $width = 120+$NumBars*15;
 7803:         $xskip = 1;
 7804:         $bar_width = 15;
 7805:     } elsif ($NumBars <= 25) {
 7806:         $width = 120+$NumBars*11;
 7807:         $xskip = 5;
 7808:         $bar_width = 8;
 7809:     } elsif ($NumBars <= 50) {
 7810:         $width = 120+$NumBars*8;
 7811:         $xskip = 5;
 7812:         $bar_width = 4;
 7813:     } else {
 7814:         $width = 120+$NumBars*8;
 7815:         $xskip = 5;
 7816:         $bar_width = 4;
 7817:     }
 7818:     #
 7819:     $Max = 1 if ($Max < 1);
 7820:     if ( int($Max) < $Max ) {
 7821:         $Max++;
 7822:         $Max = int($Max);
 7823:     }
 7824:     $Title  = '' if (! defined($Title));
 7825:     $xlabel = '' if (! defined($xlabel));
 7826:     $ylabel = '' if (! defined($ylabel));
 7827:     $ValuesHash{$id.'.title'}    = &escape($Title);
 7828:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 7829:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 7830:     $ValuesHash{$id.'.y_max_value'} = $Max;
 7831:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 7832:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 7833:     $ValuesHash{$id.'.PlotType'} = 'bar';
 7834:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7835:     $ValuesHash{$id.'.height'}   = $height;
 7836:     $ValuesHash{$id.'.width'}    = $width;
 7837:     $ValuesHash{$id.'.xskip'}    = $xskip;
 7838:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 7839:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 7840:     #
 7841:     # Deal with other parameters
 7842:     while (my ($key,$value) = each(%$extra_settings)) {
 7843:         $ValuesHash{$id.'.'.$key} = $value;
 7844:     }
 7845:     #
 7846:     &Apache::lonnet::appenv(\%ValuesHash);
 7847:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7848: }
 7849: 
 7850: ############################################################
 7851: ############################################################
 7852: 
 7853: =pod
 7854: 
 7855: =item * &DrawXYGraph()
 7856: 
 7857: Facilitates the plotting of data in an XY graph.
 7858: Puts plot definition data into the users environment in order for 
 7859: graph.png to plot it.  Returns an <img> tag for the plot.
 7860: 
 7861: Inputs:
 7862: 
 7863: =over 4
 7864: 
 7865: =item $Title: string, the title of the plot
 7866: 
 7867: =item $xlabel: string, text describing the X-axis of the plot
 7868: 
 7869: =item $ylabel: string, text describing the Y-axis of the plot
 7870: 
 7871: =item $Max: scalar, the maximum Y value to use in the plot
 7872: If $Max is < any data point, the graph will not be rendered.
 7873: 
 7874: =item $colors: Array ref containing the hex color codes for the data to be 
 7875: plotted in.  If undefined, default values will be used.
 7876: 
 7877: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7878: 
 7879: =item $Ydata: Array ref containing Array refs.  
 7880: Each of the contained arrays will be plotted as a separate curve.
 7881: 
 7882: =item %Values: hash indicating or overriding any default values which are 
 7883: passed to graph.png.  
 7884: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7885: 
 7886: =back
 7887: 
 7888: Returns:
 7889: 
 7890: An <img> tag which references graph.png and the appropriate identifying
 7891: information for the plot.
 7892: 
 7893: =cut
 7894: 
 7895: ############################################################
 7896: ############################################################
 7897: sub DrawXYGraph {
 7898:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 7899:     #
 7900:     # Create the identifier for the graph
 7901:     my $identifier = &get_cgi_id();
 7902:     my $id = 'cgi.'.$identifier;
 7903:     #
 7904:     $Title  = '' if (! defined($Title));
 7905:     $xlabel = '' if (! defined($xlabel));
 7906:     $ylabel = '' if (! defined($ylabel));
 7907:     my %ValuesHash = 
 7908:         (
 7909:          $id.'.title'  => &escape($Title),
 7910:          $id.'.xlabel' => &escape($xlabel),
 7911:          $id.'.ylabel' => &escape($ylabel),
 7912:          $id.'.y_max_value'=> $Max,
 7913:          $id.'.labels'     => join(',',@$Xlabels),
 7914:          $id.'.PlotType'   => 'XY',
 7915:          );
 7916:     #
 7917:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 7918:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7919:     }
 7920:     #
 7921:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 7922:         return '';
 7923:     }
 7924:     my $NumSets=1;
 7925:     foreach my $array (@{$Ydata}){
 7926:         next if (! ref($array));
 7927:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 7928:     }
 7929:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 7930:     #
 7931:     # Deal with other parameters
 7932:     while (my ($key,$value) = each(%Values)) {
 7933:         $ValuesHash{$id.'.'.$key} = $value;
 7934:     }
 7935:     #
 7936:     &Apache::lonnet::appenv(\%ValuesHash);
 7937:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7938: }
 7939: 
 7940: ############################################################
 7941: ############################################################
 7942: 
 7943: =pod
 7944: 
 7945: =item * &DrawXYYGraph()
 7946: 
 7947: Facilitates the plotting of data in an XY graph with two Y axes.
 7948: Puts plot definition data into the users environment in order for 
 7949: graph.png to plot it.  Returns an <img> tag for the plot.
 7950: 
 7951: Inputs:
 7952: 
 7953: =over 4
 7954: 
 7955: =item $Title: string, the title of the plot
 7956: 
 7957: =item $xlabel: string, text describing the X-axis of the plot
 7958: 
 7959: =item $ylabel: string, text describing the Y-axis of the plot
 7960: 
 7961: =item $colors: Array ref containing the hex color codes for the data to be 
 7962: plotted in.  If undefined, default values will be used.
 7963: 
 7964: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7965: 
 7966: =item $Ydata1: The first data set
 7967: 
 7968: =item $Min1: The minimum value of the left Y-axis
 7969: 
 7970: =item $Max1: The maximum value of the left Y-axis
 7971: 
 7972: =item $Ydata2: The second data set
 7973: 
 7974: =item $Min2: The minimum value of the right Y-axis
 7975: 
 7976: =item $Max2: The maximum value of the left Y-axis
 7977: 
 7978: =item %Values: hash indicating or overriding any default values which are 
 7979: passed to graph.png.  
 7980: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7981: 
 7982: =back
 7983: 
 7984: Returns:
 7985: 
 7986: An <img> tag which references graph.png and the appropriate identifying
 7987: information for the plot.
 7988: 
 7989: =cut
 7990: 
 7991: ############################################################
 7992: ############################################################
 7993: sub DrawXYYGraph {
 7994:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 7995:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 7996:     #
 7997:     # Create the identifier for the graph
 7998:     my $identifier = &get_cgi_id();
 7999:     my $id = 'cgi.'.$identifier;
 8000:     #
 8001:     $Title  = '' if (! defined($Title));
 8002:     $xlabel = '' if (! defined($xlabel));
 8003:     $ylabel = '' if (! defined($ylabel));
 8004:     my %ValuesHash = 
 8005:         (
 8006:          $id.'.title'  => &escape($Title),
 8007:          $id.'.xlabel' => &escape($xlabel),
 8008:          $id.'.ylabel' => &escape($ylabel),
 8009:          $id.'.labels' => join(',',@$Xlabels),
 8010:          $id.'.PlotType' => 'XY',
 8011:          $id.'.NumSets' => 2,
 8012:          $id.'.two_axes' => 1,
 8013:          $id.'.y1_max_value' => $Max1,
 8014:          $id.'.y1_min_value' => $Min1,
 8015:          $id.'.y2_max_value' => $Max2,
 8016:          $id.'.y2_min_value' => $Min2,
 8017:          );
 8018:     #
 8019:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8020:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8021:     }
 8022:     #
 8023:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8024:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8025:         return '';
 8026:     }
 8027:     my $NumSets=1;
 8028:     foreach my $array ($Ydata1,$Ydata2){
 8029:         next if (! ref($array));
 8030:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8031:     }
 8032:     #
 8033:     # Deal with other parameters
 8034:     while (my ($key,$value) = each(%Values)) {
 8035:         $ValuesHash{$id.'.'.$key} = $value;
 8036:     }
 8037:     #
 8038:     &Apache::lonnet::appenv(\%ValuesHash);
 8039:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8040: }
 8041: 
 8042: ############################################################
 8043: ############################################################
 8044: 
 8045: =pod
 8046: 
 8047: =back 
 8048: 
 8049: =head1 Statistics helper routines?  
 8050: 
 8051: Bad place for them but what the hell.
 8052: 
 8053: =over 4
 8054: 
 8055: =item * &chartlink()
 8056: 
 8057: Returns a link to the chart for a specific student.  
 8058: 
 8059: Inputs:
 8060: 
 8061: =over 4
 8062: 
 8063: =item $linktext: The text of the link
 8064: 
 8065: =item $sname: The students username
 8066: 
 8067: =item $sdomain: The students domain
 8068: 
 8069: =back
 8070: 
 8071: =back
 8072: 
 8073: =cut
 8074: 
 8075: ############################################################
 8076: ############################################################
 8077: sub chartlink {
 8078:     my ($linktext, $sname, $sdomain) = @_;
 8079:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8080:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8081:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8082:        '">'.$linktext.'</a>';
 8083: }
 8084: 
 8085: #######################################################
 8086: #######################################################
 8087: 
 8088: =pod
 8089: 
 8090: =head1 Course Environment Routines
 8091: 
 8092: =over 4
 8093: 
 8094: =item * &restore_course_settings()
 8095: 
 8096: =item * &store_course_settings()
 8097: 
 8098: Restores/Store indicated form parameters from the course environment.
 8099: Will not overwrite existing values of the form parameters.
 8100: 
 8101: Inputs: 
 8102: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8103: 
 8104: a hash ref describing the data to be stored.  For example:
 8105:    
 8106: %Save_Parameters = ('Status' => 'scalar',
 8107:     'chartoutputmode' => 'scalar',
 8108:     'chartoutputdata' => 'scalar',
 8109:     'Section' => 'array',
 8110:     'Group' => 'array',
 8111:     'StudentData' => 'array',
 8112:     'Maps' => 'array');
 8113: 
 8114: Returns: both routines return nothing
 8115: 
 8116: =back
 8117: 
 8118: =cut
 8119: 
 8120: #######################################################
 8121: #######################################################
 8122: sub store_course_settings {
 8123:     return &store_settings($env{'request.course.id'},@_);
 8124: }
 8125: 
 8126: sub store_settings {
 8127:     # save to the environment
 8128:     # appenv the same items, just to be safe
 8129:     my $udom  = $env{'user.domain'};
 8130:     my $uname = $env{'user.name'};
 8131:     my ($context,$prefix,$Settings) = @_;
 8132:     my %SaveHash;
 8133:     my %AppHash;
 8134:     while (my ($setting,$type) = each(%$Settings)) {
 8135:         my $basename = join('.','internal',$context,$prefix,$setting);
 8136:         my $envname = 'environment.'.$basename;
 8137:         if (exists($env{'form.'.$setting})) {
 8138:             # Save this value away
 8139:             if ($type eq 'scalar' &&
 8140:                 (! exists($env{$envname}) || 
 8141:                  $env{$envname} ne $env{'form.'.$setting})) {
 8142:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8143:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8144:             } elsif ($type eq 'array') {
 8145:                 my $stored_form;
 8146:                 if (ref($env{'form.'.$setting})) {
 8147:                     $stored_form = join(',',
 8148:                                         map {
 8149:                                             &escape($_);
 8150:                                         } sort(@{$env{'form.'.$setting}}));
 8151:                 } else {
 8152:                     $stored_form = 
 8153:                         &escape($env{'form.'.$setting});
 8154:                 }
 8155:                 # Determine if the array contents are the same.
 8156:                 if ($stored_form ne $env{$envname}) {
 8157:                     $SaveHash{$basename} = $stored_form;
 8158:                     $AppHash{$envname}   = $stored_form;
 8159:                 }
 8160:             }
 8161:         }
 8162:     }
 8163:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8164:                                           $udom,$uname);
 8165:     if ($put_result !~ /^(ok|delayed)/) {
 8166:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8167:                                  'got error:'.$put_result);
 8168:     }
 8169:     # Make sure these settings stick around in this session, too
 8170:     &Apache::lonnet::appenv(\%AppHash);
 8171:     return;
 8172: }
 8173: 
 8174: sub restore_course_settings {
 8175:     return &restore_settings($env{'request.course.id'},@_);
 8176: }
 8177: 
 8178: sub restore_settings {
 8179:     my ($context,$prefix,$Settings) = @_;
 8180:     while (my ($setting,$type) = each(%$Settings)) {
 8181:         next if (exists($env{'form.'.$setting}));
 8182:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8183:             '.'.$setting;
 8184:         if (exists($env{$envname})) {
 8185:             if ($type eq 'scalar') {
 8186:                 $env{'form.'.$setting} = $env{$envname};
 8187:             } elsif ($type eq 'array') {
 8188:                 $env{'form.'.$setting} = [ 
 8189:                                            map { 
 8190:                                                &unescape($_); 
 8191:                                            } split(',',$env{$envname})
 8192:                                            ];
 8193:             }
 8194:         }
 8195:     }
 8196: }
 8197: 
 8198: #######################################################
 8199: #######################################################
 8200: 
 8201: =pod
 8202: 
 8203: =head1 Domain E-mail Routines  
 8204: 
 8205: =over 4
 8206: 
 8207: =item * &build_recipient_list()
 8208: 
 8209: Build recipient lists for three types of e-mail:
 8210: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
 8211: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
 8212: 
 8213: Inputs:
 8214: defmail (scalar - email address of default recipient), 
 8215: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8216: defdom (domain for which to retrieve configuration settings),
 8217: origmail (scalar - email address of recipient from loncapa.conf, 
 8218: i.e., predates configuration by DC via domainprefs.pm 
 8219: 
 8220: Returns: comma separated list of addresses to which to send e-mail.
 8221: 
 8222: =back
 8223: 
 8224: =cut
 8225: 
 8226: ############################################################
 8227: ############################################################
 8228: sub build_recipient_list {
 8229:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8230:     my @recipients;
 8231:     my $otheremails;
 8232:     my %domconfig =
 8233:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8234:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8235:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8236:             my @contacts = ('adminemail','supportemail');
 8237:             foreach my $item (@contacts) {
 8238:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
 8239:                     my $addr = $domconfig{'contacts'}{$item}; 
 8240:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
 8241:                         push(@recipients,$addr);
 8242:                     }
 8243:                 }
 8244:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8245:             }
 8246:         }
 8247:     } elsif ($origmail ne '') {
 8248:         push(@recipients,$origmail);
 8249:     }
 8250:     if ($defmail ne '') {
 8251:         push(@recipients,$defmail);
 8252:     }
 8253:     if ($otheremails) {
 8254:         my @others;
 8255:         if ($otheremails =~ /,/) {
 8256:             @others = split(/,/,$otheremails);
 8257:         } else {
 8258:             push(@others,$otheremails);
 8259:         }
 8260:         foreach my $addr (@others) {
 8261:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8262:                 push(@recipients,$addr);
 8263:             }
 8264:         }
 8265:     }
 8266:     my $recipientlist = join(',',@recipients); 
 8267:     return $recipientlist;
 8268: }
 8269: 
 8270: ############################################################
 8271: ############################################################
 8272: 
 8273: =pod
 8274: 
 8275: =head1 Course Catalog Routines
 8276: 
 8277: =over 4
 8278: 
 8279: =item * &gather_categories()
 8280: 
 8281: Converts category definitions - keys of categories hash stored in  
 8282: coursecategories in configuration.db on the primary library server in a 
 8283: domain - to an array.  Also generates javascript and idx hash used to 
 8284: generate Domain Coordinator interface for editing Course Categories.
 8285: 
 8286: Inputs:
 8287: 
 8288: categories (reference to hash of category definitions).
 8289: 
 8290: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8291:       categories and subcategories).
 8292: 
 8293: idx (reference to hash of counters used in Domain Coordinator interface for 
 8294:       editing Course Categories).
 8295: 
 8296: jsarray (reference to array of categories used to create Javascript arrays for
 8297:          Domain Coordinator interface for editing Course Categories).
 8298: 
 8299: Returns: nothing
 8300: 
 8301: Side effects: populates cats, idx and jsarray. 
 8302: 
 8303: =cut
 8304: 
 8305: sub gather_categories {
 8306:     my ($categories,$cats,$idx,$jsarray) = @_;
 8307:     my %counters;
 8308:     my $num = 0;
 8309:     foreach my $item (keys(%{$categories})) {
 8310:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8311:         if ($container eq '' && $depth == 0) {
 8312:             $cats->[$depth][$categories->{$item}] = $cat;
 8313:         } else {
 8314:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8315:         }
 8316:         my ($escitem,$tail) = split(/:/,$item,2);
 8317:         if ($counters{$tail} eq '') {
 8318:             $counters{$tail} = $num;
 8319:             $num ++;
 8320:         }
 8321:         if (ref($idx) eq 'HASH') {
 8322:             $idx->{$item} = $counters{$tail};
 8323:         }
 8324:         if (ref($jsarray) eq 'ARRAY') {
 8325:             push(@{$jsarray->[$counters{$tail}]},$item);
 8326:         }
 8327:     }
 8328:     return;
 8329: }
 8330: 
 8331: =pod
 8332: 
 8333: =item * &extract_categories()
 8334: 
 8335: Used to generate breadcrumb trails for course categories.
 8336: 
 8337: Inputs:
 8338: 
 8339: categories (reference to hash of category definitions).
 8340: 
 8341: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8342:       categories and subcategories).
 8343: 
 8344: trails (reference to array of breacrumb trails for each category).
 8345: 
 8346: allitems (reference to hash - key is category key 
 8347:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8348: 
 8349: idx (reference to hash of counters used in Domain Coordinator interface for
 8350:       editing Course Categories).
 8351: 
 8352: jsarray (reference to array of categories used to create Javascript arrays for
 8353:          Domain Coordinator interface for editing Course Categories).
 8354: 
 8355: subcats (reference to hash of arrays containing all subcategories within each 
 8356:          category, -recursive)
 8357: 
 8358: Returns: nothing
 8359: 
 8360: Side effects: populates trails and allitems hash references.
 8361: 
 8362: =cut
 8363: 
 8364: sub extract_categories {
 8365:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8366:     if (ref($categories) eq 'HASH') {
 8367:         &gather_categories($categories,$cats,$idx,$jsarray);
 8368:         if (ref($cats->[0]) eq 'ARRAY') {
 8369:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8370:                 my $name = $cats->[0][$i];
 8371:                 my $item = &escape($name).'::0';
 8372:                 my $trailstr;
 8373:                 if ($name eq 'instcode') {
 8374:                     $trailstr = &mt('Official courses (with institutional codes)');
 8375:                 } else {
 8376:                     $trailstr = $name;
 8377:                 }
 8378:                 if ($allitems->{$item} eq '') {
 8379:                     push(@{$trails},$trailstr);
 8380:                     $allitems->{$item} = scalar(@{$trails})-1;
 8381:                 }
 8382:                 my @parents = ($name);
 8383:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8384:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8385:                         my $category = $cats->[1]{$name}[$j];
 8386:                         if (ref($subcats) eq 'HASH') {
 8387:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8388:                         }
 8389:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8390:                     }
 8391:                 } else {
 8392:                     if (ref($subcats) eq 'HASH') {
 8393:                         $subcats->{$item} = [];
 8394:                     }
 8395:                 }
 8396:             }
 8397:         }
 8398:     }
 8399:     return;
 8400: }
 8401: 
 8402: =pod
 8403: 
 8404: =item *&recurse_categories()
 8405: 
 8406: Recursively used to generate breadcrumb trails for course categories.
 8407: 
 8408: Inputs:
 8409: 
 8410: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8411:       categories and subcategories).
 8412: 
 8413: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8414: 
 8415: category (current course category, for which breadcrumb trail is being generated).
 8416: 
 8417: trails (reference to array of breadcrumb trails for each category).
 8418: 
 8419: allitems (reference to hash - key is category key
 8420:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8421: 
 8422: parents (array containing containers directories for current category, 
 8423:          back to top level). 
 8424: 
 8425: Returns: nothing
 8426: 
 8427: Side effects: populates trails and allitems hash references
 8428: 
 8429: =cut
 8430: 
 8431: sub recurse_categories {
 8432:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 8433:     my $shallower = $depth - 1;
 8434:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8435:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8436:             my $name = $cats->[$depth]{$category}[$k];
 8437:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8438:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8439:             if ($allitems->{$item} eq '') {
 8440:                 push(@{$trails},$trailstr);
 8441:                 $allitems->{$item} = scalar(@{$trails})-1;
 8442:             }
 8443:             my $deeper = $depth+1;
 8444:             push(@{$parents},$category);
 8445:             if (ref($subcats) eq 'HASH') {
 8446:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 8447:                 for (my $j=@{$parents}; $j>=0; $j--) {
 8448:                     my $higher;
 8449:                     if ($j > 0) {
 8450:                         $higher = &escape($parents->[$j]).':'.
 8451:                                   &escape($parents->[$j-1]).':'.$j;
 8452:                     } else {
 8453:                         $higher = &escape($parents->[$j]).'::'.$j;
 8454:                     }
 8455:                     push(@{$subcats->{$higher}},$subcat);
 8456:                 }
 8457:             }
 8458:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 8459:                                 $subcats);
 8460:             pop(@{$parents});
 8461:         }
 8462:     } else {
 8463:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8464:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8465:         if ($allitems->{$item} eq '') {
 8466:             push(@{$trails},$trailstr);
 8467:             $allitems->{$item} = scalar(@{$trails})-1;
 8468:         }
 8469:     }
 8470:     return;
 8471: }
 8472: 
 8473: =pod
 8474: 
 8475: =item *&assign_categories_table()
 8476: 
 8477: Create a datatable for display of hierarchical categories in a domain,
 8478: with checkboxes to allow a course to be categorized. 
 8479: 
 8480: Inputs:
 8481: 
 8482: cathash - reference to hash of categories defined for the domain (from
 8483:           configuration.db)
 8484: 
 8485: currcat - scalar with an & separated list of categories assigned to a course. 
 8486: 
 8487: Returns: $output (markup to be displayed) 
 8488: 
 8489: =cut
 8490: 
 8491: sub assign_categories_table {
 8492:     my ($cathash,$currcat) = @_;
 8493:     my $output;
 8494:     if (ref($cathash) eq 'HASH') {
 8495:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 8496:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 8497:         $maxdepth = scalar(@cats);
 8498:         if (@cats > 0) {
 8499:             my $itemcount = 0;
 8500:             if (ref($cats[0]) eq 'ARRAY') {
 8501:                 $output = &Apache::loncommon::start_data_table();
 8502:                 my @currcategories;
 8503:                 if ($currcat ne '') {
 8504:                     @currcategories = split('&',$currcat);
 8505:                 }
 8506:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 8507:                     my $parent = $cats[0][$i];
 8508:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8509:                     next if ($parent eq 'instcode');
 8510:                     my $item = &escape($parent).'::0';
 8511:                     my $checked = '';
 8512:                     if (@currcategories > 0) {
 8513:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 8514:                             $checked = ' checked="checked" ';
 8515:                         }
 8516:                     }
 8517:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 8518:                                '<input type="checkbox" name="usecategory" value="'.
 8519:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 8520:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 8521:                     my $depth = 1;
 8522:                     push(@path,$parent);
 8523:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 8524:                     pop(@path);
 8525:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 8526:                     $itemcount ++;
 8527:                 }
 8528:                 $output .= &Apache::loncommon::end_data_table();
 8529:             }
 8530:         }
 8531:     }
 8532:     return $output;
 8533: }
 8534: 
 8535: =pod
 8536: 
 8537: =item *&assign_category_rows()
 8538: 
 8539: Create a datatable row for display of nested categories in a domain,
 8540: with checkboxes to allow a course to be categorized,called recursively.
 8541: 
 8542: Inputs:
 8543: 
 8544: itemcount - track row number for alternating colors
 8545: 
 8546: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 8547:       categories and subcategories.
 8548: 
 8549: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 8550: 
 8551: parent - parent of current category item
 8552: 
 8553: path - Array containing all categories back up through the hierarchy from the
 8554:        current category to the top level.
 8555: 
 8556: currcategories - reference to array of current categories assigned to the course
 8557: 
 8558: Returns: $output (markup to be displayed).
 8559: 
 8560: =cut
 8561: 
 8562: sub assign_category_rows {
 8563:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 8564:     my ($text,$name,$item,$chgstr);
 8565:     if (ref($cats) eq 'ARRAY') {
 8566:         my $maxdepth = scalar(@{$cats});
 8567:         if (ref($cats->[$depth]) eq 'HASH') {
 8568:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 8569:                 my $numchildren = @{$cats->[$depth]{$parent}};
 8570:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8571:                 $text .= '<td><table class="LC_datatable">';
 8572:                 for (my $j=0; $j<$numchildren; $j++) {
 8573:                     $name = $cats->[$depth]{$parent}[$j];
 8574:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 8575:                     my $deeper = $depth+1;
 8576:                     my $checked = '';
 8577:                     if (ref($currcategories) eq 'ARRAY') {
 8578:                         if (@{$currcategories} > 0) {
 8579:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 8580:                                 $checked = ' checked="checked" ';
 8581:                             }
 8582:                         }
 8583:                     }
 8584:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 8585:                              '<input type="checkbox" name="usecategory" value="'.
 8586:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 8587:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 8588:                              '</td><td>';
 8589:                     if (ref($path) eq 'ARRAY') {
 8590:                         push(@{$path},$name);
 8591:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 8592:                         pop(@{$path});
 8593:                     }
 8594:                     $text .= '</td></tr>';
 8595:                 }
 8596:                 $text .= '</table></td>';
 8597:             }
 8598:         }
 8599:     }
 8600:     return $text;
 8601: }
 8602: 
 8603: ############################################################
 8604: ############################################################
 8605: 
 8606: 
 8607: sub commit_customrole {
 8608:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 8609:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 8610:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 8611:                          ($end?', ending '.localtime($end):'').': <b>'.
 8612:               &Apache::lonnet::assigncustomrole(
 8613:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 8614:                  '</b><br />';
 8615:     return $output;
 8616: }
 8617: 
 8618: sub commit_standardrole {
 8619:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 8620:     my ($output,$logmsg,$linefeed);
 8621:     if ($context eq 'auto') {
 8622:         $linefeed = "\n";
 8623:     } else {
 8624:         $linefeed = "<br />\n";
 8625:     }  
 8626:     if ($three eq 'st') {
 8627:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 8628:                                          $one,$two,$sec,$context);
 8629:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 8630:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 8631:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 8632:         } else {
 8633:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 8634:                ($start?', '.&mt('starting').' '.localtime($start):'').
 8635:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 8636:             if ($context eq 'auto') {
 8637:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 8638:             } else {
 8639:                $output .= '<b>'.$result.'</b>'.$linefeed.
 8640:                &mt('Add to classlist').': <b>ok</b>';
 8641:             }
 8642:             $output .= $linefeed;
 8643:         }
 8644:     } else {
 8645:         $output = &mt('Assigning').' '.$three.' in '.$url.
 8646:                ($start?', '.&mt('starting').' '.localtime($start):'').
 8647:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 8648:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 8649:         if ($context eq 'auto') {
 8650:             $output .= $result.$linefeed;
 8651:         } else {
 8652:             $output .= '<b>'.$result.'</b>'.$linefeed;
 8653:         }
 8654:     }
 8655:     return $output;
 8656: }
 8657: 
 8658: sub commit_studentrole {
 8659:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 8660:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 8661:     if ($context eq 'auto') {
 8662:         $linefeed = "\n";
 8663:     } else {
 8664:         $linefeed = '<br />'."\n";
 8665:     }
 8666:     if (defined($one) && defined($two)) {
 8667:         my $cid=$one.'_'.$two;
 8668:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 8669:         my $secchange = 0;
 8670:         my $expire_role_result;
 8671:         my $modify_section_result;
 8672:         if ($oldsec ne '-1') { 
 8673:             if ($oldsec ne $sec) {
 8674:                 $secchange = 1;
 8675:                 my $now = time;
 8676:                 my $uurl='/'.$cid;
 8677:                 $uurl=~s/\_/\//g;
 8678:                 if ($oldsec) {
 8679:                     $uurl.='/'.$oldsec;
 8680:                 }
 8681:                 $oldsecurl = $uurl;
 8682:                 $expire_role_result = 
 8683:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 8684:                 if ($env{'request.course.sec'} ne '') { 
 8685:                     if ($expire_role_result eq 'refused') {
 8686:                         my @roles = ('st');
 8687:                         my @statuses = ('previous');
 8688:                         my @roledoms = ($one);
 8689:                         my $withsec = 1;
 8690:                         my %roleshash = 
 8691:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 8692:                                               \@statuses,\@roles,\@roledoms,$withsec);
 8693:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 8694:                             my ($oldstart,$oldend) = 
 8695:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 8696:                             if ($oldend > 0 && $oldend <= $now) {
 8697:                                 $expire_role_result = 'ok';
 8698:                             }
 8699:                         }
 8700:                     }
 8701:                 }
 8702:                 $result = $expire_role_result;
 8703:             }
 8704:         }
 8705:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 8706:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 8707:             if ($modify_section_result =~ /^ok/) {
 8708:                 if ($secchange == 1) {
 8709:                     if ($sec eq '') {
 8710:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 8711:                     } else {
 8712:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 8713:                     }
 8714:                 } elsif ($oldsec eq '-1') {
 8715:                     if ($sec eq '') {
 8716:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 8717:                     } else {
 8718:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8719:                     }
 8720:                 } else {
 8721:                     if ($sec eq '') {
 8722:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 8723:                     } else {
 8724:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8725:                     }
 8726:                 }
 8727:             } else {
 8728:                 if ($secchange) {       
 8729:                     $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
 8730:                 } else {
 8731:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 8732:                 }
 8733:             }
 8734:             $result = $modify_section_result;
 8735:         } elsif ($secchange == 1) {
 8736:             if ($oldsec eq '') {
 8737:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 8738:             } else {
 8739:                 $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
 8740:             }
 8741:             if ($expire_role_result eq 'refused') {
 8742:                 my $newsecurl = '/'.$cid;
 8743:                 $newsecurl =~ s/\_/\//g;
 8744:                 if ($sec ne '') {
 8745:                     $newsecurl.='/'.$sec;
 8746:                 }
 8747:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 8748:                     if ($sec eq '') {
 8749:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
 8750:                     } else {
 8751:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
 8752:                     }
 8753:                 }
 8754:             }
 8755:         }
 8756:     } else {
 8757:         $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
 8758:         $result = "error: incomplete course id\n";
 8759:     }
 8760:     return $result;
 8761: }
 8762: 
 8763: ############################################################
 8764: ############################################################
 8765: 
 8766: sub check_clone {
 8767:     my ($args,$linefeed) = @_;
 8768:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 8769:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 8770:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 8771:     my $clonemsg;
 8772:     my $can_clone = 0;
 8773: 
 8774:     if ($clonehome eq 'no_host') {
 8775:         $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});     
 8776:     } else {
 8777: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 8778: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 8779: 	    $can_clone = 1;
 8780: 	} else {
 8781: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 8782: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 8783: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 8784:             if (grep(/^\*$/,@cloners)) {
 8785:                 $can_clone = 1;
 8786:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 8787:                 $can_clone = 1;
 8788:             } else {
 8789: 	        my %roleshash =
 8790: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 8791: 					 $args->{'ccdomain'},
 8792:                                          'userroles',['active'],['cc'],
 8793: 					 [$args->{'clonedomain'}]);
 8794: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 8795: 		    $can_clone = 1;
 8796: 	        } else {
 8797:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
 8798: 	        }
 8799: 	    }
 8800:         }
 8801:     }
 8802:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 8803: }
 8804: 
 8805: sub construct_course {
 8806:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 8807:     my $outcome;
 8808:     my $linefeed =  '<br />'."\n";
 8809:     if ($context eq 'auto') {
 8810:         $linefeed = "\n";
 8811:     }
 8812: 
 8813: #
 8814: # Are we cloning?
 8815: #
 8816:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 8817:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 8818: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 8819: 	if ($context ne 'auto') {
 8820:             if ($clonemsg ne '') {
 8821: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 8822:             }
 8823: 	}
 8824: 	$outcome .= $clonemsg.$linefeed;
 8825: 
 8826:         if (!$can_clone) {
 8827: 	    return (0,$outcome);
 8828: 	}
 8829:     }
 8830: 
 8831: #
 8832: # Open course
 8833: #
 8834:     my $crstype = lc($args->{'crstype'});
 8835:     my %cenv=();
 8836:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 8837:                                              $args->{'cdescr'},
 8838:                                              $args->{'curl'},
 8839:                                              $args->{'course_home'},
 8840:                                              $args->{'nonstandard'},
 8841:                                              $args->{'crscode'},
 8842:                                              $args->{'ccuname'}.':'.
 8843:                                              $args->{'ccdomain'},
 8844:                                              $args->{'crstype'});
 8845: 
 8846:     # Note: The testing routines depend on this being output; see 
 8847:     # Utils::Course. This needs to at least be output as a comment
 8848:     # if anyone ever decides to not show this, and Utils::Course::new
 8849:     # will need to be suitably modified.
 8850:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 8851: #
 8852: # Check if created correctly
 8853: #
 8854:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 8855:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 8856:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 8857: 
 8858: #
 8859: # Do the cloning
 8860: #   
 8861:     if ($can_clone && $cloneid) {
 8862: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 8863: 	if ($context ne 'auto') {
 8864: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 8865: 	}
 8866: 	$outcome .= $clonemsg.$linefeed;
 8867: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 8868: # Copy all files
 8869: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 8870: # Restore URL
 8871: 	$cenv{'url'}=$oldcenv{'url'};
 8872: # Restore title
 8873: 	$cenv{'description'}=$oldcenv{'description'};
 8874: # Mark as cloned
 8875: 	$cenv{'clonedfrom'}=$cloneid;
 8876: # Need to clone grading mode
 8877:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 8878:         $cenv{'grading'}=$newenv{'grading'};
 8879: # Do not clone these environment entries
 8880:         &Apache::lonnet::del('environment',
 8881:                   ['default_enrollment_start_date',
 8882:                    'default_enrollment_end_date',
 8883:                    'question.email',
 8884:                    'policy.email',
 8885:                    'comment.email',
 8886:                    'pch.users.denied',
 8887:                    'plc.users.denied'],
 8888:                    $$crsudom,$$crsunum);
 8889:     }
 8890: 
 8891: #
 8892: # Set environment (will override cloned, if existing)
 8893: #
 8894:     my @sections = ();
 8895:     my @xlists = ();
 8896:     if ($args->{'crstype'}) {
 8897:         $cenv{'type'}=$args->{'crstype'};
 8898:     }
 8899:     if ($args->{'crsid'}) {
 8900:         $cenv{'courseid'}=$args->{'crsid'};
 8901:     }
 8902:     if ($args->{'crscode'}) {
 8903:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 8904:     }
 8905:     if ($args->{'crsquota'} ne '') {
 8906:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 8907:     } else {
 8908:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 8909:     }
 8910:     if ($args->{'ccuname'}) {
 8911:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 8912:                                         ':'.$args->{'ccdomain'};
 8913:     } else {
 8914:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 8915:     }
 8916:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 8917:     if ($args->{'crssections'}) {
 8918:         $cenv{'internal.sectionnums'} = '';
 8919:         if ($args->{'crssections'} =~ m/,/) {
 8920:             @sections = split/,/,$args->{'crssections'};
 8921:         } else {
 8922:             $sections[0] = $args->{'crssections'};
 8923:         }
 8924:         if (@sections > 0) {
 8925:             foreach my $item (@sections) {
 8926:                 my ($sec,$gp) = split/:/,$item;
 8927:                 my $class = $args->{'crscode'}.$sec;
 8928:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 8929:                 $cenv{'internal.sectionnums'} .= $item.',';
 8930:                 unless ($addcheck eq 'ok') {
 8931:                     push @badclasses, $class;
 8932:                 }
 8933:             }
 8934:             $cenv{'internal.sectionnums'} =~ s/,$//;
 8935:         }
 8936:     }
 8937: # do not hide course coordinator from staff listing, 
 8938: # even if privileged
 8939:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 8940: # add crosslistings
 8941:     if ($args->{'crsxlist'}) {
 8942:         $cenv{'internal.crosslistings'}='';
 8943:         if ($args->{'crsxlist'} =~ m/,/) {
 8944:             @xlists = split/,/,$args->{'crsxlist'};
 8945:         } else {
 8946:             $xlists[0] = $args->{'crsxlist'};
 8947:         }
 8948:         if (@xlists > 0) {
 8949:             foreach my $item (@xlists) {
 8950:                 my ($xl,$gp) = split/:/,$item;
 8951:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 8952:                 $cenv{'internal.crosslistings'} .= $item.',';
 8953:                 unless ($addcheck eq 'ok') {
 8954:                     push @badclasses, $xl;
 8955:                 }
 8956:             }
 8957:             $cenv{'internal.crosslistings'} =~ s/,$//;
 8958:         }
 8959:     }
 8960:     if ($args->{'autoadds'}) {
 8961:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 8962:     }
 8963:     if ($args->{'autodrops'}) {
 8964:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 8965:     }
 8966: # check for notification of enrollment changes
 8967:     my @notified = ();
 8968:     if ($args->{'notify_owner'}) {
 8969:         if ($args->{'ccuname'} ne '') {
 8970:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 8971:         }
 8972:     }
 8973:     if ($args->{'notify_dc'}) {
 8974:         if ($uname ne '') { 
 8975:             push(@notified,$uname.':'.$udom);
 8976:         }
 8977:     }
 8978:     if (@notified > 0) {
 8979:         my $notifylist;
 8980:         if (@notified > 1) {
 8981:             $notifylist = join(',',@notified);
 8982:         } else {
 8983:             $notifylist = $notified[0];
 8984:         }
 8985:         $cenv{'internal.notifylist'} = $notifylist;
 8986:     }
 8987:     if (@badclasses > 0) {
 8988:         my %lt=&Apache::lonlocal::texthash(
 8989:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
 8990:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 8991:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 8992:         );
 8993:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 8994:                            ' ('.$lt{'adby'}.')';
 8995:         if ($context eq 'auto') {
 8996:             $outcome .= $badclass_msg.$linefeed;
 8997:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 8998:             foreach my $item (@badclasses) {
 8999:                 if ($context eq 'auto') {
 9000:                     $outcome .= " - $item\n";
 9001:                 } else {
 9002:                     $outcome .= "<li>$item</li>\n";
 9003:                 }
 9004:             }
 9005:             if ($context eq 'auto') {
 9006:                 $outcome .= $linefeed;
 9007:             } else {
 9008:                 $outcome .= "</ul><br /><br /></div>\n";
 9009:             }
 9010:         } 
 9011:     }
 9012:     if ($args->{'no_end_date'}) {
 9013:         $args->{'endaccess'} = 0;
 9014:     }
 9015:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9016:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9017:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9018:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9019:     if ($args->{'showphotos'}) {
 9020:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9021:     }
 9022:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9023:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9024:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9025:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9026:             my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student'); 
 9027:             if ($context eq 'auto') {
 9028:                 $outcome .= $krb_msg;
 9029:             } else {
 9030:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9031:             }
 9032:             $outcome .= $linefeed;
 9033:         }
 9034:     }
 9035:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9036:        if ($args->{'setpolicy'}) {
 9037:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9038:        }
 9039:        if ($args->{'setcontent'}) {
 9040:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9041:        }
 9042:     }
 9043:     if ($args->{'reshome'}) {
 9044: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9045: 	$cenv{'reshome'}=~s/\/+$/\//;
 9046:     }
 9047: #
 9048: # course has keyed access
 9049: #
 9050:     if ($args->{'setkeys'}) {
 9051:        $cenv{'keyaccess'}='yes';
 9052:     }
 9053: # if specified, key authority is not course, but user
 9054: # only active if keyaccess is yes
 9055:     if ($args->{'keyauth'}) {
 9056: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9057: 	$user = &LONCAPA::clean_username($user);
 9058: 	$domain = &LONCAPA::clean_username($domain);
 9059: 	if ($user ne '' && $domain ne '') {
 9060: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9061: 	}
 9062:     }
 9063: 
 9064:     if ($args->{'disresdis'}) {
 9065:         $cenv{'pch.roles.denied'}='st';
 9066:     }
 9067:     if ($args->{'disablechat'}) {
 9068:         $cenv{'plc.roles.denied'}='st';
 9069:     }
 9070: 
 9071:     # Record we've not yet viewed the Course Initialization Helper for this 
 9072:     # course
 9073:     $cenv{'course.helper.not.run'} = 1;
 9074:     #
 9075:     # Use new Randomseed
 9076:     #
 9077:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9078:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9079:     #
 9080:     # The encryption code and receipt prefix for this course
 9081:     #
 9082:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9083:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9084:     #
 9085:     # By default, use standard grading
 9086:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9087: 
 9088:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9089:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9090: #
 9091: # Open all assignments
 9092: #
 9093:     if ($args->{'openall'}) {
 9094:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9095:        my %storecontent = ($storeunder         => time,
 9096:                            $storeunder.'.type' => 'date_start');
 9097:        
 9098:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9099:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9100:    }
 9101: #
 9102: # Set first page
 9103: #
 9104:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9105: 	    || ($cloneid)) {
 9106: 	use LONCAPA::map;
 9107: 	$outcome .= &mt('Setting first resource').': ';
 9108: 
 9109: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9110:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9111: 
 9112:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9113:         my $title; my $url;
 9114:         if ($args->{'firstres'} eq 'syl') {
 9115: 	    $title='Syllabus';
 9116:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9117:         } else {
 9118:             $title='Navigate Contents';
 9119:             $url='/adm/navmaps';
 9120:         }
 9121: 
 9122:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9123: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9124: 
 9125: 	if ($errtext) { $fatal=2; }
 9126:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9127:     }
 9128: 
 9129:     return (1,$outcome);
 9130: }
 9131: 
 9132: ############################################################
 9133: ############################################################
 9134: 
 9135: sub course_type {
 9136:     my ($cid) = @_;
 9137:     if (!defined($cid)) {
 9138:         $cid = $env{'request.course.id'};
 9139:     }
 9140:     if (defined($env{'course.'.$cid.'.type'})) {
 9141:         return $env{'course.'.$cid.'.type'};
 9142:     } else {
 9143:         return 'Course';
 9144:     }
 9145: }
 9146: 
 9147: sub group_term {
 9148:     my $crstype = &course_type();
 9149:     my %names = (
 9150:                   'Course' => 'group',
 9151:                   'Group' => 'team',
 9152:                 );
 9153:     return $names{$crstype};
 9154: }
 9155: 
 9156: sub icon {
 9157:     my ($file)=@_;
 9158:     my $curfext = lc((split(/\./,$file))[-1]);
 9159:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9160:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9161:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9162: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9163: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9164: 	            $curfext.".gif") {
 9165: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9166: 		$curfext.".gif";
 9167: 	}
 9168:     }
 9169:     return &lonhttpdurl($iconname);
 9170: } 
 9171: 
 9172: sub lonhttpd_port {
 9173:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 9174:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 9175:     # IE doesn't like a secure page getting images from a non-secure
 9176:     # port (when logging we haven't parsed the browser type so default
 9177:     # back to secure
 9178:     if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer')
 9179: 	&& $ENV{'SERVER_PORT'} == 443) {
 9180: 	return 443;
 9181:     }
 9182:     return $lonhttpd_port;
 9183: 
 9184: }
 9185: 
 9186: sub lonhttpdurl {
 9187:     my ($url)=@_;
 9188: 
 9189:     my $lonhttpd_port = &lonhttpd_port();
 9190:     if ($lonhttpd_port == 443) {
 9191: 	return 'https://'.$ENV{'SERVER_NAME'}.$url;
 9192:     }
 9193:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 9194: }
 9195: 
 9196: sub connection_aborted {
 9197:     my ($r)=@_;
 9198:     $r->print(" ");$r->rflush();
 9199:     my $c = $r->connection;
 9200:     return $c->aborted();
 9201: }
 9202: 
 9203: #    Escapes strings that may have embedded 's that will be put into
 9204: #    strings as 'strings'.
 9205: sub escape_single {
 9206:     my ($input) = @_;
 9207:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9208:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9209:     return $input;
 9210: }
 9211: 
 9212: #  Same as escape_single, but escape's "'s  This 
 9213: #  can be used for  "strings"
 9214: sub escape_double {
 9215:     my ($input) = @_;
 9216:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9217:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9218:     return $input;
 9219: }
 9220:  
 9221: #   Escapes the last element of a full URL.
 9222: sub escape_url {
 9223:     my ($url)   = @_;
 9224:     my @urlslices = split(/\//, $url,-1);
 9225:     my $lastitem = &escape(pop(@urlslices));
 9226:     return join('/',@urlslices).'/'.$lastitem;
 9227: }
 9228: 
 9229: # -------------------------------------------------------- Initliaze user login
 9230: sub init_user_environment {
 9231:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9232:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9233: 
 9234:     my $public=($username eq 'public' && $domain eq 'public');
 9235: 
 9236: # See if old ID present, if so, remove
 9237: 
 9238:     my ($filename,$cookie,$userroles);
 9239:     my $now=time;
 9240: 
 9241:     if ($public) {
 9242: 	my $max_public=100;
 9243: 	my $oldest;
 9244: 	my $oldest_time=0;
 9245: 	for(my $next=1;$next<=$max_public;$next++) {
 9246: 	    if (-e $lonids."/publicuser_$next.id") {
 9247: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9248: 		if ($mtime<$oldest_time || !$oldest_time) {
 9249: 		    $oldest_time=$mtime;
 9250: 		    $oldest=$next;
 9251: 		}
 9252: 	    } else {
 9253: 		$cookie="publicuser_$next";
 9254: 		last;
 9255: 	    }
 9256: 	}
 9257: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9258:     } else {
 9259: 	# if this isn't a robot, kill any existing non-robot sessions
 9260: 	if (!$args->{'robot'}) {
 9261: 	    opendir(DIR,$lonids);
 9262: 	    while ($filename=readdir(DIR)) {
 9263: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9264: 		    unlink($lonids.'/'.$filename);
 9265: 		}
 9266: 	    }
 9267: 	    closedir(DIR);
 9268: 	}
 9269: # Give them a new cookie
 9270: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9271: 		                   : $now);
 9272: 	$cookie="$username\_$id\_$domain\_$authhost";
 9273:     
 9274: # Initialize roles
 9275: 
 9276: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9277:     }
 9278: # ------------------------------------ Check browser type and MathML capability
 9279: 
 9280:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9281:         $clientunicode,$clientos) = &decode_user_agent($r);
 9282: 
 9283: # -------------------------------------- Any accessibility options to remember?
 9284:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9285: 	foreach my $option ('imagesuppress','appletsuppress',
 9286: 			    'embedsuppress','fontenhance','blackwhite') {
 9287: 	    if ($form->{$option} eq 'true') {
 9288: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9289: 				     $domain,$username);
 9290: 	    } else {
 9291: 		&Apache::lonnet::del('environment',[$option],
 9292: 				     $domain,$username);
 9293: 	    }
 9294: 	}
 9295:     }
 9296: # ------------------------------------------------------------- Get environment
 9297: 
 9298:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9299:     my ($tmp) = keys(%userenv);
 9300:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9301: 	# default remote control to off
 9302: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9303:     } else {
 9304: 	undef(%userenv);
 9305:     }
 9306:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9307: 	$form->{'interface'}=$userenv{'interface'};
 9308:     }
 9309:     $env{'environment.remote'}=$userenv{'remote'};
 9310:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9311: 
 9312: # --------------- Do not trust query string to be put directly into environment
 9313:     foreach my $option ('imagesuppress','appletsuppress',
 9314: 			'embedsuppress','fontenhance','blackwhite',
 9315: 			'interface','localpath','localres') {
 9316: 	$form->{$option}=~s/[\n\r\=]//gs;
 9317:     }
 9318: # --------------------------------------------------------- Write first profile
 9319: 
 9320:     {
 9321: 	my %initial_env = 
 9322: 	    ("user.name"          => $username,
 9323: 	     "user.domain"        => $domain,
 9324: 	     "user.home"          => $authhost,
 9325: 	     "browser.type"       => $clientbrowser,
 9326: 	     "browser.version"    => $clientversion,
 9327: 	     "browser.mathml"     => $clientmathml,
 9328: 	     "browser.unicode"    => $clientunicode,
 9329: 	     "browser.os"         => $clientos,
 9330: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9331: 	     "request.course.fn"  => '',
 9332: 	     "request.course.uri" => '',
 9333: 	     "request.course.sec" => '',
 9334: 	     "request.role"       => 'cm',
 9335: 	     "request.role.adv"   => $env{'user.adv'},
 9336: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9337: 
 9338:         if ($form->{'localpath'}) {
 9339: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9340: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9341:         }
 9342: 	
 9343: 	if ($public) {
 9344: 	    $initial_env{"environment.remote"} = "off";
 9345: 	}
 9346: 	if ($form->{'interface'}) {
 9347: 	    $form->{'interface'}=~s/\W//gs;
 9348: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9349: 	    $env{'browser.interface'}=$form->{'interface'};
 9350: 	    foreach my $option ('imagesuppress','appletsuppress',
 9351: 				'embedsuppress','fontenhance','blackwhite') {
 9352: 		if (($form->{$option} eq 'true') ||
 9353: 		    ($userenv{$option} eq 'on')) {
 9354: 		    $initial_env{"browser.$option"} = "on";
 9355: 		}
 9356: 	    }
 9357: 	}
 9358: 
 9359: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9360: 	
 9361: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9362: 		 &GDBM_WRCREAT(),0640)) {
 9363: 	    &_add_to_env(\%disk_env,\%initial_env);
 9364: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9365: 	    &_add_to_env(\%disk_env,$userroles);
 9366: 	    if (ref($args->{'extra_env'})) {
 9367: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9368: 	    }
 9369: 	    untie(%disk_env);
 9370: 	} else {
 9371: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 9372: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 9373: 	    return 'error: '.$!;
 9374: 	}
 9375:     }
 9376:     $env{'request.role'}='cm';
 9377:     $env{'request.role.adv'}=$env{'user.adv'};
 9378:     $env{'browser.type'}=$clientbrowser;
 9379: 
 9380:     return $cookie;
 9381: 
 9382: }
 9383: 
 9384: sub _add_to_env {
 9385:     my ($idf,$env_data,$prefix) = @_;
 9386:     if (ref($env_data) eq 'HASH') {
 9387:         while (my ($key,$value) = each(%$env_data)) {
 9388: 	    $idf->{$prefix.$key} = $value;
 9389: 	    $env{$prefix.$key}   = $value;
 9390:         }
 9391:     }
 9392: }
 9393: 
 9394: 
 9395: =pod
 9396: 
 9397: =back
 9398: 
 9399: =cut
 9400: 
 9401: 1;
 9402: __END__;
 9403: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>