File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.692.2.12: download - view: text, annotated - select for diffs
Mon Jan 12 04:39:30 2009 UTC (15 years, 4 months ago) by raeburn
Branches: version_2_8_X
CVS tags: version_2_8_1, version_2_8_0, GCI_1
Diff to branchpoint 1.692: preferred, unified
- Backport 1.732.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.692.2.12 2009/01/12 04:39:30 raeburn 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 Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:               "<font color=yellow>INFO: Read file types</font>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript" >
  410:     var stdeditbrowser;
  411:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
  412:         var url = '/adm/pickstudent?';
  413:         var filter;
  414: 	if (!ignorefilter) {
  415: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  416: 	}
  417:         if (filter != null) {
  418:            if (filter != '') {
  419:                url += 'filter='+filter+'&';
  420: 	   }
  421:         }
  422:         url += 'form=' + formname + '&unameelement='+uname+
  423:                                     '&udomelement='+udom;
  424: 	if (roleflag) { url+="&roles=1"; }
  425:         var title = 'Student_Browser';
  426:         var options = 'scrollbars=1,resizable=1,menubar=0';
  427:         options += ',width=700,height=600';
  428:         stdeditbrowser = open(url,title,options,'1');
  429:         stdeditbrowser.focus();
  430:     }
  431: </script>
  432: ENDSTDBRW
  433: }
  434: 
  435: sub selectstudent_link {
  436:    my ($form,$unameele,$udomele)=@_;
  437:    if ($env{'request.course.id'}) {  
  438:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  439: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  440: 					'/'.$env{'request.course.sec'})) {
  441: 	   return '';
  442:        }
  443:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  444:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  445:    }
  446:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  447:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  448:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  449:    }
  450:    return '';
  451: }
  452: 
  453: sub authorbrowser_javascript {
  454:     return <<"ENDAUTHORBRW";
  455: <script type="text/javascript">
  456: var stdeditbrowser;
  457: 
  458: function openauthorbrowser(formname,udom) {
  459:     var url = '/adm/pickauthor?';
  460:     url += 'form='+formname+'&roledom='+udom;
  461:     var title = 'Author_Browser';
  462:     var options = 'scrollbars=1,resizable=1,menubar=0';
  463:     options += ',width=700,height=600';
  464:     stdeditbrowser = open(url,title,options,'1');
  465:     stdeditbrowser.focus();
  466: }
  467: 
  468: </script>
  469: ENDAUTHORBRW
  470: }
  471: 
  472: sub coursebrowser_javascript {
  473:     my ($domainfilter,$sec_element,$formname)=@_;
  474:     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');
  475:    my $output = '
  476: <script type="text/javascript">
  477:     var stdeditbrowser;'."\n";
  478:    $output .= <<"ENDSTDBRW";
  479:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  480:         var url = '/adm/pickcourse?';
  481:         var domainfilter = '';
  482:         var formid = getFormIdByName(formname);
  483:         if (formid > -1) {
  484:             var domid = getIndexByName(formid,udom);
  485:             if (domid > -1) {
  486:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  487:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  488:                 }
  489:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  490:                     domainfilter=document.forms[formid].elements[domid].value;
  491:                 }
  492:             }
  493:         }
  494:         if (domainfilter != null) {
  495:            if (domainfilter != '') {
  496:                url += 'domainfilter='+domainfilter+'&';
  497: 	   }
  498:         }
  499:         url += 'form=' + formname + '&cnumelement='+uname+
  500: 	                            '&cdomelement='+udom+
  501:                                     '&cnameelement='+desc;
  502:         if (extra_element !=null && extra_element != '') {
  503:             if (formname == 'rolechoice' || formname == 'studentform') {
  504:                 url += '&roleelement='+extra_element;
  505:                 if (domainfilter == null || domainfilter == '') {
  506:                     url += '&domainfilter='+extra_element;
  507:                 }
  508:             }
  509:             else {
  510:                 if (formname == 'portform') {
  511:                     url += '&setroles='+extra_element;
  512:                 }
  513:             }     
  514:         }
  515:         if (multflag !=null && multflag != '') {
  516:             url += '&multiple='+multflag;
  517:         }
  518:         if (crstype == 'Course/Group') {
  519:             if (formname == 'cu') {
  520:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  521:                 if (crstype == "") {
  522:                     alert("$crs_or_grp_alert");
  523:                     return;
  524:                 }
  525:             }
  526:         }
  527:         if (crstype !=null && crstype != '') {
  528:             url += '&type='+crstype;
  529:         }
  530:         var title = 'Course_Browser';
  531:         var options = 'scrollbars=1,resizable=1,menubar=0';
  532:         options += ',width=700,height=600';
  533:         stdeditbrowser = open(url,title,options,'1');
  534:         stdeditbrowser.focus();
  535:     }
  536: 
  537:     function getFormIdByName(formname) {
  538:         for (var i=0;i<document.forms.length;i++) {
  539:             if (document.forms[i].name == formname) {
  540:                 return i;
  541:             }
  542:         }
  543:         return -1; 
  544:     }
  545: 
  546:     function getIndexByName(formid,item) {
  547:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  548:             if (document.forms[formid].elements[i].name == item) {
  549:                 return i;
  550:             }
  551:         }
  552:         return -1;
  553:     }
  554: ENDSTDBRW
  555:     if ($sec_element ne '') {
  556:         $output .= &setsec_javascript($sec_element,$formname);
  557:     }
  558:     $output .= '
  559: </script>';
  560:     return $output;
  561: }
  562: 
  563: sub setsec_javascript {
  564:     my ($sec_element,$formname) = @_;
  565:     my $setsections = qq|
  566: function setSect(sectionlist) {
  567:     var sectionsArray = new Array();
  568:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  569:         sectionsArray = sectionlist.split(",");
  570:     }
  571:     var numSections = sectionsArray.length;
  572:     document.$formname.$sec_element.length = 0;
  573:     if (numSections == 0) {
  574:         document.$formname.$sec_element.multiple=false;
  575:         document.$formname.$sec_element.size=1;
  576:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  577:     } else {
  578:         if (numSections == 1) {
  579:             document.$formname.$sec_element.multiple=false;
  580:             document.$formname.$sec_element.size=1;
  581:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  582:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  583:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  584:         } else {
  585:             for (var i=0; i<numSections; i++) {
  586:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  587:             }
  588:             document.$formname.$sec_element.multiple=true
  589:             if (numSections < 3) {
  590:                 document.$formname.$sec_element.size=numSections;
  591:             } else {
  592:                 document.$formname.$sec_element.size=3;
  593:             }
  594:             document.$formname.$sec_element.options[0].selected = false
  595:         }
  596:     }
  597: }
  598: |;
  599:     return $setsections;
  600: }
  601: 
  602: 
  603: sub selectcourse_link {
  604:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  605:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  606:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
  607: }
  608: 
  609: sub selectauthor_link {
  610:    my ($form,$udom)=@_;
  611:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  612:           &mt('Select Author').'</a>';
  613: }
  614: 
  615: sub check_uncheck_jscript {
  616:     my $jscript = <<"ENDSCRT";
  617: function checkAll(field) {
  618:     if (field.length > 0) {
  619:         for (i = 0; i < field.length; i++) {
  620:             field[i].checked = true ;
  621:         }
  622:     } else {
  623:         field.checked = true
  624:     }
  625: }
  626:  
  627: function uncheckAll(field) {
  628:     if (field.length > 0) {
  629:         for (i = 0; i < field.length; i++) {
  630:             field[i].checked = false ;
  631:         }
  632:     } else {
  633:         field.checked = false ;
  634:     }
  635: }
  636: ENDSCRT
  637:     return $jscript;
  638: }
  639: 
  640: sub select_timezone {
  641:    my ($name,$selected,$onchange,$includeempty)=@_;
  642:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  643:    if ($includeempty) {
  644:        $output .= '<option value=""';
  645:        if (($selected eq '') || ($selected eq 'local')) {
  646:            $output .= ' selected="selected" ';
  647:        }
  648:        $output .= '> </option>';
  649:    }
  650:    my @timezones = DateTime::TimeZone->all_names;
  651:    foreach my $tzone (@timezones) {
  652:        $output.= '<option value="'.$tzone.'"';
  653:        if ($tzone eq $selected) {
  654:            $output.=' selected="selected"';
  655:        }
  656:        $output.=">$tzone</option>\n";
  657:    }
  658:    $output.="</select>";
  659:    return $output;
  660: }
  661: 
  662: sub select_datelocale {
  663:     my ($name,$selected,$onchange,$includeempty)=@_;
  664:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  665:     if ($includeempty) {
  666:         $output .= '<option value=""';
  667:         if ($selected eq '') {
  668:             $output .= ' selected="selected" ';
  669:         }
  670:         $output .= '> </option>';
  671:     }
  672:     my (@possibles,%locale_names);
  673:     my @locales = DateTime::Locale::Catalog::Locales;
  674:     foreach my $locale (@locales) {
  675:         if (ref($locale) eq 'HASH') {
  676:             my $id = $locale->{'id'};
  677:             if ($id ne '') {
  678:                 my $en_terr = $locale->{'en_territory'};
  679:                 my $native_terr = $locale->{'native_territory'};
  680:                 my @languages = &Apache::lonlocal::preferred_languages();
  681:                 if (grep(/^en$/,@languages) || !@languages) {
  682:                     if ($en_terr ne '') {
  683:                         $locale_names{$id} = '('.$en_terr.')';
  684:                     } elsif ($native_terr ne '') {
  685:                         $locale_names{$id} = $native_terr;
  686:                     }
  687:                 } else {
  688:                     if ($native_terr ne '') {
  689:                         $locale_names{$id} = $native_terr.' ';
  690:                     } elsif ($en_terr ne '') {
  691:                         $locale_names{$id} = '('.$en_terr.')';
  692:                     }
  693:                 }
  694:                 push (@possibles,$id);
  695:             }
  696:         }
  697:     }
  698:     foreach my $item (sort(@possibles)) {
  699:         $output.= '<option value="'.$item.'"';
  700:         if ($item eq $selected) {
  701:             $output.=' selected="selected"';
  702:         }
  703:         $output.=">$item";
  704:         if ($locale_names{$item} ne '') {
  705:             $output.="  $locale_names{$item}</option>\n";
  706:         }
  707:         $output.="</option>\n";
  708:     }
  709:     $output.="</select>";
  710:     return $output;
  711: }
  712: 
  713: =pod
  714: 
  715: =item * &linked_select_forms(...)
  716: 
  717: linked_select_forms returns a string containing a <script></script> block
  718: and html for two <select> menus.  The select menus will be linked in that
  719: changing the value of the first menu will result in new values being placed
  720: in the second menu.  The values in the select menu will appear in alphabetical
  721: order unless a defined order is provided.
  722: 
  723: linked_select_forms takes the following ordered inputs:
  724: 
  725: =over 4
  726: 
  727: =item * $formname, the name of the <form> tag
  728: 
  729: =item * $middletext, the text which appears between the <select> tags
  730: 
  731: =item * $firstdefault, the default value for the first menu
  732: 
  733: =item * $firstselectname, the name of the first <select> tag
  734: 
  735: =item * $secondselectname, the name of the second <select> tag
  736: 
  737: =item * $hashref, a reference to a hash containing the data for the menus.
  738: 
  739: =item * $menuorder, the order of values in the first menu
  740: 
  741: =back 
  742: 
  743: Below is an example of such a hash.  Only the 'text', 'default', and 
  744: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  745: values for the first select menu.  The text that coincides with the 
  746: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  747: and text for the second menu are given in the hash pointed to by 
  748: $menu{$choice1}->{'select2'}.  
  749: 
  750:  my %menu = ( A1 => { text =>"Choice A1" ,
  751:                        default => "B3",
  752:                        select2 => { 
  753:                            B1 => "Choice B1",
  754:                            B2 => "Choice B2",
  755:                            B3 => "Choice B3",
  756:                            B4 => "Choice B4"
  757:                            },
  758:                        order => ['B4','B3','B1','B2'],
  759:                    },
  760:                A2 => { text =>"Choice A2" ,
  761:                        default => "C2",
  762:                        select2 => { 
  763:                            C1 => "Choice C1",
  764:                            C2 => "Choice C2",
  765:                            C3 => "Choice C3"
  766:                            },
  767:                        order => ['C2','C1','C3'],
  768:                    },
  769:                A3 => { text =>"Choice A3" ,
  770:                        default => "D6",
  771:                        select2 => { 
  772:                            D1 => "Choice D1",
  773:                            D2 => "Choice D2",
  774:                            D3 => "Choice D3",
  775:                            D4 => "Choice D4",
  776:                            D5 => "Choice D5",
  777:                            D6 => "Choice D6",
  778:                            D7 => "Choice D7"
  779:                            },
  780:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  781:                    }
  782:                );
  783: 
  784: =cut
  785: 
  786: sub linked_select_forms {
  787:     my ($formname,
  788:         $middletext,
  789:         $firstdefault,
  790:         $firstselectname,
  791:         $secondselectname, 
  792:         $hashref,
  793:         $menuorder,
  794:         ) = @_;
  795:     my $second = "document.$formname.$secondselectname";
  796:     my $first = "document.$formname.$firstselectname";
  797:     # output the javascript to do the changing
  798:     my $result = '';
  799:     $result.="<script type=\"text/javascript\">\n";
  800:     $result.="var select2data = new Object();\n";
  801:     $" = '","';
  802:     my $debug = '';
  803:     foreach my $s1 (sort(keys(%$hashref))) {
  804:         $result.="select2data.d_$s1 = new Object();\n";        
  805:         $result.="select2data.d_$s1.def = new String('".
  806:             $hashref->{$s1}->{'default'}."');\n";
  807:         $result.="select2data.d_$s1.values = new Array(";
  808:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  809:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  810:             @s2values = @{$hashref->{$s1}->{'order'}};
  811:         }
  812:         $result.="\"@s2values\");\n";
  813:         $result.="select2data.d_$s1.texts = new Array(";        
  814:         my @s2texts;
  815:         foreach my $value (@s2values) {
  816:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  817:         }
  818:         $result.="\"@s2texts\");\n";
  819:     }
  820:     $"=' ';
  821:     $result.= <<"END";
  822: 
  823: function select1_changed() {
  824:     // Determine new choice
  825:     var newvalue = "d_" + $first.value;
  826:     // update select2
  827:     var values     = select2data[newvalue].values;
  828:     var texts      = select2data[newvalue].texts;
  829:     var select2def = select2data[newvalue].def;
  830:     var i;
  831:     // out with the old
  832:     for (i = 0; i < $second.options.length; i++) {
  833:         $second.options[i] = null;
  834:     }
  835:     // in with the nuclear
  836:     for (i=0;i<values.length; i++) {
  837:         $second.options[i] = new Option(values[i]);
  838:         $second.options[i].value = values[i];
  839:         $second.options[i].text = texts[i];
  840:         if (values[i] == select2def) {
  841:             $second.options[i].selected = true;
  842:         }
  843:     }
  844: }
  845: </script>
  846: END
  847:     # output the initial values for the selection lists
  848:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  849:     my @order = sort(keys(%{$hashref}));
  850:     if (ref($menuorder) eq 'ARRAY') {
  851:         @order = @{$menuorder};
  852:     }
  853:     foreach my $value (@order) {
  854:         $result.="    <option value=\"$value\" ";
  855:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  856:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  857:     }
  858:     $result .= "</select>\n";
  859:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  860:     $result .= $middletext;
  861:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  862:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  863:     
  864:     my @secondorder = sort(keys(%select2));
  865:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  866:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  867:     }
  868:     foreach my $value (@secondorder) {
  869:         $result.="    <option value=\"$value\" ";        
  870:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  871:         $result.=">".&mt($select2{$value})."</option>\n";
  872:     }
  873:     $result .= "</select>\n";
  874:     #    return $debug;
  875:     return $result;
  876: }   #  end of sub linked_select_forms {
  877: 
  878: =pod
  879: 
  880: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  881: 
  882: Returns a string corresponding to an HTML link to the given help
  883: $topic, where $topic corresponds to the name of a .tex file in
  884: /home/httpd/html/adm/help/tex, with underscores replaced by
  885: spaces. 
  886: 
  887: $text will optionally be linked to the same topic, allowing you to
  888: link text in addition to the graphic. If you do not want to link
  889: text, but wish to specify one of the later parameters, pass an
  890: empty string. 
  891: 
  892: $stayOnPage is a value that will be interpreted as a boolean. If true,
  893: the link will not open a new window. If false, the link will open
  894: a new window using Javascript. (Default is false.) 
  895: 
  896: $width and $height are optional numerical parameters that will
  897: override the width and height of the popped up window, which may
  898: be useful for certain help topics with big pictures included. 
  899: 
  900: =cut
  901: 
  902: sub help_open_topic {
  903:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  904:     $text = "" if (not defined $text);
  905:     $stayOnPage = 0 if (not defined $stayOnPage);
  906:     if ($env{'browser.interface'} eq 'textual') {
  907: 	$stayOnPage=1;
  908:     }
  909:     $width = 350 if (not defined $width);
  910:     $height = 400 if (not defined $height);
  911:     my $filename = $topic;
  912:     $filename =~ s/ /_/g;
  913: 
  914:     my $template = "";
  915:     my $link;
  916:     
  917:     $topic=~s/\W/\_/g;
  918: 
  919:     if (!$stayOnPage) {
  920: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  921:     } else {
  922: 	$link = "/adm/help/${filename}.hlp";
  923:     }
  924: 
  925:     # Add the text
  926:     if ($text ne "") {
  927: 	$template .= 
  928:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  929:             "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  930:     }
  931: 
  932:     # Add the graphic
  933:     my $title = &mt('Online Help');
  934:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  935:     $template .= <<"ENDTEMPLATE";
  936:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  937: ENDTEMPLATE
  938:     if ($text ne '') { $template.='</span></td></tr></table>' };
  939:     return $template;
  940: 
  941: }
  942: 
  943: # This is a quicky function for Latex cheatsheet editing, since it 
  944: # appears in at least four places
  945: sub helpLatexCheatsheet {
  946:     my ($topic,$text,$not_author) = @_;
  947:     my $out;
  948:     my $addOther = '';
  949:     if ($topic) {
  950: 	$addOther = Apache::loncommon::help_open_topic($topic,$text,
  951: 						       undef, undef, 600).
  952: 							'</td><td>';
  953:     }
  954:     $out = '<table><tr><td>'.
  955: 	   $addOther.
  956: 	   &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
  957: 					       undef,undef,600).
  958: 	   '</td><td>'.
  959: 	   &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
  960: 					       undef,undef,600).
  961: 	   '</td>';
  962:     unless ($not_author) {
  963:         $out .= '<td>'.
  964: 	        &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
  965: 	                                            undef,undef,600).
  966: 	        '</td>';
  967:     }
  968:     $out .= '</tr></table>';
  969:     return $out;
  970: }
  971: 
  972: sub general_help {
  973:     my $helptopic='Student_Intro';
  974:     if ($env{'request.role'}=~/^(ca|au)/) {
  975: 	$helptopic='Authoring_Intro';
  976:     } elsif ($env{'request.role'}=~/^cc/) {
  977: 	$helptopic='Course_Coordination_Intro';
  978:     } elsif ($env{'request.role'}=~/^dc/) {
  979:         $helptopic='Domain_Coordination_Intro';
  980:     }
  981:     return $helptopic;
  982: }
  983: 
  984: sub update_help_link {
  985:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  986:     my $origurl = $ENV{'REQUEST_URI'};
  987:     $origurl=~s|^/~|/priv/|;
  988:     my $timestamp = time;
  989:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  990:         $$datum = &escape($$datum);
  991:     }
  992: 
  993:     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";
  994:     my $output .= <<"ENDOUTPUT";
  995: <script type="text/javascript">
  996: banner_link = '$banner_link';
  997: </script>
  998: ENDOUTPUT
  999:     return $output;
 1000: }
 1001: 
 1002: # now just updates the help link and generates a blue icon
 1003: sub help_open_menu {
 1004:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1005: 	= @_;    
 1006:     $stayOnPage = 0 if (not defined $stayOnPage);
 1007:     # only use pop-up help (stayOnPage == 0)
 1008:     # if environment.remote is on (using remote control UI)
 1009:     if ($env{'browser.interface'} eq 'textual' ||
 1010:     	$env{'environment.remote'} eq 'off' ) {
 1011:         $stayOnPage=1;
 1012:     }
 1013:     my $output;
 1014:     if ($component_help) {
 1015: 	if (!$text) {
 1016: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1017: 				       $width,$height);
 1018: 	} else {
 1019: 	    my $help_text;
 1020: 	    $help_text=&unescape($topic);
 1021: 	    $output='<table><tr><td>'.
 1022: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1023: 				 $width,$height).'</td></tr></table>';
 1024: 	}
 1025:     }
 1026:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1027:     return $output.$banner_link;
 1028: }
 1029: 
 1030: sub top_nav_help {
 1031:     my ($text) = @_;
 1032:     $text = &mt($text);
 1033:     my $stay_on_page = 
 1034: 	($env{'browser.interface'}  eq 'textual' ||
 1035: 	 $env{'environment.remote'} eq 'off' );
 1036:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1037: 	                     : "javascript:helpMenu('open')";
 1038:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1039: 
 1040:     my $title = &mt('Get help');
 1041: 
 1042:     return <<"END";
 1043: $banner_link
 1044:  <a href="$link" title="$title">$text</a>
 1045: END
 1046: }
 1047: 
 1048: sub help_menu_js {
 1049:     my ($text) = @_;
 1050: 
 1051:     my $stayOnPage = 
 1052: 	($env{'browser.interface'}  eq 'textual' ||
 1053: 	 $env{'environment.remote'} eq 'off' );
 1054: 
 1055:     my $width = 620;
 1056:     my $height = 600;
 1057:     my $helptopic=&general_help();
 1058:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1059:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1060:     my $start_page =
 1061:         &Apache::loncommon::start_page('Help Menu', undef,
 1062: 				       {'frameset'    => 1,
 1063: 					'js_ready'    => 1,
 1064: 					'add_entries' => {
 1065: 					    'border' => '0',
 1066: 					    'rows'   => "110,*",},});
 1067:     my $end_page =
 1068:         &Apache::loncommon::end_page({'frameset' => 1,
 1069: 				      'js_ready' => 1,});
 1070: 
 1071:     my $template .= <<"ENDTEMPLATE";
 1072: <script type="text/javascript">
 1073: // <!-- BEGIN LON-CAPA Internal
 1074: // <![CDATA[
 1075: var banner_link = '';
 1076: function helpMenu(target) {
 1077:     var caller = this;
 1078:     if (target == 'open') {
 1079:         var newWindow = null;
 1080:         try {
 1081:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1082:         }
 1083:         catch(error) {
 1084:             writeHelp(caller);
 1085:             return;
 1086:         }
 1087:         if (newWindow) {
 1088:             caller = newWindow;
 1089:         }
 1090:     }
 1091:     writeHelp(caller);
 1092:     return;
 1093: }
 1094: function writeHelp(caller) {
 1095:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1096:     caller.document.close()
 1097:     caller.focus()
 1098: }
 1099: // ]]>
 1100: // END LON-CAPA Internal -->
 1101: </script>
 1102: ENDTEMPLATE
 1103:     return $template;
 1104: }
 1105: 
 1106: sub help_open_bug {
 1107:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1108:     unless ($env{'user.adv'}) { return ''; }
 1109:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1110:     $text = "" if (not defined $text);
 1111:     $stayOnPage = 0 if (not defined $stayOnPage);
 1112:     if ($env{'browser.interface'} eq 'textual' ||
 1113: 	$env{'environment.remote'} eq 'off' ) {
 1114: 	$stayOnPage=1;
 1115:     }
 1116:     $width = 600 if (not defined $width);
 1117:     $height = 600 if (not defined $height);
 1118: 
 1119:     $topic=~s/\W+/\+/g;
 1120:     my $link='';
 1121:     my $template='';
 1122:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1123: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1124:     if (!$stayOnPage)
 1125:     {
 1126: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1127:     }
 1128:     else
 1129:     {
 1130: 	$link = $url;
 1131:     }
 1132:     # Add the text
 1133:     if ($text ne "")
 1134:     {
 1135: 	$template .= 
 1136:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1137:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1138:     }
 1139: 
 1140:     # Add the graphic
 1141:     my $title = &mt('Report a Bug');
 1142:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1143:     $template .= <<"ENDTEMPLATE";
 1144:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1145: ENDTEMPLATE
 1146:     if ($text ne '') { $template.='</td></tr></table>' };
 1147:     return $template;
 1148: 
 1149: }
 1150: 
 1151: sub help_open_faq {
 1152:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1153:     unless ($env{'user.adv'}) { return ''; }
 1154:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1155:     $text = "" if (not defined $text);
 1156:     $stayOnPage = 0 if (not defined $stayOnPage);
 1157:     if ($env{'browser.interface'} eq 'textual' ||
 1158: 	$env{'environment.remote'} eq 'off' ) {
 1159: 	$stayOnPage=1;
 1160:     }
 1161:     $width = 350 if (not defined $width);
 1162:     $height = 400 if (not defined $height);
 1163: 
 1164:     $topic=~s/\W+/\+/g;
 1165:     my $link='';
 1166:     my $template='';
 1167:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1168:     if (!$stayOnPage)
 1169:     {
 1170: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1171:     }
 1172:     else
 1173:     {
 1174: 	$link = $url;
 1175:     }
 1176: 
 1177:     # Add the text
 1178:     if ($text ne "")
 1179:     {
 1180: 	$template .= 
 1181:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1182:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1183:     }
 1184: 
 1185:     # Add the graphic
 1186:     my $title = &mt('View the FAQ');
 1187:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1188:     $template .= <<"ENDTEMPLATE";
 1189:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1190: ENDTEMPLATE
 1191:     if ($text ne '') { $template.='</td></tr></table>' };
 1192:     return $template;
 1193: 
 1194: }
 1195: 
 1196: ###############################################################
 1197: ###############################################################
 1198: 
 1199: =pod
 1200: 
 1201: =item * &change_content_javascript():
 1202: 
 1203: This and the next function allow you to create small sections of an
 1204: otherwise static HTML page that you can update on the fly with
 1205: Javascript, even in Netscape 4.
 1206: 
 1207: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1208: must be written to the HTML page once. It will prove the Javascript
 1209: function "change(name, content)". Calling the change function with the
 1210: name of the section 
 1211: you want to update, matching the name passed to C<changable_area>, and
 1212: the new content you want to put in there, will put the content into
 1213: that area.
 1214: 
 1215: B<Note>: Netscape 4 only reserves enough space for the changable area
 1216: to contain room for the original contents. You need to "make space"
 1217: for whatever changes you wish to make, and be B<sure> to check your
 1218: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1219: it's adequate for updating a one-line status display, but little more.
 1220: This script will set the space to 100% width, so you only need to
 1221: worry about height in Netscape 4.
 1222: 
 1223: Modern browsers are much less limiting, and if you can commit to the
 1224: user not using Netscape 4, this feature may be used freely with
 1225: pretty much any HTML.
 1226: 
 1227: =cut
 1228: 
 1229: sub change_content_javascript {
 1230:     # If we're on Netscape 4, we need to use Layer-based code
 1231:     if ($env{'browser.type'} eq 'netscape' &&
 1232: 	$env{'browser.version'} =~ /^4\./) {
 1233: 	return (<<NETSCAPE4);
 1234: 	function change(name, content) {
 1235: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1236: 	    doc.open();
 1237: 	    doc.write(content);
 1238: 	    doc.close();
 1239: 	}
 1240: NETSCAPE4
 1241:     } else {
 1242: 	# Otherwise, we need to use semi-standards-compliant code
 1243: 	# (technically, "innerHTML" isn't standard but the equivalent
 1244: 	# is really scary, and every useful browser supports it
 1245: 	return (<<DOMBASED);
 1246: 	function change(name, content) {
 1247: 	    element = document.getElementById(name);
 1248: 	    element.innerHTML = content;
 1249: 	}
 1250: DOMBASED
 1251:     }
 1252: }
 1253: 
 1254: =pod
 1255: 
 1256: =item * &changable_area($name,$origContent):
 1257: 
 1258: This provides a "changable area" that can be modified on the fly via
 1259: the Javascript code provided in C<change_content_javascript>. $name is
 1260: the name you will use to reference the area later; do not repeat the
 1261: same name on a given HTML page more then once. $origContent is what
 1262: the area will originally contain, which can be left blank.
 1263: 
 1264: =cut
 1265: 
 1266: sub changable_area {
 1267:     my ($name, $origContent) = @_;
 1268: 
 1269:     if ($env{'browser.type'} eq 'netscape' &&
 1270: 	$env{'browser.version'} =~ /^4\./) {
 1271: 	# If this is netscape 4, we need to use the Layer tag
 1272: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1273:     } else {
 1274: 	return "<span id='$name'>$origContent</span>";
 1275:     }
 1276: }
 1277: 
 1278: =pod
 1279: 
 1280: =item * &viewport_geometry_js 
 1281: 
 1282: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1283: 
 1284: =cut
 1285: 
 1286: 
 1287: sub viewport_geometry_js { 
 1288:     return <<"GEOMETRY";
 1289: var Geometry = {};
 1290: function init_geometry() {
 1291:     if (Geometry.init) { return };
 1292:     Geometry.init=1;
 1293:     if (window.innerHeight) {
 1294:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1295:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1296:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1297:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1298:     }
 1299:     else if (document.documentElement && document.documentElement.clientHeight) {
 1300:         Geometry.getViewportHeight =
 1301:             function() { return document.documentElement.clientHeight; };
 1302:         Geometry.getViewportWidth =
 1303:             function() { return document.documentElement.clientWidth; };
 1304: 
 1305:         Geometry.getHorizontalScroll =
 1306:             function() { return document.documentElement.scrollLeft; };
 1307:         Geometry.getVerticalScroll =
 1308:             function() { return document.documentElement.scrollTop; };
 1309:     }
 1310:     else if (document.body.clientHeight) {
 1311:         Geometry.getViewportHeight =
 1312:             function() { return document.body.clientHeight; };
 1313:         Geometry.getViewportWidth =
 1314:             function() { return document.body.clientWidth; };
 1315:         Geometry.getHorizontalScroll =
 1316:             function() { return document.body.scrollLeft; };
 1317:         Geometry.getVerticalScroll =
 1318:             function() { return document.body.scrollTop; };
 1319:     }
 1320: }
 1321: 
 1322: GEOMETRY
 1323: }
 1324: 
 1325: =pod
 1326: 
 1327: =item * &viewport_size_js()
 1328: 
 1329: 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. 
 1330: 
 1331: =cut
 1332: 
 1333: sub viewport_size_js {
 1334:     my $geometry = &viewport_geometry_js();
 1335:     return <<"DIMS";
 1336: 
 1337: $geometry
 1338: 
 1339: function getViewportDims(width,height) {
 1340:     init_geometry();
 1341:     width.value = Geometry.getViewportWidth();
 1342:     height.value = Geometry.getViewportHeight();
 1343:     return;
 1344: }
 1345: 
 1346: DIMS
 1347: }
 1348: 
 1349: =pod
 1350: 
 1351: =item * &resize_textarea_js()
 1352: 
 1353: emits the needed javascript to resize a textarea to be as big as possible
 1354: 
 1355: creates a function resize_textrea that takes two IDs first should be
 1356: the id of the element to resize, second should be the id of a div that
 1357: surrounds everything that comes after the textarea, this routine needs
 1358: to be attached to the <body> for the onload and onresize events.
 1359: 
 1360: =back
 1361: 
 1362: =cut
 1363: 
 1364: sub resize_textarea_js {
 1365:     my $geometry = &viewport_geometry_js();
 1366:     return <<"RESIZE";
 1367:     <script type="text/javascript">
 1368: $geometry
 1369: 
 1370: function getX(element) {
 1371:     var x = 0;
 1372:     while (element) {
 1373: 	x += element.offsetLeft;
 1374: 	element = element.offsetParent;
 1375:     }
 1376:     return x;
 1377: }
 1378: function getY(element) {
 1379:     var y = 0;
 1380:     while (element) {
 1381: 	y += element.offsetTop;
 1382: 	element = element.offsetParent;
 1383:     }
 1384:     return y;
 1385: }
 1386: 
 1387: 
 1388: function resize_textarea(textarea_id,bottom_id) {
 1389:     init_geometry();
 1390:     var textarea        = document.getElementById(textarea_id);
 1391:     //alert(textarea);
 1392: 
 1393:     var textarea_top    = getY(textarea);
 1394:     var textarea_height = textarea.offsetHeight;
 1395:     var bottom          = document.getElementById(bottom_id);
 1396:     var bottom_top      = getY(bottom);
 1397:     var bottom_height   = bottom.offsetHeight;
 1398:     var window_height   = Geometry.getViewportHeight();
 1399:     var fudge           = 23;
 1400:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1401:     if (new_height < 300) {
 1402: 	new_height = 300;
 1403:     }
 1404:     textarea.style.height=new_height+'px';
 1405: }
 1406: </script>
 1407: RESIZE
 1408: 
 1409: }
 1410: 
 1411: =pod
 1412: 
 1413: =head1 Excel and CSV file utility routines
 1414: 
 1415: =over 4
 1416: 
 1417: =cut
 1418: 
 1419: ###############################################################
 1420: ###############################################################
 1421: 
 1422: =pod
 1423: 
 1424: =item * &csv_translate($text) 
 1425: 
 1426: Translate $text to allow it to be output as a 'comma separated values' 
 1427: format.
 1428: 
 1429: =cut
 1430: 
 1431: ###############################################################
 1432: ###############################################################
 1433: sub csv_translate {
 1434:     my $text = shift;
 1435:     $text =~ s/\"/\"\"/g;
 1436:     $text =~ s/\n/ /g;
 1437:     return $text;
 1438: }
 1439: 
 1440: ###############################################################
 1441: ###############################################################
 1442: 
 1443: =pod
 1444: 
 1445: =item * &define_excel_formats()
 1446: 
 1447: Define some commonly used Excel cell formats.
 1448: 
 1449: Currently supported formats:
 1450: 
 1451: =over 4
 1452: 
 1453: =item header
 1454: 
 1455: =item bold
 1456: 
 1457: =item h1
 1458: 
 1459: =item h2
 1460: 
 1461: =item h3
 1462: 
 1463: =item h4
 1464: 
 1465: =item i
 1466: 
 1467: =item date
 1468: 
 1469: =back
 1470: 
 1471: Inputs: $workbook
 1472: 
 1473: Returns: $format, a hash reference.
 1474: 
 1475: =cut
 1476: 
 1477: ###############################################################
 1478: ###############################################################
 1479: sub define_excel_formats {
 1480:     my ($workbook) = @_;
 1481:     my $format;
 1482:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1483:                                                 bottom    => 1,
 1484:                                                 align     => 'center');
 1485:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1486:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1487:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1488:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1489:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1490:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1491:     $format->{'date'} = $workbook->add_format(num_format=>
 1492:                                             'mm/dd/yyyy hh:mm:ss');
 1493:     return $format;
 1494: }
 1495: 
 1496: ###############################################################
 1497: ###############################################################
 1498: 
 1499: =pod
 1500: 
 1501: =item * &create_workbook()
 1502: 
 1503: Create an Excel worksheet.  If it fails, output message on the
 1504: request object and return undefs.
 1505: 
 1506: Inputs: Apache request object
 1507: 
 1508: Returns (undef) on failure, 
 1509:     Excel worksheet object, scalar with filename, and formats 
 1510:     from &Apache::loncommon::define_excel_formats on success
 1511: 
 1512: =cut
 1513: 
 1514: ###############################################################
 1515: ###############################################################
 1516: sub create_workbook {
 1517:     my ($r) = @_;
 1518:         #
 1519:     # Create the excel spreadsheet
 1520:     my $filename = '/prtspool/'.
 1521:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1522:         time.'_'.rand(1000000000).'.xls';
 1523:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1524:     if (! defined($workbook)) {
 1525:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1526:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1527:                             "This error has been logged.  ".
 1528:                             "Please alert your LON-CAPA administrator").
 1529:                   '</p>');
 1530:         return (undef);
 1531:     }
 1532:     #
 1533:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1534:     #
 1535:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1536:     return ($workbook,$filename,$format);
 1537: }
 1538: 
 1539: ###############################################################
 1540: ###############################################################
 1541: 
 1542: =pod
 1543: 
 1544: =item * &create_text_file()
 1545: 
 1546: Create a file to write to and eventually make available to the user.
 1547: If file creation fails, outputs an error message on the request object and 
 1548: return undefs.
 1549: 
 1550: Inputs: Apache request object, and file suffix
 1551: 
 1552: Returns (undef) on failure, 
 1553:     Filehandle and filename on success.
 1554: 
 1555: =cut
 1556: 
 1557: ###############################################################
 1558: ###############################################################
 1559: sub create_text_file {
 1560:     my ($r,$suffix) = @_;
 1561:     if (! defined($suffix)) { $suffix = 'txt'; };
 1562:     my $fh;
 1563:     my $filename = '/prtspool/'.
 1564:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1565:         time.'_'.rand(1000000000).'.'.$suffix;
 1566:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1567:     if (! defined($fh)) {
 1568:         $r->log_error("Couldn't open $filename for output $!");
 1569:         $r->print(&mt('Problems occurred in creating the output file. '
 1570:                      .'This error has been logged. '
 1571:                      .'Please alert your LON-CAPA administrator.'));
 1572:     }
 1573:     return ($fh,$filename)
 1574: }
 1575: 
 1576: 
 1577: =pod 
 1578: 
 1579: =back
 1580: 
 1581: =cut
 1582: 
 1583: ###############################################################
 1584: ##        Home server <option> list generating code          ##
 1585: ###############################################################
 1586: 
 1587: # ------------------------------------------
 1588: 
 1589: sub domain_select {
 1590:     my ($name,$value,$multiple)=@_;
 1591:     my %domains=map { 
 1592: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1593:     } &Apache::lonnet::all_domains();
 1594:     if ($multiple) {
 1595: 	$domains{''}=&mt('Any domain');
 1596: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1597: 	return &multiple_select_form($name,$value,4,\%domains);
 1598:     } else {
 1599: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1600: 	return &select_form($name,$value,%domains);
 1601:     }
 1602: }
 1603: 
 1604: #-------------------------------------------
 1605: 
 1606: =pod
 1607: 
 1608: =head1 Routines for form select boxes
 1609: 
 1610: =over 4
 1611: 
 1612: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1613: 
 1614: Returns a string containing a <select> element int multiple mode
 1615: 
 1616: 
 1617: Args:
 1618:   $name - name of the <select> element
 1619:   $value - scalar or array ref of values that should already be selected
 1620:   $size - number of rows long the select element is
 1621:   $hash - the elements should be 'option' => 'shown text'
 1622:           (shown text should already have been &mt())
 1623:   $order - (optional) array ref of the order to show the elements in
 1624: 
 1625: =cut
 1626: 
 1627: #-------------------------------------------
 1628: sub multiple_select_form {
 1629:     my ($name,$value,$size,$hash,$order)=@_;
 1630:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1631:     my $output='';
 1632:     if (! defined($size)) {
 1633:         $size = 4;
 1634:         if (scalar(keys(%$hash))<4) {
 1635:             $size = scalar(keys(%$hash));
 1636:         }
 1637:     }
 1638:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1639:     my @order;
 1640:     if (ref($order) eq 'ARRAY')  {
 1641:         @order = @{$order};
 1642:     } else {
 1643:         @order = sort(keys(%$hash));
 1644:     }
 1645:     if (exists($$hash{'select_form_order'})) {
 1646:         @order = @{$$hash{'select_form_order'}};
 1647:     }
 1648:         
 1649:     foreach my $key (@order) {
 1650:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1651:         $output.='selected="selected" ' if ($selected{$key});
 1652:         $output.='>'.$hash->{$key}."</option>\n";
 1653:     }
 1654:     $output.="</select>\n";
 1655:     return $output;
 1656: }
 1657: 
 1658: #-------------------------------------------
 1659: 
 1660: =pod
 1661: 
 1662: =item * &select_form($defdom,$name,%hash)
 1663: 
 1664: Returns a string containing a <select name='$name' size='1'> form to 
 1665: allow a user to select options from a hash option_name => displayed text.  
 1666: See lonrights.pm for an example invocation and use.
 1667: 
 1668: =cut
 1669: 
 1670: #-------------------------------------------
 1671: sub select_form {
 1672:     my ($def,$name,%hash) = @_;
 1673:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1674:     my @keys;
 1675:     if (exists($hash{'select_form_order'})) {
 1676: 	@keys=@{$hash{'select_form_order'}};
 1677:     } else {
 1678: 	@keys=sort(keys(%hash));
 1679:     }
 1680:     foreach my $key (@keys) {
 1681:         $selectform.=
 1682: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1683:             ($key eq $def ? 'selected="selected" ' : '').
 1684:                 ">".&mt($hash{$key})."</option>\n";
 1685:     }
 1686:     $selectform.="</select>";
 1687:     return $selectform;
 1688: }
 1689: 
 1690: # For display filters
 1691: 
 1692: sub display_filter {
 1693:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1694:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1695:     return '<nobr><label>'.&mt('Records [_1]',
 1696: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1697: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1698: 	   '</label></nobr> <nobr>'.
 1699:            &mt('Filter [_1]',
 1700: 	   &select_form($env{'form.displayfilter'},
 1701: 			'displayfilter',
 1702: 			('currentfolder' => 'Current folder/page',
 1703: 			 'containing' => 'Containing phrase',
 1704: 			 'none' => 'None'))).
 1705: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
 1706: }
 1707: 
 1708: sub gradeleveldescription {
 1709:     my $gradelevel=shift;
 1710:     my %gradelevels=(0 => 'Not specified',
 1711: 		     1 => 'Grade 1',
 1712: 		     2 => 'Grade 2',
 1713: 		     3 => 'Grade 3',
 1714: 		     4 => 'Grade 4',
 1715: 		     5 => 'Grade 5',
 1716: 		     6 => 'Grade 6',
 1717: 		     7 => 'Grade 7',
 1718: 		     8 => 'Grade 8',
 1719: 		     9 => 'Grade 9',
 1720: 		     10 => 'Grade 10',
 1721: 		     11 => 'Grade 11',
 1722: 		     12 => 'Grade 12',
 1723: 		     13 => 'Grade 13',
 1724: 		     14 => '100 Level',
 1725: 		     15 => '200 Level',
 1726: 		     16 => '300 Level',
 1727: 		     17 => '400 Level',
 1728: 		     18 => 'Graduate Level');
 1729:     return &mt($gradelevels{$gradelevel});
 1730: }
 1731: 
 1732: sub select_level_form {
 1733:     my ($deflevel,$name)=@_;
 1734:     unless ($deflevel) { $deflevel=0; }
 1735:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1736:     for (my $i=0; $i<=18; $i++) {
 1737:         $selectform.="<option value=\"$i\" ".
 1738:             ($i==$deflevel ? 'selected="selected" ' : '').
 1739:                 ">".&gradeleveldescription($i)."</option>\n";
 1740:     }
 1741:     $selectform.="</select>";
 1742:     return $selectform;
 1743: }
 1744: 
 1745: #-------------------------------------------
 1746: 
 1747: =pod
 1748: 
 1749: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
 1750: 
 1751: Returns a string containing a <select name='$name' size='1'> form to 
 1752: allow a user to select the domain to preform an operation in.  
 1753: See loncreateuser.pm for an example invocation and use.
 1754: 
 1755: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1756: selected");
 1757: 
 1758: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
 1759: 
 1760: =cut
 1761: 
 1762: #-------------------------------------------
 1763: sub select_dom_form {
 1764:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
 1765:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1766:     if ($includeempty) { @domains=('',@domains); }
 1767:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1768:     foreach my $dom (@domains) {
 1769:         $selectdomain.="<option value=\"$dom\" ".
 1770:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1771:         if ($showdomdesc) {
 1772:             if ($dom ne '') {
 1773:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1774:                 if ($domdesc ne '') {
 1775:                     $selectdomain .= ' ('.$domdesc.')';
 1776:                 }
 1777:             } 
 1778:         }
 1779:         $selectdomain .= "</option>\n";
 1780:     }
 1781:     $selectdomain.="</select>";
 1782:     return $selectdomain;
 1783: }
 1784: 
 1785: #-------------------------------------------
 1786: 
 1787: =pod
 1788: 
 1789: =item * &home_server_form_item($domain,$name,$defaultflag)
 1790: 
 1791: input: 4 arguments (two required, two optional) - 
 1792:     $domain - domain of new user
 1793:     $name - name of form element
 1794:     $default - Value of 'default' causes a default item to be first 
 1795:                             option, and selected by default. 
 1796:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1797:                             if 1 server found, or default, if 0 found.
 1798: output: returns 2 items: 
 1799: (a) form element which contains either:
 1800:    (i) <select name="$name">
 1801:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1802:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1803:        </select>
 1804:        form item if there are multiple library servers in $domain, or
 1805:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1806:        if there is only one library server in $domain.
 1807: 
 1808: (b) number of library servers found.
 1809: 
 1810: See loncreateuser.pm for example of use.
 1811: 
 1812: =cut
 1813: 
 1814: #-------------------------------------------
 1815: sub home_server_form_item {
 1816:     my ($domain,$name,$default,$hide) = @_;
 1817:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1818:     my $result;
 1819:     my $numlib = keys(%servers);
 1820:     if ($numlib > 1) {
 1821:         $result .= '<select name="'.$name.'" />'."\n";
 1822:         if ($default) {
 1823:             $result .= '<option value="default" selected>'.&mt('default').
 1824:                        '</option>'."\n";
 1825:         }
 1826:         foreach my $hostid (sort(keys(%servers))) {
 1827:             $result.= '<option value="'.$hostid.'">'.
 1828: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1829:         }
 1830:         $result .= '</select>'."\n";
 1831:     } elsif ($numlib == 1) {
 1832:         my $hostid;
 1833:         foreach my $item (keys(%servers)) {
 1834:             $hostid = $item;
 1835:         }
 1836:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1837:                    $hostid.'" />';
 1838:                    if (!$hide) {
 1839:                        $result .= $hostid.' '.$servers{$hostid};
 1840:                    }
 1841:                    $result .= "\n";
 1842:     } elsif ($default) {
 1843:         $result .= '<input type="hidden" name="'.$name.
 1844:                    '" value="default" />';
 1845:                    if (!$hide) {
 1846:                        $result .= &mt('default');
 1847:                    }
 1848:                    $result .= "\n";
 1849:     }
 1850:     return ($result,$numlib);
 1851: }
 1852: 
 1853: =pod
 1854: 
 1855: =back 
 1856: 
 1857: =cut
 1858: 
 1859: ###############################################################
 1860: ##                  Decoding User Agent                      ##
 1861: ###############################################################
 1862: 
 1863: =pod
 1864: 
 1865: =head1 Decoding the User Agent
 1866: 
 1867: =over 4
 1868: 
 1869: =item * &decode_user_agent()
 1870: 
 1871: Inputs: $r
 1872: 
 1873: Outputs:
 1874: 
 1875: =over 4
 1876: 
 1877: =item * $httpbrowser
 1878: 
 1879: =item * $clientbrowser
 1880: 
 1881: =item * $clientversion
 1882: 
 1883: =item * $clientmathml
 1884: 
 1885: =item * $clientunicode
 1886: 
 1887: =item * $clientos
 1888: 
 1889: =back
 1890: 
 1891: =back 
 1892: 
 1893: =cut
 1894: 
 1895: ###############################################################
 1896: ###############################################################
 1897: sub decode_user_agent {
 1898:     my ($r)=@_;
 1899:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1900:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1901:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1902:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1903:     my $clientbrowser='unknown';
 1904:     my $clientversion='0';
 1905:     my $clientmathml='';
 1906:     my $clientunicode='0';
 1907:     for (my $i=0;$i<=$#browsertype;$i++) {
 1908:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1909: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1910: 	    $clientbrowser=$bname;
 1911:             $httpbrowser=~/$vreg/i;
 1912: 	    $clientversion=$1;
 1913:             $clientmathml=($clientversion>=$minv);
 1914:             $clientunicode=($clientversion>=$univ);
 1915: 	}
 1916:     }
 1917:     my $clientos='unknown';
 1918:     if (($httpbrowser=~/linux/i) ||
 1919:         ($httpbrowser=~/unix/i) ||
 1920:         ($httpbrowser=~/ux/i) ||
 1921:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1922:     if (($httpbrowser=~/vax/i) ||
 1923:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1924:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1925:     if (($httpbrowser=~/mac/i) ||
 1926:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1927:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1928:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1929:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1930:             $clientunicode,$clientos,);
 1931: }
 1932: 
 1933: ###############################################################
 1934: ##    Authentication changing form generation subroutines    ##
 1935: ###############################################################
 1936: ##
 1937: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1938: ## hash, and have reasonable default values.
 1939: ##
 1940: ##    formname = the name given in the <form> tag.
 1941: #-------------------------------------------
 1942: 
 1943: =pod
 1944: 
 1945: =head1 Authentication Routines
 1946: 
 1947: =over 4
 1948: 
 1949: =item * &authform_xxxxxx()
 1950: 
 1951: The authform_xxxxxx subroutines provide javascript and html forms which 
 1952: handle some of the conveniences required for authentication forms.  
 1953: This is not an optimal method, but it works.  
 1954: 
 1955: =over 4
 1956: 
 1957: =item * authform_header
 1958: 
 1959: =item * authform_authorwarning
 1960: 
 1961: =item * authform_nochange
 1962: 
 1963: =item * authform_kerberos
 1964: 
 1965: =item * authform_internal
 1966: 
 1967: =item * authform_filesystem
 1968: 
 1969: =back
 1970: 
 1971: See loncreateuser.pm for invocation and use examples.
 1972: 
 1973: =cut
 1974: 
 1975: #-------------------------------------------
 1976: sub authform_header{  
 1977:     my %in = (
 1978:         formname => 'cu',
 1979:         kerb_def_dom => '',
 1980:         @_,
 1981:     );
 1982:     $in{'formname'} = 'document.' . $in{'formname'};
 1983:     my $result='';
 1984: 
 1985: #---------------------------------------------- Code for upper case translation
 1986:     my $Javascript_toUpperCase;
 1987:     unless ($in{kerb_def_dom}) {
 1988:         $Javascript_toUpperCase =<<"END";
 1989:         switch (choice) {
 1990:            case 'krb': currentform.elements[choicearg].value =
 1991:                currentform.elements[choicearg].value.toUpperCase();
 1992:                break;
 1993:            default:
 1994:         }
 1995: END
 1996:     } else {
 1997:         $Javascript_toUpperCase = "";
 1998:     }
 1999: 
 2000:     my $radioval = "'nochange'";
 2001:     if (defined($in{'curr_authtype'})) {
 2002:         if ($in{'curr_authtype'} ne '') {
 2003:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2004:         }
 2005:     }
 2006:     my $argfield = 'null';
 2007:     if (defined($in{'mode'})) {
 2008:         if ($in{'mode'} eq 'modifycourse')  {
 2009:             if (defined($in{'curr_autharg'})) {
 2010:                 if ($in{'curr_autharg'} ne '') {
 2011:                     $argfield = "'$in{'curr_autharg'}'";
 2012:                 }
 2013:             }
 2014:         }
 2015:     }
 2016: 
 2017:     $result.=<<"END";
 2018: var current = new Object();
 2019: current.radiovalue = $radioval;
 2020: current.argfield = $argfield;
 2021: 
 2022: function changed_radio(choice,currentform) {
 2023:     var choicearg = choice + 'arg';
 2024:     // If a radio button in changed, we need to change the argfield
 2025:     if (current.radiovalue != choice) {
 2026:         current.radiovalue = choice;
 2027:         if (current.argfield != null) {
 2028:             currentform.elements[current.argfield].value = '';
 2029:         }
 2030:         if (choice == 'nochange') {
 2031:             current.argfield = null;
 2032:         } else {
 2033:             current.argfield = choicearg;
 2034:             switch(choice) {
 2035:                 case 'krb': 
 2036:                     currentform.elements[current.argfield].value = 
 2037:                         "$in{'kerb_def_dom'}";
 2038:                 break;
 2039:               default:
 2040:                 break;
 2041:             }
 2042:         }
 2043:     }
 2044:     return;
 2045: }
 2046: 
 2047: function changed_text(choice,currentform) {
 2048:     var choicearg = choice + 'arg';
 2049:     if (currentform.elements[choicearg].value !='') {
 2050:         $Javascript_toUpperCase
 2051:         // clear old field
 2052:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2053:             currentform.elements[current.argfield].value = '';
 2054:         }
 2055:         current.argfield = choicearg;
 2056:     }
 2057:     set_auth_radio_buttons(choice,currentform);
 2058:     return;
 2059: }
 2060: 
 2061: function set_auth_radio_buttons(newvalue,currentform) {
 2062:     var i=0;
 2063:     while (i < currentform.login.length) {
 2064:         if (currentform.login[i].value == newvalue) { break; }
 2065:         i++;
 2066:     }
 2067:     if (i == currentform.login.length) {
 2068:         return;
 2069:     }
 2070:     current.radiovalue = newvalue;
 2071:     currentform.login[i].checked = true;
 2072:     return;
 2073: }
 2074: END
 2075:     return $result;
 2076: }
 2077: 
 2078: sub authform_authorwarning{
 2079:     my $result='';
 2080:     $result='<i>'.
 2081:         &mt('As a general rule, only authors or co-authors should be '.
 2082:             'filesystem authenticated '.
 2083:             '(which allows access to the server filesystem).')."</i>\n";
 2084:     return $result;
 2085: }
 2086: 
 2087: sub authform_nochange{  
 2088:     my %in = (
 2089:               formname => 'document.cu',
 2090:               kerb_def_dom => 'MSU.EDU',
 2091:               @_,
 2092:           );
 2093:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2094:     my $result;
 2095:     if (keys(%can_assign) == 0) {
 2096:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2097:     } else {
 2098:         $result = '<label>'.&mt('[_1] Do not change login data',
 2099:                   '<input type="radio" name="login" value="nochange" '.
 2100:                   'checked="checked" onclick="'.
 2101:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2102: 	    '</label>';
 2103:     }
 2104:     return $result;
 2105: }
 2106: 
 2107: sub authform_kerberos {
 2108:     my %in = (
 2109:               formname => 'document.cu',
 2110:               kerb_def_dom => 'MSU.EDU',
 2111:               kerb_def_auth => 'krb4',
 2112:               @_,
 2113:               );
 2114:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2115:         $autharg,$jscall);
 2116:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2117:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2118:        $check5 = ' checked="on"';
 2119:     } else {
 2120:        $check4 = ' checked="on"';
 2121:     }
 2122:     $krbarg = $in{'kerb_def_dom'};
 2123:     if (defined($in{'curr_authtype'})) {
 2124:         if ($in{'curr_authtype'} eq 'krb') {
 2125:             $krbcheck = ' checked="on"';
 2126:             if (defined($in{'mode'})) {
 2127:                 if ($in{'mode'} eq 'modifyuser') {
 2128:                     $krbcheck = '';
 2129:                 }
 2130:             }
 2131:             if (defined($in{'curr_kerb_ver'})) {
 2132:                 if ($in{'curr_krb_ver'} eq '5') {
 2133:                     $check5 = ' checked="on"';
 2134:                     $check4 = '';
 2135:                 } else {
 2136:                     $check4 = ' checked="on"';
 2137:                     $check5 = '';
 2138:                 }
 2139:             }
 2140:             if (defined($in{'curr_autharg'})) {
 2141:                 $krbarg = $in{'curr_autharg'};
 2142:             }
 2143:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2144:                 if (defined($in{'curr_autharg'})) {
 2145:                     $result = 
 2146:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2147:         $in{'curr_autharg'},$krbver);
 2148:                 } else {
 2149:                     $result =
 2150:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2151:                 }
 2152:                 return $result; 
 2153:             }
 2154:         }
 2155:     } else {
 2156:         if ($authnum == 1) {
 2157:             $authtype = '<input type="hidden" name="login" value="krb">';
 2158:         }
 2159:     }
 2160:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2161:         return;
 2162:     } elsif ($authtype eq '') {
 2163:         if (defined($in{'mode'})) {
 2164:             if ($in{'mode'} eq 'modifycourse') {
 2165:                 if ($authnum == 1) {
 2166:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2167:                 }
 2168:             }
 2169:         }
 2170:     }
 2171:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2172:     if ($authtype eq '') {
 2173:         $authtype = '<input type="radio" name="login" value="krb" '.
 2174:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2175:                     $krbcheck.' />';
 2176:     }
 2177:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2178:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2179:          $in{'curr_authtype'} eq 'krb5') ||
 2180:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2181:          $in{'curr_authtype'} eq 'krb4')) {
 2182:         $result .= &mt
 2183:         ('[_1] Kerberos authenticated with domain [_2] '.
 2184:          '[_3] Version 4 [_4] Version 5 [_5]',
 2185:          '<label>'.$authtype,
 2186:          '</label><input type="text" size="10" name="krbarg" '.
 2187:              'value="'.$krbarg.'" '.
 2188:              'onchange="'.$jscall.'" />',
 2189:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2190:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2191: 	 '</label>');
 2192:     } elsif ($can_assign{'krb4'}) {
 2193:         $result .= &mt
 2194:         ('[_1] Kerberos authenticated with domain [_2] '.
 2195:          '[_3] Version 4 [_4]',
 2196:          '<label>'.$authtype,
 2197:          '</label><input type="text" size="10" name="krbarg" '.
 2198:              'value="'.$krbarg.'" '.
 2199:              'onchange="'.$jscall.'" />',
 2200:          '<label><input type="hidden" name="krbver" value="4" />',
 2201:          '</label>');
 2202:     } elsif ($can_assign{'krb5'}) {
 2203:         $result .= &mt
 2204:         ('[_1] Kerberos authenticated with domain [_2] '.
 2205:          '[_3] Version 5 [_4]',
 2206:          '<label>'.$authtype,
 2207:          '</label><input type="text" size="10" name="krbarg" '.
 2208:              'value="'.$krbarg.'" '.
 2209:              'onchange="'.$jscall.'" />',
 2210:          '<label><input type="hidden" name="krbver" value="5" />',
 2211:          '</label>');
 2212:     }
 2213:     return $result;
 2214: }
 2215: 
 2216: sub authform_internal{  
 2217:     my %in = (
 2218:                 formname => 'document.cu',
 2219:                 kerb_def_dom => 'MSU.EDU',
 2220:                 @_,
 2221:                 );
 2222:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2223:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2224:     if (defined($in{'curr_authtype'})) {
 2225:         if ($in{'curr_authtype'} eq 'int') {
 2226:             if ($can_assign{'int'}) {
 2227:                 $intcheck = 'checked="on" ';
 2228:                 if (defined($in{'mode'})) {
 2229:                     if ($in{'mode'} eq 'modifyuser') {
 2230:                         $intcheck = '';
 2231:                     }
 2232:                 }
 2233:                 if (defined($in{'curr_autharg'})) {
 2234:                     $intarg = $in{'curr_autharg'};
 2235:                 }
 2236:             } else {
 2237:                 $result = &mt('Currently internally authenticated.');
 2238:                 return $result;
 2239:             }
 2240:         }
 2241:     } else {
 2242:         if ($authnum == 1) {
 2243:             $authtype = '<input type="hidden" name="login" value="int">';
 2244:         }
 2245:     }
 2246:     if (!$can_assign{'int'}) {
 2247:         return;
 2248:     } elsif ($authtype eq '') {
 2249:         if (defined($in{'mode'})) {
 2250:             if ($in{'mode'} eq 'modifycourse') {
 2251:                 if ($authnum == 1) {
 2252:                     $authtype = '<input type="hidden" name="login" value="int">';
 2253:                 }
 2254:             }
 2255:         }
 2256:     }
 2257:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2258:     if ($authtype eq '') {
 2259:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2260:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2261:     }
 2262:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2263:                $intarg.'" onchange="'.$jscall.'" />';
 2264:     $result = &mt
 2265:         ('[_1] Internally authenticated (with initial password [_2])',
 2266:          '<label>'.$authtype,'</label>'.$autharg);
 2267:     $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>';
 2268:     return $result;
 2269: }
 2270: 
 2271: sub authform_local{  
 2272:     my %in = (
 2273:               formname => 'document.cu',
 2274:               kerb_def_dom => 'MSU.EDU',
 2275:               @_,
 2276:               );
 2277:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2278:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2279:     if (defined($in{'curr_authtype'})) {
 2280:         if ($in{'curr_authtype'} eq 'loc') {
 2281:             if ($can_assign{'loc'}) {
 2282:                 $loccheck = 'checked="on" ';
 2283:                 if (defined($in{'mode'})) {
 2284:                     if ($in{'mode'} eq 'modifyuser') {
 2285:                         $loccheck = '';
 2286:                     }
 2287:                 }
 2288:                 if (defined($in{'curr_autharg'})) {
 2289:                     $locarg = $in{'curr_autharg'};
 2290:                 }
 2291:             } else {
 2292:                 $result = &mt('Currently using local (institutional) authentication.');
 2293:                 return $result;
 2294:             }
 2295:         }
 2296:     } else {
 2297:         if ($authnum == 1) {
 2298:             $authtype = '<input type="hidden" name="login" value="loc">';
 2299:         }
 2300:     }
 2301:     if (!$can_assign{'loc'}) {
 2302:         return;
 2303:     } elsif ($authtype eq '') {
 2304:         if (defined($in{'mode'})) {
 2305:             if ($in{'mode'} eq 'modifycourse') {
 2306:                 if ($authnum == 1) {
 2307:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2308:                 }
 2309:             }
 2310:         }
 2311:     }
 2312:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2313:     if ($authtype eq '') {
 2314:         $authtype = '<input type="radio" name="login" value="loc" '.
 2315:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2316:                     $jscall.'" />';
 2317:     }
 2318:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2319:                $locarg.'" onchange="'.$jscall.'" />';
 2320:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2321:                   '<label>'.$authtype,'</label>'.$autharg);
 2322:     return $result;
 2323: }
 2324: 
 2325: sub authform_filesystem{  
 2326:     my %in = (
 2327:               formname => 'document.cu',
 2328:               kerb_def_dom => 'MSU.EDU',
 2329:               @_,
 2330:               );
 2331:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2332:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2333:     if (defined($in{'curr_authtype'})) {
 2334:         if ($in{'curr_authtype'} eq 'fsys') {
 2335:             if ($can_assign{'fsys'}) {
 2336:                 $fsyscheck = 'checked="on" ';
 2337:                 if (defined($in{'mode'})) {
 2338:                     if ($in{'mode'} eq 'modifyuser') {
 2339:                         $fsyscheck = '';
 2340:                     }
 2341:                 }
 2342:             } else {
 2343:                 $result = &mt('Currently Filesystem Authenticated.');
 2344:                 return $result;
 2345:             }           
 2346:         }
 2347:     } else {
 2348:         if ($authnum == 1) {
 2349:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2350:         }
 2351:     }
 2352:     if (!$can_assign{'fsys'}) {
 2353:         return;
 2354:     } elsif ($authtype eq '') {
 2355:         if (defined($in{'mode'})) {
 2356:             if ($in{'mode'} eq 'modifycourse') {
 2357:                 if ($authnum == 1) {
 2358:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2359:                 }
 2360:             }
 2361:         }
 2362:     }
 2363:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2364:     if ($authtype eq '') {
 2365:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2366:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2367:                     $jscall.'" />';
 2368:     }
 2369:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2370:                ' onchange="'.$jscall.'" />';
 2371:     $result = &mt
 2372:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2373:          '<label><input type="radio" name="login" value="fsys" '.
 2374:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2375:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2376:                   'onchange="'.$jscall.'" />');
 2377:     return $result;
 2378: }
 2379: 
 2380: sub get_assignable_auth {
 2381:     my ($dom) = @_;
 2382:     if ($dom eq '') {
 2383:         $dom = $env{'request.role.domain'};
 2384:     }
 2385:     my %can_assign = (
 2386:                           krb4 => 1,
 2387:                           krb5 => 1,
 2388:                           int  => 1,
 2389:                           loc  => 1,
 2390:                      );
 2391:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2392:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2393:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2394:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2395:             my $context;
 2396:             if ($env{'request.role'} =~ /^au/) {
 2397:                 $context = 'author';
 2398:             } elsif ($env{'request.role'} =~ /^dc/) {
 2399:                 $context = 'domain';
 2400:             } elsif ($env{'request.course.id'}) {
 2401:                 $context = 'course';
 2402:             }
 2403:             if ($context) {
 2404:                 if (ref($authhash->{$context}) eq 'HASH') {
 2405:                    %can_assign = %{$authhash->{$context}}; 
 2406:                 }
 2407:             }
 2408:         }
 2409:     }
 2410:     my $authnum = 0;
 2411:     foreach my $key (keys(%can_assign)) {
 2412:         if ($can_assign{$key}) {
 2413:             $authnum ++;
 2414:         }
 2415:     }
 2416:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2417:         $authnum --;
 2418:     }
 2419:     return ($authnum,%can_assign);
 2420: }
 2421: 
 2422: ###############################################################
 2423: ##    Get Kerberos Defaults for Domain                 ##
 2424: ###############################################################
 2425: ##
 2426: ## Returns default kerberos version and an associated argument
 2427: ## as listed in file domain.tab. If not listed, provides
 2428: ## appropriate default domain and kerberos version.
 2429: ##
 2430: #-------------------------------------------
 2431: 
 2432: =pod
 2433: 
 2434: =item * &get_kerberos_defaults()
 2435: 
 2436: get_kerberos_defaults($target_domain) returns the default kerberos
 2437: version and domain. If not found, it defaults to version 4 and the 
 2438: domain of the server.
 2439: 
 2440: =over 4
 2441: 
 2442: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2443: 
 2444: =back
 2445: 
 2446: =back
 2447: 
 2448: =cut
 2449: 
 2450: #-------------------------------------------
 2451: sub get_kerberos_defaults {
 2452:     my $domain=shift;
 2453:     my ($krbdef,$krbdefdom);
 2454:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2455:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2456:         $krbdef = $domdefaults{'auth_def'};
 2457:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2458:     } else {
 2459:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2460:         my $krbdefdom=$1;
 2461:         $krbdefdom=~tr/a-z/A-Z/;
 2462:         $krbdef = "krb4";
 2463:     }
 2464:     return ($krbdef,$krbdefdom);
 2465: }
 2466: 
 2467: 
 2468: ###############################################################
 2469: ##                Thesaurus Functions                        ##
 2470: ###############################################################
 2471: 
 2472: =pod
 2473: 
 2474: =head1 Thesaurus Functions
 2475: 
 2476: =over 4
 2477: 
 2478: =item * &initialize_keywords()
 2479: 
 2480: Initializes the package variable %Keywords if it is empty.  Uses the
 2481: package variable $thesaurus_db_file.
 2482: 
 2483: =cut
 2484: 
 2485: ###################################################
 2486: 
 2487: sub initialize_keywords {
 2488:     return 1 if (scalar keys(%Keywords));
 2489:     # If we are here, %Keywords is empty, so fill it up
 2490:     #   Make sure the file we need exists...
 2491:     if (! -e $thesaurus_db_file) {
 2492:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2493:                                  " failed because it does not exist");
 2494:         return 0;
 2495:     }
 2496:     #   Set up the hash as a database
 2497:     my %thesaurus_db;
 2498:     if (! tie(%thesaurus_db,'GDBM_File',
 2499:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2500:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2501:                                  $thesaurus_db_file);
 2502:         return 0;
 2503:     } 
 2504:     #  Get the average number of appearances of a word.
 2505:     my $avecount = $thesaurus_db{'average.count'};
 2506:     #  Put keywords (those that appear > average) into %Keywords
 2507:     while (my ($word,$data)=each (%thesaurus_db)) {
 2508:         my ($count,undef) = split /:/,$data;
 2509:         $Keywords{$word}++ if ($count > $avecount);
 2510:     }
 2511:     untie %thesaurus_db;
 2512:     # Remove special values from %Keywords.
 2513:     foreach my $value ('total.count','average.count') {
 2514:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2515:   }
 2516:     return 1;
 2517: }
 2518: 
 2519: ###################################################
 2520: 
 2521: =pod
 2522: 
 2523: =item * &keyword($word)
 2524: 
 2525: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2526: than the average number of times in the thesaurus database.  Calls 
 2527: &initialize_keywords
 2528: 
 2529: =cut
 2530: 
 2531: ###################################################
 2532: 
 2533: sub keyword {
 2534:     return if (!&initialize_keywords());
 2535:     my $word=lc(shift());
 2536:     $word=~s/\W//g;
 2537:     return exists($Keywords{$word});
 2538: }
 2539: 
 2540: ###############################################################
 2541: 
 2542: =pod 
 2543: 
 2544: =item * &get_related_words()
 2545: 
 2546: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2547: an array of words.  If the keyword is not in the thesaurus, an empty array
 2548: will be returned.  The order of the words returned is determined by the
 2549: database which holds them.
 2550: 
 2551: Uses global $thesaurus_db_file.
 2552: 
 2553: =cut
 2554: 
 2555: ###############################################################
 2556: sub get_related_words {
 2557:     my $keyword = shift;
 2558:     my %thesaurus_db;
 2559:     if (! -e $thesaurus_db_file) {
 2560:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2561:                                  "failed because the file does not exist");
 2562:         return ();
 2563:     }
 2564:     if (! tie(%thesaurus_db,'GDBM_File',
 2565:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2566:         return ();
 2567:     } 
 2568:     my @Words=();
 2569:     my $count=0;
 2570:     if (exists($thesaurus_db{$keyword})) {
 2571: 	# The first element is the number of times
 2572: 	# the word appears.  We do not need it now.
 2573: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2574: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2575: 	my $threshold=$mostfrequentcount/10;
 2576:         foreach my $possibleword (@RelatedWords) {
 2577:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2578:             if ($wordcount>$threshold) {
 2579: 		push(@Words,$word);
 2580:                 $count++;
 2581:                 if ($count>10) { last; }
 2582: 	    }
 2583:         }
 2584:     }
 2585:     untie %thesaurus_db;
 2586:     return @Words;
 2587: }
 2588: 
 2589: =pod
 2590: 
 2591: =back
 2592: 
 2593: =cut
 2594: 
 2595: # -------------------------------------------------------------- Plaintext name
 2596: =pod
 2597: 
 2598: =head1 User Name Functions
 2599: 
 2600: =over 4
 2601: 
 2602: =item * &plainname($uname,$udom,$first)
 2603: 
 2604: Takes a users logon name and returns it as a string in
 2605: "first middle last generation" form 
 2606: if $first is set to 'lastname' then it returns it as
 2607: 'lastname generation, firstname middlename' if their is a lastname
 2608: 
 2609: =cut
 2610: 
 2611: 
 2612: ###############################################################
 2613: sub plainname {
 2614:     my ($uname,$udom,$first)=@_;
 2615:     return if (!defined($uname) || !defined($udom));
 2616:     my %names=&getnames($uname,$udom);
 2617:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2618: 					  $names{'middlename'},
 2619: 					  $names{'lastname'},
 2620: 					  $names{'generation'},$first);
 2621:     $name=~s/^\s+//;
 2622:     $name=~s/\s+$//;
 2623:     $name=~s/\s+/ /g;
 2624:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2625:     return $name;
 2626: }
 2627: 
 2628: # -------------------------------------------------------------------- Nickname
 2629: =pod
 2630: 
 2631: =item * &nickname($uname,$udom)
 2632: 
 2633: Gets a users name and returns it as a string as
 2634: 
 2635: "&quot;nickname&quot;"
 2636: 
 2637: if the user has a nickname or
 2638: 
 2639: "first middle last generation"
 2640: 
 2641: if the user does not
 2642: 
 2643: =cut
 2644: 
 2645: sub nickname {
 2646:     my ($uname,$udom)=@_;
 2647:     return if (!defined($uname) || !defined($udom));
 2648:     my %names=&getnames($uname,$udom);
 2649:     my $name=$names{'nickname'};
 2650:     if ($name) {
 2651:        $name='&quot;'.$name.'&quot;'; 
 2652:     } else {
 2653:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2654: 	     $names{'lastname'}.' '.$names{'generation'};
 2655:        $name=~s/\s+$//;
 2656:        $name=~s/\s+/ /g;
 2657:     }
 2658:     return $name;
 2659: }
 2660: 
 2661: sub getnames {
 2662:     my ($uname,$udom)=@_;
 2663:     return if (!defined($uname) || !defined($udom));
 2664:     if ($udom eq 'public' && $uname eq 'public') {
 2665: 	return ('lastname' => &mt('Public'));
 2666:     }
 2667:     my $id=$uname.':'.$udom;
 2668:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2669:     if ($cached) {
 2670: 	return %{$names};
 2671:     } else {
 2672: 	my %loadnames=&Apache::lonnet::get('environment',
 2673:                     ['firstname','middlename','lastname','generation','nickname'],
 2674: 					 $udom,$uname);
 2675: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2676: 	return %loadnames;
 2677:     }
 2678: }
 2679: 
 2680: # -------------------------------------------------------------------- getemails
 2681: 
 2682: =pod
 2683: 
 2684: =item * &getemails($uname,$udom)
 2685: 
 2686: Gets a user's email information and returns it as a hash with keys:
 2687: notification, critnotification, permanentemail
 2688: 
 2689: For notification and critnotification, values are comma-separated lists 
 2690: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2691:  
 2692: 
 2693: =cut
 2694: 
 2695: 
 2696: sub getemails {
 2697:     my ($uname,$udom)=@_;
 2698:     if ($udom eq 'public' && $uname eq 'public') {
 2699: 	return;
 2700:     }
 2701:     if (!$udom) { $udom=$env{'user.domain'}; }
 2702:     if (!$uname) { $uname=$env{'user.name'}; }
 2703:     my $id=$uname.':'.$udom;
 2704:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2705:     if ($cached) {
 2706: 	return %{$names};
 2707:     } else {
 2708: 	my %loadnames=&Apache::lonnet::get('environment',
 2709:                     			   ['notification','critnotification',
 2710: 					    'permanentemail'],
 2711: 					   $udom,$uname);
 2712: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2713: 	return %loadnames;
 2714:     }
 2715: }
 2716: 
 2717: sub flush_email_cache {
 2718:     my ($uname,$udom)=@_;
 2719:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2720:     if (!$uname) { $uname=$env{'user.name'};   }
 2721:     return if ($udom eq 'public' && $uname eq 'public');
 2722:     my $id=$uname.':'.$udom;
 2723:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2724: }
 2725: 
 2726: # -------------------------------------------------------------------- getlangs
 2727: 
 2728: =pod
 2729: 
 2730: =item * &getlangs($uname,$udom)
 2731: 
 2732: Gets a user's language preference and returns it as a hash with key:
 2733: language.
 2734: 
 2735: =cut
 2736: 
 2737: sub getlangs {
 2738:     my ($uname,$udom) = @_;
 2739:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2740:     if (!$uname) { $uname=$env{'user.name'};   }
 2741:     my $id=$uname.':'.$udom;
 2742:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2743:     if ($cached) {
 2744:         return %{$langs};
 2745:     } else {
 2746:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2747:                                            $udom,$uname);
 2748:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2749:         return %loadlangs;
 2750:     }
 2751: }
 2752: 
 2753: sub flush_langs_cache {
 2754:     my ($uname,$udom)=@_;
 2755:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2756:     if (!$uname) { $uname=$env{'user.name'};   }
 2757:     return if ($udom eq 'public' && $uname eq 'public');
 2758:     my $id=$uname.':'.$udom;
 2759:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2760: }
 2761: 
 2762: # ------------------------------------------------------------------ Screenname
 2763: 
 2764: =pod
 2765: 
 2766: =item * &screenname($uname,$udom)
 2767: 
 2768: Gets a users screenname and returns it as a string
 2769: 
 2770: =cut
 2771: 
 2772: sub screenname {
 2773:     my ($uname,$udom)=@_;
 2774:     if ($uname eq $env{'user.name'} &&
 2775: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2776:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2777:     return $names{'screenname'};
 2778: }
 2779: 
 2780: 
 2781: # ------------------------------------------------------------- Message Wrapper
 2782: 
 2783: sub messagewrapper {
 2784:     my ($link,$username,$domain,$subject,$text)=@_;
 2785:     return 
 2786:         '<a href="/adm/email?compose=individual&amp;'.
 2787:         'recname='.$username.'&amp;recdom='.$domain.
 2788: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2789:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2790: }
 2791: # --------------------------------------------------------------- Notes Wrapper
 2792: 
 2793: sub noteswrapper {
 2794:     my ($link,$un,$do)=@_;
 2795:     return 
 2796: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2797: }
 2798: # ------------------------------------------------------------- Aboutme Wrapper
 2799: 
 2800: sub aboutmewrapper {
 2801:     my ($link,$username,$domain,$target)=@_;
 2802:     if (!defined($username)  && !defined($domain)) {
 2803:         return;
 2804:     }
 2805:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2806: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2807: }
 2808: 
 2809: # ------------------------------------------------------------ Syllabus Wrapper
 2810: 
 2811: 
 2812: sub syllabuswrapper {
 2813:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2814:     if ($fontcolor) { 
 2815:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2816:     }
 2817:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2818: }
 2819: 
 2820: sub track_student_link {
 2821:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2822:     my $link ="/adm/trackstudent?";
 2823:     my $title = 'View recent activity';
 2824:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2825:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2826:         $link .= "selected_student=$sname:$sdom";
 2827:         $title .= ' of this student';
 2828:     } 
 2829:     if (defined($target) && $target !~ /^\s*$/) {
 2830:         $target = qq{target="$target"};
 2831:     } else {
 2832:         $target = '';
 2833:     }
 2834:     if ($start) { $link.='&amp;start='.$start; }
 2835:     $title = &mt($title);
 2836:     $linktext = &mt($linktext);
 2837:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2838: 	&help_open_topic('View_recent_activity');
 2839: }
 2840: 
 2841: # ===================================================== Display a student photo
 2842: 
 2843: 
 2844: sub student_image_tag {
 2845:     my ($domain,$user)=@_;
 2846:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2847:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2848: 	return '<img src="'.$imgsrc.'" align="right" />';
 2849:     } else {
 2850: 	return '';
 2851:     }
 2852: }
 2853: 
 2854: =pod
 2855: 
 2856: =back
 2857: 
 2858: =head1 Access .tab File Data
 2859: 
 2860: =over 4
 2861: 
 2862: =item * &languageids() 
 2863: 
 2864: returns list of all language ids
 2865: 
 2866: =cut
 2867: 
 2868: sub languageids {
 2869:     return sort(keys(%language));
 2870: }
 2871: 
 2872: =pod
 2873: 
 2874: =item * &languagedescription() 
 2875: 
 2876: returns description of a specified language id
 2877: 
 2878: =cut
 2879: 
 2880: sub languagedescription {
 2881:     my $code=shift;
 2882:     return  ($supported_language{$code}?'* ':'').
 2883:             $language{$code}.
 2884: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2885: }
 2886: 
 2887: sub plainlanguagedescription {
 2888:     my $code=shift;
 2889:     return $language{$code};
 2890: }
 2891: 
 2892: sub supportedlanguagecode {
 2893:     my $code=shift;
 2894:     return $supported_language{$code};
 2895: }
 2896: 
 2897: =pod
 2898: 
 2899: =item * &copyrightids() 
 2900: 
 2901: returns list of all copyrights
 2902: 
 2903: =cut
 2904: 
 2905: sub copyrightids {
 2906:     return sort(keys(%cprtag));
 2907: }
 2908: 
 2909: =pod
 2910: 
 2911: =item * &copyrightdescription() 
 2912: 
 2913: returns description of a specified copyright id
 2914: 
 2915: =cut
 2916: 
 2917: sub copyrightdescription {
 2918:     return &mt($cprtag{shift(@_)});
 2919: }
 2920: 
 2921: =pod
 2922: 
 2923: =item * &source_copyrightids() 
 2924: 
 2925: returns list of all source copyrights
 2926: 
 2927: =cut
 2928: 
 2929: sub source_copyrightids {
 2930:     return sort(keys(%scprtag));
 2931: }
 2932: 
 2933: =pod
 2934: 
 2935: =item * &source_copyrightdescription() 
 2936: 
 2937: returns description of a specified source copyright id
 2938: 
 2939: =cut
 2940: 
 2941: sub source_copyrightdescription {
 2942:     return &mt($scprtag{shift(@_)});
 2943: }
 2944: 
 2945: =pod
 2946: 
 2947: =item * &filecategories() 
 2948: 
 2949: returns list of all file categories
 2950: 
 2951: =cut
 2952: 
 2953: sub filecategories {
 2954:     return sort(keys(%category_extensions));
 2955: }
 2956: 
 2957: =pod
 2958: 
 2959: =item * &filecategorytypes() 
 2960: 
 2961: returns list of file types belonging to a given file
 2962: category
 2963: 
 2964: =cut
 2965: 
 2966: sub filecategorytypes {
 2967:     my ($cat) = @_;
 2968:     return @{$category_extensions{lc($cat)}};
 2969: }
 2970: 
 2971: =pod
 2972: 
 2973: =item * &fileembstyle() 
 2974: 
 2975: returns embedding style for a specified file type
 2976: 
 2977: =cut
 2978: 
 2979: sub fileembstyle {
 2980:     return $fe{lc(shift(@_))};
 2981: }
 2982: 
 2983: sub filemimetype {
 2984:     return $fm{lc(shift(@_))};
 2985: }
 2986: 
 2987: 
 2988: sub filecategoryselect {
 2989:     my ($name,$value)=@_;
 2990:     return &select_form($value,$name,
 2991: 			'' => &mt('Any category'),
 2992: 			map { $_,$_ } sort(keys(%category_extensions)));
 2993: }
 2994: 
 2995: =pod
 2996: 
 2997: =item * &filedescription() 
 2998: 
 2999: returns description for a specified file type
 3000: 
 3001: =cut
 3002: 
 3003: sub filedescription {
 3004:     my $file_description = $fd{lc(shift())};
 3005:     $file_description =~ s:([\[\]]):~$1:g;
 3006:     return &mt($file_description);
 3007: }
 3008: 
 3009: =pod
 3010: 
 3011: =item * &filedescriptionex() 
 3012: 
 3013: returns description for a specified file type with
 3014: extra formatting
 3015: 
 3016: =cut
 3017: 
 3018: sub filedescriptionex {
 3019:     my $ex=shift;
 3020:     my $file_description = $fd{lc($ex)};
 3021:     $file_description =~ s:([\[\]]):~$1:g;
 3022:     return '.'.$ex.' '.&mt($file_description);
 3023: }
 3024: 
 3025: # End of .tab access
 3026: =pod
 3027: 
 3028: =back
 3029: 
 3030: =cut
 3031: 
 3032: # ------------------------------------------------------------------ File Types
 3033: sub fileextensions {
 3034:     return sort(keys(%fe));
 3035: }
 3036: 
 3037: # ----------------------------------------------------------- Display Languages
 3038: # returns a hash with all desired display languages
 3039: #
 3040: 
 3041: sub display_languages {
 3042:     my %languages=();
 3043:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3044: 	$languages{$lang}=1;
 3045:     }
 3046:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3047:     if ($env{'form.displaylanguage'}) {
 3048: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3049: 	    $languages{$lang}=1;
 3050:         }
 3051:     }
 3052:     return %languages;
 3053: }
 3054: 
 3055: sub languages {
 3056:     my ($possible_langs) = @_;
 3057:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3058:     if (!ref($possible_langs)) {
 3059: 	if( wantarray ) {
 3060: 	    return @preferred_langs;
 3061: 	} else {
 3062: 	    return $preferred_langs[0];
 3063: 	}
 3064:     }
 3065:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3066:     my @preferred_possibilities;
 3067:     foreach my $preferred_lang (@preferred_langs) {
 3068: 	if (exists($possibilities{$preferred_lang})) {
 3069: 	    push(@preferred_possibilities, $preferred_lang);
 3070: 	}
 3071:     }
 3072:     if( wantarray ) {
 3073: 	return @preferred_possibilities;
 3074:     }
 3075:     return $preferred_possibilities[0];
 3076: }
 3077: 
 3078: ###############################################################
 3079: ##               Student Answer Attempts                     ##
 3080: ###############################################################
 3081: 
 3082: =pod
 3083: 
 3084: =head1 Alternate Problem Views
 3085: 
 3086: =over 4
 3087: 
 3088: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3089:     $getattempt, $regexp, $gradesub)
 3090: 
 3091: Return string with previous attempt on problem. Arguments:
 3092: 
 3093: =over 4
 3094: 
 3095: =item * $symb: Problem, including path
 3096: 
 3097: =item * $username: username of the desired student
 3098: 
 3099: =item * $domain: domain of the desired student
 3100: 
 3101: =item * $course: Course ID
 3102: 
 3103: =item * $getattempt: Leave blank for all attempts, otherwise put
 3104:     something
 3105: 
 3106: =item * $regexp: if string matches this regexp, the string will be
 3107:     sent to $gradesub
 3108: 
 3109: =item * $gradesub: routine that processes the string if it matches $regexp
 3110: 
 3111: =back
 3112: 
 3113: The output string is a table containing all desired attempts, if any.
 3114: 
 3115: =cut
 3116: 
 3117: sub get_previous_attempt {
 3118:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3119:   my $prevattempts='';
 3120:   no strict 'refs';
 3121:   if ($symb) {
 3122:     my (%returnhash)=
 3123:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3124:     if ($returnhash{'version'}) {
 3125:       my %lasthash=();
 3126:       my $version;
 3127:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3128:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3129: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3130:         }
 3131:       }
 3132:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3133:       $prevattempts.='<th>'.&mt('History').'</th>';
 3134:       foreach my $key (sort(keys(%lasthash))) {
 3135: 	my ($ign,@parts) = split(/\./,$key);
 3136: 	if ($#parts > 0) {
 3137: 	  my $data=$parts[-1];
 3138: 	  pop(@parts);
 3139: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3140: 	} else {
 3141: 	  if ($#parts == 0) {
 3142: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3143: 	  } else {
 3144: 	    $prevattempts.='<th>'.$ign.'</th>';
 3145: 	  }
 3146: 	}
 3147:       }
 3148:       $prevattempts.=&end_data_table_header_row();
 3149:       if ($getattempt eq '') {
 3150: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3151: 	  $prevattempts.=&start_data_table_row().
 3152: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3153: 	    foreach my $key (sort(keys(%lasthash))) {
 3154: 		my $value = &format_previous_attempt_value($key,
 3155: 							   $returnhash{$version.':'.$key});
 3156: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3157: 	    }
 3158: 	  $prevattempts.=&end_data_table_row();
 3159: 	 }
 3160:       }
 3161:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3162:       foreach my $key (sort(keys(%lasthash))) {
 3163: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3164: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3165: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3166:       }
 3167:       $prevattempts.= &end_data_table_row().&end_data_table();
 3168:     } else {
 3169:       $prevattempts=
 3170: 	  &start_data_table().&start_data_table_row().
 3171: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3172: 	  &end_data_table_row().&end_data_table();
 3173:     }
 3174:   } else {
 3175:     $prevattempts=
 3176: 	  &start_data_table().&start_data_table_row().
 3177: 	  '<td>'.&mt('No data.').'</td>'.
 3178: 	  &end_data_table_row().&end_data_table();
 3179:   }
 3180: }
 3181: 
 3182: sub format_previous_attempt_value {
 3183:     my ($key,$value) = @_;
 3184:     if ($key =~ /timestamp/) {
 3185: 	$value = &Apache::lonlocal::locallocaltime($value);
 3186:     } elsif (ref($value) eq 'ARRAY') {
 3187: 	$value = '('.join(', ', @{ $value }).')';
 3188:     } else {
 3189: 	$value = &unescape($value);
 3190:     }
 3191:     return $value;
 3192: }
 3193: 
 3194: 
 3195: sub relative_to_absolute {
 3196:     my ($url,$output)=@_;
 3197:     my $parser=HTML::TokeParser->new(\$output);
 3198:     my $token;
 3199:     my $thisdir=$url;
 3200:     my @rlinks=();
 3201:     while ($token=$parser->get_token) {
 3202: 	if ($token->[0] eq 'S') {
 3203: 	    if ($token->[1] eq 'a') {
 3204: 		if ($token->[2]->{'href'}) {
 3205: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3206: 		}
 3207: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3208: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3209: 	    } elsif ($token->[1] eq 'base') {
 3210: 		$thisdir=$token->[2]->{'href'};
 3211: 	    }
 3212: 	}
 3213:     }
 3214:     $thisdir=~s-/[^/]*$--;
 3215:     foreach my $link (@rlinks) {
 3216: 	unless (($link=~/^https?\:\/\//i) ||
 3217: 		($link=~/^\//) ||
 3218: 		($link=~/^javascript:/i) ||
 3219: 		($link=~/^mailto:/i) ||
 3220: 		($link=~/^\#/)) {
 3221: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3222: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3223: 	}
 3224:     }
 3225: # -------------------------------------------------- Deal with Applet codebases
 3226:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3227:     return $output;
 3228: }
 3229: 
 3230: =pod
 3231: 
 3232: =item * &get_student_view()
 3233: 
 3234: show a snapshot of what student was looking at
 3235: 
 3236: =cut
 3237: 
 3238: sub get_student_view {
 3239:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3240:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3241:   my (%form);
 3242:   my @elements=('symb','courseid','domain','username');
 3243:   foreach my $element (@elements) {
 3244:       $form{'grade_'.$element}=eval '$'.$element #'
 3245:   }
 3246:   if (defined($moreenv)) {
 3247:       %form=(%form,%{$moreenv});
 3248:   }
 3249:   if (defined($target)) { $form{'grade_target'} = $target; }
 3250:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3251:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3252:   $userview=~s/\<body[^\>]*\>//gi;
 3253:   $userview=~s/\<\/body\>//gi;
 3254:   $userview=~s/\<html\>//gi;
 3255:   $userview=~s/\<\/html\>//gi;
 3256:   $userview=~s/\<head\>//gi;
 3257:   $userview=~s/\<\/head\>//gi;
 3258:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3259:   $userview=&relative_to_absolute($feedurl,$userview);
 3260:   if (wantarray) {
 3261:      return ($userview,$response);
 3262:   } else {
 3263:      return $userview;
 3264:   }
 3265: }
 3266: 
 3267: sub get_student_view_with_retries {
 3268:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3269: 
 3270:     my $ok = 0;                 # True if we got a good response.
 3271:     my $content;
 3272:     my $response;
 3273: 
 3274:     # Try to get the student_view done. within the retries count:
 3275:     
 3276:     do {
 3277:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3278:          $ok      = $response->is_success;
 3279:          if (!$ok) {
 3280:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3281:          }
 3282:          $retries--;
 3283:     } while (!$ok && ($retries > 0));
 3284:     
 3285:     if (!$ok) {
 3286:        $content = '';          # On error return an empty content.
 3287:     }
 3288:     if (wantarray) {
 3289:        return ($content, $response);
 3290:     } else {
 3291:        return $content;
 3292:     }
 3293: }
 3294: 
 3295: =pod
 3296: 
 3297: =item * &get_student_answers() 
 3298: 
 3299: show a snapshot of how student was answering problem
 3300: 
 3301: =cut
 3302: 
 3303: sub get_student_answers {
 3304:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3305:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3306:   my (%moreenv);
 3307:   my @elements=('symb','courseid','domain','username');
 3308:   foreach my $element (@elements) {
 3309:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3310:   }
 3311:   $moreenv{'grade_target'}='answer';
 3312:   %moreenv=(%form,%moreenv);
 3313:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3314:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3315:   return $userview;
 3316: }
 3317: 
 3318: =pod
 3319: 
 3320: =item * &submlink()
 3321: 
 3322: Inputs: $text $uname $udom $symb $target
 3323: 
 3324: Returns: A link to grades.pm such as to see the SUBM view of a student
 3325: 
 3326: =cut
 3327: 
 3328: ###############################################
 3329: sub submlink {
 3330:     my ($text,$uname,$udom,$symb,$target)=@_;
 3331:     if (!($uname && $udom)) {
 3332: 	(my $cursymb, my $courseid,$udom,$uname)=
 3333: 	    &Apache::lonnet::whichuser($symb);
 3334: 	if (!$symb) { $symb=$cursymb; }
 3335:     }
 3336:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3337:     $symb=&escape($symb);
 3338:     if ($target) { $target="target=\"$target\""; }
 3339:     return '<a href="/adm/grades?&command=submission&'.
 3340: 	'symb='.$symb.'&student='.$uname.
 3341: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3342: }
 3343: ##############################################
 3344: 
 3345: =pod
 3346: 
 3347: =item * &pgrdlink()
 3348: 
 3349: Inputs: $text $uname $udom $symb $target
 3350: 
 3351: Returns: A link to grades.pm such as to see the PGRD view of a student
 3352: 
 3353: =cut
 3354: 
 3355: ###############################################
 3356: sub pgrdlink {
 3357:     my $link=&submlink(@_);
 3358:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3359:     return $link;
 3360: }
 3361: ##############################################
 3362: 
 3363: =pod
 3364: 
 3365: =item * &pprmlink()
 3366: 
 3367: Inputs: $text $uname $udom $symb $target
 3368: 
 3369: Returns: A link to parmset.pm such as to see the PPRM view of a
 3370: student and a specific resource
 3371: 
 3372: =cut
 3373: 
 3374: ###############################################
 3375: sub pprmlink {
 3376:     my ($text,$uname,$udom,$symb,$target)=@_;
 3377:     if (!($uname && $udom)) {
 3378: 	(my $cursymb, my $courseid,$udom,$uname)=
 3379: 	    &Apache::lonnet::whichuser($symb);
 3380: 	if (!$symb) { $symb=$cursymb; }
 3381:     }
 3382:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3383:     $symb=&escape($symb);
 3384:     if ($target) { $target="target=\"$target\""; }
 3385:     return '<a href="/adm/parmset?command=set&amp;'.
 3386: 	'symb='.$symb.'&amp;uname='.$uname.
 3387: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3388: }
 3389: ##############################################
 3390: 
 3391: =pod
 3392: 
 3393: =back
 3394: 
 3395: =cut
 3396: 
 3397: ###############################################
 3398: 
 3399: 
 3400: sub timehash {
 3401:     my ($thistime) = @_;
 3402:     my $timezone = &Apache::lonlocal::gettimezone();
 3403:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3404:                      ->set_time_zone($timezone);
 3405:     my $wday = $dt->day_of_week();
 3406:     if ($wday == 7) { $wday = 0; }
 3407:     return ( 'second' => $dt->second(),
 3408:              'minute' => $dt->minute(),
 3409:              'hour'   => $dt->hour(),
 3410:              'day'     => $dt->day_of_month(),
 3411:              'month'   => $dt->month(),
 3412:              'year'    => $dt->year(),
 3413:              'weekday' => $wday,
 3414:              'dayyear' => $dt->day_of_year(),
 3415:              'dlsav'   => $dt->is_dst() );
 3416: }
 3417: 
 3418: sub utc_string {
 3419:     my ($date)=@_;
 3420:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3421: }
 3422: 
 3423: sub maketime {
 3424:     my %th=@_;
 3425:     my ($epoch_time,$timezone,$dt);
 3426:     $timezone = &Apache::lonlocal::gettimezone();
 3427:     eval {
 3428:         $dt = DateTime->new( year   => $th{'year'},
 3429:                              month  => $th{'month'},
 3430:                              day    => $th{'day'},
 3431:                              hour   => $th{'hour'},
 3432:                              minute => $th{'minute'},
 3433:                              second => $th{'second'},
 3434:                              time_zone => $timezone,
 3435:                          );
 3436:     };
 3437:     if (!$@) {
 3438:         $epoch_time = $dt->epoch;
 3439:         if ($epoch_time) {
 3440:             return $epoch_time;
 3441:         }
 3442:     }
 3443:     return POSIX::mktime(
 3444:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3445:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3446: }
 3447: 
 3448: #########################################
 3449: 
 3450: sub findallcourses {
 3451:     my ($roles,$uname,$udom) = @_;
 3452:     my %roles;
 3453:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3454:     my %courses;
 3455:     my $now=time;
 3456:     if (!defined($uname)) {
 3457:         $uname = $env{'user.name'};
 3458:     }
 3459:     if (!defined($udom)) {
 3460:         $udom = $env{'user.domain'};
 3461:     }
 3462:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3463:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3464:         if (!%roles) {
 3465:             %roles = (
 3466:                        cc => 1,
 3467:                        in => 1,
 3468:                        ep => 1,
 3469:                        ta => 1,
 3470:                        cr => 1,
 3471:                        st => 1,
 3472:              );
 3473:         }
 3474:         foreach my $entry (keys(%roleshash)) {
 3475:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3476:             if ($trole =~ /^cr/) { 
 3477:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3478:             } else {
 3479:                 next if (!exists($roles{$trole}));
 3480:             }
 3481:             if ($tend) {
 3482:                 next if ($tend < $now);
 3483:             }
 3484:             if ($tstart) {
 3485:                 next if ($tstart > $now);
 3486:             }
 3487:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3488:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3489:             if ($secpart eq '') {
 3490:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3491:                 $sec = 'none';
 3492:                 $realsec = '';
 3493:             } else {
 3494:                 $cnum = $cnumpart;
 3495:                 ($sec,$role) = split(/_/,$secpart);
 3496:                 $realsec = $sec;
 3497:             }
 3498:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3499:         }
 3500:     } else {
 3501:         foreach my $key (keys(%env)) {
 3502: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3503:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3504: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3505: 	        next if ($role eq 'ca' || $role eq 'aa');
 3506: 	        next if (%roles && !exists($roles{$role}));
 3507: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3508:                 my $active=1;
 3509:                 if ($starttime) {
 3510: 		    if ($now<$starttime) { $active=0; }
 3511:                 }
 3512:                 if ($endtime) {
 3513:                     if ($now>$endtime) { $active=0; }
 3514:                 }
 3515:                 if ($active) {
 3516:                     if ($sec eq '') {
 3517:                         $sec = 'none';
 3518:                     }
 3519:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3520:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3521:                 }
 3522:             }
 3523:         }
 3524:     }
 3525:     return %courses;
 3526: }
 3527: 
 3528: ###############################################
 3529: 
 3530: sub blockcheck {
 3531:     my ($setters,$activity,$uname,$udom) = @_;
 3532: 
 3533:     if (!defined($udom)) {
 3534:         $udom = $env{'user.domain'};
 3535:     }
 3536:     if (!defined($uname)) {
 3537:         $uname = $env{'user.name'};
 3538:     }
 3539: 
 3540:     # If uname and udom are for a course, check for blocks in the course.
 3541: 
 3542:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3543:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3544:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3545:         return ($startblock,$endblock);
 3546:     }
 3547: 
 3548:     my $startblock = 0;
 3549:     my $endblock = 0;
 3550:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3551: 
 3552:     # If uname is for a user, and activity is course-specific, i.e.,
 3553:     # boards, chat or groups, check for blocking in current course only.
 3554: 
 3555:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3556:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3557:         foreach my $key (keys(%live_courses)) {
 3558:             if ($key ne $env{'request.course.id'}) {
 3559:                 delete($live_courses{$key});
 3560:             }
 3561:         }
 3562:     }
 3563: 
 3564:     my $otheruser = 0;
 3565:     my %own_courses;
 3566:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3567:         # Resource belongs to user other than current user.
 3568:         $otheruser = 1;
 3569:         # Gather courses for current user
 3570:         %own_courses = 
 3571:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3572:     }
 3573: 
 3574:     # Gather active course roles - course coordinator, instructor, 
 3575:     # exam proctor, ta, student, or custom role.
 3576: 
 3577:     foreach my $course (keys(%live_courses)) {
 3578:         my ($cdom,$cnum);
 3579:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3580:             $cdom = $env{'course.'.$course.'.domain'};
 3581:             $cnum = $env{'course.'.$course.'.num'};
 3582:         } else {
 3583:             ($cdom,$cnum) = split(/_/,$course); 
 3584:         }
 3585:         my $no_ownblock = 0;
 3586:         my $no_userblock = 0;
 3587:         if ($otheruser && $activity ne 'com') {
 3588:             # Check if current user has 'evb' priv for this
 3589:             if (defined($own_courses{$course})) {
 3590:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3591:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3592:                     if ($sec ne 'none') {
 3593:                         $checkrole .= '/'.$sec;
 3594:                     }
 3595:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3596:                         $no_ownblock = 1;
 3597:                         last;
 3598:                     }
 3599:                 }
 3600:             }
 3601:             # if they have 'evb' priv and are currently not playing student
 3602:             next if (($no_ownblock) &&
 3603:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3604:         }
 3605:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3606:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3607:             if ($sec ne 'none') {
 3608:                 $checkrole .= '/'.$sec;
 3609:             }
 3610:             if ($otheruser) {
 3611:                 # Resource belongs to user other than current user.
 3612:                 # Assemble privs for that user, and check for 'evb' priv.
 3613:                 my ($trole,$tdom,$tnum,$tsec);
 3614:                 my $entry = $live_courses{$course}{$sec};
 3615:                 if ($entry =~ /^cr/) {
 3616:                     ($trole,$tdom,$tnum,$tsec) = 
 3617:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3618:                 } else {
 3619:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3620:                 }
 3621:                 my ($spec,$area,$trest,%allroles,%userroles);
 3622:                 $area = '/'.$tdom.'/'.$tnum;
 3623:                 $trest = $tnum;
 3624:                 if ($tsec ne '') {
 3625:                     $area .= '/'.$tsec;
 3626:                     $trest .= '/'.$tsec;
 3627:                 }
 3628:                 $spec = $trole.'.'.$area;
 3629:                 if ($trole =~ /^cr/) {
 3630:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3631:                                                       $tdom,$spec,$trest,$area);
 3632:                 } else {
 3633:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3634:                                                        $tdom,$spec,$trest,$area);
 3635:                 }
 3636:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3637:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3638:                     if ($1) {
 3639:                         $no_userblock = 1;
 3640:                         last;
 3641:                     }
 3642:                 }
 3643:             } else {
 3644:                 # Resource belongs to current user
 3645:                 # Check for 'evb' priv via lonnet::allowed().
 3646:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3647:                     $no_ownblock = 1;
 3648:                     last;
 3649:                 }
 3650:             }
 3651:         }
 3652:         # if they have the evb priv and are currently not playing student
 3653:         next if (($no_ownblock) &&
 3654:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3655:         next if ($no_userblock);
 3656: 
 3657:         # Retrieve blocking times and identity of blocker for course
 3658:         # of specified user, unless user has 'evb' privilege.
 3659:         
 3660:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3661:         if (($start != 0) && 
 3662:             (($startblock == 0) || ($startblock > $start))) {
 3663:             $startblock = $start;
 3664:         }
 3665:         if (($end != 0)  &&
 3666:             (($endblock == 0) || ($endblock < $end))) {
 3667:             $endblock = $end;
 3668:         }
 3669:     }
 3670:     return ($startblock,$endblock);
 3671: }
 3672: 
 3673: sub get_blocks {
 3674:     my ($setters,$activity,$cdom,$cnum) = @_;
 3675:     my $startblock = 0;
 3676:     my $endblock = 0;
 3677:     my $course = $cdom.'_'.$cnum;
 3678:     $setters->{$course} = {};
 3679:     $setters->{$course}{'staff'} = [];
 3680:     $setters->{$course}{'times'} = [];
 3681:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3682:     foreach my $record (keys(%records)) {
 3683:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3684:         if ($start <= time && $end >= time) {
 3685:             my ($staff_name,$staff_dom,$title,$blocks) =
 3686:                 &parse_block_record($records{$record});
 3687:             if ($blocks->{$activity} eq 'on') {
 3688:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3689:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3690:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3691:                     $startblock = $start;
 3692:                 }
 3693:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3694:                     $endblock = $end;
 3695:                 }
 3696:             }
 3697:         }
 3698:     }
 3699:     return ($startblock,$endblock);
 3700: }
 3701: 
 3702: sub parse_block_record {
 3703:     my ($record) = @_;
 3704:     my ($setuname,$setudom,$title,$blocks);
 3705:     if (ref($record) eq 'HASH') {
 3706:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3707:         $title = &unescape($record->{'event'});
 3708:         $blocks = $record->{'blocks'};
 3709:     } else {
 3710:         my @data = split(/:/,$record,3);
 3711:         if (scalar(@data) eq 2) {
 3712:             $title = $data[1];
 3713:             ($setuname,$setudom) = split(/@/,$data[0]);
 3714:         } else {
 3715:             ($setuname,$setudom,$title) = @data;
 3716:         }
 3717:         $blocks = { 'com' => 'on' };
 3718:     }
 3719:     return ($setuname,$setudom,$title,$blocks);
 3720: }
 3721: 
 3722: sub build_block_table {
 3723:     my ($startblock,$endblock,$setters) = @_;
 3724:     my %lt = &Apache::lonlocal::texthash(
 3725:         'cacb' => 'Currently active communication blocks',
 3726:         'cour' => 'Course',
 3727:         'dura' => 'Duration',
 3728:         'blse' => 'Block set by'
 3729:     );
 3730:     my $output;
 3731:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3732:     $output .= &start_data_table();
 3733:     $output .= '
 3734: <tr>
 3735:  <th>'.$lt{'cour'}.'</th>
 3736:  <th>'.$lt{'dura'}.'</th>
 3737:  <th>'.$lt{'blse'}.'</th>
 3738: </tr>
 3739: ';
 3740:     foreach my $course (keys(%{$setters})) {
 3741:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3742:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3743:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3744:             my $fullname = &plainname($uname,$udom);
 3745:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3746:                 && $env{'user.name'} ne 'public' 
 3747:                 && $env{'user.domain'} ne 'public') {
 3748:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3749:             }
 3750:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3751:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3752:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3753:             $output .= &Apache::loncommon::start_data_table_row().
 3754:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3755:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3756:                        '<td>'.$fullname.'</td>'.
 3757:                         &Apache::loncommon::end_data_table_row();
 3758:         }
 3759:     }
 3760:     $output .= &end_data_table();
 3761: }
 3762: 
 3763: sub blocking_status {
 3764:     my ($activity,$uname,$udom) = @_;
 3765:     my %setters;
 3766:     my ($blocked,$output,$ownitem,$is_course);
 3767:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3768:     if ($startblock && $endblock) {
 3769:         $blocked = 1;
 3770:         if (wantarray) {
 3771:             my $category;
 3772:             if ($activity eq 'boards') {
 3773:                 $category = 'Discussion posts in this course';
 3774:             } elsif ($activity eq 'blogs') {
 3775:                 $category = 'Blogs';
 3776:             } elsif ($activity eq 'port') {
 3777:                 if (defined($uname) && defined($udom)) {
 3778:                     if ($uname eq $env{'user.name'} &&
 3779:                         $udom eq $env{'user.domain'}) {
 3780:                         $ownitem = 1;
 3781:                     }
 3782:                 }
 3783:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3784:                 if ($ownitem) { 
 3785:                     $category = 'Your portfolio files';  
 3786:                 } elsif ($is_course) {
 3787:                     my $coursedesc;
 3788:                     foreach my $course (keys(%setters)) {
 3789:                         my %courseinfo =
 3790:                              &Apache::lonnet::coursedescription($course);
 3791:                         $coursedesc = $courseinfo{'description'};
 3792:                     }
 3793:                     $category = "Group files in the course '$coursedesc'";
 3794:                 } else {
 3795:                     $category = 'Portfolio files belonging to ';
 3796:                     if ($env{'user.name'} eq 'public' && 
 3797:                         $env{'user.domain'} eq 'public') {
 3798:                         $category .= &plainname($uname,$udom);
 3799:                     } else {
 3800:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3801:                     }
 3802:                 }
 3803:             } elsif ($activity eq 'groups') {
 3804:                 $category = 'Groups in this course';
 3805:             }
 3806:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3807:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3808:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3809:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3810:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3811:             }
 3812:         }
 3813:     }
 3814:     if (wantarray) {
 3815:         return ($blocked,$output);
 3816:     } else {
 3817:         return $blocked;
 3818:     }
 3819: }
 3820: 
 3821: ###############################################
 3822: 
 3823: sub check_ip_acc {
 3824:     my ($acc)=@_;
 3825:     &Apache::lonxml::debug("acc is $acc");
 3826:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3827:         return 1;
 3828:     }
 3829:     my $allowed=0;
 3830:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3831: 
 3832:     my $name;
 3833:     foreach my $pattern (split(',',$acc)) {
 3834:         $pattern =~ s/^\s*//;
 3835:         $pattern =~ s/\s*$//;
 3836:         if ($pattern =~ /\*$/) {
 3837:             #35.8.*
 3838:             $pattern=~s/\*//;
 3839:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3840:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3841:             #35.8.3.[34-56]
 3842:             my $low=$2;
 3843:             my $high=$3;
 3844:             $pattern=$1;
 3845:             if ($ip =~ /^\Q$pattern\E/) {
 3846:                 my $last=(split(/\./,$ip))[3];
 3847:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3848:             }
 3849:         } elsif ($pattern =~ /^\*/) {
 3850:             #*.msu.edu
 3851:             $pattern=~s/\*//;
 3852:             if (!defined($name)) {
 3853:                 use Socket;
 3854:                 my $netaddr=inet_aton($ip);
 3855:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3856:             }
 3857:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3858:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3859:             #127.0.0.1
 3860:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3861:         } else {
 3862:             #some.name.com
 3863:             if (!defined($name)) {
 3864:                 use Socket;
 3865:                 my $netaddr=inet_aton($ip);
 3866:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3867:             }
 3868:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3869:         }
 3870:         if ($allowed) { last; }
 3871:     }
 3872:     return $allowed;
 3873: }
 3874: 
 3875: ###############################################
 3876: 
 3877: =pod
 3878: 
 3879: =head1 Domain Template Functions
 3880: 
 3881: =over 4
 3882: 
 3883: =item * &determinedomain()
 3884: 
 3885: Inputs: $domain (usually will be undef)
 3886: 
 3887: Returns: Determines which domain should be used for designs
 3888: 
 3889: =cut
 3890: 
 3891: ###############################################
 3892: sub determinedomain {
 3893:     my $domain=shift;
 3894:     if (! $domain) {
 3895:         # Determine domain if we have not been given one
 3896:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3897:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3898:         if ($env{'request.role.domain'}) { 
 3899:             $domain=$env{'request.role.domain'}; 
 3900:         }
 3901:     }
 3902:     return $domain;
 3903: }
 3904: ###############################################
 3905: 
 3906: sub devalidate_domconfig_cache {
 3907:     my ($udom)=@_;
 3908:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3909: }
 3910: 
 3911: # ---------------------- Get domain configuration for a domain
 3912: sub get_domainconf {
 3913:     my ($udom) = @_;
 3914:     my $cachetime=1800;
 3915:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3916:     if (defined($cached)) { return %{$result}; }
 3917: 
 3918:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3919: 					     ['login','rolecolors'],$udom);
 3920:     my (%designhash,%legacy);
 3921:     if (keys(%domconfig) > 0) {
 3922:         if (ref($domconfig{'login'}) eq 'HASH') {
 3923:             if (keys(%{$domconfig{'login'}})) {
 3924:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3925:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3926:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 3927:                             $designhash{$udom.'.login.'.$key.'_'.$img} =
 3928:                                 $domconfig{'login'}{$key}{$img};
 3929:                         }
 3930:                     } else {
 3931:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3932:                     }
 3933:                 }
 3934:             } else {
 3935:                 $legacy{'login'} = 1;
 3936:             }
 3937:         } else {
 3938:             $legacy{'login'} = 1;
 3939:         }
 3940:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3941:             if (keys(%{$domconfig{'rolecolors'}})) {
 3942:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3943:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3944:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3945:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3946:                         }
 3947:                     }
 3948:                 }
 3949:             } else {
 3950:                 $legacy{'rolecolors'} = 1;
 3951:             }
 3952:         } else {
 3953:             $legacy{'rolecolors'} = 1;
 3954:         }
 3955:         if (keys(%legacy) > 0) {
 3956:             my %legacyhash = &get_legacy_domconf($udom);
 3957:             foreach my $item (keys(%legacyhash)) {
 3958:                 if ($item =~ /^\Q$udom\E\.login/) {
 3959:                     if ($legacy{'login'}) { 
 3960:                         $designhash{$item} = $legacyhash{$item};
 3961:                     }
 3962:                 } else {
 3963:                     if ($legacy{'rolecolors'}) {
 3964:                         $designhash{$item} = $legacyhash{$item};
 3965:                     }
 3966:                 }
 3967:             }
 3968:         }
 3969:     } else {
 3970:         %designhash = &get_legacy_domconf($udom); 
 3971:     }
 3972:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 3973: 				  $cachetime);
 3974:     return %designhash;
 3975: }
 3976: 
 3977: sub get_legacy_domconf {
 3978:     my ($udom) = @_;
 3979:     my %legacyhash;
 3980:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 3981:     my $designfile =  $designdir.'/'.$udom.'.tab';
 3982:     if (-e $designfile) {
 3983:         if ( open (my $fh,"<$designfile") ) {
 3984:             while (my $line = <$fh>) {
 3985:                 next if ($line =~ /^\#/);
 3986:                 chomp($line);
 3987:                 my ($key,$val)=(split(/\=/,$line));
 3988:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 3989:             }
 3990:             close($fh);
 3991:         }
 3992:     }
 3993:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 3994:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 3995:     }
 3996:     return %legacyhash;
 3997: }
 3998: 
 3999: =pod
 4000: 
 4001: =item * &domainlogo()
 4002: 
 4003: Inputs: $domain (usually will be undef)
 4004: 
 4005: Returns: A link to a domain logo, if the domain logo exists.
 4006: If the domain logo does not exist, a description of the domain.
 4007: 
 4008: =cut
 4009: 
 4010: ###############################################
 4011: sub domainlogo {
 4012:     my $domain = &determinedomain(shift);
 4013:     my %designhash = &get_domainconf($domain);    
 4014:     # See if there is a logo
 4015:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4016:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4017:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4018: 	    if ($imgsrc =~ m{^/res/}) {
 4019: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4020: 		&Apache::lonnet::repcopy($local_name);
 4021: 	    }
 4022: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4023:         } 
 4024:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4025:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4026:         return &Apache::lonnet::domain($domain,'description');
 4027:     } else {
 4028:         return '';
 4029:     }
 4030: }
 4031: ##############################################
 4032: 
 4033: =pod
 4034: 
 4035: =item * &designparm()
 4036: 
 4037: Inputs: $which parameter; $domain (usually will be undef)
 4038: 
 4039: Returns: value of designparamter $which
 4040: 
 4041: =cut
 4042: 
 4043: 
 4044: ##############################################
 4045: sub designparm {
 4046:     my ($which,$domain)=@_;
 4047:     if ($env{'browser.blackwhite'} eq 'on') {
 4048: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4049: 	    return '#000000';
 4050: 	}
 4051: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4052: 	    return '#FFFFFF';
 4053: 	}
 4054: 	if ($which=~/\.tabbg$/) {
 4055: 	    return '#CCCCCC';
 4056: 	}
 4057:     }
 4058:     if (exists($env{'environment.color.'.$which})) {
 4059: 	return $env{'environment.color.'.$which};
 4060:     }
 4061:     $domain=&determinedomain($domain);
 4062:     my %domdesign = &get_domainconf($domain);
 4063:     my $output;
 4064:     if ($domdesign{$domain.'.'.$which} ne '') {
 4065: 	$output = $domdesign{$domain.'.'.$which};
 4066:     } else {
 4067:         $output = $defaultdesign{$which};
 4068:     }
 4069:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4070:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4071:         if ($output =~ m{^/(adm|res)/}) {
 4072: 	    if ($output =~ m{^/res/}) {
 4073: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4074: 		&Apache::lonnet::repcopy($local_name);
 4075: 	    }
 4076:             $output = &lonhttpdurl($output);
 4077:         }
 4078:     }
 4079:     return $output;
 4080: }
 4081: 
 4082: ###############################################
 4083: ###############################################
 4084: 
 4085: =pod
 4086: 
 4087: =back
 4088: 
 4089: =head1 HTML Helpers
 4090: 
 4091: =over 4
 4092: 
 4093: =item * &bodytag()
 4094: 
 4095: Returns a uniform header for LON-CAPA web pages.
 4096: 
 4097: Inputs: 
 4098: 
 4099: =over 4
 4100: 
 4101: =item * $title, A title to be displayed on the page.
 4102: 
 4103: =item * $function, the current role (can be undef).
 4104: 
 4105: =item * $addentries, extra parameters for the <body> tag.
 4106: 
 4107: =item * $bodyonly, if defined, only return the <body> tag.
 4108: 
 4109: =item * $domain, if defined, force a given domain.
 4110: 
 4111: =item * $forcereg, if page should register as content page (relevant for 
 4112:             text interface only)
 4113: 
 4114: =item * $customtitle, alternate text to use instead of $title
 4115:                       in the title box that appears, this text
 4116:                       is not auto translated like the $title is
 4117: 
 4118: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4119:                    navigational links
 4120: 
 4121: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4122: 
 4123: =item * $notitle, if true keep the nav controls, but remove the title bar
 4124: 
 4125: =item * $no_inline_link, if true and in remote mode, don't show the 
 4126:          'Switch To Inline Menu' link
 4127: 
 4128: =item * $args, optional argument valid values are
 4129:             no_auto_mt_title -> prevents &mt()ing the title arg
 4130:             inherit_jsmath -> when creating popup window in a page,
 4131:                               should it have jsmath forced on by the
 4132:                               current page
 4133: 
 4134: =back
 4135: 
 4136: Returns: A uniform header for LON-CAPA web pages.  
 4137: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4138: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4139: other decorations will be returned.
 4140: 
 4141: =cut
 4142: 
 4143: sub bodytag {
 4144:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4145: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4146: 
 4147:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4148: 
 4149:     $function = &get_users_function() if (!$function);
 4150:     my $img =    &designparm($function.'.img',$domain);
 4151:     my $font =   &designparm($function.'.font',$domain);
 4152:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4153: 
 4154:     my %design = ( 'style'   => 'margin-top: 0px',
 4155: 		   'bgcolor' => $pgbg,
 4156: 		   'text'    => $font,
 4157:                    'alink'   => &designparm($function.'.alink',$domain),
 4158: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4159: 		   'link'    => &designparm($function.'.link',$domain),);
 4160:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4161: 
 4162:  # role and realm
 4163:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4164:     if ($role  eq 'ca') {
 4165:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4166:         $realm = &plainname($rname,$rdom);
 4167:     } 
 4168: # realm
 4169:     if ($env{'request.course.id'}) {
 4170:         if ($env{'request.role'} !~ /^cr/) {
 4171:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4172:         }
 4173: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4174:     } else {
 4175:         $role = &Apache::lonnet::plaintext($role);
 4176:     }
 4177: 
 4178:     if (!$realm) { $realm='&nbsp;'; }
 4179: # Set messages
 4180:     my $messages=&domainlogo($domain);
 4181: 
 4182:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4183: 
 4184: # construct main body tag
 4185:     my $bodytag = "<body $extra_body_attr>".
 4186: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4187: 
 4188:     if ($bodyonly) {
 4189:         return $bodytag;
 4190:     } elsif ($env{'browser.interface'} eq 'textual') {
 4191: # Accessibility
 4192:           
 4193: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4194: 	if (!$notitle) {
 4195: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4196: 	}
 4197: 	return $bodytag;
 4198:     }
 4199: 
 4200:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4201:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4202: 	undef($role);
 4203:     } else {
 4204: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4205:     }
 4206:     
 4207:     my $roleinfo=(<<ENDROLE);
 4208: <td class="LC_title_bar_who">
 4209: <div class="LC_title_bar_name">
 4210:     $name
 4211:     &nbsp;
 4212: </div>
 4213: <div class="LC_title_bar_role">
 4214: $role&nbsp;
 4215: </div>
 4216: <div class="LC_title_bar_realm">
 4217: $realm&nbsp;
 4218: </div>
 4219: </td>
 4220: ENDROLE
 4221: 
 4222:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4223:     if ($customtitle) {
 4224:         $titleinfo = $customtitle;
 4225:     }
 4226:     #
 4227:     # Extra info if you are the DC
 4228:     my $dc_info = '';
 4229:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4230:                         $env{'course.'.$env{'request.course.id'}.
 4231:                                  '.domain'}.'/'})) {
 4232:         my $cid = $env{'request.course.id'};
 4233:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4234:         $dc_info =~ s/\s+$//;
 4235:         $dc_info = '('.$dc_info.')';
 4236:     }
 4237: 
 4238:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4239:         # No Remote
 4240: 	if ($env{'request.state'} eq 'construct') {
 4241: 	    $forcereg=1;
 4242: 	}
 4243: 
 4244: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4245: 	    # this is for resources; directories have customtitle, and crumbs
 4246:             # and select recent are created in lonpubdir.pm  
 4247: 	    my ($uname,$thisdisfn)=
 4248: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4249: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4250: 	    $formaction=~s/\/+/\//g;
 4251: 
 4252: 	    my $parentpath = '';
 4253: 	    my $lastitem = '';
 4254: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4255: 		$parentpath = $1;
 4256: 		$lastitem = $2;
 4257: 	    } else {
 4258: 		$lastitem = $thisdisfn;
 4259: 	    }
 4260: 	    $titleinfo = 
 4261: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4262: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4263: 		.'<form name="dirs" method="post" action="'.$formaction
 4264: 		.'" target="_top"><tt><b>'
 4265: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 4266: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4267: 		.'</form>'
 4268: 		.&Apache::lonmenu::constspaceform();
 4269:         }
 4270: 
 4271:         my $titletable;
 4272: 	if (!$notitle) {
 4273: 	    $titletable =
 4274: 		'<table id="LC_title_bar">'.
 4275:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4276: 			 '</tr></table>';
 4277: 	}
 4278: 	if ($notopbar) {
 4279: 	    $bodytag .= $titletable;
 4280: 	} else {
 4281: 	    if ($env{'request.state'} eq 'construct') {
 4282:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4283: 							  $titletable);
 4284:             } else {
 4285:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4286: 		    $titletable;
 4287:             }
 4288:         }
 4289:         return $bodytag;
 4290:     }
 4291: 
 4292: #
 4293: # Top frame rendering, Remote is up
 4294: #
 4295: 
 4296:     my $imgsrc = $img;
 4297:     if ($img =~ /^\/adm/) {
 4298:         $imgsrc = &lonhttpdurl($img);
 4299:     }
 4300:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4301: 
 4302:     # Explicit link to get inline menu
 4303:     my $menu= ($no_inline_link?''
 4304: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4305:     #
 4306:     if ($notitle) {
 4307: 	return $bodytag;
 4308:     }
 4309:     return(<<ENDBODY);
 4310: $bodytag
 4311: <table id="LC_title_bar" class="LC_with_remote">
 4312: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4313:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4314: </tr>
 4315: <tr><td>$titleinfo $dc_info $menu</td>
 4316: $roleinfo
 4317: </tr>
 4318: </table>
 4319: ENDBODY
 4320: }
 4321: 
 4322: sub make_attr_string {
 4323:     my ($register,$attr_ref) = @_;
 4324: 
 4325:     if ($attr_ref && !ref($attr_ref)) {
 4326: 	die("addentries Must be a hash ref ".
 4327: 	    join(':',caller(1))." ".
 4328: 	    join(':',caller(0))." ");
 4329:     }
 4330: 
 4331:     if ($register) {
 4332: 	my ($on_load,$on_unload);
 4333: 	foreach my $key (keys(%{$attr_ref})) {
 4334: 	    if      (lc($key) eq 'onload') {
 4335: 		$on_load.=$attr_ref->{$key}.';';
 4336: 		delete($attr_ref->{$key});
 4337: 
 4338: 	    } elsif (lc($key) eq 'onunload') {
 4339: 		$on_unload.=$attr_ref->{$key}.';';
 4340: 		delete($attr_ref->{$key});
 4341: 	    }
 4342: 	}
 4343: 	$attr_ref->{'onload'}  =
 4344: 	    &Apache::lonmenu::loadevents().  $on_load;
 4345: 	$attr_ref->{'onunload'}=
 4346: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4347:     }
 4348: 
 4349: # Accessibility font enhance
 4350:     if ($env{'browser.fontenhance'} eq 'on') {
 4351: 	my $style;
 4352: 	foreach my $key (keys(%{$attr_ref})) {
 4353: 	    if (lc($key) eq 'style') {
 4354: 		$style.=$attr_ref->{$key}.';';
 4355: 		delete($attr_ref->{$key});
 4356: 	    }
 4357: 	}
 4358: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4359:     }
 4360: 
 4361:     if ($env{'browser.blackwhite'} eq 'on') {
 4362: 	delete($attr_ref->{'font'});
 4363: 	delete($attr_ref->{'link'});
 4364: 	delete($attr_ref->{'alink'});
 4365: 	delete($attr_ref->{'vlink'});
 4366: 	delete($attr_ref->{'bgcolor'});
 4367: 	delete($attr_ref->{'background'});
 4368:     }
 4369: 
 4370:     my $attr_string;
 4371:     foreach my $attr (keys(%$attr_ref)) {
 4372: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4373:     }
 4374:     return $attr_string;
 4375: }
 4376: 
 4377: 
 4378: ###############################################
 4379: ###############################################
 4380: 
 4381: =pod
 4382: 
 4383: =item * &endbodytag()
 4384: 
 4385: Returns a uniform footer for LON-CAPA web pages.
 4386: 
 4387: Inputs: 1 - optional reference to an args hash
 4388: If in the hash, key for noredirectlink has a value which evaluates to true,
 4389: a 'Continue' link is not displayed if the page contains an
 4390: internal redirect in the <head></head> section,
 4391: i.e., $env{'internal.head.redirect'} exists   
 4392: 
 4393: =cut
 4394: 
 4395: sub endbodytag {
 4396:     my ($args) = @_;
 4397:     my $endbodytag='</body>';
 4398:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4399:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4400:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4401: 	    $endbodytag=
 4402: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4403: 	        &mt('Continue').'</a>'.
 4404: 	        $endbodytag;
 4405:         }
 4406:     }
 4407:     return $endbodytag;
 4408: }
 4409: 
 4410: =pod
 4411: 
 4412: =item * &standard_css()
 4413: 
 4414: Returns a style sheet
 4415: 
 4416: Inputs: (all optional)
 4417:             domain         -> force to color decorate a page for a specific
 4418:                                domain
 4419:             function       -> force usage of a specific rolish color scheme
 4420:             bgcolor        -> override the default page bgcolor
 4421: 
 4422: =cut
 4423: 
 4424: sub standard_css {
 4425:     my ($function,$domain,$bgcolor) = @_;
 4426:     $function  = &get_users_function() if (!$function);
 4427:     my $img    = &designparm($function.'.img',   $domain);
 4428:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4429:     my $font   = &designparm($function.'.font',  $domain);
 4430:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4431:     my $pgbg_or_bgcolor =
 4432: 	         $bgcolor ||
 4433: 	         &designparm($function.'.pgbg',  $domain);
 4434:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4435:     my $alink  = &designparm($function.'.alink', $domain);
 4436:     my $vlink  = &designparm($function.'.vlink', $domain);
 4437:     my $link   = &designparm($function.'.link',  $domain);
 4438: 
 4439:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4440:     my $mono                 = 'monospace';
 4441:     my $data_table_head      = $tabbg;
 4442:     my $data_table_light     = '#EEEEEE';
 4443:     my $data_table_dark      = '#DDDDDD';
 4444:     my $data_table_darker    = '#CCCCCC';
 4445:     my $data_table_highlight = '#FFFF00';
 4446:     my $mail_new             = '#FFBB77';
 4447:     my $mail_new_hover       = '#DD9955';
 4448:     my $mail_read            = '#BBBB77';
 4449:     my $mail_read_hover      = '#999944';
 4450:     my $mail_replied         = '#AAAA88';
 4451:     my $mail_replied_hover   = '#888855';
 4452:     my $mail_other           = '#99BBBB';
 4453:     my $mail_other_hover     = '#669999';
 4454:     my $table_header         = '#DDDDDD';
 4455:     my $feedback_link_bg     = '#BBBBBB';
 4456: 
 4457:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4458: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4459: 	                                                 : '0px 3px 0px 4px';
 4460: 
 4461: 
 4462:     return <<END;
 4463: h1, h2, h3, th { font-family: $sans }
 4464: a:focus { color: red; background: yellow } 
 4465: table.thinborder,
 4466: 
 4467: table.thinborder tr th {
 4468:   border-style: solid;
 4469:   border-width: 1px;
 4470:   background: $tabbg;
 4471: }
 4472: table.thinborder tr td {
 4473:   border-style: solid;
 4474:   border-width: 1px
 4475: }
 4476: 
 4477: form, .inline { display: inline; }
 4478: .center { text-align: center; }
 4479: .LC_filename {font-family: $mono; white-space:pre;}
 4480: .LC_error {
 4481:   color: red;
 4482:   font-size: larger;
 4483: }
 4484: .LC_warning,
 4485: .LC_diff_removed {
 4486:   color: red;
 4487: }
 4488: 
 4489: .LC_info,
 4490: .LC_success,
 4491: .LC_diff_added {
 4492:   color: green;
 4493: }
 4494: .LC_unknown {
 4495:   color: yellow;
 4496: }
 4497: 
 4498: .LC_icon {
 4499:   border: 0px;
 4500: }
 4501: .LC_indexer_icon {
 4502:   border: 0px;
 4503:   height: 22px;
 4504: }
 4505: .LC_docs_spacer {
 4506:   width: 25px;
 4507:   height: 1px;
 4508:   border: 0px;
 4509: }
 4510: 
 4511: .LC_internal_info {
 4512:   color: #999;
 4513: }
 4514: 
 4515: table.LC_pastsubmission {
 4516:   border: 1px solid black;
 4517:   margin: 2px;
 4518: }
 4519: 
 4520: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4521:   width: 100%;
 4522:   background: $pgbg;
 4523:   border: 2px;
 4524:   border-collapse: separate;
 4525:   padding: 0px;
 4526: }
 4527: 
 4528: table#LC_title_bar, table.LC_breadcrumbs, 
 4529: table#LC_title_bar.LC_with_remote {
 4530:   width: 100%;
 4531:   border-color: $pgbg;
 4532:   border-style: solid;
 4533:   border-width: $border;
 4534: 
 4535:   background: $pgbg;
 4536:   font-family: $sans;
 4537:   border-collapse: collapse;
 4538:   padding: 0px;
 4539: }
 4540: 
 4541: table.LC_docs_path {
 4542:   width: 100%;
 4543:   border: 0;
 4544:   background: $pgbg;
 4545:   font-family: $sans;
 4546:   border-collapse: collapse;
 4547:   padding: 0px;
 4548: }
 4549: 
 4550: table#LC_title_bar td {
 4551:   background: $tabbg;
 4552: }
 4553: table#LC_title_bar td.LC_title_bar_who {
 4554:   background: $tabbg;
 4555:   color: $font;
 4556:   font: small $sans;
 4557:   text-align: right;
 4558: }
 4559: span.LC_metadata {
 4560:     font-family: $sans;
 4561: }
 4562: span.LC_title_bar_title {
 4563:   font: bold x-large $sans;
 4564: }
 4565: table#LC_title_bar td.LC_title_bar_domain_logo {
 4566:   background: $sidebg;
 4567:   text-align: right;
 4568:   padding: 0px;
 4569: }
 4570: table#LC_title_bar td.LC_title_bar_role_logo {
 4571:   background: $sidebg;
 4572:   padding: 0px;
 4573: }
 4574: 
 4575: table#LC_menubuttons_mainmenu {
 4576:   width: 100%;
 4577:   border: 0px;
 4578:   border-spacing: 1px;
 4579:   padding: 0px 1px;
 4580:   margin: 0px;
 4581:   border-collapse: separate;
 4582: }
 4583: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4584:   border: 0px;
 4585: }
 4586: table#LC_top_nav td {
 4587:   background: $tabbg;
 4588:   border: 0px;
 4589:   font-size: small;
 4590: }
 4591: table#LC_top_nav td a, div#LC_top_nav a {
 4592:   color: $font;
 4593:   font-family: $sans;
 4594: }
 4595: table#LC_top_nav td.LC_top_nav_logo {
 4596:   background: $tabbg;
 4597:   text-align: left;
 4598:   white-space: nowrap;
 4599:   width: 31px;
 4600: }
 4601: table#LC_top_nav td.LC_top_nav_logo img {
 4602:   border: 0px;
 4603:   vertical-align: bottom;
 4604: }
 4605: table#LC_top_nav td.LC_top_nav_exit,
 4606: table#LC_top_nav td.LC_top_nav_help {
 4607:   width: 2.0em;
 4608: }
 4609: table#LC_top_nav td.LC_top_nav_login {
 4610:   width: 4.0em;
 4611:   text-align: center;
 4612: }
 4613: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4614:   background: $tabbg;
 4615:   color: $font;
 4616:   font-family: $sans;
 4617:   font-size: smaller;
 4618: }
 4619: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4620: table.LC_docs_path td.LC_docs_path_component {
 4621:   background: $tabbg;
 4622:   color: $font;
 4623:   font-family: $sans;
 4624:   font-size: larger;
 4625:   text-align: right;
 4626: }
 4627: td.LC_table_cell_checkbox {
 4628:   text-align: center;
 4629: }
 4630: table#LC_mainmenu td.LC_mainmenu_column {
 4631:     vertical-align: top;
 4632: }
 4633: 
 4634: .LC_menubuttons_inline_text {
 4635:   color: $font;
 4636:   font-family: $sans;
 4637:   font-size: smaller;
 4638: }
 4639: 
 4640: .LC_menubuttons_link {
 4641:   text-decoration: none;
 4642: }
 4643: /*2008--9-5: new menu style sheet.Changed category*/
 4644: .LC_menubuttons_category {
 4645:   color: $font;
 4646:   background: $pgbg;
 4647:   font-family: $sans;
 4648:   font-size: larger;
 4649:   font-weight: bold;
 4650: }
 4651: 
 4652: td.LC_menubuttons_text {
 4653:   width: 90%;
 4654:   color: $font;
 4655:   font-family: $sans;
 4656: }
 4657: 
 4658: td.LC_menubuttons_img {
 4659: }
 4660: 
 4661: .LC_current_location {
 4662:   font-family: $sans;
 4663:   background: $tabbg;
 4664: }
 4665: .LC_new_mail {
 4666:   font-family: $sans;
 4667:   background: $tabbg;
 4668:   font-weight: bold;
 4669: }
 4670: 
 4671: .LC_rolesmenu_is {
 4672:   font-family: $sans;
 4673: }
 4674: 
 4675: .LC_rolesmenu_selected {
 4676:   font-family: $sans;
 4677: }
 4678: 
 4679: .LC_rolesmenu_future {
 4680:   font-family: $sans;
 4681: }
 4682: 
 4683: 
 4684: .LC_rolesmenu_will {
 4685:   font-family: $sans;
 4686: }
 4687: 
 4688: .LC_rolesmenu_will_not {
 4689:   font-family: $sans;
 4690: }
 4691: 
 4692: .LC_rolesmenu_expired {
 4693:   font-family: $sans;
 4694: }
 4695: 
 4696: .LC_rolesinfo {
 4697:   font-family: $sans;
 4698: }
 4699: 
 4700: .LC_dropadd_labeltext {
 4701:   font-family: $sans;
 4702:   text-align: right;
 4703: }
 4704: 
 4705: .LC_preferences_labeltext {
 4706:   font-family: $sans;
 4707:   text-align: right;
 4708: }
 4709: 
 4710: .LC_roleslog_note {
 4711:   font-size: smaller;
 4712: }
 4713: 
 4714: .LC_mail_functions {
 4715:     font-weight: bold;
 4716: }
 4717: 
 4718: table.LC_aboutme_port {
 4719:   border: 0px;
 4720:   border-collapse: collapse;
 4721:   border-spacing: 0px;
 4722: }
 4723: table.LC_data_table, table.LC_mail_list {
 4724:   border: 1px solid #000000;
 4725:   border-collapse: separate;
 4726:   border-spacing: 1px;
 4727:   background: $pgbg;
 4728: }
 4729: .LC_data_table_dense {
 4730:   font-size: small;
 4731: }
 4732: table.LC_nested_outer {
 4733:   border: 1px solid #000000;
 4734:   border-collapse: collapse;
 4735:   border-spacing: 0px;
 4736:   width: 100%;
 4737: }
 4738: table.LC_nested {
 4739:   border: 0px;
 4740:   border-collapse: collapse;
 4741:   border-spacing: 0px;
 4742:   width: 100%;
 4743: }
 4744: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4745: table.LC_prior_tries tr th {
 4746:   font-weight: bold;
 4747:   background-color: $data_table_head;
 4748:   font-size: smaller;
 4749: }
 4750: table.LC_data_table tr.LC_info_row > td {
 4751:   background-color: #CCC;
 4752:   font-weight: bold;
 4753:   text-align: left;
 4754: }
 4755: table.LC_data_table tr.LC_odd_row > td, 
 4756: table.LC_aboutme_port tr td {
 4757:   background-color: $data_table_light;
 4758:   padding: 2px;
 4759: }
 4760: table.LC_data_table tr.LC_even_row > td,
 4761: table.LC_aboutme_port tr.LC_even_row td {
 4762:   background-color: $data_table_dark;
 4763: }
 4764: table.LC_data_table tr.LC_data_table_highlight td {
 4765:   background-color: $data_table_darker;
 4766: }
 4767: table.LC_data_table tr td.LC_leftcol_header {
 4768:   background-color: $data_table_head;
 4769:   font-weight: bold;
 4770: }
 4771: table.LC_data_table tr.LC_empty_row td,
 4772: table.LC_nested tr.LC_empty_row td {
 4773:   background-color: #FFFFFF;
 4774:   font-weight: bold;
 4775:   font-style: italic;
 4776:   text-align: center;
 4777:   padding: 8px;
 4778: }
 4779: table.LC_nested tr.LC_empty_row td {
 4780:   padding: 4ex
 4781: }
 4782: table.LC_nested_outer tr th {
 4783:   font-weight: bold;
 4784:   background-color: $data_table_head;
 4785:   font-size: smaller;
 4786:   border-bottom: 1px solid #000000;
 4787: }
 4788: table.LC_nested_outer tr td.LC_subheader {
 4789:   background-color: $data_table_head;
 4790:   font-weight: bold;
 4791:   font-size: small;
 4792:   border-bottom: 1px solid #000000;
 4793:   text-align: right;
 4794: }
 4795: table.LC_nested tr.LC_info_row td {
 4796:   background-color: #CCC;
 4797:   font-weight: bold;
 4798:   font-size: small;
 4799:   text-align: center;
 4800: }
 4801: table.LC_nested tr.LC_info_row td.LC_left_item,
 4802: table.LC_nested_outer tr th.LC_left_item {
 4803:   text-align: left;
 4804: }
 4805: table.LC_nested td {
 4806:   background-color: #FFF;
 4807:   font-size: small;
 4808: }
 4809: table.LC_nested_outer tr th.LC_right_item,
 4810: table.LC_nested tr.LC_info_row td.LC_right_item,
 4811: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4812: table.LC_nested tr td.LC_right_item {
 4813:   text-align: right;
 4814: }
 4815: 
 4816: table.LC_nested tr.LC_odd_row td {
 4817:   background-color: #EEE;
 4818: }
 4819: 
 4820: table.LC_createuser {
 4821: }
 4822: 
 4823: table.LC_createuser tr.LC_section_row td {
 4824:   font-size: smaller;
 4825: }
 4826: 
 4827: table.LC_createuser tr.LC_info_row td  {
 4828:   background-color: #CCC;
 4829:   font-weight: bold;
 4830:   text-align: center;
 4831: }
 4832: 
 4833: table.LC_calendar {
 4834:   border: 1px solid #000000;
 4835:   border-collapse: collapse;
 4836: }
 4837: table.LC_calendar_pickdate {
 4838:   font-size: xx-small;
 4839: }
 4840: table.LC_calendar tr td {
 4841:   border: 1px solid #000000;
 4842:   vertical-align: top;
 4843: }
 4844: table.LC_calendar tr td.LC_calendar_day_empty {
 4845:   background-color: $data_table_dark;
 4846: }
 4847: table.LC_calendar tr td.LC_calendar_day_current {
 4848:   background-color: $data_table_highlight;
 4849: }
 4850: 
 4851: table.LC_mail_list tr.LC_mail_new {
 4852:   background-color: $mail_new;
 4853: }
 4854: table.LC_mail_list tr.LC_mail_new:hover {
 4855:   background-color: $mail_new_hover;
 4856: }
 4857: table.LC_mail_list tr.LC_mail_read {
 4858:   background-color: $mail_read;
 4859: }
 4860: table.LC_mail_list tr.LC_mail_read:hover {
 4861:   background-color: $mail_read_hover;
 4862: }
 4863: table.LC_mail_list tr.LC_mail_replied {
 4864:   background-color: $mail_replied;
 4865: }
 4866: table.LC_mail_list tr.LC_mail_replied:hover {
 4867:   background-color: $mail_replied_hover;
 4868: }
 4869: table.LC_mail_list tr.LC_mail_other {
 4870:   background-color: $mail_other;
 4871: }
 4872: table.LC_mail_list tr.LC_mail_other:hover {
 4873:   background-color: $mail_other_hover;
 4874: }
 4875: table.LC_mail_list tr.LC_mail_even {
 4876: }
 4877: table.LC_mail_list tr.LC_mail_odd {
 4878: }
 4879: 
 4880: 
 4881: table#LC_portfolio_actions {
 4882:   width: auto;
 4883:   background: $pgbg;
 4884:   border: 0px;
 4885:   border-spacing: 2px 2px;
 4886:   padding: 0px;
 4887:   margin: 0px;
 4888:   border-collapse: separate;
 4889: }
 4890: table#LC_portfolio_actions td.LC_label {
 4891:   background: $tabbg;
 4892:   text-align: right;
 4893: }
 4894: table#LC_portfolio_actions td.LC_value {
 4895:   background: $tabbg;
 4896: }
 4897: 
 4898: table#LC_cstr_controls {
 4899:   width: 100%;
 4900:   border-collapse: collapse;
 4901: }
 4902: table#LC_cstr_controls tr td {
 4903:   border: 4px solid $pgbg;
 4904:   padding: 4px;
 4905:   text-align: center;
 4906:   background: $tabbg;
 4907: }
 4908: table#LC_cstr_controls tr th {
 4909:   border: 4px solid $pgbg;
 4910:   background: $table_header;
 4911:   text-align: center;
 4912:   font-family: $sans;
 4913:   font-size: smaller;
 4914: }
 4915: 
 4916: table#LC_browser {
 4917:  
 4918: }
 4919: table#LC_browser tr th {
 4920:   background: $table_header;
 4921: }
 4922: table#LC_browser tr td {
 4923:   padding: 2px;
 4924: }
 4925: table#LC_browser tr.LC_browser_file,
 4926: table#LC_browser tr.LC_browser_file_published {
 4927:   background: #CCFF88;
 4928: }
 4929: table#LC_browser tr.LC_browser_file_locked,
 4930: table#LC_browser tr.LC_browser_file_unpublished {
 4931:   background: #FFAA99;
 4932: }
 4933: table#LC_browser tr.LC_browser_file_obsolete {
 4934:   background: #AAAAAA;
 4935: }
 4936: table#LC_browser tr.LC_browser_file_modified,
 4937: table#LC_browser tr.LC_browser_file_metamodified {
 4938:   background: #FFFF77;
 4939: }
 4940: table#LC_browser tr.LC_browser_folder {
 4941:   background: #CCCCFF;
 4942: }
 4943: span.LC_current_location {
 4944:   font-size: x-large;
 4945:   background: $pgbg;
 4946: }
 4947: 
 4948: span.LC_parm_menu_item {
 4949:   font-size: larger;
 4950:   font-family: $sans;
 4951: }
 4952: span.LC_parm_scope_all {
 4953:   color: red;
 4954: }
 4955: span.LC_parm_scope_folder {
 4956:   color: green;
 4957: }
 4958: span.LC_parm_scope_resource {
 4959:   color: orange;
 4960: }
 4961: span.LC_parm_part {
 4962:   color: blue;
 4963: }
 4964: span.LC_parm_folder, span.LC_parm_symb {
 4965:   font-size: x-small;
 4966:   font-family: $mono;
 4967:   color: #AAAAAA;
 4968: }
 4969: 
 4970: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4971: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 4972:   border: 1px solid black;
 4973:   border-collapse: collapse;
 4974: }
 4975: table.LC_parm_overview_restrictions td {
 4976:   border-width: 1px 4px 1px 4px;
 4977:   border-style: solid;
 4978:   border-color: $pgbg;
 4979:   text-align: center;
 4980: }
 4981: table.LC_parm_overview_restrictions th {
 4982:   background: $tabbg;
 4983:   border-width: 1px 4px 1px 4px;
 4984:   border-style: solid;
 4985:   border-color: $pgbg;
 4986: }
 4987: table#LC_helpmenu {
 4988:   border: 0px;
 4989:   height: 55px;
 4990:   border-spacing: 0px;
 4991: }
 4992: 
 4993: table#LC_helpmenu fieldset legend {
 4994:   font-size: larger;
 4995:   font-weight: bold;
 4996: }
 4997: table#LC_helpmenu_links {
 4998:   width: 100%;
 4999:   border: 1px solid black;
 5000:   background: $pgbg;
 5001:   padding: 0px;
 5002:   border-spacing: 1px;
 5003: }
 5004: table#LC_helpmenu_links tr td {
 5005:   padding: 1px;
 5006:   background: $tabbg;
 5007:   text-align: center;
 5008:   font-weight: bold;
 5009: }
 5010: 
 5011: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 5012: table#LC_helpmenu_links a:active {
 5013:   text-decoration: none;
 5014:   color: $font;
 5015: }
 5016: table#LC_helpmenu_links a:hover {
 5017:   text-decoration: underline;
 5018:   color: $vlink;
 5019: }
 5020: 
 5021: .LC_chrt_popup_exists {
 5022:   border: 1px solid #339933;
 5023:   margin: -1px;
 5024: }
 5025: .LC_chrt_popup_up {
 5026:   border: 1px solid yellow;
 5027:   margin: -1px;
 5028: }
 5029: .LC_chrt_popup {
 5030:   border: 1px solid #8888FF;
 5031:   background: #CCCCFF;
 5032: }
 5033: table.LC_pick_box {
 5034:   border-collapse: separate;
 5035:   background: white;
 5036:   border: 1px solid black;
 5037:   border-spacing: 1px;
 5038: }
 5039: table.LC_pick_box td.LC_pick_box_title {
 5040:   background: $tabbg;
 5041:   font-weight: bold;
 5042:   text-align: right;
 5043:   width: 184px;
 5044:   padding: 8px;
 5045: }
 5046: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5047:   background: $tabbg;
 5048:   font-weight: bold;
 5049:   text-align: right;
 5050:   width: 350px;
 5051:   padding: 8px;
 5052: }
 5053: 
 5054: table.LC_pick_box td.LC_pick_box_value {
 5055:   text-align: left;
 5056:   padding: 8px;
 5057: }
 5058: table.LC_pick_box td.LC_pick_box_select {
 5059:   text-align: left;
 5060:   padding: 8px;
 5061: }
 5062: table.LC_pick_box td.LC_pick_box_separator {
 5063:   padding: 0px;
 5064:   height: 1px;
 5065:   background: black;
 5066: }
 5067: table.LC_pick_box td.LC_pick_box_submit {
 5068:   text-align: right;
 5069: }
 5070: table.LC_pick_box td.LC_evenrow_value {
 5071:   text-align: left;
 5072:   padding: 8px;
 5073:   background-color: $data_table_light;
 5074: }
 5075: table.LC_pick_box td.LC_oddrow_value {
 5076:   text-align: left;
 5077:   padding: 8px;
 5078:   background-color: $data_table_light;
 5079: }
 5080: table.LC_helpform_receipt {
 5081:   width: 620px;
 5082:   border-collapse: separate;
 5083:   background: white;
 5084:   border: 1px solid black;
 5085:   border-spacing: 1px;
 5086: }
 5087: table.LC_helpform_receipt td.LC_pick_box_title {
 5088:   background: $tabbg;
 5089:   font-weight: bold;
 5090:   text-align: right;
 5091:   width: 184px;
 5092:   padding: 8px;
 5093: }
 5094: table.LC_helpform_receipt td.LC_evenrow_value {
 5095:   text-align: left;
 5096:   padding: 8px;
 5097:   background-color: $data_table_light;
 5098: }
 5099: table.LC_helpform_receipt td.LC_oddrow_value {
 5100:   text-align: left;
 5101:   padding: 8px;
 5102:   background-color: $data_table_light;
 5103: }
 5104: table.LC_helpform_receipt td.LC_pick_box_separator {
 5105:   padding: 0px;
 5106:   height: 1px;
 5107:   background: black;
 5108: }
 5109: span.LC_helpform_receipt_cat {
 5110:   font-weight: bold;
 5111: }
 5112: table.LC_group_priv_box {
 5113:   background: white;
 5114:   border: 1px solid black;
 5115:   border-spacing: 1px;
 5116: }
 5117: table.LC_group_priv_box td.LC_pick_box_title {
 5118:   background: $tabbg;
 5119:   font-weight: bold;
 5120:   text-align: right;
 5121:   width: 184px;
 5122: }
 5123: table.LC_group_priv_box td.LC_groups_fixed {
 5124:   background: $data_table_light;
 5125:   text-align: center;
 5126: }
 5127: table.LC_group_priv_box td.LC_groups_optional {
 5128:   background: $data_table_dark;
 5129:   text-align: center;
 5130: }
 5131: table.LC_group_priv_box td.LC_groups_functionality {
 5132:   background: $data_table_darker;
 5133:   text-align: center;
 5134:   font-weight: bold;
 5135: }
 5136: table.LC_group_priv td {
 5137:   text-align: left;
 5138:   padding: 0px;
 5139: }
 5140: 
 5141: table.LC_notify_front_page {
 5142:   background: white;
 5143:   border: 1px solid black;
 5144:   padding: 8px;
 5145: }
 5146: table.LC_notify_front_page td {
 5147:   padding: 8px;
 5148: }
 5149: .LC_navbuttons {
 5150:   margin: 2ex 0ex 2ex 0ex;
 5151: }
 5152: .LC_topic_bar {
 5153:   font-family: $sans;
 5154:   font-weight: bold;
 5155:   width: 100%;
 5156:   background: $tabbg;
 5157:   vertical-align: middle;
 5158:   margin: 2ex 0ex 2ex 0ex;
 5159: }
 5160: .LC_topic_bar span {
 5161:   vertical-align: middle;
 5162: }
 5163: .LC_topic_bar img {
 5164:   vertical-align: bottom;
 5165: }
 5166: table.LC_course_group_status {
 5167:   margin: 20px;
 5168: }
 5169: table.LC_status_selector td {
 5170:   vertical-align: top;
 5171:   text-align: center;
 5172:   padding: 4px;
 5173: }
 5174: table.LC_descriptive_input td.LC_description {
 5175:   vertical-align: top;
 5176:   text-align: right;
 5177:   font-weight: bold;
 5178: }
 5179: div.LC_feedback_link {
 5180:   clear: both;
 5181:   background: white;
 5182:   width: 100%;  
 5183: }
 5184: span.LC_feedback_link {
 5185:   background: $feedback_link_bg;
 5186:   font-size: larger;
 5187: }
 5188: span.LC_message_link {
 5189:   background: $feedback_link_bg;
 5190:   font-size: larger;
 5191:   position: absolute;
 5192:   right: 1em;
 5193: }
 5194: 
 5195: table.LC_prior_tries {
 5196:   border: 1px solid #000000;
 5197:   border-collapse: separate;
 5198:   border-spacing: 1px;
 5199: }
 5200: 
 5201: table.LC_prior_tries td {
 5202:   padding: 2px;
 5203: }
 5204: 
 5205: .LC_answer_correct {
 5206:   background: #AAFFAA;
 5207:   color: black;
 5208: }
 5209: .LC_answer_charged_try {
 5210:   background: #FFAAAA ! important;
 5211:   color: black;
 5212: }
 5213: .LC_answer_not_charged_try, 
 5214: .LC_answer_no_grade,
 5215: .LC_answer_late {
 5216:   background: #FFFFAA;
 5217:   color: black;
 5218: }
 5219: .LC_answer_previous {
 5220:   background: #AAAAFF;
 5221:   color: black;
 5222: }
 5223: .LC_answer_no_message {
 5224:   background: #FFFFFF;
 5225:   color: black;
 5226: }
 5227: .LC_answer_unknown {
 5228:   background: orange;
 5229:   color: black;
 5230: }
 5231: 
 5232: 
 5233: span.LC_prior_numerical,
 5234: span.LC_prior_string,
 5235: span.LC_prior_custom,
 5236: span.LC_prior_reaction,
 5237: span.LC_prior_math {
 5238:   font-family: monospace;
 5239:   white-space: pre;
 5240: }
 5241: 
 5242: span.LC_prior_string {
 5243:   font-family: monospace;
 5244:   white-space: pre;
 5245: }
 5246: 
 5247: table.LC_prior_option {
 5248:   width: 100%;
 5249:   border-collapse: collapse;
 5250: }
 5251: table.LC_prior_rank, table.LC_prior_match {
 5252:   border-collapse: collapse;
 5253: }
 5254: table.LC_prior_option tr td,
 5255: table.LC_prior_rank tr td,
 5256: table.LC_prior_match tr td {
 5257:   border: 1px solid #000000;
 5258: }
 5259: 
 5260: span.LC_nobreak {
 5261:   white-space: nowrap;
 5262: }
 5263: 
 5264: span.LC_cusr_emph {
 5265:   font-style: italic;
 5266: }
 5267: 
 5268: span.LC_cusr_subheading {
 5269:   font-weight: normal;
 5270:   font-size: 85%;
 5271: }
 5272: 
 5273: table.LC_docs_documents {
 5274:   background: #BBBBBB;
 5275:   border-width: 0px;
 5276:   border-collapse: collapse;
 5277: }
 5278: 
 5279: table.LC_docs_documents td.LC_docs_document {
 5280:   border: 2px solid black;
 5281:   padding: 4px;
 5282: }
 5283: 
 5284: .LC_docs_course_commands div {
 5285:   float: left;
 5286:   border: 4px solid #AAAAAA;
 5287:   padding: 4px;
 5288:   background: #DDDDCC;
 5289: }
 5290: 
 5291: .LC_docs_entry_move {
 5292:   border: 0px;
 5293:   border-collapse: collapse;
 5294: }
 5295: 
 5296: .LC_docs_entry_move td {
 5297:   border: 2px solid #BBBBBB;
 5298:   background: #DDDDDD;
 5299: }
 5300: 
 5301: .LC_docs_editor td.LC_docs_entry_commands {
 5302:   background: #DDDDDD;
 5303:   font-size: x-small;
 5304: }
 5305: .LC_docs_copy {
 5306:   color: #000099;
 5307: }
 5308: .LC_docs_cut {
 5309:   color: #550044;
 5310: }
 5311: .LC_docs_rename {
 5312:   color: #009900;
 5313: }
 5314: .LC_docs_remove {
 5315:   color: #990000;
 5316: }
 5317: 
 5318: .LC_docs_reinit_warn,
 5319: .LC_docs_ext_edit {
 5320:   font-size: x-small;
 5321: }
 5322: 
 5323: .LC_docs_editor td.LC_docs_entry_title,
 5324: .LC_docs_editor td.LC_docs_entry_icon {
 5325:   background: #FFFFBB;
 5326: }
 5327: .LC_docs_editor td.LC_docs_entry_parameter {
 5328:   background: #BBBBFF;
 5329:   font-size: x-small;
 5330:   white-space: nowrap;
 5331: }
 5332: 
 5333: table.LC_docs_adddocs td,
 5334: table.LC_docs_adddocs th {
 5335:   border: 1px solid #BBBBBB;
 5336:   padding: 4px;
 5337:   background: #DDDDDD;
 5338: }
 5339: 
 5340: table.LC_sty_begin {
 5341:   background: #BBFFBB;
 5342: }
 5343: table.LC_sty_end {
 5344:   background: #FFBBBB;
 5345: }
 5346: 
 5347: table.LC_double_column {
 5348:   border-width: 0px;
 5349:   border-collapse: collapse;
 5350:   width: 100%;
 5351:   padding: 2px;
 5352: }
 5353: 
 5354: table.LC_double_column tr td.LC_left_col {
 5355:   top: 2px;
 5356:   left: 2px;
 5357:   width: 47%;
 5358:   vertical-align: top;
 5359: }
 5360: 
 5361: table.LC_double_column tr td.LC_right_col {
 5362:   top: 2px;
 5363:   right: 2px; 
 5364:   width: 47%;
 5365:   vertical-align: top;
 5366: }
 5367: 
 5368: span.LC_role_level {
 5369:   font-weight: bold;
 5370: }
 5371: 
 5372: div.LC_left_float {
 5373:   float: left;
 5374:   padding-right: 5%;
 5375:   padding-bottom: 4px;
 5376: }
 5377: 
 5378: div.LC_clear_float_header {
 5379:   padding-bottom: 2px;
 5380: }
 5381: 
 5382: div.LC_clear_float_footer {
 5383:   padding-top: 10px;
 5384:   clear: both;
 5385: }
 5386: 
 5387: 
 5388: div.LC_grade_select_mode {
 5389:   font-family: $sans;
 5390: }
 5391: div.LC_grade_select_mode div div {
 5392:   margin: 5px;
 5393: }
 5394: div.LC_grade_select_mode_selector {
 5395:   margin: 5px;
 5396:   float: left;
 5397: }
 5398: div.LC_grade_select_mode_selector_header {
 5399:   font: bold medium $sans;
 5400: }
 5401: div.LC_grade_select_mode_type {
 5402:   clear: left;
 5403: }
 5404: 
 5405: div.LC_grade_show_user {
 5406:   margin-top: 20px;
 5407:   border: 1px solid black;
 5408: }
 5409: div.LC_grade_user_name {
 5410:   background: #DDDDEE;
 5411:   border-bottom: 1px solid black;
 5412:   font: bold large $sans;
 5413: }
 5414: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5415:   background: #DDEEDD;
 5416: }
 5417: 
 5418: div.LC_grade_show_problem,
 5419: div.LC_grade_submissions,
 5420: div.LC_grade_message_center,
 5421: div.LC_grade_info_links,
 5422: div.LC_grade_assign {
 5423:   margin: 5px;
 5424:   width: 99%;
 5425:   background: #FFFFFF;
 5426: }
 5427: div.LC_grade_show_problem_header,
 5428: div.LC_grade_submissions_header,
 5429: div.LC_grade_message_center_header,
 5430: div.LC_grade_assign_header {
 5431:   font: bold large $sans;
 5432: }
 5433: div.LC_grade_show_problem_problem,
 5434: div.LC_grade_submissions_body,
 5435: div.LC_grade_message_center_body,
 5436: div.LC_grade_assign_body {
 5437:   border: 1px solid black;
 5438:   width: 99%;
 5439:   background: #FFFFFF;
 5440: }
 5441: span.LC_grade_check_note {
 5442:   font: normal medium $sans;
 5443:   display: inline;
 5444:   position: absolute;
 5445:   right: 1em;
 5446: }
 5447: 
 5448: table.LC_scantron_action {
 5449:   width: 100%;
 5450: }
 5451: table.LC_scantron_action tr th {
 5452:   font: normal bold $sans;
 5453: }
 5454: 
 5455: div.LC_edit_problem_header, 
 5456: div.LC_edit_problem_footer {
 5457:   font: normal medium $sans;
 5458:   margin: 2px;
 5459: }
 5460: div.LC_edit_problem_header,
 5461: div.LC_edit_problem_header div,
 5462: div.LC_edit_problem_footer,
 5463: div.LC_edit_problem_footer div,
 5464: div.LC_edit_problem_editxml_header,
 5465: div.LC_edit_problem_editxml_header div {
 5466:   margin-top: 5px;
 5467: }
 5468: div.LC_edit_problem_header_edit_row {
 5469:   background: $tabbg;
 5470:   padding: 3px;
 5471:   margin-bottom: 5px;
 5472: }
 5473: div.LC_edit_problem_header_title {
 5474:   font: larger bold $sans;
 5475:   background: $tabbg;
 5476:   padding: 3px;
 5477: }
 5478: table.LC_edit_problem_header_title {
 5479:   font: larger bold $sans;
 5480:   width: 100%;
 5481:   border-color: $pgbg;
 5482:   border-style: solid;
 5483:   border-width: $border;
 5484: 
 5485:   background: $tabbg;
 5486:   border-collapse: collapse;
 5487:   padding: 0px
 5488: }
 5489: 
 5490: div.LC_edit_problem_discards {
 5491:   float: left;
 5492:   padding-bottom: 5px;
 5493: }
 5494: div.LC_edit_problem_saves {
 5495:   float: right;
 5496:   padding-bottom: 5px;
 5497: }
 5498: hr.LC_edit_problem_divide {
 5499:   clear: both;
 5500:   color: $tabbg;
 5501:   background-color: $tabbg;
 5502:   height: 3px;
 5503:   border: 0px;
 5504: }
 5505: img.stift{
 5506:   border-width:0;
 5507:   vertical-align:middle;
 5508: }
 5509: 
 5510: table#LC_mainmenu{
 5511:  margin-top:10px;
 5512:  width:80%;
 5513: 
 5514: }
 5515: 
 5516: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5517:   vertical-align: top;
 5518:   width: 45%;
 5519: }
 5520: .LC_mainmenu_fieldset_category {
 5521:   color: $font;
 5522:   background: $pgbg;
 5523:   font-family: $sans;
 5524:   font-size: small;
 5525:   font-weight: bold;
 5526: }
 5527: fieldset#LC_mainmenu_fieldset {
 5528:   margin:0px 10px 10px 0px;
 5529: 
 5530: }
 5531: 
 5532: div.LC_createcourse {
 5533:     margin: 10px 10px 10px 10px;
 5534: }
 5535: 
 5536: END
 5537: }
 5538: 
 5539: =pod
 5540: 
 5541: =item * &headtag()
 5542: 
 5543: Returns a uniform footer for LON-CAPA web pages.
 5544: 
 5545: Inputs: $title - optional title for the head
 5546:         $head_extra - optional extra HTML to put inside the <head>
 5547:         $args - optional arguments
 5548:             force_register - if is true call registerurl so the remote is 
 5549:                              informed
 5550:             redirect       -> array ref of
 5551:                                    1- seconds before redirect occurs
 5552:                                    2- url to redirect to
 5553:                                    3- whether the side effect should occur
 5554:                            (side effect of setting 
 5555:                                $env{'internal.head.redirect'} to the url 
 5556:                                redirected too)
 5557:             domain         -> force to color decorate a page for a specific
 5558:                                domain
 5559:             function       -> force usage of a specific rolish color scheme
 5560:             bgcolor        -> override the default page bgcolor
 5561:             no_auto_mt_title
 5562:                            -> prevent &mt()ing the title arg
 5563: 
 5564: =cut
 5565: 
 5566: sub headtag {
 5567:     my ($title,$head_extra,$args) = @_;
 5568:     
 5569:     my $function = $args->{'function'} || &get_users_function();
 5570:     my $domain   = $args->{'domain'}   || &determinedomain();
 5571:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5572:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5573: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5574: 		   #time(),
 5575: 		   $env{'environment.color.timestamp'},
 5576: 		   $function,$domain,$bgcolor);
 5577: 
 5578:     $url = '/adm/css/'.&escape($url).'.css';
 5579: 
 5580:     my $result =
 5581: 	'<head>'.
 5582: 	&font_settings();
 5583: 
 5584:     if (!$args->{'frameset'}) {
 5585: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5586:     }
 5587:     if ($args->{'force_register'}) {
 5588: 	$result .= &Apache::lonmenu::registerurl(1);
 5589:     }
 5590:     if (!$args->{'no_nav_bar'} 
 5591: 	&& !$args->{'only_body'}
 5592: 	&& !$args->{'frameset'}) {
 5593: 	$result .= &help_menu_js();
 5594:     }
 5595: 
 5596:     if (ref($args->{'redirect'})) {
 5597: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5598: 	$url = &Apache::lonenc::check_encrypt($url);
 5599: 	if (!$inhibit_continue) {
 5600: 	    $env{'internal.head.redirect'} = $url;
 5601: 	}
 5602: 	$result.=<<ADDMETA
 5603: <meta http-equiv="pragma" content="no-cache" />
 5604: <meta http-equiv="Refresh" content="$time; url=$url" />
 5605: ADDMETA
 5606:     }
 5607:     if (!defined($title)) {
 5608: 	$title = 'The LearningOnline Network with CAPA';
 5609:     }
 5610:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5611:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5612: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5613: 	.$head_extra;
 5614:     return $result;
 5615: }
 5616: 
 5617: =pod
 5618: 
 5619: =item * &font_settings()
 5620: 
 5621: Returns neccessary <meta> to set the proper encoding
 5622: 
 5623: Inputs: none
 5624: 
 5625: =cut
 5626: 
 5627: sub font_settings {
 5628:     my $headerstring='';
 5629:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5630: 	$headerstring.=
 5631: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5632:     }
 5633:     return $headerstring;
 5634: }
 5635: 
 5636: =pod
 5637: 
 5638: =item * &xml_begin()
 5639: 
 5640: Returns the needed doctype and <html>
 5641: 
 5642: Inputs: none
 5643: 
 5644: =cut
 5645: 
 5646: sub xml_begin {
 5647:     my $output='';
 5648: 
 5649:     if ($env{'internal.start_page'}==1) {
 5650: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5651:     }
 5652: 
 5653:     if ($env{'browser.mathml'}) {
 5654: 	$output='<?xml version="1.0"?>'
 5655:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5656: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5657:             
 5658: #	    .'<!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">] >'
 5659: 	    .'<!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">'
 5660:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5661: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5662:     } else {
 5663: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 5664:     }
 5665:     return $output;
 5666: }
 5667: 
 5668: =pod
 5669: 
 5670: =item * &endheadtag()
 5671: 
 5672: Returns a uniform </head> for LON-CAPA web pages.
 5673: 
 5674: Inputs: none
 5675: 
 5676: =cut
 5677: 
 5678: sub endheadtag {
 5679:     return '</head>';
 5680: }
 5681: 
 5682: =pod
 5683: 
 5684: =item * &head()
 5685: 
 5686: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5687: 
 5688: Inputs:
 5689: 
 5690: =over 4
 5691: 
 5692: $title - optional title for the page
 5693: 
 5694: $head_extra - optional extra HTML to put inside the <head>
 5695: 
 5696: =back
 5697: 
 5698: =cut
 5699: 
 5700: sub head {
 5701:     my ($title,$head_extra,$args) = @_;
 5702:     return &headtag($title,$head_extra,$args).&endheadtag();
 5703: }
 5704: 
 5705: =pod
 5706: 
 5707: =item * &start_page()
 5708: 
 5709: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5710: 
 5711: Inputs:
 5712: 
 5713: =over 4
 5714: 
 5715: $title - optional title for the page
 5716: 
 5717: $head_extra - optional extra HTML to incude inside the <head>
 5718: 
 5719: $args - additional optional args supported are:
 5720: 
 5721: =over 8
 5722: 
 5723:              only_body      -> is true will set &bodytag() onlybodytag
 5724:                                     arg on
 5725:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5726:              add_entries    -> additional attributes to add to the  <body>
 5727:              domain         -> force to color decorate a page for a 
 5728:                                     specific domain
 5729:              function       -> force usage of a specific rolish color
 5730:                                     scheme
 5731:              redirect       -> see &headtag()
 5732:              bgcolor        -> override the default page bg color
 5733:              js_ready       -> return a string ready for being used in 
 5734:                                     a javascript writeln
 5735:              html_encode    -> return a string ready for being used in 
 5736:                                     a html attribute
 5737:              force_register -> if is true will turn on the &bodytag()
 5738:                                     $forcereg arg
 5739:              body_title     -> alternate text to use instead of $title
 5740:                                     in the title box that appears, this text
 5741:                                     is not auto translated like the $title is
 5742:              frameset       -> if true will start with a <frameset>
 5743:                                     rather than <body>
 5744:              no_title       -> if true the title bar won't be shown
 5745:              skip_phases    -> hash ref of 
 5746:                                     head -> skip the <html><head> generation
 5747:                                     body -> skip all <body> generation
 5748:              no_inline_link -> if true and in remote mode, don't show the 
 5749:                                     'Switch To Inline Menu' link
 5750:              no_auto_mt_title -> prevent &mt()ing the title arg
 5751:              inherit_jsmath -> when creating popup window in a page,
 5752:                                     should it have jsmath forced on by the
 5753:                                     current page
 5754: 
 5755: =back
 5756: 
 5757: =back
 5758: 
 5759: =cut
 5760: 
 5761: sub start_page {
 5762:     my ($title,$head_extra,$args) = @_;
 5763:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5764:     my %head_args;
 5765:     foreach my $arg ('redirect','force_register','domain','function',
 5766: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5767: 		     'no_auto_mt_title') {
 5768: 	if (defined($args->{$arg})) {
 5769: 	    $head_args{$arg} = $args->{$arg};
 5770: 	}
 5771:     }
 5772: 
 5773:     $env{'internal.start_page'}++;
 5774:     my $result;
 5775:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 5776: 	$result.=
 5777: 	    &xml_begin().
 5778: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 5779:     }
 5780:     
 5781:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 5782: 	if ($args->{'frameset'}) {
 5783: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 5784: 						$args->{'add_entries'});
 5785: 	    $result .= "\n<frameset $attr_string>\n";
 5786: 	} else {
 5787: 	    $result .=
 5788: 		&bodytag($title, 
 5789: 			 $args->{'function'},       $args->{'add_entries'},
 5790: 			 $args->{'only_body'},      $args->{'domain'},
 5791: 			 $args->{'force_register'}, $args->{'body_title'},
 5792: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 5793: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 5794: 			 $args);
 5795: 	}
 5796:     }
 5797: 
 5798:     if ($args->{'js_ready'}) {
 5799: 	$result = &js_ready($result);
 5800:     }
 5801:     if ($args->{'html_encode'}) {
 5802: 	$result = &html_encode($result);
 5803:     }
 5804:     return $result;
 5805: }
 5806: 
 5807: 
 5808: =pod
 5809: 
 5810: =item * &head()
 5811: 
 5812: Returns a complete </body></html> section for LON-CAPA web pages.
 5813: 
 5814: Inputs:         $args - additional optional args supported are:
 5815:                  js_ready     -> return a string ready for being used in 
 5816:                                  a javascript writeln
 5817:                  html_encode  -> return a string ready for being used in 
 5818:                                  a html attribute
 5819:                  frameset     -> if true will start with a <frameset>
 5820:                                  rather than <body>
 5821:                  dicsussion   -> if true will get discussion from
 5822:                                   lonxml::xmlend
 5823:                                  (you can pass the target and parser arguments
 5824:                                   through optional 'target' and 'parser' args
 5825:                                   to this routine)
 5826: 
 5827: =cut
 5828: 
 5829: sub end_page {
 5830:     my ($args) = @_;
 5831:     $env{'internal.end_page'}++;
 5832:     my $result;
 5833:     if ($args->{'discussion'}) {
 5834: 	my ($target,$parser);
 5835: 	if (ref($args->{'discussion'})) {
 5836: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 5837: 				$args->{'discussion'}{'parser'});
 5838: 	}
 5839: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 5840:     }
 5841: 
 5842:     if ($args->{'frameset'}) {
 5843: 	$result .= '</frameset>';
 5844:     } else {
 5845: 	$result .= &endbodytag($args);
 5846:     }
 5847:     $result .= "\n</html>";
 5848: 
 5849:     if ($args->{'js_ready'}) {
 5850: 	$result = &js_ready($result);
 5851:     }
 5852: 
 5853:     if ($args->{'html_encode'}) {
 5854: 	$result = &html_encode($result);
 5855:     }
 5856: 
 5857:     return $result;
 5858: }
 5859: 
 5860: sub html_encode {
 5861:     my ($result) = @_;
 5862: 
 5863:     $result = &HTML::Entities::encode($result,'<>&"');
 5864:     
 5865:     return $result;
 5866: }
 5867: sub js_ready {
 5868:     my ($result) = @_;
 5869: 
 5870:     $result =~ s/[\n\r]/ /xmsg;
 5871:     $result =~ s/\\/\\\\/xmsg;
 5872:     $result =~ s/'/\\'/xmsg;
 5873:     $result =~ s{</}{<\\/}xmsg;
 5874:     
 5875:     return $result;
 5876: }
 5877: 
 5878: sub validate_page {
 5879:     if (  exists($env{'internal.start_page'})
 5880: 	  &&     $env{'internal.start_page'} > 1) {
 5881: 	&Apache::lonnet::logthis('start_page called multiple times '.
 5882: 				 $env{'internal.start_page'}.' '.
 5883: 				 $ENV{'request.filename'});
 5884:     }
 5885:     if (  exists($env{'internal.end_page'})
 5886: 	  &&     $env{'internal.end_page'} > 1) {
 5887: 	&Apache::lonnet::logthis('end_page called multiple times '.
 5888: 				 $env{'internal.end_page'}.' '.
 5889: 				 $env{'request.filename'});
 5890:     }
 5891:     if (     exists($env{'internal.start_page'})
 5892: 	&& ! exists($env{'internal.end_page'})) {
 5893: 	&Apache::lonnet::logthis('start_page called without end_page '.
 5894: 				 $env{'request.filename'});
 5895:     }
 5896:     if (   ! exists($env{'internal.start_page'})
 5897: 	&&   exists($env{'internal.end_page'})) {
 5898: 	&Apache::lonnet::logthis('end_page called without start_page'.
 5899: 				 $env{'request.filename'});
 5900:     }
 5901: }
 5902: 
 5903: sub simple_error_page {
 5904:     my ($r,$title,$msg) = @_;
 5905:     my $page =
 5906: 	&Apache::loncommon::start_page($title).
 5907: 	&mt($msg).
 5908: 	&Apache::loncommon::end_page();
 5909:     if (ref($r)) {
 5910: 	$r->print($page);
 5911: 	return;
 5912:     }
 5913:     return $page;
 5914: }
 5915: 
 5916: {
 5917:     my @row_count;
 5918:     sub start_data_table {
 5919: 	my ($add_class) = @_;
 5920: 	my $css_class = (join(' ','LC_data_table',$add_class));
 5921: 	unshift(@row_count,0);
 5922: 	return '<table class="'.$css_class.'">'."\n";
 5923:     }
 5924: 
 5925:     sub end_data_table {
 5926: 	shift(@row_count);
 5927: 	return '</table>'."\n";;
 5928:     }
 5929: 
 5930:     sub start_data_table_row {
 5931: 	my ($add_class) = @_;
 5932: 	$row_count[0]++;
 5933: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5934: 	$css_class = (join(' ',$css_class,$add_class));
 5935: 	return  '<tr class="'.$css_class.'">'."\n";;
 5936:     }
 5937:     
 5938:     sub continue_data_table_row {
 5939: 	my ($add_class) = @_;
 5940: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 5941: 	$css_class = (join(' ',$css_class,$add_class));
 5942: 	return  '<tr class="'.$css_class.'">'."\n";;
 5943:     }
 5944: 
 5945:     sub end_data_table_row {
 5946: 	return '</tr>'."\n";;
 5947:     }
 5948: 
 5949:     sub start_data_table_empty_row {
 5950: 	$row_count[0]++;
 5951: 	return  '<tr class="LC_empty_row" >'."\n";;
 5952:     }
 5953: 
 5954:     sub end_data_table_empty_row {
 5955: 	return '</tr>'."\n";;
 5956:     }
 5957: 
 5958:     sub start_data_table_header_row {
 5959: 	return  '<tr class="LC_header_row">'."\n";;
 5960:     }
 5961: 
 5962:     sub end_data_table_header_row {
 5963: 	return '</tr>'."\n";;
 5964:     }
 5965: }
 5966: 
 5967: =pod
 5968: 
 5969: =item * &inhibit_menu_check($arg)
 5970: 
 5971: Checks for a inhibitmenu state and generates output to preserve it
 5972: 
 5973: Inputs:         $arg - can be any of
 5974:                      - undef - in which case the return value is a string 
 5975:                                to add  into arguments list of a uri
 5976:                      - 'input' - in which case the return value is a HTML
 5977:                                  <form> <input> field of type hidden to
 5978:                                  preserve the value
 5979:                      - a url - in which case the return value is the url with
 5980:                                the neccesary cgi args added to preserve the
 5981:                                inhibitmenu state
 5982:                      - a ref to a url - no return value, but the string is
 5983:                                         updated to include the neccessary cgi
 5984:                                         args to preserve the inhibitmenu state
 5985: 
 5986: =cut
 5987: 
 5988: sub inhibit_menu_check {
 5989:     my ($arg) = @_;
 5990:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5991:     if ($arg eq 'input') {
 5992: 	if ($env{'form.inhibitmenu'}) {
 5993: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 5994: 	} else {
 5995: 	    return
 5996: 	}
 5997:     }
 5998:     if ($env{'form.inhibitmenu'}) {
 5999: 	if (ref($arg)) {
 6000: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6001: 	} elsif ($arg eq '') {
 6002: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6003: 	} else {
 6004: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6005: 	}
 6006:     }
 6007:     if (!ref($arg)) {
 6008: 	return $arg;
 6009:     }
 6010: }
 6011: 
 6012: ###############################################
 6013: 
 6014: =pod
 6015: 
 6016: =back
 6017: 
 6018: =head1 User Information Routines
 6019: 
 6020: =over 4
 6021: 
 6022: =item * &get_users_function()
 6023: 
 6024: Used by &bodytag to determine the current users primary role.
 6025: Returns either 'student','coordinator','admin', or 'author'.
 6026: 
 6027: =cut
 6028: 
 6029: ###############################################
 6030: sub get_users_function {
 6031:     my $function = 'student';
 6032:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6033:         $function='coordinator';
 6034:     }
 6035:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6036:         $function='admin';
 6037:     }
 6038:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6039:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6040:         $function='author';
 6041:     }
 6042:     return $function;
 6043: }
 6044: 
 6045: ###############################################
 6046: 
 6047: =pod
 6048: 
 6049: =item * &check_user_status()
 6050: 
 6051: Determines current status of supplied role for a
 6052: specific user. Roles can be active, previous or future.
 6053: 
 6054: Inputs: 
 6055: user's domain, user's username, course's domain,
 6056: course's number, optional section ID.
 6057: 
 6058: Outputs:
 6059: role status: active, previous or future. 
 6060: 
 6061: =cut
 6062: 
 6063: sub check_user_status {
 6064:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6065:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6066:     my @uroles = keys %userinfo;
 6067:     my $srchstr;
 6068:     my $active_chk = 'none';
 6069:     my $now = time;
 6070:     if (@uroles > 0) {
 6071:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6072:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6073:         } else {
 6074:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6075:         }
 6076:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6077:             my $role_end = 0;
 6078:             my $role_start = 0;
 6079:             $active_chk = 'active';
 6080:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6081:                 $role_end = $1;
 6082:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6083:                     $role_start = $1;
 6084:                 }
 6085:             }
 6086:             if ($role_start > 0) {
 6087:                 if ($now < $role_start) {
 6088:                     $active_chk = 'future';
 6089:                 }
 6090:             }
 6091:             if ($role_end > 0) {
 6092:                 if ($now > $role_end) {
 6093:                     $active_chk = 'previous';
 6094:                 }
 6095:             }
 6096:         }
 6097:     }
 6098:     return $active_chk;
 6099: }
 6100: 
 6101: ###############################################
 6102: 
 6103: =pod
 6104: 
 6105: =item * &get_sections()
 6106: 
 6107: Determines all the sections for a course including
 6108: sections with students and sections containing other roles.
 6109: Incoming parameters: 
 6110: 
 6111: 1. domain
 6112: 2. course number 
 6113: 3. reference to array containing roles for which sections should 
 6114: be gathered (optional).
 6115: 4. reference to array containing status types for which sections 
 6116: should be gathered (optional).
 6117: 
 6118: If the third argument is undefined, sections are gathered for any role. 
 6119: If the fourth argument is undefined, sections are gathered for any status.
 6120: Permissible values are 'active' or 'future' or 'previous'.
 6121:  
 6122: Returns section hash (keys are section IDs, values are
 6123: number of users in each section), subject to the
 6124: optional roles filter, optional status filter 
 6125: 
 6126: =cut
 6127: 
 6128: ###############################################
 6129: sub get_sections {
 6130:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6131:     if (!defined($cdom) || !defined($cnum)) {
 6132:         my $cid =  $env{'request.course.id'};
 6133: 
 6134: 	return if (!defined($cid));
 6135: 
 6136:         $cdom = $env{'course.'.$cid.'.domain'};
 6137:         $cnum = $env{'course.'.$cid.'.num'};
 6138:     }
 6139: 
 6140:     my %sectioncount;
 6141:     my $now = time;
 6142: 
 6143:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6144: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6145: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6146: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6147:         my $start_index = &Apache::loncoursedata::CL_START();
 6148:         my $end_index = &Apache::loncoursedata::CL_END();
 6149:         my $status;
 6150: 	while (my ($student,$data) = each(%$classlist)) {
 6151: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6152: 				                     $data->[$status_index],
 6153:                                                      $data->[$start_index],
 6154:                                                      $data->[$end_index]);
 6155:             if ($stu_status eq 'Active') {
 6156:                 $status = 'active';
 6157:             } elsif ($end < $now) {
 6158:                 $status = 'previous';
 6159:             } elsif ($start > $now) {
 6160:                 $status = 'future';
 6161:             } 
 6162: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6163:                 if ((!defined($possible_status)) || (($status ne '') && 
 6164:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6165: 		    $sectioncount{$section}++;
 6166:                 }
 6167: 	    }
 6168: 	}
 6169:     }
 6170:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6171:     foreach my $user (sort(keys(%courseroles))) {
 6172: 	if ($user !~ /^(\w{2})/) { next; }
 6173: 	my ($role) = ($user =~ /^(\w{2})/);
 6174: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6175: 	my ($section,$status);
 6176: 	if ($role eq 'cr' &&
 6177: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6178: 	    $section=$1;
 6179: 	}
 6180: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6181: 	if (!defined($section) || $section eq '-1') { next; }
 6182:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6183:         if ($end == -1 && $start == -1) {
 6184:             next; #deleted role
 6185:         }
 6186:         if (!defined($possible_status)) { 
 6187:             $sectioncount{$section}++;
 6188:         } else {
 6189:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6190:                 $status = 'active';
 6191:             } elsif ($end < $now) {
 6192:                 $status = 'future';
 6193:             } elsif ($start > $now) {
 6194:                 $status = 'previous';
 6195:             }
 6196:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6197:                 $sectioncount{$section}++;
 6198:             }
 6199:         }
 6200:     }
 6201:     return %sectioncount;
 6202: }
 6203: 
 6204: ###############################################
 6205: 
 6206: =pod
 6207: 
 6208: =item * &get_course_users()
 6209: 
 6210: Retrieves usernames:domains for users in the specified course
 6211: with specific role(s), and access status. 
 6212: 
 6213: Incoming parameters:
 6214: 1. course domain
 6215: 2. course number
 6216: 3. access status: users must have - either active, 
 6217: previous, future, or all.
 6218: 4. reference to array of permissible roles
 6219: 5. reference to array of section restrictions (optional)
 6220: 6. reference to results object (hash of hashes).
 6221: 7. reference to optional userdata hash
 6222: 8. reference to optional statushash
 6223: 9. flag if privileged users (except those set to unhide in
 6224:    course settings) should be excluded    
 6225: Keys of top level results hash are roles.
 6226: Keys of inner hashes are username:domain, with 
 6227: values set to access type.
 6228: Optional userdata hash returns an array with arguments in the 
 6229: same order as loncoursedata::get_classlist() for student data.
 6230: 
 6231: Optional statushash returns
 6232: 
 6233: Entries for end, start, section and status are blank because
 6234: of the possibility of multiple values for non-student roles.
 6235: 
 6236: =cut
 6237: 
 6238: ###############################################
 6239: 
 6240: sub get_course_users {
 6241:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6242:     my %idx = ();
 6243:     my %seclists;
 6244: 
 6245:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6246:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6247:     $idx{end} = &Apache::loncoursedata::CL_END();
 6248:     $idx{start} = &Apache::loncoursedata::CL_START();
 6249:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6250:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6251:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6252:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6253: 
 6254:     if (grep(/^st$/,@{$roles})) {
 6255:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6256:         my $now = time;
 6257:         foreach my $student (keys(%{$classlist})) {
 6258:             my $match = 0;
 6259:             my $secmatch = 0;
 6260:             my $section = $$classlist{$student}[$idx{section}];
 6261:             my $status = $$classlist{$student}[$idx{status}];
 6262:             if ($section eq '') {
 6263:                 $section = 'none';
 6264:             }
 6265:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6266:                 if (grep(/^all$/,@{$sections})) {
 6267:                     $secmatch = 1;
 6268:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6269:                     if (grep(/^none$/,@{$sections})) {
 6270:                         $secmatch = 1;
 6271:                     }
 6272:                 } else {  
 6273: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6274: 		        $secmatch = 1;
 6275:                     }
 6276: 		}
 6277:                 if (!$secmatch) {
 6278:                     next;
 6279:                 }
 6280:             }
 6281:             if (defined($$types{'active'})) {
 6282:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6283:                     push(@{$$users{st}{$student}},'active');
 6284:                     $match = 1;
 6285:                 }
 6286:             }
 6287:             if (defined($$types{'previous'})) {
 6288:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6289:                     push(@{$$users{st}{$student}},'previous');
 6290:                     $match = 1;
 6291:                 }
 6292:             }
 6293:             if (defined($$types{'future'})) {
 6294:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6295:                     push(@{$$users{st}{$student}},'future');
 6296:                     $match = 1;
 6297:                 }
 6298:             }
 6299:             if ($match) {
 6300:                 push(@{$seclists{$student}},$section);
 6301:                 if (ref($userdata) eq 'HASH') {
 6302:                     $$userdata{$student} = $$classlist{$student};
 6303:                 }
 6304:                 if (ref($statushash) eq 'HASH') {
 6305:                     $statushash->{$student}{'st'}{$section} = $status;
 6306:                 }
 6307:             }
 6308:         }
 6309:     }
 6310:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6311:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6312:         my $now = time;
 6313:         my %displaystatus = ( previous => 'Expired',
 6314:                               active   => 'Active',
 6315:                               future   => 'Future',
 6316:                             );
 6317:         my %nothide;
 6318:         if ($hidepriv) {
 6319:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6320:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6321:                 if ($user !~ /:/) {
 6322:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6323:                 } else {
 6324:                     $nothide{$user} = 1;
 6325:                 }
 6326:             }
 6327:         }
 6328:         foreach my $person (sort(keys(%coursepersonnel))) {
 6329:             my $match = 0;
 6330:             my $secmatch = 0;
 6331:             my $status;
 6332:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6333:             $user =~ s/:$//;
 6334:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6335:             if ($end == -1 || $start == -1) {
 6336:                 next;
 6337:             }
 6338:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6339:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6340:                 my ($uname,$udom) = split(/:/,$user);
 6341:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6342:                     if (grep(/^all$/,@{$sections})) {
 6343:                         $secmatch = 1;
 6344:                     } elsif ($usec eq '') {
 6345:                         if (grep(/^none$/,@{$sections})) {
 6346:                             $secmatch = 1;
 6347:                         }
 6348:                     } else {
 6349:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6350:                             $secmatch = 1;
 6351:                         }
 6352:                     }
 6353:                     if (!$secmatch) {
 6354:                         next;
 6355:                     }
 6356:                 }
 6357:                 if ($usec eq '') {
 6358:                     $usec = 'none';
 6359:                 }
 6360:                 if ($uname ne '' && $udom ne '') {
 6361:                     if ($hidepriv) {
 6362:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6363:                             (!$nothide{$uname.':'.$udom})) {
 6364:                             next;
 6365:                         }
 6366:                     }
 6367:                     if ($end > 0 && $end < $now) {
 6368:                         $status = 'previous';
 6369:                     } elsif ($start > $now) {
 6370:                         $status = 'future';
 6371:                     } else {
 6372:                         $status = 'active';
 6373:                     }
 6374:                     foreach my $type (keys(%{$types})) { 
 6375:                         if ($status eq $type) {
 6376:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6377:                                 push(@{$$users{$role}{$user}},$type);
 6378:                             }
 6379:                             $match = 1;
 6380:                         }
 6381:                     }
 6382:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6383:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6384: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6385:                         }
 6386:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6387:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6388:                         }
 6389:                         if (ref($statushash) eq 'HASH') {
 6390:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6391:                         }
 6392:                     }
 6393:                 }
 6394:             }
 6395:         }
 6396:         if (grep(/^ow$/,@{$roles})) {
 6397:             if ((defined($cdom)) && (defined($cnum))) {
 6398:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6399:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6400:                     my $owner = $csettings{'internal.courseowner'};
 6401:                     next if ($owner eq '');
 6402:                     my ($ownername,$ownerdom);
 6403:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6404:                         $ownername = $1;
 6405:                         $ownerdom = $2;
 6406:                     } else {
 6407:                         $ownername = $owner;
 6408:                         $ownerdom = $cdom;
 6409:                         $owner = $ownername.':'.$ownerdom;
 6410:                     }
 6411:                     @{$$users{'ow'}{$owner}} = 'any';
 6412:                     if (defined($userdata) && 
 6413: 			!exists($$userdata{$owner})) {
 6414: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6415:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6416:                             push(@{$seclists{$owner}},'none');
 6417:                         }
 6418:                         if (ref($statushash) eq 'HASH') {
 6419:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6420:                         }
 6421: 		    }
 6422:                 }
 6423:             }
 6424:         }
 6425:         foreach my $user (keys(%seclists)) {
 6426:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6427:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6428:         }
 6429:     }
 6430:     return;
 6431: }
 6432: 
 6433: sub get_user_info {
 6434:     my ($udom,$uname,$idx,$userdata) = @_;
 6435:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6436: 	&plainname($uname,$udom,'lastname');
 6437:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6438:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6439:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6440:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6441:     return;
 6442: }
 6443: 
 6444: ###############################################
 6445: 
 6446: =pod
 6447: 
 6448: =item * &get_user_quota()
 6449: 
 6450: Retrieves quota assigned for storage of portfolio files for a user  
 6451: 
 6452: Incoming parameters:
 6453: 1. user's username
 6454: 2. user's domain
 6455: 
 6456: Returns:
 6457: 1. Disk quota (in Mb) assigned to student.
 6458: 2. (Optional) Type of setting: custom or default
 6459:    (individually assigned or default for user's 
 6460:    institutional status).
 6461: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6462:    or student - types as defined in localenroll::inst_usertypes 
 6463:    for user's domain, which determines default quota for user.
 6464: 4. (Optional) - Default quota which would apply to the user.
 6465: 
 6466: If a value has been stored in the user's environment, 
 6467: it will return that, otherwise it returns the maximal default
 6468: defined for the user's instituional status(es) in the domain.
 6469: 
 6470: =cut
 6471: 
 6472: ###############################################
 6473: 
 6474: 
 6475: sub get_user_quota {
 6476:     my ($uname,$udom) = @_;
 6477:     my ($quota,$quotatype,$settingstatus,$defquota);
 6478:     if (!defined($udom)) {
 6479:         $udom = $env{'user.domain'};
 6480:     }
 6481:     if (!defined($uname)) {
 6482:         $uname = $env{'user.name'};
 6483:     }
 6484:     if (($udom eq '' || $uname eq '') ||
 6485:         ($udom eq 'public') && ($uname eq 'public')) {
 6486:         $quota = 0;
 6487:         $quotatype = 'default';
 6488:         $defquota = 0; 
 6489:     } else {
 6490:         my $inststatus;
 6491:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6492:             $quota = $env{'environment.portfolioquota'};
 6493:             $inststatus = $env{'environment.inststatus'};
 6494:         } else {
 6495:             my %userenv = 
 6496:                 &Apache::lonnet::get('environment',['portfolioquota',
 6497:                                      'inststatus'],$udom,$uname);
 6498:             my ($tmp) = keys(%userenv);
 6499:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6500:                 $quota = $userenv{'portfolioquota'};
 6501:                 $inststatus = $userenv{'inststatus'};
 6502:             } else {
 6503:                 undef(%userenv);
 6504:             }
 6505:         }
 6506:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6507:         if ($quota eq '') {
 6508:             $quota = $defquota;
 6509:             $quotatype = 'default';
 6510:         } else {
 6511:             $quotatype = 'custom';
 6512:         }
 6513:     }
 6514:     if (wantarray) {
 6515:         return ($quota,$quotatype,$settingstatus,$defquota);
 6516:     } else {
 6517:         return $quota;
 6518:     }
 6519: }
 6520: 
 6521: ###############################################
 6522: 
 6523: =pod
 6524: 
 6525: =item * &default_quota()
 6526: 
 6527: Retrieves default quota assigned for storage of user portfolio files,
 6528: given an (optional) user's institutional status.
 6529: 
 6530: Incoming parameters:
 6531: 1. domain
 6532: 2. (Optional) institutional status(es).  This is a : separated list of 
 6533:    status types (e.g., faculty, staff, student etc.)
 6534:    which apply to the user for whom the default is being retrieved.
 6535:    If the institutional status string in undefined, the domain
 6536:    default quota will be returned. 
 6537: 
 6538: Returns:
 6539: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6540: 2. (Optional) institutional type which determined the value of the
 6541:    default quota.
 6542: 
 6543: If a value has been stored in the domain's configuration db,
 6544: it will return that, otherwise it returns 20 (for backwards 
 6545: compatibility with domains which have not set up a configuration
 6546: db file; the original statically defined portfolio quota was 20 Mb). 
 6547: 
 6548: If the user's status includes multiple types (e.g., staff and student),
 6549: the largest default quota which applies to the user determines the
 6550: default quota returned.
 6551: 
 6552: =cut
 6553: 
 6554: ###############################################
 6555: 
 6556: 
 6557: sub default_quota {
 6558:     my ($udom,$inststatus) = @_;
 6559:     my ($defquota,$settingstatus);
 6560:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6561:                                             ['quotas'],$udom);
 6562:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6563:         if ($inststatus ne '') {
 6564:             my @statuses = split(/:/,$inststatus);
 6565:             foreach my $item (@statuses) {
 6566:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6567:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 6568:                         if ($defquota eq '') {
 6569:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6570:                             $settingstatus = $item;
 6571:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 6572:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6573:                             $settingstatus = $item;
 6574:                         }
 6575:                     }
 6576:                 } else {
 6577:                     if ($quotahash{'quotas'}{$item} ne '') {
 6578:                         if ($defquota eq '') {
 6579:                             $defquota = $quotahash{'quotas'}{$item};
 6580:                             $settingstatus = $item;
 6581:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6582:                             $defquota = $quotahash{'quotas'}{$item};
 6583:                             $settingstatus = $item;
 6584:                         }
 6585:                     }
 6586:                 }
 6587:             }
 6588:         }
 6589:         if ($defquota eq '') {
 6590:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6591:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 6592:             } else {
 6593:                 $defquota = $quotahash{'quotas'}{'default'};
 6594:             }
 6595:             $settingstatus = 'default';
 6596:         }
 6597:     } else {
 6598:         $settingstatus = 'default';
 6599:         $defquota = 20;
 6600:     }
 6601:     if (wantarray) {
 6602:         return ($defquota,$settingstatus);
 6603:     } else {
 6604:         return $defquota;
 6605:     }
 6606: }
 6607: 
 6608: sub get_secgrprole_info {
 6609:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6610:     my %sections_count = &get_sections($cdom,$cnum);
 6611:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6612:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6613:     my @groups = sort(keys(%curr_groups));
 6614:     my $allroles = [];
 6615:     my $rolehash;
 6616:     my $accesshash = {
 6617:                      active => 'Currently has access',
 6618:                      future => 'Will have future access',
 6619:                      previous => 'Previously had access',
 6620:                   };
 6621:     if ($needroles) {
 6622:         $rolehash = {'all' => 'all'};
 6623:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6624: 	if (&Apache::lonnet::error(%user_roles)) {
 6625: 	    undef(%user_roles);
 6626: 	}
 6627:         foreach my $item (keys(%user_roles)) {
 6628:             my ($role)=split(/\:/,$item,2);
 6629:             if ($role eq 'cr') { next; }
 6630:             if ($role =~ /^cr/) {
 6631:                 $$rolehash{$role} = (split('/',$role))[3];
 6632:             } else {
 6633:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6634:             }
 6635:         }
 6636:         foreach my $key (sort(keys(%{$rolehash}))) {
 6637:             push(@{$allroles},$key);
 6638:         }
 6639:         push (@{$allroles},'st');
 6640:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6641:     }
 6642:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6643: }
 6644: 
 6645: sub user_picker {
 6646:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6647:     my $currdom = $dom;
 6648:     my %curr_selected = (
 6649:                         srchin => 'dom',
 6650:                         srchby => 'lastname',
 6651:                       );
 6652:     my $srchterm;
 6653:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6654:         if ($srch->{'srchby'} ne '') {
 6655:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6656:         }
 6657:         if ($srch->{'srchin'} ne '') {
 6658:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6659:         }
 6660:         if ($srch->{'srchtype'} ne '') {
 6661:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6662:         }
 6663:         if ($srch->{'srchdomain'} ne '') {
 6664:             $currdom = $srch->{'srchdomain'};
 6665:         }
 6666:         $srchterm = $srch->{'srchterm'};
 6667:     }
 6668:     my %lt=&Apache::lonlocal::texthash(
 6669:                     'usr'       => 'Search criteria',
 6670:                     'doma'      => 'Domain/institution to search',
 6671:                     'uname'     => 'username',
 6672:                     'lastname'  => 'last name',
 6673:                     'lastfirst' => 'last name, first name',
 6674:                     'crs'       => 'in this course',
 6675:                     'dom'       => 'in selected LON-CAPA domain', 
 6676:                     'alc'       => 'all LON-CAPA',
 6677:                     'instd'     => 'in institutional directory for selected domain',
 6678:                     'exact'     => 'is',
 6679:                     'contains'  => 'contains',
 6680:                     'begins'    => 'begins with',
 6681:                     'youm'      => "You must include some text to search for.",
 6682:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6683:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6684:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6685:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6686:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6687:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6688:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6689:                                        );
 6690:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6691:     my $srchinsel = ' <select name="srchin">';
 6692: 
 6693:     my @srchins = ('crs','dom','alc','instd');
 6694: 
 6695:     foreach my $option (@srchins) {
 6696:         # FIXME 'alc' option unavailable until 
 6697:         #       loncreateuser::print_user_query_page()
 6698:         #       has been completed.
 6699:         next if ($option eq 'alc');
 6700:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6701:         if ($curr_selected{'srchin'} eq $option) {
 6702:             $srchinsel .= ' 
 6703:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6704:         } else {
 6705:             $srchinsel .= '
 6706:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6707:         }
 6708:     }
 6709:     $srchinsel .= "\n  </select>\n";
 6710: 
 6711:     my $srchbysel =  ' <select name="srchby">';
 6712:     foreach my $option ('lastname','lastfirst','uname') {
 6713:         if ($curr_selected{'srchby'} eq $option) {
 6714:             $srchbysel .= '
 6715:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6716:         } else {
 6717:             $srchbysel .= '
 6718:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6719:          }
 6720:     }
 6721:     $srchbysel .= "\n  </select>\n";
 6722: 
 6723:     my $srchtypesel = ' <select name="srchtype">';
 6724:     foreach my $option ('begins','contains','exact') {
 6725:         if ($curr_selected{'srchtype'} eq $option) {
 6726:             $srchtypesel .= '
 6727:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6728:         } else {
 6729:             $srchtypesel .= '
 6730:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6731:         }
 6732:     }
 6733:     $srchtypesel .= "\n  </select>\n";
 6734: 
 6735:     my ($newuserscript,$new_user_create);
 6736: 
 6737:     if ($forcenewuser) {
 6738:         if (ref($srch) eq 'HASH') {
 6739:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 6740:                 if ($cancreate) {
 6741:                     $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>';
 6742:                 } else {
 6743:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 6744:                     my %usertypetext = (
 6745:                         official   => 'institutional',
 6746:                         unofficial => 'non-institutional',
 6747:                     );
 6748:                     $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 />';
 6749:                 }
 6750:             }
 6751:         }
 6752: 
 6753:         $newuserscript = <<"ENDSCRIPT";
 6754: 
 6755: function setSearch(createnew,callingForm) {
 6756:     if (createnew == 1) {
 6757:         for (var i=0; i<callingForm.srchby.length; i++) {
 6758:             if (callingForm.srchby.options[i].value == 'uname') {
 6759:                 callingForm.srchby.selectedIndex = i;
 6760:             }
 6761:         }
 6762:         for (var i=0; i<callingForm.srchin.length; i++) {
 6763:             if ( callingForm.srchin.options[i].value == 'dom') {
 6764: 		callingForm.srchin.selectedIndex = i;
 6765:             }
 6766:         }
 6767:         for (var i=0; i<callingForm.srchtype.length; i++) {
 6768:             if (callingForm.srchtype.options[i].value == 'exact') {
 6769:                 callingForm.srchtype.selectedIndex = i;
 6770:             }
 6771:         }
 6772:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 6773:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 6774:                 callingForm.srchdomain.selectedIndex = i;
 6775:             }
 6776:         }
 6777:     }
 6778: }
 6779: ENDSCRIPT
 6780: 
 6781:     }
 6782: 
 6783:     my $output = <<"END_BLOCK";
 6784: <script type="text/javascript">
 6785: function validateEntry(callingForm) {
 6786: 
 6787:     var checkok = 1;
 6788:     var srchin;
 6789:     for (var i=0; i<callingForm.srchin.length; i++) {
 6790: 	if ( callingForm.srchin[i].checked ) {
 6791: 	    srchin = callingForm.srchin[i].value;
 6792: 	}
 6793:     }
 6794: 
 6795:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 6796:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 6797:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 6798:     var srchterm =  callingForm.srchterm.value;
 6799:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 6800:     var msg = "";
 6801: 
 6802:     if (srchterm == "") {
 6803:         checkok = 0;
 6804:         msg += "$lt{'youm'}\\n";
 6805:     }
 6806: 
 6807:     if (srchtype== 'begins') {
 6808:         if (srchterm.length < 2) {
 6809:             checkok = 0;
 6810:             msg += "$lt{'thte'}\\n";
 6811:         }
 6812:     }
 6813: 
 6814:     if (srchtype== 'contains') {
 6815:         if (srchterm.length < 3) {
 6816:             checkok = 0;
 6817:             msg += "$lt{'thet'}\\n";
 6818:         }
 6819:     }
 6820:     if (srchin == 'instd') {
 6821:         if (srchdomain == '') {
 6822:             checkok = 0;
 6823:             msg += "$lt{'yomc'}\\n";
 6824:         }
 6825:     }
 6826:     if (srchin == 'dom') {
 6827:         if (srchdomain == '') {
 6828:             checkok = 0;
 6829:             msg += "$lt{'ymcd'}\\n";
 6830:         }
 6831:     }
 6832:     if (srchby == 'lastfirst') {
 6833:         if (srchterm.indexOf(",") == -1) {
 6834:             checkok = 0;
 6835:             msg += "$lt{'whus'}\\n";
 6836:         }
 6837:         if (srchterm.indexOf(",") == srchterm.length -1) {
 6838:             checkok = 0;
 6839:             msg += "$lt{'whse'}\\n";
 6840:         }
 6841:     }
 6842:     if (checkok == 0) {
 6843:         alert("$lt{'thfo'}\\n"+msg);
 6844:         return;
 6845:     }
 6846:     if (checkok == 1) {
 6847:         callingForm.submit();
 6848:     }
 6849: }
 6850: 
 6851: $newuserscript
 6852: 
 6853: </script>
 6854: 
 6855: $new_user_create
 6856: 
 6857: <table>
 6858:  <tr>
 6859:   <td>$lt{'doma'}:</td>
 6860:   <td>$domform</td>
 6861:   </td>
 6862:  </tr>
 6863:  <tr>
 6864:   <td>$lt{'usr'}:</td>
 6865:   <td>$srchbysel
 6866:       $srchtypesel 
 6867:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 6868:       $srchinsel 
 6869:   </td>
 6870:  </tr>
 6871: </table>
 6872: <br />
 6873: END_BLOCK
 6874: 
 6875:     return $output;
 6876: }
 6877: 
 6878: sub user_rule_check {
 6879:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 6880:     my $response;
 6881:     if (ref($usershash) eq 'HASH') {
 6882:         foreach my $user (keys(%{$usershash})) {
 6883:             my ($uname,$udom) = split(/:/,$user);
 6884:             next if ($udom eq '' || $uname eq '');
 6885:             my ($id,$newuser);
 6886:             if (ref($usershash->{$user}) eq 'HASH') {
 6887:                 $newuser = $usershash->{$user}->{'newuser'};
 6888:                 $id = $usershash->{$user}->{'id'};
 6889:             }
 6890:             my $inst_response;
 6891:             if (ref($checks) eq 'HASH') {
 6892:                 if (defined($checks->{'username'})) {
 6893:                     ($inst_response,%{$inst_results->{$user}}) = 
 6894:                         &Apache::lonnet::get_instuser($udom,$uname);
 6895:                 } elsif (defined($checks->{'id'})) {
 6896:                     ($inst_response,%{$inst_results->{$user}}) =
 6897:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 6898:                 }
 6899:             } else {
 6900:                 ($inst_response,%{$inst_results->{$user}}) =
 6901:                     &Apache::lonnet::get_instuser($udom,$uname);
 6902:                 return;
 6903:             }
 6904:             if (!$got_rules->{$udom}) {
 6905:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 6906:                                                   ['usercreation'],$udom);
 6907:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6908:                     foreach my $item ('username','id') {
 6909:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 6910:                             $$curr_rules{$udom}{$item} = 
 6911:                                 $domconfig{'usercreation'}{$item.'_rule'};
 6912:                         }
 6913:                     }
 6914:                 }
 6915:                 $got_rules->{$udom} = 1;  
 6916:             }
 6917:             foreach my $item (keys(%{$checks})) {
 6918:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 6919:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 6920:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 6921:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 6922:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 6923:                                 if ($rule_check{$rule}) {
 6924:                                     $$rulematch{$user}{$item} = $rule;
 6925:                                     if ($inst_response eq 'ok') {
 6926:                                         if (ref($inst_results) eq 'HASH') {
 6927:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 6928:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 6929:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 6930:                                                 }
 6931:                                             }
 6932:                                         }
 6933:                                     }
 6934:                                     last;
 6935:                                 }
 6936:                             }
 6937:                         }
 6938:                     }
 6939:                 }
 6940:             }
 6941:         }
 6942:     }
 6943:     return;
 6944: }
 6945: 
 6946: sub user_rule_formats {
 6947:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 6948:     my %text = ( 
 6949:                  'username' => 'Usernames',
 6950:                  'id'       => 'IDs',
 6951:                );
 6952:     my $output;
 6953:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 6954:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 6955:         if (@{$ruleorder} > 0) {
 6956:             $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>';
 6957:             foreach my $rule (@{$ruleorder}) {
 6958:                 if (ref($curr_rules) eq 'ARRAY') {
 6959:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 6960:                         if (ref($rules->{$rule}) eq 'HASH') {
 6961:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 6962:                                         $rules->{$rule}{'desc'}.'</li>';
 6963:                         }
 6964:                     }
 6965:                 }
 6966:             }
 6967:             $output .= '</ul>';
 6968:         }
 6969:     }
 6970:     return $output;
 6971: }
 6972: 
 6973: sub instrule_disallow_msg {
 6974:     my ($checkitem,$domdesc,$count,$mode) = @_;
 6975:     my $response;
 6976:     my %text = (
 6977:                   item   => 'username',
 6978:                   items  => 'usernames',
 6979:                   match  => 'matches',
 6980:                   do     => 'does',
 6981:                   action => 'a username',
 6982:                   one    => 'one',
 6983:                );
 6984:     if ($count > 1) {
 6985:         $text{'item'} = 'usernames';
 6986:         $text{'match'} ='match';
 6987:         $text{'do'} = 'do';
 6988:         $text{'action'} = 'usernames',
 6989:         $text{'one'} = 'ones';
 6990:     }
 6991:     if ($checkitem eq 'id') {
 6992:         $text{'items'} = 'IDs';
 6993:         $text{'item'} = 'ID';
 6994:         $text{'action'} = 'an ID';
 6995:         if ($count > 1) {
 6996:             $text{'item'} = 'IDs';
 6997:             $text{'action'} = 'IDs';
 6998:         }
 6999:     }
 7000:     $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 />';
 7001:     if ($mode eq 'upload') {
 7002:         if ($checkitem eq 'username') {
 7003:             $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'}.");
 7004:         } elsif ($checkitem eq 'id') {
 7005:             $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.");
 7006:         }
 7007:     } elsif ($mode eq 'selfcreate') {
 7008:         if ($checkitem eq 'id') {
 7009:             $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.");
 7010:         }
 7011:     } else {
 7012:         if ($checkitem eq 'username') {
 7013:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7014:         } elsif ($checkitem eq 'id') {
 7015:             $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.");
 7016:         }
 7017:     }
 7018:     return $response;
 7019: }
 7020: 
 7021: sub personal_data_fieldtitles {
 7022:     my %fieldtitles = &Apache::lonlocal::texthash (
 7023:                         id => 'Student/Employee ID',
 7024:                         permanentemail => 'E-mail address',
 7025:                         lastname => 'Last Name',
 7026:                         firstname => 'First Name',
 7027:                         middlename => 'Middle Name',
 7028:                         generation => 'Generation',
 7029:                         gen => 'Generation',
 7030:                    );
 7031:     return %fieldtitles;
 7032: }
 7033: 
 7034: sub sorted_inst_types {
 7035:     my ($dom) = @_;
 7036:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7037:     my $othertitle = &mt('All users');
 7038:     if ($env{'request.course.id'}) {
 7039:         $othertitle  = &mt('Any users');
 7040:     }
 7041:     my @types;
 7042:     if (ref($order) eq 'ARRAY') {
 7043:         @types = @{$order};
 7044:     }
 7045:     if (@types == 0) {
 7046:         if (ref($usertypes) eq 'HASH') {
 7047:             @types = sort(keys(%{$usertypes}));
 7048:         }
 7049:     }
 7050:     if (keys(%{$usertypes}) > 0) {
 7051:         $othertitle = &mt('Other users');
 7052:     }
 7053:     return ($othertitle,$usertypes,\@types);
 7054: }
 7055: 
 7056: sub get_institutional_codes {
 7057:     my ($settings,$allcourses,$LC_code) = @_;
 7058: # Get complete list of course sections to update
 7059:     my @currsections = ();
 7060:     my @currxlists = ();
 7061:     my $coursecode = $$settings{'internal.coursecode'};
 7062: 
 7063:     if ($$settings{'internal.sectionnums'} ne '') {
 7064:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7065:     }
 7066: 
 7067:     if ($$settings{'internal.crosslistings'} ne '') {
 7068:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7069:     }
 7070: 
 7071:     if (@currxlists > 0) {
 7072:         foreach (@currxlists) {
 7073:             if (m/^([^:]+):(\w*)$/) {
 7074:                 unless (grep/^$1$/,@{$allcourses}) {
 7075:                     push @{$allcourses},$1;
 7076:                     $$LC_code{$1} = $2;
 7077:                 }
 7078:             }
 7079:         }
 7080:     }
 7081:  
 7082:     if (@currsections > 0) {
 7083:         foreach (@currsections) {
 7084:             if (m/^(\w+):(\w*)$/) {
 7085:                 my $sec = $coursecode.$1;
 7086:                 my $lc_sec = $2;
 7087:                 unless (grep/^$sec$/,@{$allcourses}) {
 7088:                     push @{$allcourses},$sec;
 7089:                     $$LC_code{$sec} = $lc_sec;
 7090:                 }
 7091:             }
 7092:         }
 7093:     }
 7094:     return;
 7095: }
 7096: 
 7097: =pod
 7098: 
 7099: =back
 7100: 
 7101: =head1 HTTP Helpers
 7102: 
 7103: =over 4
 7104: 
 7105: =item * &get_unprocessed_cgi($query,$possible_names)
 7106: 
 7107: Modify the %env hash to contain unprocessed CGI form parameters held in
 7108: $query.  The parameters listed in $possible_names (an array reference),
 7109: will be set in $env{'form.name'} if they do not already exist.
 7110: 
 7111: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7112: $possible_names is an ref to an array of form element names.  As an example:
 7113: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7114: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7115: 
 7116: =cut
 7117: 
 7118: sub get_unprocessed_cgi {
 7119:   my ($query,$possible_names)= @_;
 7120:   # $Apache::lonxml::debug=1;
 7121:   foreach my $pair (split(/&/,$query)) {
 7122:     my ($name, $value) = split(/=/,$pair);
 7123:     $name = &unescape($name);
 7124:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7125:       $value =~ tr/+/ /;
 7126:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7127:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7128:     }
 7129:   }
 7130: }
 7131: 
 7132: =pod
 7133: 
 7134: =item * &cacheheader() 
 7135: 
 7136: returns cache-controlling header code
 7137: 
 7138: =cut
 7139: 
 7140: sub cacheheader {
 7141:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7142:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7143:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7144:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7145:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7146:     return $output;
 7147: }
 7148: 
 7149: =pod
 7150: 
 7151: =item * &no_cache($r) 
 7152: 
 7153: specifies header code to not have cache
 7154: 
 7155: =cut
 7156: 
 7157: sub no_cache {
 7158:     my ($r) = @_;
 7159:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7160: 	$env{'request.method'} ne 'GET') { return ''; }
 7161:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7162:     $r->no_cache(1);
 7163:     $r->header_out("Expires" => $date);
 7164:     $r->header_out("Pragma" => "no-cache");
 7165: }
 7166: 
 7167: sub content_type {
 7168:     my ($r,$type,$charset) = @_;
 7169:     if ($r) {
 7170: 	#  Note that printout.pl calls this with undef for $r.
 7171: 	&no_cache($r);
 7172:     }
 7173:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7174:     unless ($charset) {
 7175: 	$charset=&Apache::lonlocal::current_encoding;
 7176:     }
 7177:     if ($charset) { $type.='; charset='.$charset; }
 7178:     if ($r) {
 7179: 	$r->content_type($type);
 7180:     } else {
 7181: 	print("Content-type: $type\n\n");
 7182:     }
 7183: }
 7184: 
 7185: =pod
 7186: 
 7187: =item * &add_to_env($name,$value) 
 7188: 
 7189: adds $name to the %env hash with value
 7190: $value, if $name already exists, the entry is converted to an array
 7191: reference and $value is added to the array.
 7192: 
 7193: =cut
 7194: 
 7195: sub add_to_env {
 7196:   my ($name,$value)=@_;
 7197:   if (defined($env{$name})) {
 7198:     if (ref($env{$name})) {
 7199:       #already have multiple values
 7200:       push(@{ $env{$name} },$value);
 7201:     } else {
 7202:       #first time seeing multiple values, convert hash entry to an arrayref
 7203:       my $first=$env{$name};
 7204:       undef($env{$name});
 7205:       push(@{ $env{$name} },$first,$value);
 7206:     }
 7207:   } else {
 7208:     $env{$name}=$value;
 7209:   }
 7210: }
 7211: 
 7212: =pod
 7213: 
 7214: =item * &get_env_multiple($name) 
 7215: 
 7216: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7217: values may be defined and end up as an array ref.
 7218: 
 7219: returns an array of values
 7220: 
 7221: =cut
 7222: 
 7223: sub get_env_multiple {
 7224:     my ($name) = @_;
 7225:     my @values;
 7226:     if (defined($env{$name})) {
 7227:         # exists is it an array
 7228:         if (ref($env{$name})) {
 7229:             @values=@{ $env{$name} };
 7230:         } else {
 7231:             $values[0]=$env{$name};
 7232:         }
 7233:     }
 7234:     return(@values);
 7235: }
 7236: 
 7237: sub ask_for_embedded_content {
 7238:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7239:     my $upload_output = '
 7240:    <form name="upload_embedded" action="'.$actionurl.'"
 7241:                   method="post" enctype="multipart/form-data">';
 7242:     $upload_output .= $state;
 7243:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7244: 
 7245:     my $num = 0;
 7246:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7247:         $upload_output .= &start_data_table_row().
 7248:             '<td>'.$embed_file.'</td><td>';
 7249:         if ($args->{'ignore_remote_references'}
 7250:             && $embed_file =~ m{^\w+://}) {
 7251:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7252:         } elsif ($args->{'error_on_invalid_names'}
 7253:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7254: 
 7255:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7256: 
 7257:         } else {
 7258:             $upload_output .='
 7259:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7260:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7261:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7262:             $upload_output .=
 7263:                 "\n\t\t".
 7264:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7265:                 $attrib.'" />';
 7266:             if (exists($$codebase{$embed_file})) {
 7267:                 $upload_output .=
 7268:                     "\n\t\t".
 7269:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7270:                     &escape($$codebase{$embed_file}).'" />';
 7271:             }
 7272:         }
 7273:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7274:         $num++;
 7275:     }
 7276:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7277:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7278:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7279:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7280:    </form>';
 7281:     return $upload_output;
 7282: }
 7283: 
 7284: sub upload_embedded {
 7285:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7286:         $current_disk_usage) = @_;
 7287:     my $output;
 7288:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7289:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7290:         my $orig_uploaded_filename =
 7291:             $env{'form.embedded_item_'.$i.'.filename'};
 7292: 
 7293:         $env{'form.embedded_orig_'.$i} =
 7294:             &unescape($env{'form.embedded_orig_'.$i});
 7295:         my ($path,$fname) =
 7296:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7297:         # no path, whole string is fname
 7298:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7299: 
 7300:         $path = $env{'form.currentpath'}.$path;
 7301:         $fname = &Apache::lonnet::clean_filename($fname);
 7302:         # See if there is anything left
 7303:         next if ($fname eq '');
 7304: 
 7305:         # Check if file already exists as a file or directory.
 7306:         my ($state,$msg);
 7307:         if ($context eq 'portfolio') {
 7308:             my $port_path = $dirpath;
 7309:             if ($group ne '') {
 7310:                 $port_path = "groups/$group/$port_path";
 7311:             }
 7312:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7313:                                               $dir_root,$port_path,$disk_quota,
 7314:                                               $current_disk_usage,$uname,$udom);
 7315:             if ($state eq 'will_exceed_quota'
 7316:                 || $state eq 'file_locked'
 7317:                 || $state eq 'file_exists' ) {
 7318:                 $output .= $msg;
 7319:                 next;
 7320:             }
 7321:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7322:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7323:             if ($state eq 'exists') {
 7324:                 $output .= $msg;
 7325:                 next;
 7326:             }
 7327:         }
 7328:         # Check if extension is valid
 7329:         if (($fname =~ /\.(\w+)$/) &&
 7330:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7331:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7332:             next;
 7333:         } elsif (($fname =~ /\.(\w+)$/) &&
 7334:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7335:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7336:             next;
 7337:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7338:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7339:             next;
 7340:         }
 7341: 
 7342:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7343:         if ($context eq 'portfolio') {
 7344:             my $result=
 7345:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7346:                                                 $dirpath.$path);
 7347:             if ($result !~ m|^/uploaded/|) {
 7348:                 $output .= '<span class="LC_error">'
 7349:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7350:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7351:                       .'</span><br />';
 7352:                 next;
 7353:             } else {
 7354:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7355:                            $path.$fname.'</span>').'</p>';     
 7356:             }
 7357:         } else {
 7358: # Save the file
 7359:             my $target = $env{'form.embedded_item_'.$i};
 7360:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7361:             my $dest = $fullpath.$fname;
 7362:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7363:             my @parts=split(/\//,$fullpath);
 7364:             my $count;
 7365:             my $filepath = $dir_root;
 7366:             for ($count=4;$count<=$#parts;$count++) {
 7367:                 $filepath .= "/$parts[$count]";
 7368:                 if ((-e $filepath)!=1) {
 7369:                     mkdir($filepath,0770);
 7370:                 }
 7371:             }
 7372:             my $fh;
 7373:             if (!open($fh,'>'.$dest)) {
 7374:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7375:                 $output .= '<span class="LC_error">'.
 7376:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7377:                            '</span><br />';
 7378:             } else {
 7379:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7380:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7381:                     $output .= '<span class="LC_error">'.
 7382:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7383:                               '</span><br />';
 7384:                 } else {
 7385:                     if ($context eq 'testbank') {
 7386:                         $output .= &mt('Embedded file uploaded successfully:').
 7387:                                    '&nbsp;<a href="'.$url.'">'.
 7388:                                    $orig_uploaded_filename.'</a><br />';
 7389:                     } else {
 7390:                         $output .= '<font size="+2">'.
 7391:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7392:                                    $orig_uploaded_filename.'</a>').'</font><br />';
 7393:                     }
 7394:                 }
 7395:                 close($fh);
 7396:             }
 7397:         }
 7398:     }
 7399:     return $output;
 7400: }
 7401: 
 7402: sub check_for_existing {
 7403:     my ($path,$fname,$element) = @_;
 7404:     my ($state,$msg);
 7405:     if (-d $path.'/'.$fname) {
 7406:         $state = 'exists';
 7407:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7408:     } elsif (-e $path.'/'.$fname) {
 7409:         $state = 'exists';
 7410:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7411:     }
 7412:     if ($state eq 'exists') {
 7413:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7414:     }
 7415:     return ($state,$msg);
 7416: }
 7417: 
 7418: sub check_for_upload {
 7419:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7420:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7421:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7422:     my $getpropath = 1;
 7423:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7424:                                             $getpropath);
 7425:     my $found_file = 0;
 7426:     my $locked_file = 0;
 7427:     foreach my $line (@dir_list) {
 7428:         my ($file_name)=split(/\&/,$line,2);
 7429:         if ($file_name eq $fname){
 7430:             $file_name = $path.$file_name;
 7431:             if ($group ne '') {
 7432:                 $file_name = $group.$file_name;
 7433:             }
 7434:             $found_file = 1;
 7435:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7436:                 $locked_file = 1;
 7437:             }
 7438:         }
 7439:     }
 7440:     if (($current_disk_usage + $filesize) > $disk_quota){
 7441:         my $msg = '<span class="LC_error">'.
 7442:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7443:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7444:         return ('will_exceed_quota',$msg);
 7445:     } elsif ($found_file) {
 7446:         if ($locked_file) {
 7447:             my $msg = '<span class="LC_error">';
 7448:             $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>');
 7449:             $msg .= '</span><br />';
 7450:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7451:             return ('file_locked',$msg);
 7452:         } else {
 7453:             my $msg = '<span class="LC_error">';
 7454:             $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'});
 7455:             $msg .= '</span>';
 7456:             $msg .= '<br />';
 7457:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7458:             return ('file_exists',$msg);
 7459:         }
 7460:     }
 7461: }
 7462: 
 7463: 
 7464: =pod
 7465: 
 7466: =back
 7467: 
 7468: =head1 CSV Upload/Handling functions
 7469: 
 7470: =over 4
 7471: 
 7472: =item * &upfile_store($r)
 7473: 
 7474: Store uploaded file, $r should be the HTTP Request object,
 7475: needs $env{'form.upfile'}
 7476: returns $datatoken to be put into hidden field
 7477: 
 7478: =cut
 7479: 
 7480: sub upfile_store {
 7481:     my $r=shift;
 7482:     $env{'form.upfile'}=~s/\r/\n/gs;
 7483:     $env{'form.upfile'}=~s/\f/\n/gs;
 7484:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7485:     $env{'form.upfile'}=~s/\n+$//gs;
 7486: 
 7487:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7488: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7489:     {
 7490:         my $datafile = $r->dir_config('lonDaemons').
 7491:                            '/tmp/'.$datatoken.'.tmp';
 7492:         if ( open(my $fh,">$datafile") ) {
 7493:             print $fh $env{'form.upfile'};
 7494:             close($fh);
 7495:         }
 7496:     }
 7497:     return $datatoken;
 7498: }
 7499: 
 7500: =pod
 7501: 
 7502: =item * &load_tmp_file($r)
 7503: 
 7504: Load uploaded file from tmp, $r should be the HTTP Request object,
 7505: needs $env{'form.datatoken'},
 7506: sets $env{'form.upfile'} to the contents of the file
 7507: 
 7508: =cut
 7509: 
 7510: sub load_tmp_file {
 7511:     my $r=shift;
 7512:     my @studentdata=();
 7513:     {
 7514:         my $studentfile = $r->dir_config('lonDaemons').
 7515:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7516:         if ( open(my $fh,"<$studentfile") ) {
 7517:             @studentdata=<$fh>;
 7518:             close($fh);
 7519:         }
 7520:     }
 7521:     $env{'form.upfile'}=join('',@studentdata);
 7522: }
 7523: 
 7524: =pod
 7525: 
 7526: =item * &upfile_record_sep()
 7527: 
 7528: Separate uploaded file into records
 7529: returns array of records,
 7530: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7531: 
 7532: =cut
 7533: 
 7534: sub upfile_record_sep {
 7535:     if ($env{'form.upfiletype'} eq 'xml') {
 7536:     } else {
 7537: 	my @records;
 7538: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7539: 	    if ($line=~/^\s*$/) { next; }
 7540: 	    push(@records,$line);
 7541: 	}
 7542: 	return @records;
 7543:     }
 7544: }
 7545: 
 7546: =pod
 7547: 
 7548: =item * &record_sep($record)
 7549: 
 7550: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7551: 
 7552: =cut
 7553: 
 7554: sub takeleft {
 7555:     my $index=shift;
 7556:     return substr('0000'.$index,-4,4);
 7557: }
 7558: 
 7559: sub record_sep {
 7560:     my $record=shift;
 7561:     my %components=();
 7562:     if ($env{'form.upfiletype'} eq 'xml') {
 7563:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7564:         my $i=0;
 7565:         foreach my $field (split(/\s+/,$record)) {
 7566:             $field=~s/^(\"|\')//;
 7567:             $field=~s/(\"|\')$//;
 7568:             $components{&takeleft($i)}=$field;
 7569:             $i++;
 7570:         }
 7571:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7572:         my $i=0;
 7573:         foreach my $field (split(/\t/,$record)) {
 7574:             $field=~s/^(\"|\')//;
 7575:             $field=~s/(\"|\')$//;
 7576:             $components{&takeleft($i)}=$field;
 7577:             $i++;
 7578:         }
 7579:     } else {
 7580:         my $separator=',';
 7581:         if ($env{'form.upfiletype'} eq 'semisv') {
 7582:             $separator=';';
 7583:         }
 7584:         my $i=0;
 7585: # the character we are looking for to indicate the end of a quote or a record 
 7586:         my $looking_for=$separator;
 7587: # do not add the characters to the fields
 7588:         my $ignore=0;
 7589: # we just encountered a separator (or the beginning of the record)
 7590:         my $just_found_separator=1;
 7591: # store the field we are working on here
 7592:         my $field='';
 7593: # work our way through all characters in record
 7594:         foreach my $character ($record=~/(.)/g) {
 7595:             if ($character eq $looking_for) {
 7596:                if ($character ne $separator) {
 7597: # Found the end of a quote, again looking for separator
 7598:                   $looking_for=$separator;
 7599:                   $ignore=1;
 7600:                } else {
 7601: # Found a separator, store away what we got
 7602:                   $components{&takeleft($i)}=$field;
 7603: 	          $i++;
 7604:                   $just_found_separator=1;
 7605:                   $ignore=0;
 7606:                   $field='';
 7607:                }
 7608:                next;
 7609:             }
 7610: # single or double quotation marks after a separator indicate beginning of a quote
 7611: # we are now looking for the end of the quote and need to ignore separators
 7612:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7613:                $looking_for=$character;
 7614:                next;
 7615:             }
 7616: # ignore would be true after we reached the end of a quote
 7617:             if ($ignore) { next; }
 7618:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7619:             $field.=$character;
 7620:             $just_found_separator=0; 
 7621:         }
 7622: # catch the very last entry, since we never encountered the separator
 7623:         $components{&takeleft($i)}=$field;
 7624:     }
 7625:     return %components;
 7626: }
 7627: 
 7628: ######################################################
 7629: ######################################################
 7630: 
 7631: =pod
 7632: 
 7633: =item * &upfile_select_html()
 7634: 
 7635: Return HTML code to select a file from the users machine and specify 
 7636: the file type.
 7637: 
 7638: =cut
 7639: 
 7640: ######################################################
 7641: ######################################################
 7642: sub upfile_select_html {
 7643:     my %Types = (
 7644:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7645:                  semisv => &mt('Semicolon separated values'),
 7646:                  space => &mt('Space separated'),
 7647:                  tab   => &mt('Tabulator separated'),
 7648: #                 xml   => &mt('HTML/XML'),
 7649:                  );
 7650:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7651:         '<br />Type: <select name="upfiletype">';
 7652:     foreach my $type (sort(keys(%Types))) {
 7653:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7654:     }
 7655:     $Str .= "</select>\n";
 7656:     return $Str;
 7657: }
 7658: 
 7659: sub get_samples {
 7660:     my ($records,$toget) = @_;
 7661:     my @samples=({});
 7662:     my $got=0;
 7663:     foreach my $rec (@$records) {
 7664: 	my %temp = &record_sep($rec);
 7665: 	if (! grep(/\S/, values(%temp))) { next; }
 7666: 	if (%temp) {
 7667: 	    $samples[$got]=\%temp;
 7668: 	    $got++;
 7669: 	    if ($got == $toget) { last; }
 7670: 	}
 7671:     }
 7672:     return \@samples;
 7673: }
 7674: 
 7675: ######################################################
 7676: ######################################################
 7677: 
 7678: =pod
 7679: 
 7680: =item * &csv_print_samples($r,$records)
 7681: 
 7682: Prints a table of sample values from each column uploaded $r is an
 7683: Apache Request ref, $records is an arrayref from
 7684: &Apache::loncommon::upfile_record_sep
 7685: 
 7686: =cut
 7687: 
 7688: ######################################################
 7689: ######################################################
 7690: sub csv_print_samples {
 7691:     my ($r,$records) = @_;
 7692:     my $samples = &get_samples($records,5);
 7693: 
 7694:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 7695:               &start_data_table_header_row());
 7696:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 7697:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 7698:     $r->print(&end_data_table_header_row());
 7699:     foreach my $hash (@$samples) {
 7700: 	$r->print(&start_data_table_row());
 7701: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7702: 	    $r->print('<td>');
 7703: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 7704: 	    $r->print('</td>');
 7705: 	}
 7706: 	$r->print(&end_data_table_row());
 7707:     }
 7708:     $r->print(&end_data_table().'<br />'."\n");
 7709: }
 7710: 
 7711: ######################################################
 7712: ######################################################
 7713: 
 7714: =pod
 7715: 
 7716: =item * &csv_print_select_table($r,$records,$d)
 7717: 
 7718: Prints a table to create associations between values and table columns.
 7719: 
 7720: $r is an Apache Request ref,
 7721: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7722: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 7723: 
 7724: =cut
 7725: 
 7726: ######################################################
 7727: ######################################################
 7728: sub csv_print_select_table {
 7729:     my ($r,$records,$d) = @_;
 7730:     my $i=0;
 7731:     my $samples = &get_samples($records,1);
 7732:     $r->print(&mt('Associate columns with student attributes.')."\n".
 7733: 	      &start_data_table().&start_data_table_header_row().
 7734:               '<th>'.&mt('Attribute').'</th>'.
 7735:               '<th>'.&mt('Column').'</th>'.
 7736:               &end_data_table_header_row()."\n");
 7737:     foreach my $array_ref (@$d) {
 7738: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 7739: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 7740: 
 7741: 	$r->print('<td><select name=f'.$i.
 7742: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7743: 	$r->print('<option value="none"></option>');
 7744: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7745: 	    $r->print('<option value="'.$sample.'"'.
 7746:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 7747:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 7748: 	}
 7749: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 7750: 	$i++;
 7751:     }
 7752:     $r->print(&end_data_table());
 7753:     $i--;
 7754:     return $i;
 7755: }
 7756: 
 7757: ######################################################
 7758: ######################################################
 7759: 
 7760: =pod
 7761: 
 7762: =item * &csv_samples_select_table($r,$records,$d)
 7763: 
 7764: Prints a table of sample values from the upload and can make associate samples to internal names.
 7765: 
 7766: $r is an Apache Request ref,
 7767: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7768: $d is an array of 2 element arrays (internal name, displayed name)
 7769: 
 7770: =cut
 7771: 
 7772: ######################################################
 7773: ######################################################
 7774: sub csv_samples_select_table {
 7775:     my ($r,$records,$d) = @_;
 7776:     my $i=0;
 7777:     #
 7778:     my $max_samples = 5;
 7779:     my $samples = &get_samples($records,$max_samples);
 7780:     $r->print(&start_data_table().
 7781:               &start_data_table_header_row().'<th>'.
 7782:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 7783:               &end_data_table_header_row());
 7784: 
 7785:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 7786: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 7787: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7788: 	foreach my $option (@$d) {
 7789: 	    my ($value,$display,$defaultcol)=@{ $option };
 7790: 	    $r->print('<option value="'.$value.'"'.
 7791:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 7792:                       $display.'</option>');
 7793: 	}
 7794: 	$r->print('</select></td><td>');
 7795: 	foreach my $line (0..($max_samples-1)) {
 7796: 	    if (defined($samples->[$line]{$key})) { 
 7797: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 7798: 	    }
 7799: 	}
 7800: 	$r->print('</td>'.&end_data_table_row());
 7801: 	$i++;
 7802:     }
 7803:     $r->print(&end_data_table());
 7804:     $i--;
 7805:     return($i);
 7806: }
 7807: 
 7808: ######################################################
 7809: ######################################################
 7810: 
 7811: =pod
 7812: 
 7813: =item * &clean_excel_name($name)
 7814: 
 7815: Returns a replacement for $name which does not contain any illegal characters.
 7816: 
 7817: =cut
 7818: 
 7819: ######################################################
 7820: ######################################################
 7821: sub clean_excel_name {
 7822:     my ($name) = @_;
 7823:     $name =~ s/[:\*\?\/\\]//g;
 7824:     if (length($name) > 31) {
 7825:         $name = substr($name,0,31);
 7826:     }
 7827:     return $name;
 7828: }
 7829: 
 7830: =pod
 7831: 
 7832: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 7833: 
 7834: Returns either 1 or undef
 7835: 
 7836: 1 if the part is to be hidden, undef if it is to be shown
 7837: 
 7838: Arguments are:
 7839: 
 7840: $id the id of the part to be checked
 7841: $symb, optional the symb of the resource to check
 7842: $udom, optional the domain of the user to check for
 7843: $uname, optional the username of the user to check for
 7844: 
 7845: =cut
 7846: 
 7847: sub check_if_partid_hidden {
 7848:     my ($id,$symb,$udom,$uname) = @_;
 7849:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 7850: 					 $symb,$udom,$uname);
 7851:     my $truth=1;
 7852:     #if the string starts with !, then the list is the list to show not hide
 7853:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 7854:     my @hiddenlist=split(/,/,$hiddenparts);
 7855:     foreach my $checkid (@hiddenlist) {
 7856: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 7857:     }
 7858:     return !$truth;
 7859: }
 7860: 
 7861: 
 7862: ############################################################
 7863: ############################################################
 7864: 
 7865: =pod
 7866: 
 7867: =back 
 7868: 
 7869: =head1 cgi-bin script and graphing routines
 7870: 
 7871: =over 4
 7872: 
 7873: =item * &get_cgi_id()
 7874: 
 7875: Inputs: none
 7876: 
 7877: Returns an id which can be used to pass environment variables
 7878: to various cgi-bin scripts.  These environment variables will
 7879: be removed from the users environment after a given time by
 7880: the routine &Apache::lonnet::transfer_profile_to_env.
 7881: 
 7882: =cut
 7883: 
 7884: ############################################################
 7885: ############################################################
 7886: my $uniq=0;
 7887: sub get_cgi_id {
 7888:     $uniq=($uniq+1)%100000;
 7889:     return (time.'_'.$$.'_'.$uniq);
 7890: }
 7891: 
 7892: ############################################################
 7893: ############################################################
 7894: 
 7895: =pod
 7896: 
 7897: =item * &DrawBarGraph()
 7898: 
 7899: Facilitates the plotting of data in a (stacked) bar graph.
 7900: Puts plot definition data into the users environment in order for 
 7901: graph.png to plot it.  Returns an <img> tag for the plot.
 7902: The bars on the plot are labeled '1','2',...,'n'.
 7903: 
 7904: Inputs:
 7905: 
 7906: =over 4
 7907: 
 7908: =item $Title: string, the title of the plot
 7909: 
 7910: =item $xlabel: string, text describing the X-axis of the plot
 7911: 
 7912: =item $ylabel: string, text describing the Y-axis of the plot
 7913: 
 7914: =item $Max: scalar, the maximum Y value to use in the plot
 7915: If $Max is < any data point, the graph will not be rendered.
 7916: 
 7917: =item $colors: array ref holding the colors to be used for the data sets when
 7918: they are plotted.  If undefined, default values will be used.
 7919: 
 7920: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 7921: 
 7922: =item @Values: An array of array references.  Each array reference holds data
 7923: to be plotted in a stacked bar chart.
 7924: 
 7925: =item If the final element of @Values is a hash reference the key/value
 7926: pairs will be added to the graph definition.
 7927: 
 7928: =back
 7929: 
 7930: Returns:
 7931: 
 7932: An <img> tag which references graph.png and the appropriate identifying
 7933: information for the plot.
 7934: 
 7935: =cut
 7936: 
 7937: ############################################################
 7938: ############################################################
 7939: sub DrawBarGraph {
 7940:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 7941:     #
 7942:     if (! defined($colors)) {
 7943:         $colors = ['#33ff00', 
 7944:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 7945:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 7946:                   ]; 
 7947:     }
 7948:     my $extra_settings = {};
 7949:     if (ref($Values[-1]) eq 'HASH') {
 7950:         $extra_settings = pop(@Values);
 7951:     }
 7952:     #
 7953:     my $identifier = &get_cgi_id();
 7954:     my $id = 'cgi.'.$identifier;        
 7955:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 7956:         return '';
 7957:     }
 7958:     #
 7959:     my @Labels;
 7960:     if (defined($labels)) {
 7961:         @Labels = @$labels;
 7962:     } else {
 7963:         for (my $i=0;$i<@{$Values[0]};$i++) {
 7964:             push (@Labels,$i+1);
 7965:         }
 7966:     }
 7967:     #
 7968:     my $NumBars = scalar(@{$Values[0]});
 7969:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 7970:     my %ValuesHash;
 7971:     my $NumSets=1;
 7972:     foreach my $array (@Values) {
 7973:         next if (! ref($array));
 7974:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 7975:             join(',',@$array);
 7976:     }
 7977:     #
 7978:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 7979:     if ($NumBars < 3) {
 7980:         $width = 120+$NumBars*32;
 7981:         $xskip = 1;
 7982:         $bar_width = 30;
 7983:     } elsif ($NumBars < 5) {
 7984:         $width = 120+$NumBars*20;
 7985:         $xskip = 1;
 7986:         $bar_width = 20;
 7987:     } elsif ($NumBars < 10) {
 7988:         $width = 120+$NumBars*15;
 7989:         $xskip = 1;
 7990:         $bar_width = 15;
 7991:     } elsif ($NumBars <= 25) {
 7992:         $width = 120+$NumBars*11;
 7993:         $xskip = 5;
 7994:         $bar_width = 8;
 7995:     } elsif ($NumBars <= 50) {
 7996:         $width = 120+$NumBars*8;
 7997:         $xskip = 5;
 7998:         $bar_width = 4;
 7999:     } else {
 8000:         $width = 120+$NumBars*8;
 8001:         $xskip = 5;
 8002:         $bar_width = 4;
 8003:     }
 8004:     #
 8005:     $Max = 1 if ($Max < 1);
 8006:     if ( int($Max) < $Max ) {
 8007:         $Max++;
 8008:         $Max = int($Max);
 8009:     }
 8010:     $Title  = '' if (! defined($Title));
 8011:     $xlabel = '' if (! defined($xlabel));
 8012:     $ylabel = '' if (! defined($ylabel));
 8013:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8014:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8015:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8016:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8017:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8018:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8019:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8020:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8021:     $ValuesHash{$id.'.height'}   = $height;
 8022:     $ValuesHash{$id.'.width'}    = $width;
 8023:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8024:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8025:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8026:     #
 8027:     # Deal with other parameters
 8028:     while (my ($key,$value) = each(%$extra_settings)) {
 8029:         $ValuesHash{$id.'.'.$key} = $value;
 8030:     }
 8031:     #
 8032:     &Apache::lonnet::appenv(\%ValuesHash);
 8033:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8034: }
 8035: 
 8036: ############################################################
 8037: ############################################################
 8038: 
 8039: =pod
 8040: 
 8041: =item * &DrawXYGraph()
 8042: 
 8043: Facilitates the plotting of data in an XY graph.
 8044: Puts plot definition data into the users environment in order for 
 8045: graph.png to plot it.  Returns an <img> tag for the plot.
 8046: 
 8047: Inputs:
 8048: 
 8049: =over 4
 8050: 
 8051: =item $Title: string, the title of the plot
 8052: 
 8053: =item $xlabel: string, text describing the X-axis of the plot
 8054: 
 8055: =item $ylabel: string, text describing the Y-axis of the plot
 8056: 
 8057: =item $Max: scalar, the maximum Y value to use in the plot
 8058: If $Max is < any data point, the graph will not be rendered.
 8059: 
 8060: =item $colors: Array ref containing the hex color codes for the data to be 
 8061: plotted in.  If undefined, default values will be used.
 8062: 
 8063: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8064: 
 8065: =item $Ydata: Array ref containing Array refs.  
 8066: Each of the contained arrays will be plotted as a separate curve.
 8067: 
 8068: =item %Values: hash indicating or overriding any default values which are 
 8069: passed to graph.png.  
 8070: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8071: 
 8072: =back
 8073: 
 8074: Returns:
 8075: 
 8076: An <img> tag which references graph.png and the appropriate identifying
 8077: information for the plot.
 8078: 
 8079: =cut
 8080: 
 8081: ############################################################
 8082: ############################################################
 8083: sub DrawXYGraph {
 8084:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8085:     #
 8086:     # Create the identifier for the graph
 8087:     my $identifier = &get_cgi_id();
 8088:     my $id = 'cgi.'.$identifier;
 8089:     #
 8090:     $Title  = '' if (! defined($Title));
 8091:     $xlabel = '' if (! defined($xlabel));
 8092:     $ylabel = '' if (! defined($ylabel));
 8093:     my %ValuesHash = 
 8094:         (
 8095:          $id.'.title'  => &escape($Title),
 8096:          $id.'.xlabel' => &escape($xlabel),
 8097:          $id.'.ylabel' => &escape($ylabel),
 8098:          $id.'.y_max_value'=> $Max,
 8099:          $id.'.labels'     => join(',',@$Xlabels),
 8100:          $id.'.PlotType'   => 'XY',
 8101:          );
 8102:     #
 8103:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8104:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8105:     }
 8106:     #
 8107:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8108:         return '';
 8109:     }
 8110:     my $NumSets=1;
 8111:     foreach my $array (@{$Ydata}){
 8112:         next if (! ref($array));
 8113:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8114:     }
 8115:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8116:     #
 8117:     # Deal with other parameters
 8118:     while (my ($key,$value) = each(%Values)) {
 8119:         $ValuesHash{$id.'.'.$key} = $value;
 8120:     }
 8121:     #
 8122:     &Apache::lonnet::appenv(\%ValuesHash);
 8123:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8124: }
 8125: 
 8126: ############################################################
 8127: ############################################################
 8128: 
 8129: =pod
 8130: 
 8131: =item * &DrawXYYGraph()
 8132: 
 8133: Facilitates the plotting of data in an XY graph with two Y axes.
 8134: Puts plot definition data into the users environment in order for 
 8135: graph.png to plot it.  Returns an <img> tag for the plot.
 8136: 
 8137: Inputs:
 8138: 
 8139: =over 4
 8140: 
 8141: =item $Title: string, the title of the plot
 8142: 
 8143: =item $xlabel: string, text describing the X-axis of the plot
 8144: 
 8145: =item $ylabel: string, text describing the Y-axis of the plot
 8146: 
 8147: =item $colors: Array ref containing the hex color codes for the data to be 
 8148: plotted in.  If undefined, default values will be used.
 8149: 
 8150: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8151: 
 8152: =item $Ydata1: The first data set
 8153: 
 8154: =item $Min1: The minimum value of the left Y-axis
 8155: 
 8156: =item $Max1: The maximum value of the left Y-axis
 8157: 
 8158: =item $Ydata2: The second data set
 8159: 
 8160: =item $Min2: The minimum value of the right Y-axis
 8161: 
 8162: =item $Max2: The maximum value of the left Y-axis
 8163: 
 8164: =item %Values: hash indicating or overriding any default values which are 
 8165: passed to graph.png.  
 8166: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8167: 
 8168: =back
 8169: 
 8170: Returns:
 8171: 
 8172: An <img> tag which references graph.png and the appropriate identifying
 8173: information for the plot.
 8174: 
 8175: =cut
 8176: 
 8177: ############################################################
 8178: ############################################################
 8179: sub DrawXYYGraph {
 8180:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8181:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8182:     #
 8183:     # Create the identifier for the graph
 8184:     my $identifier = &get_cgi_id();
 8185:     my $id = 'cgi.'.$identifier;
 8186:     #
 8187:     $Title  = '' if (! defined($Title));
 8188:     $xlabel = '' if (! defined($xlabel));
 8189:     $ylabel = '' if (! defined($ylabel));
 8190:     my %ValuesHash = 
 8191:         (
 8192:          $id.'.title'  => &escape($Title),
 8193:          $id.'.xlabel' => &escape($xlabel),
 8194:          $id.'.ylabel' => &escape($ylabel),
 8195:          $id.'.labels' => join(',',@$Xlabels),
 8196:          $id.'.PlotType' => 'XY',
 8197:          $id.'.NumSets' => 2,
 8198:          $id.'.two_axes' => 1,
 8199:          $id.'.y1_max_value' => $Max1,
 8200:          $id.'.y1_min_value' => $Min1,
 8201:          $id.'.y2_max_value' => $Max2,
 8202:          $id.'.y2_min_value' => $Min2,
 8203:          );
 8204:     #
 8205:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8206:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8207:     }
 8208:     #
 8209:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8210:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8211:         return '';
 8212:     }
 8213:     my $NumSets=1;
 8214:     foreach my $array ($Ydata1,$Ydata2){
 8215:         next if (! ref($array));
 8216:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8217:     }
 8218:     #
 8219:     # Deal with other parameters
 8220:     while (my ($key,$value) = each(%Values)) {
 8221:         $ValuesHash{$id.'.'.$key} = $value;
 8222:     }
 8223:     #
 8224:     &Apache::lonnet::appenv(\%ValuesHash);
 8225:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8226: }
 8227: 
 8228: ############################################################
 8229: ############################################################
 8230: 
 8231: =pod
 8232: 
 8233: =back 
 8234: 
 8235: =head1 Statistics helper routines?  
 8236: 
 8237: Bad place for them but what the hell.
 8238: 
 8239: =over 4
 8240: 
 8241: =item * &chartlink()
 8242: 
 8243: Returns a link to the chart for a specific student.  
 8244: 
 8245: Inputs:
 8246: 
 8247: =over 4
 8248: 
 8249: =item $linktext: The text of the link
 8250: 
 8251: =item $sname: The students username
 8252: 
 8253: =item $sdomain: The students domain
 8254: 
 8255: =back
 8256: 
 8257: =back
 8258: 
 8259: =cut
 8260: 
 8261: ############################################################
 8262: ############################################################
 8263: sub chartlink {
 8264:     my ($linktext, $sname, $sdomain) = @_;
 8265:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8266:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8267:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8268:        '">'.$linktext.'</a>';
 8269: }
 8270: 
 8271: #######################################################
 8272: #######################################################
 8273: 
 8274: =pod
 8275: 
 8276: =head1 Course Environment Routines
 8277: 
 8278: =over 4
 8279: 
 8280: =item * &restore_course_settings()
 8281: 
 8282: =item * &store_course_settings()
 8283: 
 8284: Restores/Store indicated form parameters from the course environment.
 8285: Will not overwrite existing values of the form parameters.
 8286: 
 8287: Inputs: 
 8288: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8289: 
 8290: a hash ref describing the data to be stored.  For example:
 8291:    
 8292: %Save_Parameters = ('Status' => 'scalar',
 8293:     'chartoutputmode' => 'scalar',
 8294:     'chartoutputdata' => 'scalar',
 8295:     'Section' => 'array',
 8296:     'Group' => 'array',
 8297:     'StudentData' => 'array',
 8298:     'Maps' => 'array');
 8299: 
 8300: Returns: both routines return nothing
 8301: 
 8302: =back
 8303: 
 8304: =cut
 8305: 
 8306: #######################################################
 8307: #######################################################
 8308: sub store_course_settings {
 8309:     return &store_settings($env{'request.course.id'},@_);
 8310: }
 8311: 
 8312: sub store_settings {
 8313:     # save to the environment
 8314:     # appenv the same items, just to be safe
 8315:     my $udom  = $env{'user.domain'};
 8316:     my $uname = $env{'user.name'};
 8317:     my ($context,$prefix,$Settings) = @_;
 8318:     my %SaveHash;
 8319:     my %AppHash;
 8320:     while (my ($setting,$type) = each(%$Settings)) {
 8321:         my $basename = join('.','internal',$context,$prefix,$setting);
 8322:         my $envname = 'environment.'.$basename;
 8323:         if (exists($env{'form.'.$setting})) {
 8324:             # Save this value away
 8325:             if ($type eq 'scalar' &&
 8326:                 (! exists($env{$envname}) || 
 8327:                  $env{$envname} ne $env{'form.'.$setting})) {
 8328:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8329:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8330:             } elsif ($type eq 'array') {
 8331:                 my $stored_form;
 8332:                 if (ref($env{'form.'.$setting})) {
 8333:                     $stored_form = join(',',
 8334:                                         map {
 8335:                                             &escape($_);
 8336:                                         } sort(@{$env{'form.'.$setting}}));
 8337:                 } else {
 8338:                     $stored_form = 
 8339:                         &escape($env{'form.'.$setting});
 8340:                 }
 8341:                 # Determine if the array contents are the same.
 8342:                 if ($stored_form ne $env{$envname}) {
 8343:                     $SaveHash{$basename} = $stored_form;
 8344:                     $AppHash{$envname}   = $stored_form;
 8345:                 }
 8346:             }
 8347:         }
 8348:     }
 8349:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8350:                                           $udom,$uname);
 8351:     if ($put_result !~ /^(ok|delayed)/) {
 8352:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8353:                                  'got error:'.$put_result);
 8354:     }
 8355:     # Make sure these settings stick around in this session, too
 8356:     &Apache::lonnet::appenv(\%AppHash);
 8357:     return;
 8358: }
 8359: 
 8360: sub restore_course_settings {
 8361:     return &restore_settings($env{'request.course.id'},@_);
 8362: }
 8363: 
 8364: sub restore_settings {
 8365:     my ($context,$prefix,$Settings) = @_;
 8366:     while (my ($setting,$type) = each(%$Settings)) {
 8367:         next if (exists($env{'form.'.$setting}));
 8368:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8369:             '.'.$setting;
 8370:         if (exists($env{$envname})) {
 8371:             if ($type eq 'scalar') {
 8372:                 $env{'form.'.$setting} = $env{$envname};
 8373:             } elsif ($type eq 'array') {
 8374:                 $env{'form.'.$setting} = [ 
 8375:                                            map { 
 8376:                                                &unescape($_); 
 8377:                                            } split(',',$env{$envname})
 8378:                                            ];
 8379:             }
 8380:         }
 8381:     }
 8382: }
 8383: 
 8384: #######################################################
 8385: #######################################################
 8386: 
 8387: =pod
 8388: 
 8389: =head1 Domain E-mail Routines  
 8390: 
 8391: =over 4
 8392: 
 8393: =item * &build_recipient_list()
 8394: 
 8395: Build recipient lists for three types of e-mail:
 8396: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
 8397: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
 8398: 
 8399: Inputs:
 8400: defmail (scalar - email address of default recipient), 
 8401: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8402: defdom (domain for which to retrieve configuration settings),
 8403: origmail (scalar - email address of recipient from loncapa.conf, 
 8404: i.e., predates configuration by DC via domainprefs.pm 
 8405: 
 8406: Returns: comma separated list of addresses to which to send e-mail.
 8407: 
 8408: =back
 8409: 
 8410: =cut
 8411: 
 8412: ############################################################
 8413: ############################################################
 8414: sub build_recipient_list {
 8415:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8416:     my @recipients;
 8417:     my $otheremails;
 8418:     my %domconfig =
 8419:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8420:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8421:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8422:             my @contacts = ('adminemail','supportemail');
 8423:             foreach my $item (@contacts) {
 8424:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
 8425:                     my $addr = $domconfig{'contacts'}{$item}; 
 8426:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
 8427:                         push(@recipients,$addr);
 8428:                     }
 8429:                 }
 8430:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8431:             }
 8432:         }
 8433:     } elsif ($origmail ne '') {
 8434:         push(@recipients,$origmail);
 8435:     }
 8436:     if (defined($defmail)) {
 8437:         if ($defmail ne '') {
 8438:             push(@recipients,$defmail);
 8439:         }
 8440:     }
 8441:     if ($otheremails) {
 8442:         my @others;
 8443:         if ($otheremails =~ /,/) {
 8444:             @others = split(/,/,$otheremails);
 8445:         } else {
 8446:             push(@others,$otheremails);
 8447:         }
 8448:         foreach my $addr (@others) {
 8449:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8450:                 push(@recipients,$addr);
 8451:             }
 8452:         }
 8453:     }
 8454:     my $recipientlist = join(',',@recipients); 
 8455:     return $recipientlist;
 8456: }
 8457: 
 8458: ############################################################
 8459: ############################################################
 8460: 
 8461: =pod
 8462: 
 8463: =head1 Course Catalog Routines
 8464: 
 8465: =over 4
 8466: 
 8467: =item * &gather_categories()
 8468: 
 8469: Converts category definitions - keys of categories hash stored in  
 8470: coursecategories in configuration.db on the primary library server in a 
 8471: domain - to an array.  Also generates javascript and idx hash used to 
 8472: generate Domain Coordinator interface for editing Course Categories.
 8473: 
 8474: Inputs:
 8475: 
 8476: categories (reference to hash of category definitions).
 8477: 
 8478: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8479:       categories and subcategories).
 8480: 
 8481: idx (reference to hash of counters used in Domain Coordinator interface for 
 8482:       editing Course Categories).
 8483: 
 8484: jsarray (reference to array of categories used to create Javascript arrays for
 8485:          Domain Coordinator interface for editing Course Categories).
 8486: 
 8487: Returns: nothing
 8488: 
 8489: Side effects: populates cats, idx and jsarray. 
 8490: 
 8491: =cut
 8492: 
 8493: sub gather_categories {
 8494:     my ($categories,$cats,$idx,$jsarray) = @_;
 8495:     my %counters;
 8496:     my $num = 0;
 8497:     foreach my $item (keys(%{$categories})) {
 8498:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8499:         if ($container eq '' && $depth == 0) {
 8500:             $cats->[$depth][$categories->{$item}] = $cat;
 8501:         } else {
 8502:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8503:         }
 8504:         my ($escitem,$tail) = split(/:/,$item,2);
 8505:         if ($counters{$tail} eq '') {
 8506:             $counters{$tail} = $num;
 8507:             $num ++;
 8508:         }
 8509:         if (ref($idx) eq 'HASH') {
 8510:             $idx->{$item} = $counters{$tail};
 8511:         }
 8512:         if (ref($jsarray) eq 'ARRAY') {
 8513:             push(@{$jsarray->[$counters{$tail}]},$item);
 8514:         }
 8515:     }
 8516:     return;
 8517: }
 8518: 
 8519: =pod
 8520: 
 8521: =item * &extract_categories()
 8522: 
 8523: Used to generate breadcrumb trails for course categories.
 8524: 
 8525: Inputs:
 8526: 
 8527: categories (reference to hash of category definitions).
 8528: 
 8529: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8530:       categories and subcategories).
 8531: 
 8532: trails (reference to array of breacrumb trails for each category).
 8533: 
 8534: allitems (reference to hash - key is category key 
 8535:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8536: 
 8537: idx (reference to hash of counters used in Domain Coordinator interface for
 8538:       editing Course Categories).
 8539: 
 8540: jsarray (reference to array of categories used to create Javascript arrays for
 8541:          Domain Coordinator interface for editing Course Categories).
 8542: 
 8543: subcats (reference to hash of arrays containing all subcategories within each 
 8544:          category, -recursive)
 8545: 
 8546: Returns: nothing
 8547: 
 8548: Side effects: populates trails and allitems hash references.
 8549: 
 8550: =cut
 8551: 
 8552: sub extract_categories {
 8553:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8554:     if (ref($categories) eq 'HASH') {
 8555:         &gather_categories($categories,$cats,$idx,$jsarray);
 8556:         if (ref($cats->[0]) eq 'ARRAY') {
 8557:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8558:                 my $name = $cats->[0][$i];
 8559:                 my $item = &escape($name).'::0';
 8560:                 my $trailstr;
 8561:                 if ($name eq 'instcode') {
 8562:                     $trailstr = &mt('Official courses (with institutional codes)');
 8563:                 } else {
 8564:                     $trailstr = $name;
 8565:                 }
 8566:                 if ($allitems->{$item} eq '') {
 8567:                     push(@{$trails},$trailstr);
 8568:                     $allitems->{$item} = scalar(@{$trails})-1;
 8569:                 }
 8570:                 my @parents = ($name);
 8571:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8572:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8573:                         my $category = $cats->[1]{$name}[$j];
 8574:                         if (ref($subcats) eq 'HASH') {
 8575:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8576:                         }
 8577:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8578:                     }
 8579:                 } else {
 8580:                     if (ref($subcats) eq 'HASH') {
 8581:                         $subcats->{$item} = [];
 8582:                     }
 8583:                 }
 8584:             }
 8585:         }
 8586:     }
 8587:     return;
 8588: }
 8589: 
 8590: =pod
 8591: 
 8592: =item *&recurse_categories()
 8593: 
 8594: Recursively used to generate breadcrumb trails for course categories.
 8595: 
 8596: Inputs:
 8597: 
 8598: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8599:       categories and subcategories).
 8600: 
 8601: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8602: 
 8603: category (current course category, for which breadcrumb trail is being generated).
 8604: 
 8605: trails (reference to array of breadcrumb trails for each category).
 8606: 
 8607: allitems (reference to hash - key is category key
 8608:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8609: 
 8610: parents (array containing containers directories for current category, 
 8611:          back to top level). 
 8612: 
 8613: Returns: nothing
 8614: 
 8615: Side effects: populates trails and allitems hash references
 8616: 
 8617: =cut
 8618: 
 8619: sub recurse_categories {
 8620:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 8621:     my $shallower = $depth - 1;
 8622:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8623:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8624:             my $name = $cats->[$depth]{$category}[$k];
 8625:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8626:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8627:             if ($allitems->{$item} eq '') {
 8628:                 push(@{$trails},$trailstr);
 8629:                 $allitems->{$item} = scalar(@{$trails})-1;
 8630:             }
 8631:             my $deeper = $depth+1;
 8632:             push(@{$parents},$category);
 8633:             if (ref($subcats) eq 'HASH') {
 8634:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 8635:                 for (my $j=@{$parents}; $j>=0; $j--) {
 8636:                     my $higher;
 8637:                     if ($j > 0) {
 8638:                         $higher = &escape($parents->[$j]).':'.
 8639:                                   &escape($parents->[$j-1]).':'.$j;
 8640:                     } else {
 8641:                         $higher = &escape($parents->[$j]).'::'.$j;
 8642:                     }
 8643:                     push(@{$subcats->{$higher}},$subcat);
 8644:                 }
 8645:             }
 8646:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 8647:                                 $subcats);
 8648:             pop(@{$parents});
 8649:         }
 8650:     } else {
 8651:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8652:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8653:         if ($allitems->{$item} eq '') {
 8654:             push(@{$trails},$trailstr);
 8655:             $allitems->{$item} = scalar(@{$trails})-1;
 8656:         }
 8657:     }
 8658:     return;
 8659: }
 8660: 
 8661: =pod
 8662: 
 8663: =item *&assign_categories_table()
 8664: 
 8665: Create a datatable for display of hierarchical categories in a domain,
 8666: with checkboxes to allow a course to be categorized. 
 8667: 
 8668: Inputs:
 8669: 
 8670: cathash - reference to hash of categories defined for the domain (from
 8671:           configuration.db)
 8672: 
 8673: currcat - scalar with an & separated list of categories assigned to a course. 
 8674: 
 8675: Returns: $output (markup to be displayed) 
 8676: 
 8677: =cut
 8678: 
 8679: sub assign_categories_table {
 8680:     my ($cathash,$currcat) = @_;
 8681:     my $output;
 8682:     if (ref($cathash) eq 'HASH') {
 8683:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 8684:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 8685:         $maxdepth = scalar(@cats);
 8686:         if (@cats > 0) {
 8687:             my $itemcount = 0;
 8688:             if (ref($cats[0]) eq 'ARRAY') {
 8689:                 $output = &Apache::loncommon::start_data_table();
 8690:                 my @currcategories;
 8691:                 if ($currcat ne '') {
 8692:                     @currcategories = split('&',$currcat);
 8693:                 }
 8694:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 8695:                     my $parent = $cats[0][$i];
 8696:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8697:                     next if ($parent eq 'instcode');
 8698:                     my $item = &escape($parent).'::0';
 8699:                     my $checked = '';
 8700:                     if (@currcategories > 0) {
 8701:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 8702:                             $checked = ' checked="checked" ';
 8703:                         }
 8704:                     }
 8705:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 8706:                                '<input type="checkbox" name="usecategory" value="'.
 8707:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 8708:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 8709:                     my $depth = 1;
 8710:                     push(@path,$parent);
 8711:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 8712:                     pop(@path);
 8713:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 8714:                     $itemcount ++;
 8715:                 }
 8716:                 $output .= &Apache::loncommon::end_data_table();
 8717:             }
 8718:         }
 8719:     }
 8720:     return $output;
 8721: }
 8722: 
 8723: =pod
 8724: 
 8725: =item *&assign_category_rows()
 8726: 
 8727: Create a datatable row for display of nested categories in a domain,
 8728: with checkboxes to allow a course to be categorized,called recursively.
 8729: 
 8730: Inputs:
 8731: 
 8732: itemcount - track row number for alternating colors
 8733: 
 8734: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 8735:       categories and subcategories.
 8736: 
 8737: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 8738: 
 8739: parent - parent of current category item
 8740: 
 8741: path - Array containing all categories back up through the hierarchy from the
 8742:        current category to the top level.
 8743: 
 8744: currcategories - reference to array of current categories assigned to the course
 8745: 
 8746: Returns: $output (markup to be displayed).
 8747: 
 8748: =cut
 8749: 
 8750: sub assign_category_rows {
 8751:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 8752:     my ($text,$name,$item,$chgstr);
 8753:     if (ref($cats) eq 'ARRAY') {
 8754:         my $maxdepth = scalar(@{$cats});
 8755:         if (ref($cats->[$depth]) eq 'HASH') {
 8756:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 8757:                 my $numchildren = @{$cats->[$depth]{$parent}};
 8758:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8759:                 $text .= '<td><table class="LC_datatable">';
 8760:                 for (my $j=0; $j<$numchildren; $j++) {
 8761:                     $name = $cats->[$depth]{$parent}[$j];
 8762:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 8763:                     my $deeper = $depth+1;
 8764:                     my $checked = '';
 8765:                     if (ref($currcategories) eq 'ARRAY') {
 8766:                         if (@{$currcategories} > 0) {
 8767:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 8768:                                 $checked = ' checked="checked" ';
 8769:                             }
 8770:                         }
 8771:                     }
 8772:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 8773:                              '<input type="checkbox" name="usecategory" value="'.
 8774:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 8775:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 8776:                              '</td><td>';
 8777:                     if (ref($path) eq 'ARRAY') {
 8778:                         push(@{$path},$name);
 8779:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 8780:                         pop(@{$path});
 8781:                     }
 8782:                     $text .= '</td></tr>';
 8783:                 }
 8784:                 $text .= '</table></td>';
 8785:             }
 8786:         }
 8787:     }
 8788:     return $text;
 8789: }
 8790: 
 8791: ############################################################
 8792: ############################################################
 8793: 
 8794: 
 8795: sub commit_customrole {
 8796:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 8797:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 8798:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 8799:                          ($end?', ending '.localtime($end):'').': <b>'.
 8800:               &Apache::lonnet::assigncustomrole(
 8801:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 8802:                  '</b><br />';
 8803:     return $output;
 8804: }
 8805: 
 8806: sub commit_standardrole {
 8807:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 8808:     my ($output,$logmsg,$linefeed);
 8809:     if ($context eq 'auto') {
 8810:         $linefeed = "\n";
 8811:     } else {
 8812:         $linefeed = "<br />\n";
 8813:     }  
 8814:     if ($three eq 'st') {
 8815:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 8816:                                          $one,$two,$sec,$context);
 8817:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 8818:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 8819:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 8820:         } else {
 8821:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 8822:                ($start?', '.&mt('starting').' '.localtime($start):'').
 8823:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 8824:             if ($context eq 'auto') {
 8825:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 8826:             } else {
 8827:                $output .= '<b>'.$result.'</b>'.$linefeed.
 8828:                &mt('Add to classlist').': <b>ok</b>';
 8829:             }
 8830:             $output .= $linefeed;
 8831:         }
 8832:     } else {
 8833:         $output = &mt('Assigning').' '.$three.' in '.$url.
 8834:                ($start?', '.&mt('starting').' '.localtime($start):'').
 8835:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 8836:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 8837:         if ($context eq 'auto') {
 8838:             $output .= $result.$linefeed;
 8839:         } else {
 8840:             $output .= '<b>'.$result.'</b>'.$linefeed;
 8841:         }
 8842:     }
 8843:     return $output;
 8844: }
 8845: 
 8846: sub commit_studentrole {
 8847:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 8848:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 8849:     if ($context eq 'auto') {
 8850:         $linefeed = "\n";
 8851:     } else {
 8852:         $linefeed = '<br />'."\n";
 8853:     }
 8854:     if (defined($one) && defined($two)) {
 8855:         my $cid=$one.'_'.$two;
 8856:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 8857:         my $secchange = 0;
 8858:         my $expire_role_result;
 8859:         my $modify_section_result;
 8860:         if ($oldsec ne '-1') { 
 8861:             if ($oldsec ne $sec) {
 8862:                 $secchange = 1;
 8863:                 my $now = time;
 8864:                 my $uurl='/'.$cid;
 8865:                 $uurl=~s/\_/\//g;
 8866:                 if ($oldsec) {
 8867:                     $uurl.='/'.$oldsec;
 8868:                 }
 8869:                 $oldsecurl = $uurl;
 8870:                 $expire_role_result = 
 8871:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 8872:                 if ($env{'request.course.sec'} ne '') { 
 8873:                     if ($expire_role_result eq 'refused') {
 8874:                         my @roles = ('st');
 8875:                         my @statuses = ('previous');
 8876:                         my @roledoms = ($one);
 8877:                         my $withsec = 1;
 8878:                         my %roleshash = 
 8879:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 8880:                                               \@statuses,\@roles,\@roledoms,$withsec);
 8881:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 8882:                             my ($oldstart,$oldend) = 
 8883:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 8884:                             if ($oldend > 0 && $oldend <= $now) {
 8885:                                 $expire_role_result = 'ok';
 8886:                             }
 8887:                         }
 8888:                     }
 8889:                 }
 8890:                 $result = $expire_role_result;
 8891:             }
 8892:         }
 8893:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 8894:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 8895:             if ($modify_section_result =~ /^ok/) {
 8896:                 if ($secchange == 1) {
 8897:                     if ($sec eq '') {
 8898:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 8899:                     } else {
 8900:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 8901:                     }
 8902:                 } elsif ($oldsec eq '-1') {
 8903:                     if ($sec eq '') {
 8904:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 8905:                     } else {
 8906:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8907:                     }
 8908:                 } else {
 8909:                     if ($sec eq '') {
 8910:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 8911:                     } else {
 8912:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 8913:                     }
 8914:                 }
 8915:             } else {
 8916:                 if ($secchange) {       
 8917:                     $$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;
 8918:                 } else {
 8919:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 8920:                 }
 8921:             }
 8922:             $result = $modify_section_result;
 8923:         } elsif ($secchange == 1) {
 8924:             if ($oldsec eq '') {
 8925:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 8926:             } else {
 8927:                 $$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;
 8928:             }
 8929:             if ($expire_role_result eq 'refused') {
 8930:                 my $newsecurl = '/'.$cid;
 8931:                 $newsecurl =~ s/\_/\//g;
 8932:                 if ($sec ne '') {
 8933:                     $newsecurl.='/'.$sec;
 8934:                 }
 8935:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 8936:                     if ($sec eq '') {
 8937:                         $$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;
 8938:                     } else {
 8939:                         $$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;
 8940:                     }
 8941:                 }
 8942:             }
 8943:         }
 8944:     } else {
 8945:         $$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;
 8946:         $result = "error: incomplete course id\n";
 8947:     }
 8948:     return $result;
 8949: }
 8950: 
 8951: ############################################################
 8952: ############################################################
 8953: 
 8954: sub check_clone {
 8955:     my ($args,$linefeed) = @_;
 8956:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 8957:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 8958:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 8959:     my $clonemsg;
 8960:     my $can_clone = 0;
 8961: 
 8962:     if ($clonehome eq 'no_host') {
 8963:         $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'});     
 8964:     } else {
 8965: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 8966: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 8967: 	    $can_clone = 1;
 8968: 	} else {
 8969: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 8970: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 8971: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 8972:             if (grep(/^\*$/,@cloners)) {
 8973:                 $can_clone = 1;
 8974:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 8975:                 $can_clone = 1;
 8976:             } else {
 8977: 	        my %roleshash =
 8978: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 8979: 					 $args->{'ccdomain'},
 8980:                                          'userroles',['active'],['cc'],
 8981: 					 [$args->{'clonedomain'}]);
 8982: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 8983: 		    $can_clone = 1;
 8984: 	        } else {
 8985:                     $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'});
 8986: 	        }
 8987: 	    }
 8988:         }
 8989:     }
 8990:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 8991: }
 8992: 
 8993: sub construct_course {
 8994:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 8995:     my $outcome;
 8996:     my $linefeed =  '<br />'."\n";
 8997:     if ($context eq 'auto') {
 8998:         $linefeed = "\n";
 8999:     }
 9000: 
 9001: #
 9002: # Are we cloning?
 9003: #
 9004:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9005:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9006: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9007: 	if ($context ne 'auto') {
 9008:             if ($clonemsg ne '') {
 9009: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9010:             }
 9011: 	}
 9012: 	$outcome .= $clonemsg.$linefeed;
 9013: 
 9014:         if (!$can_clone) {
 9015: 	    return (0,$outcome);
 9016: 	}
 9017:     }
 9018: 
 9019: #
 9020: # Open course
 9021: #
 9022:     my $crstype = lc($args->{'crstype'});
 9023:     my %cenv=();
 9024:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9025:                                              $args->{'cdescr'},
 9026:                                              $args->{'curl'},
 9027:                                              $args->{'course_home'},
 9028:                                              $args->{'nonstandard'},
 9029:                                              $args->{'crscode'},
 9030:                                              $args->{'ccuname'}.':'.
 9031:                                              $args->{'ccdomain'},
 9032:                                              $args->{'crstype'});
 9033: 
 9034:     # Note: The testing routines depend on this being output; see 
 9035:     # Utils::Course. This needs to at least be output as a comment
 9036:     # if anyone ever decides to not show this, and Utils::Course::new
 9037:     # will need to be suitably modified.
 9038:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9039: #
 9040: # Check if created correctly
 9041: #
 9042:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9043:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9044:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9045: 
 9046: #
 9047: # Do the cloning
 9048: #   
 9049:     if ($can_clone && $cloneid) {
 9050: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9051: 	if ($context ne 'auto') {
 9052: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9053: 	}
 9054: 	$outcome .= $clonemsg.$linefeed;
 9055: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9056: # Copy all files
 9057: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9058: # Restore URL
 9059: 	$cenv{'url'}=$oldcenv{'url'};
 9060: # Restore title
 9061: 	$cenv{'description'}=$oldcenv{'description'};
 9062: # Mark as cloned
 9063: 	$cenv{'clonedfrom'}=$cloneid;
 9064: # Need to clone grading mode
 9065:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9066:         $cenv{'grading'}=$newenv{'grading'};
 9067: # Do not clone these environment entries
 9068:         &Apache::lonnet::del('environment',
 9069:                   ['default_enrollment_start_date',
 9070:                    'default_enrollment_end_date',
 9071:                    'question.email',
 9072:                    'policy.email',
 9073:                    'comment.email',
 9074:                    'pch.users.denied',
 9075:                    'plc.users.denied',
 9076:                    'hidefromcat',
 9077:                    'categories'],
 9078:                    $$crsudom,$$crsunum);
 9079:     }
 9080: 
 9081: #
 9082: # Set environment (will override cloned, if existing)
 9083: #
 9084:     my @sections = ();
 9085:     my @xlists = ();
 9086:     if ($args->{'crstype'}) {
 9087:         $cenv{'type'}=$args->{'crstype'};
 9088:     }
 9089:     if ($args->{'crsid'}) {
 9090:         $cenv{'courseid'}=$args->{'crsid'};
 9091:     }
 9092:     if ($args->{'crscode'}) {
 9093:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9094:     }
 9095:     if ($args->{'crsquota'} ne '') {
 9096:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9097:     } else {
 9098:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9099:     }
 9100:     if ($args->{'ccuname'}) {
 9101:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9102:                                         ':'.$args->{'ccdomain'};
 9103:     } else {
 9104:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9105:     }
 9106:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9107:     if ($args->{'crssections'}) {
 9108:         $cenv{'internal.sectionnums'} = '';
 9109:         if ($args->{'crssections'} =~ m/,/) {
 9110:             @sections = split/,/,$args->{'crssections'};
 9111:         } else {
 9112:             $sections[0] = $args->{'crssections'};
 9113:         }
 9114:         if (@sections > 0) {
 9115:             foreach my $item (@sections) {
 9116:                 my ($sec,$gp) = split/:/,$item;
 9117:                 my $class = $args->{'crscode'}.$sec;
 9118:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9119:                 $cenv{'internal.sectionnums'} .= $item.',';
 9120:                 unless ($addcheck eq 'ok') {
 9121:                     push @badclasses, $class;
 9122:                 }
 9123:             }
 9124:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9125:         }
 9126:     }
 9127: # do not hide course coordinator from staff listing, 
 9128: # even if privileged
 9129:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9130: # add crosslistings
 9131:     if ($args->{'crsxlist'}) {
 9132:         $cenv{'internal.crosslistings'}='';
 9133:         if ($args->{'crsxlist'} =~ m/,/) {
 9134:             @xlists = split/,/,$args->{'crsxlist'};
 9135:         } else {
 9136:             $xlists[0] = $args->{'crsxlist'};
 9137:         }
 9138:         if (@xlists > 0) {
 9139:             foreach my $item (@xlists) {
 9140:                 my ($xl,$gp) = split/:/,$item;
 9141:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9142:                 $cenv{'internal.crosslistings'} .= $item.',';
 9143:                 unless ($addcheck eq 'ok') {
 9144:                     push @badclasses, $xl;
 9145:                 }
 9146:             }
 9147:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9148:         }
 9149:     }
 9150:     if ($args->{'autoadds'}) {
 9151:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9152:     }
 9153:     if ($args->{'autodrops'}) {
 9154:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9155:     }
 9156: # check for notification of enrollment changes
 9157:     my @notified = ();
 9158:     if ($args->{'notify_owner'}) {
 9159:         if ($args->{'ccuname'} ne '') {
 9160:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9161:         }
 9162:     }
 9163:     if ($args->{'notify_dc'}) {
 9164:         if ($uname ne '') { 
 9165:             push(@notified,$uname.':'.$udom);
 9166:         }
 9167:     }
 9168:     if (@notified > 0) {
 9169:         my $notifylist;
 9170:         if (@notified > 1) {
 9171:             $notifylist = join(',',@notified);
 9172:         } else {
 9173:             $notifylist = $notified[0];
 9174:         }
 9175:         $cenv{'internal.notifylist'} = $notifylist;
 9176:     }
 9177:     if (@badclasses > 0) {
 9178:         my %lt=&Apache::lonlocal::texthash(
 9179:                 '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',
 9180:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9181:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9182:         );
 9183:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9184:                            ' ('.$lt{'adby'}.')';
 9185:         if ($context eq 'auto') {
 9186:             $outcome .= $badclass_msg.$linefeed;
 9187:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9188:             foreach my $item (@badclasses) {
 9189:                 if ($context eq 'auto') {
 9190:                     $outcome .= " - $item\n";
 9191:                 } else {
 9192:                     $outcome .= "<li>$item</li>\n";
 9193:                 }
 9194:             }
 9195:             if ($context eq 'auto') {
 9196:                 $outcome .= $linefeed;
 9197:             } else {
 9198:                 $outcome .= "</ul><br /><br /></div>\n";
 9199:             }
 9200:         } 
 9201:     }
 9202:     if ($args->{'no_end_date'}) {
 9203:         $args->{'endaccess'} = 0;
 9204:     }
 9205:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9206:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9207:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9208:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9209:     if ($args->{'showphotos'}) {
 9210:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9211:     }
 9212:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9213:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9214:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9215:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9216:             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'); 
 9217:             if ($context eq 'auto') {
 9218:                 $outcome .= $krb_msg;
 9219:             } else {
 9220:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9221:             }
 9222:             $outcome .= $linefeed;
 9223:         }
 9224:     }
 9225:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9226:        if ($args->{'setpolicy'}) {
 9227:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9228:        }
 9229:        if ($args->{'setcontent'}) {
 9230:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9231:        }
 9232:     }
 9233:     if ($args->{'reshome'}) {
 9234: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9235: 	$cenv{'reshome'}=~s/\/+$/\//;
 9236:     }
 9237: #
 9238: # course has keyed access
 9239: #
 9240:     if ($args->{'setkeys'}) {
 9241:        $cenv{'keyaccess'}='yes';
 9242:     }
 9243: # if specified, key authority is not course, but user
 9244: # only active if keyaccess is yes
 9245:     if ($args->{'keyauth'}) {
 9246: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9247: 	$user = &LONCAPA::clean_username($user);
 9248: 	$domain = &LONCAPA::clean_username($domain);
 9249: 	if ($user ne '' && $domain ne '') {
 9250: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9251: 	}
 9252:     }
 9253: 
 9254:     if ($args->{'disresdis'}) {
 9255:         $cenv{'pch.roles.denied'}='st';
 9256:     }
 9257:     if ($args->{'disablechat'}) {
 9258:         $cenv{'plc.roles.denied'}='st';
 9259:     }
 9260: 
 9261:     # Record we've not yet viewed the Course Initialization Helper for this 
 9262:     # course
 9263:     $cenv{'course.helper.not.run'} = 1;
 9264:     #
 9265:     # Use new Randomseed
 9266:     #
 9267:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9268:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9269:     #
 9270:     # The encryption code and receipt prefix for this course
 9271:     #
 9272:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9273:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9274:     #
 9275:     # By default, use standard grading
 9276:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9277: 
 9278:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9279:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9280: #
 9281: # Open all assignments
 9282: #
 9283:     if ($args->{'openall'}) {
 9284:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9285:        my %storecontent = ($storeunder         => time,
 9286:                            $storeunder.'.type' => 'date_start');
 9287:        
 9288:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9289:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9290:    }
 9291: #
 9292: # Set first page
 9293: #
 9294:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9295: 	    || ($cloneid)) {
 9296: 	use LONCAPA::map;
 9297: 	$outcome .= &mt('Setting first resource').': ';
 9298: 
 9299: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9300:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9301: 
 9302:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9303:         my $title; my $url;
 9304:         if ($args->{'firstres'} eq 'syl') {
 9305: 	    $title=&mt('Syllabus');
 9306:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9307:         } else {
 9308:             $title=&mt('Navigate Contents');
 9309:             $url='/adm/navmaps';
 9310:         }
 9311: 
 9312:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9313: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9314: 
 9315: 	if ($errtext) { $fatal=2; }
 9316:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9317:     }
 9318: 
 9319:     return (1,$outcome);
 9320: }
 9321: 
 9322: ############################################################
 9323: ############################################################
 9324: 
 9325: sub course_type {
 9326:     my ($cid) = @_;
 9327:     if (!defined($cid)) {
 9328:         $cid = $env{'request.course.id'};
 9329:     }
 9330:     if (defined($env{'course.'.$cid.'.type'})) {
 9331:         return $env{'course.'.$cid.'.type'};
 9332:     } else {
 9333:         return 'Course';
 9334:     }
 9335: }
 9336: 
 9337: sub group_term {
 9338:     my $crstype = &course_type();
 9339:     my %names = (
 9340:                   'Course' => 'group',
 9341:                   'Group' => 'team',
 9342:                 );
 9343:     return $names{$crstype};
 9344: }
 9345: 
 9346: sub icon {
 9347:     my ($file)=@_;
 9348:     my $curfext = lc((split(/\./,$file))[-1]);
 9349:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9350:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9351:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9352: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9353: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9354: 	            $curfext.".gif") {
 9355: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9356: 		$curfext.".gif";
 9357: 	}
 9358:     }
 9359:     return &lonhttpdurl($iconname);
 9360: } 
 9361: 
 9362: sub lonhttpdurl {
 9363: #
 9364: # Had been used for "small fry" static images on separate port 8080.
 9365: # Modify here if lightweight http functionality desired again.
 9366: # Currently eliminated due to increasing firewall issues.
 9367: #
 9368:     my ($url)=@_;
 9369:     return $url;
 9370: }
 9371: 
 9372: sub connection_aborted {
 9373:     my ($r)=@_;
 9374:     $r->print(" ");$r->rflush();
 9375:     my $c = $r->connection;
 9376:     return $c->aborted();
 9377: }
 9378: 
 9379: #    Escapes strings that may have embedded 's that will be put into
 9380: #    strings as 'strings'.
 9381: sub escape_single {
 9382:     my ($input) = @_;
 9383:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9384:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9385:     return $input;
 9386: }
 9387: 
 9388: #  Same as escape_single, but escape's "'s  This 
 9389: #  can be used for  "strings"
 9390: sub escape_double {
 9391:     my ($input) = @_;
 9392:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9393:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9394:     return $input;
 9395: }
 9396:  
 9397: #   Escapes the last element of a full URL.
 9398: sub escape_url {
 9399:     my ($url)   = @_;
 9400:     my @urlslices = split(/\//, $url,-1);
 9401:     my $lastitem = &escape(pop(@urlslices));
 9402:     return join('/',@urlslices).'/'.$lastitem;
 9403: }
 9404: 
 9405: # -------------------------------------------------------- Initliaze user login
 9406: sub init_user_environment {
 9407:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9408:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9409: 
 9410:     my $public=($username eq 'public' && $domain eq 'public');
 9411: 
 9412: # See if old ID present, if so, remove
 9413: 
 9414:     my ($filename,$cookie,$userroles);
 9415:     my $now=time;
 9416: 
 9417:     if ($public) {
 9418: 	my $max_public=100;
 9419: 	my $oldest;
 9420: 	my $oldest_time=0;
 9421: 	for(my $next=1;$next<=$max_public;$next++) {
 9422: 	    if (-e $lonids."/publicuser_$next.id") {
 9423: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9424: 		if ($mtime<$oldest_time || !$oldest_time) {
 9425: 		    $oldest_time=$mtime;
 9426: 		    $oldest=$next;
 9427: 		}
 9428: 	    } else {
 9429: 		$cookie="publicuser_$next";
 9430: 		last;
 9431: 	    }
 9432: 	}
 9433: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9434:     } else {
 9435: 	# if this isn't a robot, kill any existing non-robot sessions
 9436: 	if (!$args->{'robot'}) {
 9437: 	    opendir(DIR,$lonids);
 9438: 	    while ($filename=readdir(DIR)) {
 9439: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9440: 		    unlink($lonids.'/'.$filename);
 9441: 		}
 9442: 	    }
 9443: 	    closedir(DIR);
 9444: 	}
 9445: # Give them a new cookie
 9446: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9447: 		                   : $now.$$.int(rand(10000)));
 9448: 	$cookie="$username\_$id\_$domain\_$authhost";
 9449:     
 9450: # Initialize roles
 9451: 
 9452: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9453:     }
 9454: # ------------------------------------ Check browser type and MathML capability
 9455: 
 9456:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9457:         $clientunicode,$clientos) = &decode_user_agent($r);
 9458: 
 9459: # -------------------------------------- Any accessibility options to remember?
 9460:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9461: 	foreach my $option ('imagesuppress','appletsuppress',
 9462: 			    'embedsuppress','fontenhance','blackwhite') {
 9463: 	    if ($form->{$option} eq 'true') {
 9464: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9465: 				     $domain,$username);
 9466: 	    } else {
 9467: 		&Apache::lonnet::del('environment',[$option],
 9468: 				     $domain,$username);
 9469: 	    }
 9470: 	}
 9471:     }
 9472: # ------------------------------------------------------------- Get environment
 9473: 
 9474:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9475:     my ($tmp) = keys(%userenv);
 9476:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9477: 	# default remote control to off
 9478: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9479:     } else {
 9480: 	undef(%userenv);
 9481:     }
 9482:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9483: 	$form->{'interface'}=$userenv{'interface'};
 9484:     }
 9485:     $env{'environment.remote'}=$userenv{'remote'};
 9486:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9487: 
 9488: # --------------- Do not trust query string to be put directly into environment
 9489:     foreach my $option ('imagesuppress','appletsuppress',
 9490: 			'embedsuppress','fontenhance','blackwhite',
 9491: 			'interface','localpath','localres') {
 9492: 	$form->{$option}=~s/[\n\r\=]//gs;
 9493:     }
 9494: # --------------------------------------------------------- Write first profile
 9495: 
 9496:     {
 9497: 	my %initial_env = 
 9498: 	    ("user.name"          => $username,
 9499: 	     "user.domain"        => $domain,
 9500: 	     "user.home"          => $authhost,
 9501: 	     "browser.type"       => $clientbrowser,
 9502: 	     "browser.version"    => $clientversion,
 9503: 	     "browser.mathml"     => $clientmathml,
 9504: 	     "browser.unicode"    => $clientunicode,
 9505: 	     "browser.os"         => $clientos,
 9506: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9507: 	     "request.course.fn"  => '',
 9508: 	     "request.course.uri" => '',
 9509: 	     "request.course.sec" => '',
 9510: 	     "request.role"       => 'cm',
 9511: 	     "request.role.adv"   => $env{'user.adv'},
 9512: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9513: 
 9514:         if ($form->{'localpath'}) {
 9515: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9516: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9517:         }
 9518: 	
 9519: 	if ($public) {
 9520: 	    $initial_env{"environment.remote"} = "off";
 9521: 	}
 9522: 	if ($form->{'interface'}) {
 9523: 	    $form->{'interface'}=~s/\W//gs;
 9524: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9525: 	    $env{'browser.interface'}=$form->{'interface'};
 9526: 	    foreach my $option ('imagesuppress','appletsuppress',
 9527: 				'embedsuppress','fontenhance','blackwhite') {
 9528: 		if (($form->{$option} eq 'true') ||
 9529: 		    ($userenv{$option} eq 'on')) {
 9530: 		    $initial_env{"browser.$option"} = "on";
 9531: 		}
 9532: 	    }
 9533: 	}
 9534: 
 9535:         foreach my $tool ('aboutme','blog','portfolio') {
 9536:             $userenv{'availabletools.'.$tool} = 
 9537:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
 9538:         }
 9539: 
 9540: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9541: 	
 9542: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9543: 		 &GDBM_WRCREAT(),0640)) {
 9544: 	    &_add_to_env(\%disk_env,\%initial_env);
 9545: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9546: 	    &_add_to_env(\%disk_env,$userroles);
 9547: 	    if (ref($args->{'extra_env'})) {
 9548: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9549: 	    }
 9550: 	    untie(%disk_env);
 9551: 	} else {
 9552: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 9553: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 9554: 	    return 'error: '.$!;
 9555: 	}
 9556:     }
 9557:     $env{'request.role'}='cm';
 9558:     $env{'request.role.adv'}=$env{'user.adv'};
 9559:     $env{'browser.type'}=$clientbrowser;
 9560: 
 9561:     return $cookie;
 9562: 
 9563: }
 9564: 
 9565: sub _add_to_env {
 9566:     my ($idf,$env_data,$prefix) = @_;
 9567:     if (ref($env_data) eq 'HASH') {
 9568:         while (my ($key,$value) = each(%$env_data)) {
 9569: 	    $idf->{$prefix.$key} = $value;
 9570: 	    $env{$prefix.$key}   = $value;
 9571:         }
 9572:     }
 9573: }
 9574: 
 9575: # --- Get the symbolic name of a problem and the url
 9576: sub get_symb {
 9577:     my ($request,$silent) = @_;
 9578:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9579:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
 9580:     if ($symb eq '') {
 9581:         if (!$silent) {
 9582:             $request->print("Unable to handle ambiguous references:$url:.");
 9583:             return ();
 9584:         }
 9585:     }
 9586:     &Apache::lonenc::check_decrypt(\$symb);
 9587:     return ($symb);
 9588: }
 9589: 
 9590: # --------------------------------------------------------------Get annotation
 9591: 
 9592: sub get_annotation {
 9593:     my ($symb,$enc) = @_;
 9594: 
 9595:     my $key = $symb;
 9596:     if (!$enc) {
 9597:         $key =
 9598:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 9599:     }
 9600:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
 9601:     return $annotation{$key};
 9602: }
 9603: 
 9604: sub clean_symb {
 9605:     my ($symb,$delete_enc) = @_;
 9606: 
 9607:     &Apache::lonenc::check_decrypt(\$symb);
 9608:     my $enc = $env{'request.enc'};
 9609:     if ($delete_enc) {
 9610:         delete($env{'request.enc'});
 9611:     }
 9612: 
 9613:     return ($symb,$enc);
 9614: }
 9615: 
 9616: =pod
 9617: 
 9618: =back
 9619: 
 9620: =cut
 9621: 
 9622: 1;
 9623: __END__;
 9624: 

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