File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1034: download - view: text, annotated - select for diffs
Fri Dec 9 01:04:27 2011 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Fix wishlist link in lonindexer
Eliminate some popups in favor of modal windows

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1034 2011/12/09 01:04:27 www 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:              "<span style='color:yellow;'>INFO: Read file types</span>");
  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: // <![CDATA[
  411:     var stdeditbrowser;
  412:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  413:         var url = '/adm/pickstudent?';
  414:         var filter;
  415: 	if (!ignorefilter) {
  416: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  417: 	}
  418:         if (filter != null) {
  419:            if (filter != '') {
  420:                url += 'filter='+filter+'&';
  421: 	   }
  422:         }
  423:         url += 'form=' + formname + '&unameelement='+uname+
  424:                                     '&udomelement='+udom+
  425:                                     '&clicker='+clicker;
  426: 	if (roleflag) { url+="&roles=1"; }
  427:         if (courseadvonly) { url+="&courseadvonly=1"; }
  428:         var title = 'Student_Browser';
  429:         var options = 'scrollbars=1,resizable=1,menubar=0';
  430:         options += ',width=700,height=600';
  431:         stdeditbrowser = open(url,title,options,'1');
  432:         stdeditbrowser.focus();
  433:     }
  434: // ]]>
  435: </script>
  436: ENDSTDBRW
  437: }
  438: 
  439: sub resourcebrowser_javascript {
  440:    unless ($env{'request.course.id'}) { return ''; }
  441:    return (<<'ENDRESBRW');
  442: <script type="text/javascript" language="Javascript">
  443: // <![CDATA[
  444:     var reseditbrowser;
  445:     function openresbrowser(formname,reslink) {
  446:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  447:         var title = 'Resource_Browser';
  448:         var options = 'scrollbars=1,resizable=1,menubar=0';
  449:         options += ',width=700,height=500';
  450:         reseditbrowser = open(url,title,options,'1');
  451:         reseditbrowser.focus();
  452:     }
  453: // ]]>
  454: </script>
  455: ENDRESBRW
  456: }
  457: 
  458: sub selectstudent_link {
  459:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  460:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  461:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  462:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  463:    if ($env{'request.course.id'}) {  
  464:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  465: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  466: 					'/'.$env{'request.course.sec'})) {
  467: 	   return '';
  468:        }
  469:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  470:        if ($courseadvonly)  {
  471:            $callargs .= ",'',1,1";
  472:        }
  473:        return '<span class="LC_nobreak">'.
  474:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  475:               &mt('Select User').'</a></span>';
  476:    }
  477:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  478:        $callargs .= ",'',1"; 
  479:        return '<span class="LC_nobreak">'.
  480:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  481:               &mt('Select User').'</a></span>';
  482:    }
  483:    return '';
  484: }
  485: 
  486: sub selectresource_link {
  487:    my ($form,$reslink,$arg)=@_;
  488:    
  489:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  490:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  491:    unless ($env{'request.course.id'}) { return $arg; }
  492:    return '<span class="LC_nobreak">'.
  493:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  494:               $arg.'</a></span>';
  495: }
  496: 
  497: 
  498: 
  499: sub authorbrowser_javascript {
  500:     return <<"ENDAUTHORBRW";
  501: <script type="text/javascript" language="JavaScript">
  502: // <![CDATA[
  503: var stdeditbrowser;
  504: 
  505: function openauthorbrowser(formname,udom) {
  506:     var url = '/adm/pickauthor?';
  507:     url += 'form='+formname+'&roledom='+udom;
  508:     var title = 'Author_Browser';
  509:     var options = 'scrollbars=1,resizable=1,menubar=0';
  510:     options += ',width=700,height=600';
  511:     stdeditbrowser = open(url,title,options,'1');
  512:     stdeditbrowser.focus();
  513: }
  514: 
  515: // ]]>
  516: </script>
  517: ENDAUTHORBRW
  518: }
  519: 
  520: sub coursebrowser_javascript {
  521:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  522:     my $wintitle = 'Course_Browser';
  523:     if ($crstype eq 'Community') {
  524:         $wintitle = 'Community_Browser';
  525:     }
  526:     my $id_functions = &javascript_index_functions();
  527:     my $output = '
  528: <script type="text/javascript" language="JavaScript">
  529: // <![CDATA[
  530:     var stdeditbrowser;'."\n";
  531: 
  532:     $output .= <<"ENDSTDBRW";
  533:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  534:         var url = '/adm/pickcourse?';
  535:         var formid = getFormIdByName(formname);
  536:         var domainfilter = getDomainFromSelectbox(formname,udom);
  537:         if (domainfilter != null) {
  538:            if (domainfilter != '') {
  539:                url += 'domainfilter='+domainfilter+'&';
  540: 	   }
  541:         }
  542:         url += 'form=' + formname + '&cnumelement='+uname+
  543: 	                            '&cdomelement='+udom+
  544:                                     '&cnameelement='+desc;
  545:         if (extra_element !=null && extra_element != '') {
  546:             if (formname == 'rolechoice' || formname == 'studentform') {
  547:                 url += '&roleelement='+extra_element;
  548:                 if (domainfilter == null || domainfilter == '') {
  549:                     url += '&domainfilter='+extra_element;
  550:                 }
  551:             }
  552:             else {
  553:                 if (formname == 'portform') {
  554:                     url += '&setroles='+extra_element;
  555:                 } else {
  556:                     if (formname == 'rules') {
  557:                         url += '&fixeddom='+extra_element; 
  558:                     }
  559:                 }
  560:             }     
  561:         }
  562:         if (type != null && type != '') {
  563:             url += '&type='+type;
  564:         }
  565:         if (type_elem != null && type_elem != '') {
  566:             url += '&typeelement='+type_elem;
  567:         }
  568:         if (formname == 'ccrs') {
  569:             var ownername = document.forms[formid].ccuname.value;
  570:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  571:             url += '&cloner='+ownername+':'+ownerdom;
  572:         }
  573:         if (multflag !=null && multflag != '') {
  574:             url += '&multiple='+multflag;
  575:         }
  576:         var title = '$wintitle';
  577:         var options = 'scrollbars=1,resizable=1,menubar=0';
  578:         options += ',width=700,height=600';
  579:         stdeditbrowser = open(url,title,options,'1');
  580:         stdeditbrowser.focus();
  581:     }
  582: $id_functions
  583: ENDSTDBRW
  584:     if (($sec_element ne '') || ($role_element ne '')) {
  585:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  586:     }
  587:     $output .= '
  588: // ]]>
  589: </script>';
  590:     return $output;
  591: }
  592: 
  593: sub javascript_index_functions {
  594:     return <<"ENDJS";
  595: 
  596: function getFormIdByName(formname) {
  597:     for (var i=0;i<document.forms.length;i++) {
  598:         if (document.forms[i].name == formname) {
  599:             return i;
  600:         }
  601:     }
  602:     return -1;
  603: }
  604: 
  605: function getIndexByName(formid,item) {
  606:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  607:         if (document.forms[formid].elements[i].name == item) {
  608:             return i;
  609:         }
  610:     }
  611:     return -1;
  612: }
  613: 
  614: function getDomainFromSelectbox(formname,udom) {
  615:     var userdom;
  616:     var formid = getFormIdByName(formname);
  617:     if (formid > -1) {
  618:         var domid = getIndexByName(formid,udom);
  619:         if (domid > -1) {
  620:             if (document.forms[formid].elements[domid].type == 'select-one') {
  621:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  622:             }
  623:             if (document.forms[formid].elements[domid].type == 'hidden') {
  624:                 userdom=document.forms[formid].elements[domid].value;
  625:             }
  626:         }
  627:     }
  628:     return userdom;
  629: }
  630: 
  631: ENDJS
  632: 
  633: }
  634: 
  635: sub javascript_array_indexof {
  636:     return <<ENDJS;
  637: <script type="text/javascript" language="JavaScript">
  638: // <![CDATA[
  639: 
  640: if (!Array.prototype.indexOf) {
  641:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  642:         "use strict";
  643:         if (this === void 0 || this === null) {
  644:             throw new TypeError();
  645:         }
  646:         var t = Object(this);
  647:         var len = t.length >>> 0;
  648:         if (len === 0) {
  649:             return -1;
  650:         }
  651:         var n = 0;
  652:         if (arguments.length > 0) {
  653:             n = Number(arguments[1]);
  654:             if (n !== n) { // shortcut for verifying if it's NaN
  655:                 n = 0;
  656:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  657:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  658:             }
  659:         }
  660:         if (n >= len) {
  661:             return -1;
  662:         }
  663:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  664:         for (; k < len; k++) {
  665:             if (k in t && t[k] === searchElement) {
  666:                 return k;
  667:             }
  668:         }
  669:         return -1;
  670:     }
  671: }
  672: 
  673: // ]]>
  674: </script>
  675: 
  676: ENDJS
  677: 
  678: }
  679: 
  680: sub userbrowser_javascript {
  681:     my $id_functions = &javascript_index_functions();
  682:     return <<"ENDUSERBRW";
  683: 
  684: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  685:     var url = '/adm/pickuser?';
  686:     var userdom = getDomainFromSelectbox(formname,udom);
  687:     if (userdom != null) {
  688:        if (userdom != '') {
  689:            url += 'srchdom='+userdom+'&';
  690:        }
  691:     }
  692:     url += 'form=' + formname + '&unameelement='+uname+
  693:                                 '&udomelement='+udom+
  694:                                 '&ulastelement='+ulast+
  695:                                 '&ufirstelement='+ufirst+
  696:                                 '&uemailelement='+uemail+
  697:                                 '&hideudomelement='+hideudom+
  698:                                 '&coursedom='+crsdom;
  699:     if ((caller != null) && (caller != undefined)) {
  700:         url += '&caller='+caller;
  701:     }
  702:     var title = 'User_Browser';
  703:     var options = 'scrollbars=1,resizable=1,menubar=0';
  704:     options += ',width=700,height=600';
  705:     var stdeditbrowser = open(url,title,options,'1');
  706:     stdeditbrowser.focus();
  707: }
  708: 
  709: function fix_domain (formname,udom,origdom,uname) {
  710:     var formid = getFormIdByName(formname);
  711:     if (formid > -1) {
  712:         var unameid = getIndexByName(formid,uname);
  713:         var domid = getIndexByName(formid,udom);
  714:         var hidedomid = getIndexByName(formid,origdom);
  715:         if (hidedomid > -1) {
  716:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  717:             var unameval = document.forms[formid].elements[unameid].value;
  718:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  719:                 if (domid > -1) {
  720:                     var slct = document.forms[formid].elements[domid];
  721:                     if (slct.type == 'select-one') {
  722:                         var i;
  723:                         for (i=0;i<slct.length;i++) {
  724:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  725:                         }
  726:                     }
  727:                     if (slct.type == 'hidden') {
  728:                         slct.value = fixeddom;
  729:                     }
  730:                 }
  731:             }
  732:         }
  733:     }
  734:     return;
  735: }
  736: 
  737: $id_functions
  738: ENDUSERBRW
  739: }
  740: 
  741: sub setsec_javascript {
  742:     my ($sec_element,$formname,$role_element) = @_;
  743:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  744:         $communityrolestr);
  745:     if ($role_element ne '') {
  746:         my @allroles = ('st','ta','ep','in','ad');
  747:         foreach my $crstype ('Course','Community') {
  748:             if ($crstype eq 'Community') {
  749:                 foreach my $role (@allroles) {
  750:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  751:                 }
  752:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  753:             } else {
  754:                 foreach my $role (@allroles) {
  755:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  756:                 }
  757:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  758:             }
  759:         }
  760:         $rolestr = '"'.join('","',@allroles).'"';
  761:         $courserolestr = '"'.join('","',@courserolenames).'"';
  762:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  763:     }
  764:     my $setsections = qq|
  765: function setSect(sectionlist) {
  766:     var sectionsArray = new Array();
  767:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  768:         sectionsArray = sectionlist.split(",");
  769:     }
  770:     var numSections = sectionsArray.length;
  771:     document.$formname.$sec_element.length = 0;
  772:     if (numSections == 0) {
  773:         document.$formname.$sec_element.multiple=false;
  774:         document.$formname.$sec_element.size=1;
  775:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  776:     } else {
  777:         if (numSections == 1) {
  778:             document.$formname.$sec_element.multiple=false;
  779:             document.$formname.$sec_element.size=1;
  780:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  781:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  782:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  783:         } else {
  784:             for (var i=0; i<numSections; i++) {
  785:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  786:             }
  787:             document.$formname.$sec_element.multiple=true
  788:             if (numSections < 3) {
  789:                 document.$formname.$sec_element.size=numSections;
  790:             } else {
  791:                 document.$formname.$sec_element.size=3;
  792:             }
  793:             document.$formname.$sec_element.options[0].selected = false
  794:         }
  795:     }
  796: }
  797: 
  798: function setRole(crstype) {
  799: |;
  800:     if ($role_element eq '') {
  801:         $setsections .= '    return;
  802: }
  803: ';
  804:     } else {
  805:         $setsections .= qq|
  806:     var elementLength = document.$formname.$role_element.length;
  807:     var allroles = Array($rolestr);
  808:     var courserolenames = Array($courserolestr);
  809:     var communityrolenames = Array($communityrolestr);
  810:     if (elementLength != undefined) {
  811:         if (document.$formname.$role_element.options[5].value == 'cc') {
  812:             if (crstype == 'Course') {
  813:                 return;
  814:             } else {
  815:                 allroles[5] = 'co';
  816:                 for (var i=0; i<6; i++) {
  817:                     document.$formname.$role_element.options[i].value = allroles[i];
  818:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  819:                 }
  820:             }
  821:         } else {
  822:             if (crstype == 'Community') {
  823:                 return;
  824:             } else {
  825:                 allroles[5] = 'cc';
  826:                 for (var i=0; i<6; i++) {
  827:                     document.$formname.$role_element.options[i].value = allroles[i];
  828:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  829:                 }
  830:             }
  831:         }
  832:     }
  833:     return;
  834: }
  835: |;
  836:     }
  837:     return $setsections;
  838: }
  839: 
  840: sub selectcourse_link {
  841:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  842:        $typeelement) = @_;
  843:    my $type = $selecttype;
  844:    my $linktext = &mt('Select Course');
  845:    if ($selecttype eq 'Community') {
  846:        $linktext = &mt('Select Community');
  847:    } elsif ($selecttype eq 'Course/Community') {
  848:        $linktext = &mt('Select Course/Community');
  849:        $type = '';
  850:    } elsif ($selecttype eq 'Select') {
  851:        $linktext = &mt('Select');
  852:        $type = '';
  853:    }
  854:    return '<span class="LC_nobreak">'
  855:          ."<a href='"
  856:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  857:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  858:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  859:          ."'>".$linktext.'</a>'
  860:          .'</span>';
  861: }
  862: 
  863: sub selectauthor_link {
  864:    my ($form,$udom)=@_;
  865:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  866:           &mt('Select Author').'</a>';
  867: }
  868: 
  869: sub selectuser_link {
  870:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  871:         $coursedom,$linktext,$caller) = @_;
  872:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  873:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  874:            ');">'.$linktext.'</a>';
  875: }
  876: 
  877: sub check_uncheck_jscript {
  878:     my $jscript = <<"ENDSCRT";
  879: function checkAll(field) {
  880:     if (field.length > 0) {
  881:         for (i = 0; i < field.length; i++) {
  882:             field[i].checked = true ;
  883:         }
  884:     } else {
  885:         field.checked = true
  886:     }
  887: }
  888:  
  889: function uncheckAll(field) {
  890:     if (field.length > 0) {
  891:         for (i = 0; i < field.length; i++) {
  892:             field[i].checked = false ;
  893:         }
  894:     } else {
  895:         field.checked = false ;
  896:     }
  897: }
  898: ENDSCRT
  899:     return $jscript;
  900: }
  901: 
  902: sub select_timezone {
  903:    my ($name,$selected,$onchange,$includeempty)=@_;
  904:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  905:    if ($includeempty) {
  906:        $output .= '<option value=""';
  907:        if (($selected eq '') || ($selected eq 'local')) {
  908:            $output .= ' selected="selected" ';
  909:        }
  910:        $output .= '> </option>';
  911:    }
  912:    my @timezones = DateTime::TimeZone->all_names;
  913:    foreach my $tzone (@timezones) {
  914:        $output.= '<option value="'.$tzone.'"';
  915:        if ($tzone eq $selected) {
  916:            $output.=' selected="selected"';
  917:        }
  918:        $output.=">$tzone</option>\n";
  919:    }
  920:    $output.="</select>";
  921:    return $output;
  922: }
  923: 
  924: sub select_datelocale {
  925:     my ($name,$selected,$onchange,$includeempty)=@_;
  926:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  927:     if ($includeempty) {
  928:         $output .= '<option value=""';
  929:         if ($selected eq '') {
  930:             $output .= ' selected="selected" ';
  931:         }
  932:         $output .= '> </option>';
  933:     }
  934:     my (@possibles,%locale_names);
  935:     my @locales = DateTime::Locale::Catalog::Locales;
  936:     foreach my $locale (@locales) {
  937:         if (ref($locale) eq 'HASH') {
  938:             my $id = $locale->{'id'};
  939:             if ($id ne '') {
  940:                 my $en_terr = $locale->{'en_territory'};
  941:                 my $native_terr = $locale->{'native_territory'};
  942:                 my @languages = &Apache::lonlocal::preferred_languages();
  943:                 if (grep(/^en$/,@languages) || !@languages) {
  944:                     if ($en_terr ne '') {
  945:                         $locale_names{$id} = '('.$en_terr.')';
  946:                     } elsif ($native_terr ne '') {
  947:                         $locale_names{$id} = $native_terr;
  948:                     }
  949:                 } else {
  950:                     if ($native_terr ne '') {
  951:                         $locale_names{$id} = $native_terr.' ';
  952:                     } elsif ($en_terr ne '') {
  953:                         $locale_names{$id} = '('.$en_terr.')';
  954:                     }
  955:                 }
  956:                 push (@possibles,$id);
  957:             }
  958:         }
  959:     }
  960:     foreach my $item (sort(@possibles)) {
  961:         $output.= '<option value="'.$item.'"';
  962:         if ($item eq $selected) {
  963:             $output.=' selected="selected"';
  964:         }
  965:         $output.=">$item";
  966:         if ($locale_names{$item} ne '') {
  967:             $output.="  $locale_names{$item}</option>\n";
  968:         }
  969:         $output.="</option>\n";
  970:     }
  971:     $output.="</select>";
  972:     return $output;
  973: }
  974: 
  975: sub select_language {
  976:     my ($name,$selected,$includeempty) = @_;
  977:     my %langchoices;
  978:     if ($includeempty) {
  979:         %langchoices = ('' => 'No language preference');
  980:     }
  981:     foreach my $id (&languageids()) {
  982:         my $code = &supportedlanguagecode($id);
  983:         if ($code) {
  984:             $langchoices{$code} = &plainlanguagedescription($id);
  985:         }
  986:     }
  987:     return &select_form($selected,$name,\%langchoices);
  988: }
  989: 
  990: =pod
  991: 
  992: =item * &linked_select_forms(...)
  993: 
  994: linked_select_forms returns a string containing a <script></script> block
  995: and html for two <select> menus.  The select menus will be linked in that
  996: changing the value of the first menu will result in new values being placed
  997: in the second menu.  The values in the select menu will appear in alphabetical
  998: order unless a defined order is provided.
  999: 
 1000: linked_select_forms takes the following ordered inputs:
 1001: 
 1002: =over 4
 1003: 
 1004: =item * $formname, the name of the <form> tag
 1005: 
 1006: =item * $middletext, the text which appears between the <select> tags
 1007: 
 1008: =item * $firstdefault, the default value for the first menu
 1009: 
 1010: =item * $firstselectname, the name of the first <select> tag
 1011: 
 1012: =item * $secondselectname, the name of the second <select> tag
 1013: 
 1014: =item * $hashref, a reference to a hash containing the data for the menus.
 1015: 
 1016: =item * $menuorder, the order of values in the first menu
 1017: 
 1018: =back 
 1019: 
 1020: Below is an example of such a hash.  Only the 'text', 'default', and 
 1021: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1022: values for the first select menu.  The text that coincides with the 
 1023: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1024: and text for the second menu are given in the hash pointed to by 
 1025: $menu{$choice1}->{'select2'}.  
 1026: 
 1027:  my %menu = ( A1 => { text =>"Choice A1" ,
 1028:                        default => "B3",
 1029:                        select2 => { 
 1030:                            B1 => "Choice B1",
 1031:                            B2 => "Choice B2",
 1032:                            B3 => "Choice B3",
 1033:                            B4 => "Choice B4"
 1034:                            },
 1035:                        order => ['B4','B3','B1','B2'],
 1036:                    },
 1037:                A2 => { text =>"Choice A2" ,
 1038:                        default => "C2",
 1039:                        select2 => { 
 1040:                            C1 => "Choice C1",
 1041:                            C2 => "Choice C2",
 1042:                            C3 => "Choice C3"
 1043:                            },
 1044:                        order => ['C2','C1','C3'],
 1045:                    },
 1046:                A3 => { text =>"Choice A3" ,
 1047:                        default => "D6",
 1048:                        select2 => { 
 1049:                            D1 => "Choice D1",
 1050:                            D2 => "Choice D2",
 1051:                            D3 => "Choice D3",
 1052:                            D4 => "Choice D4",
 1053:                            D5 => "Choice D5",
 1054:                            D6 => "Choice D6",
 1055:                            D7 => "Choice D7"
 1056:                            },
 1057:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1058:                    }
 1059:                );
 1060: 
 1061: =cut
 1062: 
 1063: sub linked_select_forms {
 1064:     my ($formname,
 1065:         $middletext,
 1066:         $firstdefault,
 1067:         $firstselectname,
 1068:         $secondselectname, 
 1069:         $hashref,
 1070:         $menuorder,
 1071:         ) = @_;
 1072:     my $second = "document.$formname.$secondselectname";
 1073:     my $first = "document.$formname.$firstselectname";
 1074:     # output the javascript to do the changing
 1075:     my $result = '';
 1076:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1077:     $result.="// <![CDATA[\n";
 1078:     $result.="var select2data = new Object();\n";
 1079:     $" = '","';
 1080:     my $debug = '';
 1081:     foreach my $s1 (sort(keys(%$hashref))) {
 1082:         $result.="select2data.d_$s1 = new Object();\n";        
 1083:         $result.="select2data.d_$s1.def = new String('".
 1084:             $hashref->{$s1}->{'default'}."');\n";
 1085:         $result.="select2data.d_$s1.values = new Array(";
 1086:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1087:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1088:             @s2values = @{$hashref->{$s1}->{'order'}};
 1089:         }
 1090:         $result.="\"@s2values\");\n";
 1091:         $result.="select2data.d_$s1.texts = new Array(";        
 1092:         my @s2texts;
 1093:         foreach my $value (@s2values) {
 1094:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1095:         }
 1096:         $result.="\"@s2texts\");\n";
 1097:     }
 1098:     $"=' ';
 1099:     $result.= <<"END";
 1100: 
 1101: function select1_changed() {
 1102:     // Determine new choice
 1103:     var newvalue = "d_" + $first.value;
 1104:     // update select2
 1105:     var values     = select2data[newvalue].values;
 1106:     var texts      = select2data[newvalue].texts;
 1107:     var select2def = select2data[newvalue].def;
 1108:     var i;
 1109:     // out with the old
 1110:     for (i = 0; i < $second.options.length; i++) {
 1111:         $second.options[i] = null;
 1112:     }
 1113:     // in with the nuclear
 1114:     for (i=0;i<values.length; i++) {
 1115:         $second.options[i] = new Option(values[i]);
 1116:         $second.options[i].value = values[i];
 1117:         $second.options[i].text = texts[i];
 1118:         if (values[i] == select2def) {
 1119:             $second.options[i].selected = true;
 1120:         }
 1121:     }
 1122: }
 1123: // ]]>
 1124: </script>
 1125: END
 1126:     # output the initial values for the selection lists
 1127:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1128:     my @order = sort(keys(%{$hashref}));
 1129:     if (ref($menuorder) eq 'ARRAY') {
 1130:         @order = @{$menuorder};
 1131:     }
 1132:     foreach my $value (@order) {
 1133:         $result.="    <option value=\"$value\" ";
 1134:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1135:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1136:     }
 1137:     $result .= "</select>\n";
 1138:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1139:     $result .= $middletext;
 1140:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1141:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1142:     
 1143:     my @secondorder = sort(keys(%select2));
 1144:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1145:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1146:     }
 1147:     foreach my $value (@secondorder) {
 1148:         $result.="    <option value=\"$value\" ";        
 1149:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1150:         $result.=">".&mt($select2{$value})."</option>\n";
 1151:     }
 1152:     $result .= "</select>\n";
 1153:     #    return $debug;
 1154:     return $result;
 1155: }   #  end of sub linked_select_forms {
 1156: 
 1157: =pod
 1158: 
 1159: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1160: 
 1161: Returns a string corresponding to an HTML link to the given help
 1162: $topic, where $topic corresponds to the name of a .tex file in
 1163: /home/httpd/html/adm/help/tex, with underscores replaced by
 1164: spaces. 
 1165: 
 1166: $text will optionally be linked to the same topic, allowing you to
 1167: link text in addition to the graphic. If you do not want to link
 1168: text, but wish to specify one of the later parameters, pass an
 1169: empty string. 
 1170: 
 1171: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1172: the link will not open a new window. If false, the link will open
 1173: a new window using Javascript. (Default is false.) 
 1174: 
 1175: $width and $height are optional numerical parameters that will
 1176: override the width and height of the popped up window, which may
 1177: be useful for certain help topics with big pictures included.
 1178: 
 1179: $imgid is the id of the img tag used for the help icon. This may be
 1180: used in a javascript call to switch the image src.  See 
 1181: lonhtmlcommon::htmlareaselectactive() for an example.
 1182: 
 1183: =cut
 1184: 
 1185: sub help_open_topic {
 1186:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1187:     $text = "" if (not defined $text);
 1188:     $stayOnPage = 0 if (not defined $stayOnPage);
 1189:     $width = 500 if (not defined $width);
 1190:     $height = 400 if (not defined $height);
 1191:     my $filename = $topic;
 1192:     $filename =~ s/ /_/g;
 1193: 
 1194:     my $template = "";
 1195:     my $link;
 1196:     
 1197:     $topic=~s/\W/\_/g;
 1198: 
 1199:     if (!$stayOnPage) {
 1200: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1201:     } else {
 1202: 	$link = "/adm/help/${filename}.hlp";
 1203:     }
 1204: 
 1205:     # Add the text
 1206:     if ($text ne "") {	
 1207: 	$template.='<span class="LC_help_open_topic">'
 1208:                   .'<a target="_top" href="'.$link.'">'
 1209:                   .$text.'</a>';
 1210:     }
 1211: 
 1212:     # (Always) Add the graphic
 1213:     my $title = &mt('Online Help');
 1214:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1215:     if ($imgid ne '') {
 1216:         $imgid = ' id="'.$imgid.'"';
 1217:     }
 1218:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1219:               .'<img src="'.$helpicon.'" border="0"'
 1220:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1221:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1222:               .' /></a>';
 1223:     if ($text ne "") {	
 1224:         $template.='</span>';
 1225:     }
 1226:     return $template;
 1227: 
 1228: }
 1229: 
 1230: # This is a quicky function for Latex cheatsheet editing, since it 
 1231: # appears in at least four places
 1232: sub helpLatexCheatsheet {
 1233:     my ($topic,$text,$not_author) = @_;
 1234:     my $out;
 1235:     my $addOther = '';
 1236:     if ($topic) {
 1237: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1238: 							       undef, undef, 600).
 1239: 								   '</span> ';
 1240:     }
 1241:     $out = '<span>' # Start cheatsheet
 1242: 	  .$addOther
 1243:           .'<span>'
 1244: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1245: 					       undef,undef,600)
 1246: 	  .'</span> <span>'
 1247: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1248: 					       undef,undef,600)
 1249: 	  .'</span>';
 1250:     unless ($not_author) {
 1251:         $out .= ' <span>'
 1252: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1253: 	                                            undef,undef,600)
 1254: 	       .'</span>';
 1255:     }
 1256:     $out .= '</span>'; # End cheatsheet
 1257:     return $out;
 1258: }
 1259: 
 1260: sub general_help {
 1261:     my $helptopic='Student_Intro';
 1262:     if ($env{'request.role'}=~/^(ca|au)/) {
 1263: 	$helptopic='Authoring_Intro';
 1264:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1265: 	$helptopic='Course_Coordination_Intro';
 1266:     } elsif ($env{'request.role'}=~/^dc/) {
 1267:         $helptopic='Domain_Coordination_Intro';
 1268:     }
 1269:     return $helptopic;
 1270: }
 1271: 
 1272: sub update_help_link {
 1273:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1274:     my $origurl = $ENV{'REQUEST_URI'};
 1275:     $origurl=~s|^/~|/priv/|;
 1276:     my $timestamp = time;
 1277:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1278:         $$datum = &escape($$datum);
 1279:     }
 1280: 
 1281:     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";
 1282:     my $output .= <<"ENDOUTPUT";
 1283: <script type="text/javascript">
 1284: // <![CDATA[
 1285: banner_link = '$banner_link';
 1286: // ]]>
 1287: </script>
 1288: ENDOUTPUT
 1289:     return $output;
 1290: }
 1291: 
 1292: # now just updates the help link and generates a blue icon
 1293: sub help_open_menu {
 1294:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1295: 	= @_;    
 1296:     $stayOnPage = 1;
 1297:     my $output;
 1298:     if ($component_help) {
 1299: 	if (!$text) {
 1300: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1301: 				       $width,$height);
 1302: 	} else {
 1303: 	    my $help_text;
 1304: 	    $help_text=&unescape($topic);
 1305: 	    $output='<table><tr><td>'.
 1306: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1307: 				 $width,$height).'</td></tr></table>';
 1308: 	}
 1309:     }
 1310:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1311:     return $output.$banner_link;
 1312: }
 1313: 
 1314: sub top_nav_help {
 1315:     my ($text) = @_;
 1316:     $text = &mt($text);
 1317:     my $stay_on_page = 1;
 1318: 
 1319:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1320: 	                     : "javascript:helpMenu('open')";
 1321:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1322: 
 1323:     my $title = &mt('Get help');
 1324: 
 1325:     return <<"END";
 1326: $banner_link
 1327:  <a href="$link" title="$title">$text</a>
 1328: END
 1329: }
 1330: 
 1331: sub help_menu_js {
 1332:     my ($text) = @_;
 1333:     my $stayOnPage = 1;
 1334:     my $width = 620;
 1335:     my $height = 600;
 1336:     my $helptopic=&general_help();
 1337:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1338:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1339:     my $start_page =
 1340:         &Apache::loncommon::start_page('Help Menu', undef,
 1341: 				       {'frameset'    => 1,
 1342: 					'js_ready'    => 1,
 1343: 					'add_entries' => {
 1344: 					    'border' => '0',
 1345: 					    'rows'   => "110,*",},});
 1346:     my $end_page =
 1347:         &Apache::loncommon::end_page({'frameset' => 1,
 1348: 				      'js_ready' => 1,});
 1349: 
 1350:     my $template .= <<"ENDTEMPLATE";
 1351: <script type="text/javascript">
 1352: // <![CDATA[
 1353: // <!-- BEGIN LON-CAPA Internal
 1354: var banner_link = '';
 1355: function helpMenu(target) {
 1356:     var caller = this;
 1357:     if (target == 'open') {
 1358:         var newWindow = null;
 1359:         try {
 1360:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1361:         }
 1362:         catch(error) {
 1363:             writeHelp(caller);
 1364:             return;
 1365:         }
 1366:         if (newWindow) {
 1367:             caller = newWindow;
 1368:         }
 1369:     }
 1370:     writeHelp(caller);
 1371:     return;
 1372: }
 1373: function writeHelp(caller) {
 1374:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1375:     caller.document.close()
 1376:     caller.focus()
 1377: }
 1378: // END LON-CAPA Internal -->
 1379: // ]]>
 1380: </script>
 1381: ENDTEMPLATE
 1382:     return $template;
 1383: }
 1384: 
 1385: sub help_open_bug {
 1386:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1387:     unless ($env{'user.adv'}) { return ''; }
 1388:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1389:     $text = "" if (not defined $text);
 1390: 	$stayOnPage=1;
 1391:     $width = 600 if (not defined $width);
 1392:     $height = 600 if (not defined $height);
 1393: 
 1394:     $topic=~s/\W+/\+/g;
 1395:     my $link='';
 1396:     my $template='';
 1397:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1398: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1399:     if (!$stayOnPage)
 1400:     {
 1401: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1402:     }
 1403:     else
 1404:     {
 1405: 	$link = $url;
 1406:     }
 1407:     # Add the text
 1408:     if ($text ne "")
 1409:     {
 1410: 	$template .= 
 1411:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1412:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1413:     }
 1414: 
 1415:     # Add the graphic
 1416:     my $title = &mt('Report a Bug');
 1417:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1418:     $template .= <<"ENDTEMPLATE";
 1419:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1420: ENDTEMPLATE
 1421:     if ($text ne '') { $template.='</td></tr></table>' };
 1422:     return $template;
 1423: 
 1424: }
 1425: 
 1426: sub help_open_faq {
 1427:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1428:     unless ($env{'user.adv'}) { return ''; }
 1429:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1430:     $text = "" if (not defined $text);
 1431: 	$stayOnPage=1;
 1432:     $width = 350 if (not defined $width);
 1433:     $height = 400 if (not defined $height);
 1434: 
 1435:     $topic=~s/\W+/\+/g;
 1436:     my $link='';
 1437:     my $template='';
 1438:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1439:     if (!$stayOnPage)
 1440:     {
 1441: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1442:     }
 1443:     else
 1444:     {
 1445: 	$link = $url;
 1446:     }
 1447: 
 1448:     # Add the text
 1449:     if ($text ne "")
 1450:     {
 1451: 	$template .= 
 1452:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1453:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1454:     }
 1455: 
 1456:     # Add the graphic
 1457:     my $title = &mt('View the FAQ');
 1458:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1459:     $template .= <<"ENDTEMPLATE";
 1460:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1461: ENDTEMPLATE
 1462:     if ($text ne '') { $template.='</td></tr></table>' };
 1463:     return $template;
 1464: 
 1465: }
 1466: 
 1467: ###############################################################
 1468: ###############################################################
 1469: 
 1470: =pod
 1471: 
 1472: =item * &change_content_javascript():
 1473: 
 1474: This and the next function allow you to create small sections of an
 1475: otherwise static HTML page that you can update on the fly with
 1476: Javascript, even in Netscape 4.
 1477: 
 1478: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1479: must be written to the HTML page once. It will prove the Javascript
 1480: function "change(name, content)". Calling the change function with the
 1481: name of the section 
 1482: you want to update, matching the name passed to C<changable_area>, and
 1483: the new content you want to put in there, will put the content into
 1484: that area.
 1485: 
 1486: B<Note>: Netscape 4 only reserves enough space for the changable area
 1487: to contain room for the original contents. You need to "make space"
 1488: for whatever changes you wish to make, and be B<sure> to check your
 1489: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1490: it's adequate for updating a one-line status display, but little more.
 1491: This script will set the space to 100% width, so you only need to
 1492: worry about height in Netscape 4.
 1493: 
 1494: Modern browsers are much less limiting, and if you can commit to the
 1495: user not using Netscape 4, this feature may be used freely with
 1496: pretty much any HTML.
 1497: 
 1498: =cut
 1499: 
 1500: sub change_content_javascript {
 1501:     # If we're on Netscape 4, we need to use Layer-based code
 1502:     if ($env{'browser.type'} eq 'netscape' &&
 1503: 	$env{'browser.version'} =~ /^4\./) {
 1504: 	return (<<NETSCAPE4);
 1505: 	function change(name, content) {
 1506: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1507: 	    doc.open();
 1508: 	    doc.write(content);
 1509: 	    doc.close();
 1510: 	}
 1511: NETSCAPE4
 1512:     } else {
 1513: 	# Otherwise, we need to use semi-standards-compliant code
 1514: 	# (technically, "innerHTML" isn't standard but the equivalent
 1515: 	# is really scary, and every useful browser supports it
 1516: 	return (<<DOMBASED);
 1517: 	function change(name, content) {
 1518: 	    element = document.getElementById(name);
 1519: 	    element.innerHTML = content;
 1520: 	}
 1521: DOMBASED
 1522:     }
 1523: }
 1524: 
 1525: =pod
 1526: 
 1527: =item * &changable_area($name,$origContent):
 1528: 
 1529: This provides a "changable area" that can be modified on the fly via
 1530: the Javascript code provided in C<change_content_javascript>. $name is
 1531: the name you will use to reference the area later; do not repeat the
 1532: same name on a given HTML page more then once. $origContent is what
 1533: the area will originally contain, which can be left blank.
 1534: 
 1535: =cut
 1536: 
 1537: sub changable_area {
 1538:     my ($name, $origContent) = @_;
 1539: 
 1540:     if ($env{'browser.type'} eq 'netscape' &&
 1541: 	$env{'browser.version'} =~ /^4\./) {
 1542: 	# If this is netscape 4, we need to use the Layer tag
 1543: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1544:     } else {
 1545: 	return "<span id='$name'>$origContent</span>";
 1546:     }
 1547: }
 1548: 
 1549: =pod
 1550: 
 1551: =item * &viewport_geometry_js 
 1552: 
 1553: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1554: 
 1555: =cut
 1556: 
 1557: 
 1558: sub viewport_geometry_js { 
 1559:     return <<"GEOMETRY";
 1560: var Geometry = {};
 1561: function init_geometry() {
 1562:     if (Geometry.init) { return };
 1563:     Geometry.init=1;
 1564:     if (window.innerHeight) {
 1565:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1566:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1567:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1568:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1569:     }
 1570:     else if (document.documentElement && document.documentElement.clientHeight) {
 1571:         Geometry.getViewportHeight =
 1572:             function() { return document.documentElement.clientHeight; };
 1573:         Geometry.getViewportWidth =
 1574:             function() { return document.documentElement.clientWidth; };
 1575: 
 1576:         Geometry.getHorizontalScroll =
 1577:             function() { return document.documentElement.scrollLeft; };
 1578:         Geometry.getVerticalScroll =
 1579:             function() { return document.documentElement.scrollTop; };
 1580:     }
 1581:     else if (document.body.clientHeight) {
 1582:         Geometry.getViewportHeight =
 1583:             function() { return document.body.clientHeight; };
 1584:         Geometry.getViewportWidth =
 1585:             function() { return document.body.clientWidth; };
 1586:         Geometry.getHorizontalScroll =
 1587:             function() { return document.body.scrollLeft; };
 1588:         Geometry.getVerticalScroll =
 1589:             function() { return document.body.scrollTop; };
 1590:     }
 1591: }
 1592: 
 1593: GEOMETRY
 1594: }
 1595: 
 1596: =pod
 1597: 
 1598: =item * &viewport_size_js()
 1599: 
 1600: 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. 
 1601: 
 1602: =cut
 1603: 
 1604: sub viewport_size_js {
 1605:     my $geometry = &viewport_geometry_js();
 1606:     return <<"DIMS";
 1607: 
 1608: $geometry
 1609: 
 1610: function getViewportDims(width,height) {
 1611:     init_geometry();
 1612:     width.value = Geometry.getViewportWidth();
 1613:     height.value = Geometry.getViewportHeight();
 1614:     return;
 1615: }
 1616: 
 1617: DIMS
 1618: }
 1619: 
 1620: =pod
 1621: 
 1622: =item * &resize_textarea_js()
 1623: 
 1624: emits the needed javascript to resize a textarea to be as big as possible
 1625: 
 1626: creates a function resize_textrea that takes two IDs first should be
 1627: the id of the element to resize, second should be the id of a div that
 1628: surrounds everything that comes after the textarea, this routine needs
 1629: to be attached to the <body> for the onload and onresize events.
 1630: 
 1631: =back
 1632: 
 1633: =cut
 1634: 
 1635: sub resize_textarea_js {
 1636:     my $geometry = &viewport_geometry_js();
 1637:     return <<"RESIZE";
 1638:     <script type="text/javascript">
 1639: // <![CDATA[
 1640: $geometry
 1641: 
 1642: function getX(element) {
 1643:     var x = 0;
 1644:     while (element) {
 1645: 	x += element.offsetLeft;
 1646: 	element = element.offsetParent;
 1647:     }
 1648:     return x;
 1649: }
 1650: function getY(element) {
 1651:     var y = 0;
 1652:     while (element) {
 1653: 	y += element.offsetTop;
 1654: 	element = element.offsetParent;
 1655:     }
 1656:     return y;
 1657: }
 1658: 
 1659: 
 1660: function resize_textarea(textarea_id,bottom_id) {
 1661:     init_geometry();
 1662:     var textarea        = document.getElementById(textarea_id);
 1663:     //alert(textarea);
 1664: 
 1665:     var textarea_top    = getY(textarea);
 1666:     var textarea_height = textarea.offsetHeight;
 1667:     var bottom          = document.getElementById(bottom_id);
 1668:     var bottom_top      = getY(bottom);
 1669:     var bottom_height   = bottom.offsetHeight;
 1670:     var window_height   = Geometry.getViewportHeight();
 1671:     var fudge           = 23;
 1672:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1673:     if (new_height < 300) {
 1674: 	new_height = 300;
 1675:     }
 1676:     textarea.style.height=new_height+'px';
 1677: }
 1678: // ]]>
 1679: </script>
 1680: RESIZE
 1681: 
 1682: }
 1683: 
 1684: =pod
 1685: 
 1686: =head1 Excel and CSV file utility routines
 1687: 
 1688: =over 4
 1689: 
 1690: =cut
 1691: 
 1692: ###############################################################
 1693: ###############################################################
 1694: 
 1695: =pod
 1696: 
 1697: =item * &csv_translate($text) 
 1698: 
 1699: Translate $text to allow it to be output as a 'comma separated values' 
 1700: format.
 1701: 
 1702: =cut
 1703: 
 1704: ###############################################################
 1705: ###############################################################
 1706: sub csv_translate {
 1707:     my $text = shift;
 1708:     $text =~ s/\"/\"\"/g;
 1709:     $text =~ s/\n/ /g;
 1710:     return $text;
 1711: }
 1712: 
 1713: ###############################################################
 1714: ###############################################################
 1715: 
 1716: =pod
 1717: 
 1718: =item * &define_excel_formats()
 1719: 
 1720: Define some commonly used Excel cell formats.
 1721: 
 1722: Currently supported formats:
 1723: 
 1724: =over 4
 1725: 
 1726: =item header
 1727: 
 1728: =item bold
 1729: 
 1730: =item h1
 1731: 
 1732: =item h2
 1733: 
 1734: =item h3
 1735: 
 1736: =item h4
 1737: 
 1738: =item i
 1739: 
 1740: =item date
 1741: 
 1742: =back
 1743: 
 1744: Inputs: $workbook
 1745: 
 1746: Returns: $format, a hash reference.
 1747: 
 1748: =cut
 1749: 
 1750: ###############################################################
 1751: ###############################################################
 1752: sub define_excel_formats {
 1753:     my ($workbook) = @_;
 1754:     my $format;
 1755:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1756:                                                 bottom    => 1,
 1757:                                                 align     => 'center');
 1758:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1759:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1760:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1761:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1762:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1763:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1764:     $format->{'date'} = $workbook->add_format(num_format=>
 1765:                                             'mm/dd/yyyy hh:mm:ss');
 1766:     return $format;
 1767: }
 1768: 
 1769: ###############################################################
 1770: ###############################################################
 1771: 
 1772: =pod
 1773: 
 1774: =item * &create_workbook()
 1775: 
 1776: Create an Excel worksheet.  If it fails, output message on the
 1777: request object and return undefs.
 1778: 
 1779: Inputs: Apache request object
 1780: 
 1781: Returns (undef) on failure, 
 1782:     Excel worksheet object, scalar with filename, and formats 
 1783:     from &Apache::loncommon::define_excel_formats on success
 1784: 
 1785: =cut
 1786: 
 1787: ###############################################################
 1788: ###############################################################
 1789: sub create_workbook {
 1790:     my ($r) = @_;
 1791:         #
 1792:     # Create the excel spreadsheet
 1793:     my $filename = '/prtspool/'.
 1794:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1795:         time.'_'.rand(1000000000).'.xls';
 1796:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1797:     if (! defined($workbook)) {
 1798:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1799:         $r->print(
 1800:             '<p class="LC_error">'
 1801:            .&mt('Problems occurred in creating the new Excel file.')
 1802:            .' '.&mt('This error has been logged.')
 1803:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1804:            .'</p>'
 1805:         );
 1806:         return (undef);
 1807:     }
 1808:     #
 1809:     $workbook->set_tempdir(LONCAPA::tempdir());
 1810:     #
 1811:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1812:     return ($workbook,$filename,$format);
 1813: }
 1814: 
 1815: ###############################################################
 1816: ###############################################################
 1817: 
 1818: =pod
 1819: 
 1820: =item * &create_text_file()
 1821: 
 1822: Create a file to write to and eventually make available to the user.
 1823: If file creation fails, outputs an error message on the request object and 
 1824: return undefs.
 1825: 
 1826: Inputs: Apache request object, and file suffix
 1827: 
 1828: Returns (undef) on failure, 
 1829:     Filehandle and filename on success.
 1830: 
 1831: =cut
 1832: 
 1833: ###############################################################
 1834: ###############################################################
 1835: sub create_text_file {
 1836:     my ($r,$suffix) = @_;
 1837:     if (! defined($suffix)) { $suffix = 'txt'; };
 1838:     my $fh;
 1839:     my $filename = '/prtspool/'.
 1840:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1841:         time.'_'.rand(1000000000).'.'.$suffix;
 1842:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1843:     if (! defined($fh)) {
 1844:         $r->log_error("Couldn't open $filename for output $!");
 1845:         $r->print(
 1846:             '<p class="LC_error">'
 1847:            .&mt('Problems occurred in creating the output file.')
 1848:            .' '.&mt('This error has been logged.')
 1849:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1850:            .'</p>'
 1851:         );
 1852:     }
 1853:     return ($fh,$filename)
 1854: }
 1855: 
 1856: 
 1857: =pod 
 1858: 
 1859: =back
 1860: 
 1861: =cut
 1862: 
 1863: ###############################################################
 1864: ##        Home server <option> list generating code          ##
 1865: ###############################################################
 1866: 
 1867: # ------------------------------------------
 1868: 
 1869: sub domain_select {
 1870:     my ($name,$value,$multiple)=@_;
 1871:     my %domains=map { 
 1872: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1873:     } &Apache::lonnet::all_domains();
 1874:     if ($multiple) {
 1875: 	$domains{''}=&mt('Any domain');
 1876: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1877: 	return &multiple_select_form($name,$value,4,\%domains);
 1878:     } else {
 1879: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1880: 	return &select_form($name,$value,\%domains);
 1881:     }
 1882: }
 1883: 
 1884: #-------------------------------------------
 1885: 
 1886: =pod
 1887: 
 1888: =head1 Routines for form select boxes
 1889: 
 1890: =over 4
 1891: 
 1892: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1893: 
 1894: Returns a string containing a <select> element int multiple mode
 1895: 
 1896: 
 1897: Args:
 1898:   $name - name of the <select> element
 1899:   $value - scalar or array ref of values that should already be selected
 1900:   $size - number of rows long the select element is
 1901:   $hash - the elements should be 'option' => 'shown text'
 1902:           (shown text should already have been &mt())
 1903:   $order - (optional) array ref of the order to show the elements in
 1904: 
 1905: =cut
 1906: 
 1907: #-------------------------------------------
 1908: sub multiple_select_form {
 1909:     my ($name,$value,$size,$hash,$order)=@_;
 1910:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1911:     my $output='';
 1912:     if (! defined($size)) {
 1913:         $size = 4;
 1914:         if (scalar(keys(%$hash))<4) {
 1915:             $size = scalar(keys(%$hash));
 1916:         }
 1917:     }
 1918:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1919:     my @order;
 1920:     if (ref($order) eq 'ARRAY')  {
 1921:         @order = @{$order};
 1922:     } else {
 1923:         @order = sort(keys(%$hash));
 1924:     }
 1925:     if (exists($$hash{'select_form_order'})) {
 1926:         @order = @{$$hash{'select_form_order'}};
 1927:     }
 1928:         
 1929:     foreach my $key (@order) {
 1930:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1931:         $output.='selected="selected" ' if ($selected{$key});
 1932:         $output.='>'.$hash->{$key}."</option>\n";
 1933:     }
 1934:     $output.="</select>\n";
 1935:     return $output;
 1936: }
 1937: 
 1938: #-------------------------------------------
 1939: 
 1940: =pod
 1941: 
 1942: =item * &select_form($defdom,$name,$hashref,$onchange)
 1943: 
 1944: Returns a string containing a <select name='$name' size='1'> form to 
 1945: allow a user to select options from a ref to a hash containing:
 1946: option_name => displayed text. An optional $onchange can include
 1947: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1948: 
 1949: See lonrights.pm for an example invocation and use.
 1950: 
 1951: =cut
 1952: 
 1953: #-------------------------------------------
 1954: sub select_form {
 1955:     my ($def,$name,$hashref,$onchange) = @_;
 1956:     return unless (ref($hashref) eq 'HASH');
 1957:     if ($onchange) {
 1958:         $onchange = ' onchange="'.$onchange.'"';
 1959:     }
 1960:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1961:     my @keys;
 1962:     if (exists($hashref->{'select_form_order'})) {
 1963: 	@keys=@{$hashref->{'select_form_order'}};
 1964:     } else {
 1965: 	@keys=sort(keys(%{$hashref}));
 1966:     }
 1967:     foreach my $key (@keys) {
 1968:         $selectform.=
 1969: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1970:             ($key eq $def ? 'selected="selected" ' : '').
 1971:                 ">".$hashref->{$key}."</option>\n";
 1972:     }
 1973:     $selectform.="</select>";
 1974:     return $selectform;
 1975: }
 1976: 
 1977: # For display filters
 1978: 
 1979: sub display_filter {
 1980:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1981:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1982:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1983: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1984: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1985: 	   '</label></span> <span class="LC_nobreak">'.
 1986:            &mt('Filter [_1]',
 1987: 	   &select_form($env{'form.displayfilter'},
 1988: 			'displayfilter',
 1989: 			{'currentfolder' => 'Current folder/page',
 1990: 			 'containing' => 'Containing phrase',
 1991: 			 'none' => 'None'})).
 1992: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1993: }
 1994: 
 1995: sub gradeleveldescription {
 1996:     my $gradelevel=shift;
 1997:     my %gradelevels=(0 => 'Not specified',
 1998: 		     1 => 'Grade 1',
 1999: 		     2 => 'Grade 2',
 2000: 		     3 => 'Grade 3',
 2001: 		     4 => 'Grade 4',
 2002: 		     5 => 'Grade 5',
 2003: 		     6 => 'Grade 6',
 2004: 		     7 => 'Grade 7',
 2005: 		     8 => 'Grade 8',
 2006: 		     9 => 'Grade 9',
 2007: 		     10 => 'Grade 10',
 2008: 		     11 => 'Grade 11',
 2009: 		     12 => 'Grade 12',
 2010: 		     13 => 'Grade 13',
 2011: 		     14 => '100 Level',
 2012: 		     15 => '200 Level',
 2013: 		     16 => '300 Level',
 2014: 		     17 => '400 Level',
 2015: 		     18 => 'Graduate Level');
 2016:     return &mt($gradelevels{$gradelevel});
 2017: }
 2018: 
 2019: sub select_level_form {
 2020:     my ($deflevel,$name)=@_;
 2021:     unless ($deflevel) { $deflevel=0; }
 2022:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2023:     for (my $i=0; $i<=18; $i++) {
 2024:         $selectform.="<option value=\"$i\" ".
 2025:             ($i==$deflevel ? 'selected="selected" ' : '').
 2026:                 ">".&gradeleveldescription($i)."</option>\n";
 2027:     }
 2028:     $selectform.="</select>";
 2029:     return $selectform;
 2030: }
 2031: 
 2032: #-------------------------------------------
 2033: 
 2034: =pod
 2035: 
 2036: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2037: 
 2038: Returns a string containing a <select name='$name' size='1'> form to 
 2039: allow a user to select the domain to preform an operation in.  
 2040: See loncreateuser.pm for an example invocation and use.
 2041: 
 2042: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2043: selected");
 2044: 
 2045: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2046: 
 2047: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 2048: 
 2049: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2050: 
 2051: =cut
 2052: 
 2053: #-------------------------------------------
 2054: sub select_dom_form {
 2055:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2056:     if ($onchange) {
 2057:         $onchange = ' onchange="'.$onchange.'"';
 2058:     }
 2059:     my @domains;
 2060:     if (ref($incdoms) eq 'ARRAY') {
 2061:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2062:     } else {
 2063:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2064:     }
 2065:     if ($includeempty) { @domains=('',@domains); }
 2066:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2067:     foreach my $dom (@domains) {
 2068:         $selectdomain.="<option value=\"$dom\" ".
 2069:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2070:         if ($showdomdesc) {
 2071:             if ($dom ne '') {
 2072:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2073:                 if ($domdesc ne '') {
 2074:                     $selectdomain .= ' ('.$domdesc.')';
 2075:                 }
 2076:             } 
 2077:         }
 2078:         $selectdomain .= "</option>\n";
 2079:     }
 2080:     $selectdomain.="</select>";
 2081:     return $selectdomain;
 2082: }
 2083: 
 2084: #-------------------------------------------
 2085: 
 2086: =pod
 2087: 
 2088: =item * &home_server_form_item($domain,$name,$defaultflag)
 2089: 
 2090: input: 4 arguments (two required, two optional) - 
 2091:     $domain - domain of new user
 2092:     $name - name of form element
 2093:     $default - Value of 'default' causes a default item to be first 
 2094:                             option, and selected by default. 
 2095:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2096:                             if 1 server found, or default, if 0 found.
 2097: output: returns 2 items: 
 2098: (a) form element which contains either:
 2099:    (i) <select name="$name">
 2100:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2101:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2102:        </select>
 2103:        form item if there are multiple library servers in $domain, or
 2104:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2105:        if there is only one library server in $domain.
 2106: 
 2107: (b) number of library servers found.
 2108: 
 2109: See loncreateuser.pm for example of use.
 2110: 
 2111: =cut
 2112: 
 2113: #-------------------------------------------
 2114: sub home_server_form_item {
 2115:     my ($domain,$name,$default,$hide) = @_;
 2116:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2117:     my $result;
 2118:     my $numlib = keys(%servers);
 2119:     if ($numlib > 1) {
 2120:         $result .= '<select name="'.$name.'" />'."\n";
 2121:         if ($default) {
 2122:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2123:                        '</option>'."\n";
 2124:         }
 2125:         foreach my $hostid (sort(keys(%servers))) {
 2126:             $result.= '<option value="'.$hostid.'">'.
 2127: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2128:         }
 2129:         $result .= '</select>'."\n";
 2130:     } elsif ($numlib == 1) {
 2131:         my $hostid;
 2132:         foreach my $item (keys(%servers)) {
 2133:             $hostid = $item;
 2134:         }
 2135:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2136:                    $hostid.'" />';
 2137:                    if (!$hide) {
 2138:                        $result .= $hostid.' '.$servers{$hostid};
 2139:                    }
 2140:                    $result .= "\n";
 2141:     } elsif ($default) {
 2142:         $result .= '<input type="hidden" name="'.$name.
 2143:                    '" value="default" />';
 2144:                    if (!$hide) {
 2145:                        $result .= &mt('default');
 2146:                    }
 2147:                    $result .= "\n";
 2148:     }
 2149:     return ($result,$numlib);
 2150: }
 2151: 
 2152: =pod
 2153: 
 2154: =back 
 2155: 
 2156: =cut
 2157: 
 2158: ###############################################################
 2159: ##                  Decoding User Agent                      ##
 2160: ###############################################################
 2161: 
 2162: =pod
 2163: 
 2164: =head1 Decoding the User Agent
 2165: 
 2166: =over 4
 2167: 
 2168: =item * &decode_user_agent()
 2169: 
 2170: Inputs: $r
 2171: 
 2172: Outputs:
 2173: 
 2174: =over 4
 2175: 
 2176: =item * $httpbrowser
 2177: 
 2178: =item * $clientbrowser
 2179: 
 2180: =item * $clientversion
 2181: 
 2182: =item * $clientmathml
 2183: 
 2184: =item * $clientunicode
 2185: 
 2186: =item * $clientos
 2187: 
 2188: =back
 2189: 
 2190: =back 
 2191: 
 2192: =cut
 2193: 
 2194: ###############################################################
 2195: ###############################################################
 2196: sub decode_user_agent {
 2197:     my ($r)=@_;
 2198:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2199:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2200:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2201:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2202:     my $clientbrowser='unknown';
 2203:     my $clientversion='0';
 2204:     my $clientmathml='';
 2205:     my $clientunicode='0';
 2206:     for (my $i=0;$i<=$#browsertype;$i++) {
 2207:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2208: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2209: 	    $clientbrowser=$bname;
 2210:             $httpbrowser=~/$vreg/i;
 2211: 	    $clientversion=$1;
 2212:             $clientmathml=($clientversion>=$minv);
 2213:             $clientunicode=($clientversion>=$univ);
 2214: 	}
 2215:     }
 2216:     my $clientos='unknown';
 2217:     if (($httpbrowser=~/linux/i) ||
 2218:         ($httpbrowser=~/unix/i) ||
 2219:         ($httpbrowser=~/ux/i) ||
 2220:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2221:     if (($httpbrowser=~/vax/i) ||
 2222:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2223:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2224:     if (($httpbrowser=~/mac/i) ||
 2225:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2226:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2227:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2228:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2229:             $clientunicode,$clientos,);
 2230: }
 2231: 
 2232: ###############################################################
 2233: ##    Authentication changing form generation subroutines    ##
 2234: ###############################################################
 2235: ##
 2236: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2237: ## hash, and have reasonable default values.
 2238: ##
 2239: ##    formname = the name given in the <form> tag.
 2240: #-------------------------------------------
 2241: 
 2242: =pod
 2243: 
 2244: =head1 Authentication Routines
 2245: 
 2246: =over 4
 2247: 
 2248: =item * &authform_xxxxxx()
 2249: 
 2250: The authform_xxxxxx subroutines provide javascript and html forms which 
 2251: handle some of the conveniences required for authentication forms.  
 2252: This is not an optimal method, but it works.  
 2253: 
 2254: =over 4
 2255: 
 2256: =item * authform_header
 2257: 
 2258: =item * authform_authorwarning
 2259: 
 2260: =item * authform_nochange
 2261: 
 2262: =item * authform_kerberos
 2263: 
 2264: =item * authform_internal
 2265: 
 2266: =item * authform_filesystem
 2267: 
 2268: =back
 2269: 
 2270: See loncreateuser.pm for invocation and use examples.
 2271: 
 2272: =cut
 2273: 
 2274: #-------------------------------------------
 2275: sub authform_header{  
 2276:     my %in = (
 2277:         formname => 'cu',
 2278:         kerb_def_dom => '',
 2279:         @_,
 2280:     );
 2281:     $in{'formname'} = 'document.' . $in{'formname'};
 2282:     my $result='';
 2283: 
 2284: #---------------------------------------------- Code for upper case translation
 2285:     my $Javascript_toUpperCase;
 2286:     unless ($in{kerb_def_dom}) {
 2287:         $Javascript_toUpperCase =<<"END";
 2288:         switch (choice) {
 2289:            case 'krb': currentform.elements[choicearg].value =
 2290:                currentform.elements[choicearg].value.toUpperCase();
 2291:                break;
 2292:            default:
 2293:         }
 2294: END
 2295:     } else {
 2296:         $Javascript_toUpperCase = "";
 2297:     }
 2298: 
 2299:     my $radioval = "'nochange'";
 2300:     if (defined($in{'curr_authtype'})) {
 2301:         if ($in{'curr_authtype'} ne '') {
 2302:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2303:         }
 2304:     }
 2305:     my $argfield = 'null';
 2306:     if (defined($in{'mode'})) {
 2307:         if ($in{'mode'} eq 'modifycourse')  {
 2308:             if (defined($in{'curr_autharg'})) {
 2309:                 if ($in{'curr_autharg'} ne '') {
 2310:                     $argfield = "'$in{'curr_autharg'}'";
 2311:                 }
 2312:             }
 2313:         }
 2314:     }
 2315: 
 2316:     $result.=<<"END";
 2317: var current = new Object();
 2318: current.radiovalue = $radioval;
 2319: current.argfield = $argfield;
 2320: 
 2321: function changed_radio(choice,currentform) {
 2322:     var choicearg = choice + 'arg';
 2323:     // If a radio button in changed, we need to change the argfield
 2324:     if (current.radiovalue != choice) {
 2325:         current.radiovalue = choice;
 2326:         if (current.argfield != null) {
 2327:             currentform.elements[current.argfield].value = '';
 2328:         }
 2329:         if (choice == 'nochange') {
 2330:             current.argfield = null;
 2331:         } else {
 2332:             current.argfield = choicearg;
 2333:             switch(choice) {
 2334:                 case 'krb': 
 2335:                     currentform.elements[current.argfield].value = 
 2336:                         "$in{'kerb_def_dom'}";
 2337:                 break;
 2338:               default:
 2339:                 break;
 2340:             }
 2341:         }
 2342:     }
 2343:     return;
 2344: }
 2345: 
 2346: function changed_text(choice,currentform) {
 2347:     var choicearg = choice + 'arg';
 2348:     if (currentform.elements[choicearg].value !='') {
 2349:         $Javascript_toUpperCase
 2350:         // clear old field
 2351:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2352:             currentform.elements[current.argfield].value = '';
 2353:         }
 2354:         current.argfield = choicearg;
 2355:     }
 2356:     set_auth_radio_buttons(choice,currentform);
 2357:     return;
 2358: }
 2359: 
 2360: function set_auth_radio_buttons(newvalue,currentform) {
 2361:     var numauthchoices = currentform.login.length;
 2362:     if (typeof numauthchoices  == "undefined") {
 2363:         return;
 2364:     } 
 2365:     var i=0;
 2366:     while (i < numauthchoices) {
 2367:         if (currentform.login[i].value == newvalue) { break; }
 2368:         i++;
 2369:     }
 2370:     if (i == numauthchoices) {
 2371:         return;
 2372:     }
 2373:     current.radiovalue = newvalue;
 2374:     currentform.login[i].checked = true;
 2375:     return;
 2376: }
 2377: END
 2378:     return $result;
 2379: }
 2380: 
 2381: sub authform_authorwarning{
 2382:     my $result='';
 2383:     $result='<i>'.
 2384:         &mt('As a general rule, only authors or co-authors should be '.
 2385:             'filesystem authenticated '.
 2386:             '(which allows access to the server filesystem).')."</i>\n";
 2387:     return $result;
 2388: }
 2389: 
 2390: sub authform_nochange{  
 2391:     my %in = (
 2392:               formname => 'document.cu',
 2393:               kerb_def_dom => 'MSU.EDU',
 2394:               @_,
 2395:           );
 2396:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2397:     my $result;
 2398:     if (keys(%can_assign) == 0) {
 2399:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2400:     } else {
 2401:         $result = '<label>'.&mt('[_1] Do not change login data',
 2402:                   '<input type="radio" name="login" value="nochange" '.
 2403:                   'checked="checked" onclick="'.
 2404:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2405: 	    '</label>';
 2406:     }
 2407:     return $result;
 2408: }
 2409: 
 2410: sub authform_kerberos {
 2411:     my %in = (
 2412:               formname => 'document.cu',
 2413:               kerb_def_dom => 'MSU.EDU',
 2414:               kerb_def_auth => 'krb4',
 2415:               @_,
 2416:               );
 2417:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2418:         $autharg,$jscall);
 2419:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2420:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2421:        $check5 = ' checked="checked"';
 2422:     } else {
 2423:        $check4 = ' checked="checked"';
 2424:     }
 2425:     $krbarg = $in{'kerb_def_dom'};
 2426:     if (defined($in{'curr_authtype'})) {
 2427:         if ($in{'curr_authtype'} eq 'krb') {
 2428:             $krbcheck = ' checked="checked"';
 2429:             if (defined($in{'mode'})) {
 2430:                 if ($in{'mode'} eq 'modifyuser') {
 2431:                     $krbcheck = '';
 2432:                 }
 2433:             }
 2434:             if (defined($in{'curr_kerb_ver'})) {
 2435:                 if ($in{'curr_krb_ver'} eq '5') {
 2436:                     $check5 = ' checked="checked"';
 2437:                     $check4 = '';
 2438:                 } else {
 2439:                     $check4 = ' checked="checked"';
 2440:                     $check5 = '';
 2441:                 }
 2442:             }
 2443:             if (defined($in{'curr_autharg'})) {
 2444:                 $krbarg = $in{'curr_autharg'};
 2445:             }
 2446:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2447:                 if (defined($in{'curr_autharg'})) {
 2448:                     $result = 
 2449:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2450:         $in{'curr_autharg'},$krbver);
 2451:                 } else {
 2452:                     $result =
 2453:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2454:                 }
 2455:                 return $result; 
 2456:             }
 2457:         }
 2458:     } else {
 2459:         if ($authnum == 1) {
 2460:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2461:         }
 2462:     }
 2463:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2464:         return;
 2465:     } elsif ($authtype eq '') {
 2466:         if (defined($in{'mode'})) {
 2467:             if ($in{'mode'} eq 'modifycourse') {
 2468:                 if ($authnum == 1) {
 2469:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2470:                 }
 2471:             }
 2472:         }
 2473:     }
 2474:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2475:     if ($authtype eq '') {
 2476:         $authtype = '<input type="radio" name="login" value="krb" '.
 2477:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2478:                     $krbcheck.' />';
 2479:     }
 2480:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2481:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2482:          $in{'curr_authtype'} eq 'krb5') ||
 2483:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2484:          $in{'curr_authtype'} eq 'krb4')) {
 2485:         $result .= &mt
 2486:         ('[_1] Kerberos authenticated with domain [_2] '.
 2487:          '[_3] Version 4 [_4] Version 5 [_5]',
 2488:          '<label>'.$authtype,
 2489:          '</label><input type="text" size="10" name="krbarg" '.
 2490:              'value="'.$krbarg.'" '.
 2491:              'onchange="'.$jscall.'" />',
 2492:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2493:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2494: 	 '</label>');
 2495:     } elsif ($can_assign{'krb4'}) {
 2496:         $result .= &mt
 2497:         ('[_1] Kerberos authenticated with domain [_2] '.
 2498:          '[_3] Version 4 [_4]',
 2499:          '<label>'.$authtype,
 2500:          '</label><input type="text" size="10" name="krbarg" '.
 2501:              'value="'.$krbarg.'" '.
 2502:              'onchange="'.$jscall.'" />',
 2503:          '<label><input type="hidden" name="krbver" value="4" />',
 2504:          '</label>');
 2505:     } elsif ($can_assign{'krb5'}) {
 2506:         $result .= &mt
 2507:         ('[_1] Kerberos authenticated with domain [_2] '.
 2508:          '[_3] Version 5 [_4]',
 2509:          '<label>'.$authtype,
 2510:          '</label><input type="text" size="10" name="krbarg" '.
 2511:              'value="'.$krbarg.'" '.
 2512:              'onchange="'.$jscall.'" />',
 2513:          '<label><input type="hidden" name="krbver" value="5" />',
 2514:          '</label>');
 2515:     }
 2516:     return $result;
 2517: }
 2518: 
 2519: sub authform_internal{  
 2520:     my %in = (
 2521:                 formname => 'document.cu',
 2522:                 kerb_def_dom => 'MSU.EDU',
 2523:                 @_,
 2524:                 );
 2525:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2526:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2527:     if (defined($in{'curr_authtype'})) {
 2528:         if ($in{'curr_authtype'} eq 'int') {
 2529:             if ($can_assign{'int'}) {
 2530:                 $intcheck = 'checked="checked" ';
 2531:                 if (defined($in{'mode'})) {
 2532:                     if ($in{'mode'} eq 'modifyuser') {
 2533:                         $intcheck = '';
 2534:                     }
 2535:                 }
 2536:                 if (defined($in{'curr_autharg'})) {
 2537:                     $intarg = $in{'curr_autharg'};
 2538:                 }
 2539:             } else {
 2540:                 $result = &mt('Currently internally authenticated.');
 2541:                 return $result;
 2542:             }
 2543:         }
 2544:     } else {
 2545:         if ($authnum == 1) {
 2546:             $authtype = '<input type="hidden" name="login" value="int" />';
 2547:         }
 2548:     }
 2549:     if (!$can_assign{'int'}) {
 2550:         return;
 2551:     } elsif ($authtype eq '') {
 2552:         if (defined($in{'mode'})) {
 2553:             if ($in{'mode'} eq 'modifycourse') {
 2554:                 if ($authnum == 1) {
 2555:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2556:                 }
 2557:             }
 2558:         }
 2559:     }
 2560:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2561:     if ($authtype eq '') {
 2562:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2563:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2564:     }
 2565:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2566:                $intarg.'" onchange="'.$jscall.'" />';
 2567:     $result = &mt
 2568:         ('[_1] Internally authenticated (with initial password [_2])',
 2569:          '<label>'.$authtype,'</label>'.$autharg);
 2570:     $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>';
 2571:     return $result;
 2572: }
 2573: 
 2574: sub authform_local{  
 2575:     my %in = (
 2576:               formname => 'document.cu',
 2577:               kerb_def_dom => 'MSU.EDU',
 2578:               @_,
 2579:               );
 2580:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2581:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2582:     if (defined($in{'curr_authtype'})) {
 2583:         if ($in{'curr_authtype'} eq 'loc') {
 2584:             if ($can_assign{'loc'}) {
 2585:                 $loccheck = 'checked="checked" ';
 2586:                 if (defined($in{'mode'})) {
 2587:                     if ($in{'mode'} eq 'modifyuser') {
 2588:                         $loccheck = '';
 2589:                     }
 2590:                 }
 2591:                 if (defined($in{'curr_autharg'})) {
 2592:                     $locarg = $in{'curr_autharg'};
 2593:                 }
 2594:             } else {
 2595:                 $result = &mt('Currently using local (institutional) authentication.');
 2596:                 return $result;
 2597:             }
 2598:         }
 2599:     } else {
 2600:         if ($authnum == 1) {
 2601:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2602:         }
 2603:     }
 2604:     if (!$can_assign{'loc'}) {
 2605:         return;
 2606:     } elsif ($authtype eq '') {
 2607:         if (defined($in{'mode'})) {
 2608:             if ($in{'mode'} eq 'modifycourse') {
 2609:                 if ($authnum == 1) {
 2610:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2611:                 }
 2612:             }
 2613:         }
 2614:     }
 2615:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2616:     if ($authtype eq '') {
 2617:         $authtype = '<input type="radio" name="login" value="loc" '.
 2618:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2619:                     $jscall.'" />';
 2620:     }
 2621:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2622:                $locarg.'" onchange="'.$jscall.'" />';
 2623:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2624:                   '<label>'.$authtype,'</label>'.$autharg);
 2625:     return $result;
 2626: }
 2627: 
 2628: sub authform_filesystem{  
 2629:     my %in = (
 2630:               formname => 'document.cu',
 2631:               kerb_def_dom => 'MSU.EDU',
 2632:               @_,
 2633:               );
 2634:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2635:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2636:     if (defined($in{'curr_authtype'})) {
 2637:         if ($in{'curr_authtype'} eq 'fsys') {
 2638:             if ($can_assign{'fsys'}) {
 2639:                 $fsyscheck = 'checked="checked" ';
 2640:                 if (defined($in{'mode'})) {
 2641:                     if ($in{'mode'} eq 'modifyuser') {
 2642:                         $fsyscheck = '';
 2643:                     }
 2644:                 }
 2645:             } else {
 2646:                 $result = &mt('Currently Filesystem Authenticated.');
 2647:                 return $result;
 2648:             }           
 2649:         }
 2650:     } else {
 2651:         if ($authnum == 1) {
 2652:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2653:         }
 2654:     }
 2655:     if (!$can_assign{'fsys'}) {
 2656:         return;
 2657:     } elsif ($authtype eq '') {
 2658:         if (defined($in{'mode'})) {
 2659:             if ($in{'mode'} eq 'modifycourse') {
 2660:                 if ($authnum == 1) {
 2661:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2662:                 }
 2663:             }
 2664:         }
 2665:     }
 2666:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2667:     if ($authtype eq '') {
 2668:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2669:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2670:                     $jscall.'" />';
 2671:     }
 2672:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2673:                ' onchange="'.$jscall.'" />';
 2674:     $result = &mt
 2675:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2676:          '<label><input type="radio" name="login" value="fsys" '.
 2677:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2678:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2679:                   'onchange="'.$jscall.'" />');
 2680:     return $result;
 2681: }
 2682: 
 2683: sub get_assignable_auth {
 2684:     my ($dom) = @_;
 2685:     if ($dom eq '') {
 2686:         $dom = $env{'request.role.domain'};
 2687:     }
 2688:     my %can_assign = (
 2689:                           krb4 => 1,
 2690:                           krb5 => 1,
 2691:                           int  => 1,
 2692:                           loc  => 1,
 2693:                      );
 2694:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2695:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2696:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2697:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2698:             my $context;
 2699:             if ($env{'request.role'} =~ /^au/) {
 2700:                 $context = 'author';
 2701:             } elsif ($env{'request.role'} =~ /^dc/) {
 2702:                 $context = 'domain';
 2703:             } elsif ($env{'request.course.id'}) {
 2704:                 $context = 'course';
 2705:             }
 2706:             if ($context) {
 2707:                 if (ref($authhash->{$context}) eq 'HASH') {
 2708:                    %can_assign = %{$authhash->{$context}}; 
 2709:                 }
 2710:             }
 2711:         }
 2712:     }
 2713:     my $authnum = 0;
 2714:     foreach my $key (keys(%can_assign)) {
 2715:         if ($can_assign{$key}) {
 2716:             $authnum ++;
 2717:         }
 2718:     }
 2719:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2720:         $authnum --;
 2721:     }
 2722:     return ($authnum,%can_assign);
 2723: }
 2724: 
 2725: ###############################################################
 2726: ##    Get Kerberos Defaults for Domain                 ##
 2727: ###############################################################
 2728: ##
 2729: ## Returns default kerberos version and an associated argument
 2730: ## as listed in file domain.tab. If not listed, provides
 2731: ## appropriate default domain and kerberos version.
 2732: ##
 2733: #-------------------------------------------
 2734: 
 2735: =pod
 2736: 
 2737: =item * &get_kerberos_defaults()
 2738: 
 2739: get_kerberos_defaults($target_domain) returns the default kerberos
 2740: version and domain. If not found, it defaults to version 4 and the 
 2741: domain of the server.
 2742: 
 2743: =over 4
 2744: 
 2745: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2746: 
 2747: =back
 2748: 
 2749: =back
 2750: 
 2751: =cut
 2752: 
 2753: #-------------------------------------------
 2754: sub get_kerberos_defaults {
 2755:     my $domain=shift;
 2756:     my ($krbdef,$krbdefdom);
 2757:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2758:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2759:         $krbdef = $domdefaults{'auth_def'};
 2760:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2761:     } else {
 2762:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2763:         my $krbdefdom=$1;
 2764:         $krbdefdom=~tr/a-z/A-Z/;
 2765:         $krbdef = "krb4";
 2766:     }
 2767:     return ($krbdef,$krbdefdom);
 2768: }
 2769: 
 2770: 
 2771: ###############################################################
 2772: ##                Thesaurus Functions                        ##
 2773: ###############################################################
 2774: 
 2775: =pod
 2776: 
 2777: =head1 Thesaurus Functions
 2778: 
 2779: =over 4
 2780: 
 2781: =item * &initialize_keywords()
 2782: 
 2783: Initializes the package variable %Keywords if it is empty.  Uses the
 2784: package variable $thesaurus_db_file.
 2785: 
 2786: =cut
 2787: 
 2788: ###################################################
 2789: 
 2790: sub initialize_keywords {
 2791:     return 1 if (scalar keys(%Keywords));
 2792:     # If we are here, %Keywords is empty, so fill it up
 2793:     #   Make sure the file we need exists...
 2794:     if (! -e $thesaurus_db_file) {
 2795:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2796:                                  " failed because it does not exist");
 2797:         return 0;
 2798:     }
 2799:     #   Set up the hash as a database
 2800:     my %thesaurus_db;
 2801:     if (! tie(%thesaurus_db,'GDBM_File',
 2802:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2803:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2804:                                  $thesaurus_db_file);
 2805:         return 0;
 2806:     } 
 2807:     #  Get the average number of appearances of a word.
 2808:     my $avecount = $thesaurus_db{'average.count'};
 2809:     #  Put keywords (those that appear > average) into %Keywords
 2810:     while (my ($word,$data)=each (%thesaurus_db)) {
 2811:         my ($count,undef) = split /:/,$data;
 2812:         $Keywords{$word}++ if ($count > $avecount);
 2813:     }
 2814:     untie %thesaurus_db;
 2815:     # Remove special values from %Keywords.
 2816:     foreach my $value ('total.count','average.count') {
 2817:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2818:   }
 2819:     return 1;
 2820: }
 2821: 
 2822: ###################################################
 2823: 
 2824: =pod
 2825: 
 2826: =item * &keyword($word)
 2827: 
 2828: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2829: than the average number of times in the thesaurus database.  Calls 
 2830: &initialize_keywords
 2831: 
 2832: =cut
 2833: 
 2834: ###################################################
 2835: 
 2836: sub keyword {
 2837:     return if (!&initialize_keywords());
 2838:     my $word=lc(shift());
 2839:     $word=~s/\W//g;
 2840:     return exists($Keywords{$word});
 2841: }
 2842: 
 2843: ###############################################################
 2844: 
 2845: =pod 
 2846: 
 2847: =item * &get_related_words()
 2848: 
 2849: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2850: an array of words.  If the keyword is not in the thesaurus, an empty array
 2851: will be returned.  The order of the words returned is determined by the
 2852: database which holds them.
 2853: 
 2854: Uses global $thesaurus_db_file.
 2855: 
 2856: =cut
 2857: 
 2858: ###############################################################
 2859: sub get_related_words {
 2860:     my $keyword = shift;
 2861:     my %thesaurus_db;
 2862:     if (! -e $thesaurus_db_file) {
 2863:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2864:                                  "failed because the file does not exist");
 2865:         return ();
 2866:     }
 2867:     if (! tie(%thesaurus_db,'GDBM_File',
 2868:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2869:         return ();
 2870:     } 
 2871:     my @Words=();
 2872:     my $count=0;
 2873:     if (exists($thesaurus_db{$keyword})) {
 2874: 	# The first element is the number of times
 2875: 	# the word appears.  We do not need it now.
 2876: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2877: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2878: 	my $threshold=$mostfrequentcount/10;
 2879:         foreach my $possibleword (@RelatedWords) {
 2880:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2881:             if ($wordcount>$threshold) {
 2882: 		push(@Words,$word);
 2883:                 $count++;
 2884:                 if ($count>10) { last; }
 2885: 	    }
 2886:         }
 2887:     }
 2888:     untie %thesaurus_db;
 2889:     return @Words;
 2890: }
 2891: 
 2892: =pod
 2893: 
 2894: =back
 2895: 
 2896: =cut
 2897: 
 2898: # -------------------------------------------------------------- Plaintext name
 2899: =pod
 2900: 
 2901: =head1 User Name Functions
 2902: 
 2903: =over 4
 2904: 
 2905: =item * &plainname($uname,$udom,$first)
 2906: 
 2907: Takes a users logon name and returns it as a string in
 2908: "first middle last generation" form 
 2909: if $first is set to 'lastname' then it returns it as
 2910: 'lastname generation, firstname middlename' if their is a lastname
 2911: 
 2912: =cut
 2913: 
 2914: 
 2915: ###############################################################
 2916: sub plainname {
 2917:     my ($uname,$udom,$first)=@_;
 2918:     return if (!defined($uname) || !defined($udom));
 2919:     my %names=&getnames($uname,$udom);
 2920:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2921: 					  $names{'middlename'},
 2922: 					  $names{'lastname'},
 2923: 					  $names{'generation'},$first);
 2924:     $name=~s/^\s+//;
 2925:     $name=~s/\s+$//;
 2926:     $name=~s/\s+/ /g;
 2927:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2928:     return $name;
 2929: }
 2930: 
 2931: # -------------------------------------------------------------------- Nickname
 2932: =pod
 2933: 
 2934: =item * &nickname($uname,$udom)
 2935: 
 2936: Gets a users name and returns it as a string as
 2937: 
 2938: "&quot;nickname&quot;"
 2939: 
 2940: if the user has a nickname or
 2941: 
 2942: "first middle last generation"
 2943: 
 2944: if the user does not
 2945: 
 2946: =cut
 2947: 
 2948: sub nickname {
 2949:     my ($uname,$udom)=@_;
 2950:     return if (!defined($uname) || !defined($udom));
 2951:     my %names=&getnames($uname,$udom);
 2952:     my $name=$names{'nickname'};
 2953:     if ($name) {
 2954:        $name='&quot;'.$name.'&quot;'; 
 2955:     } else {
 2956:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2957: 	     $names{'lastname'}.' '.$names{'generation'};
 2958:        $name=~s/\s+$//;
 2959:        $name=~s/\s+/ /g;
 2960:     }
 2961:     return $name;
 2962: }
 2963: 
 2964: sub getnames {
 2965:     my ($uname,$udom)=@_;
 2966:     return if (!defined($uname) || !defined($udom));
 2967:     if ($udom eq 'public' && $uname eq 'public') {
 2968: 	return ('lastname' => &mt('Public'));
 2969:     }
 2970:     my $id=$uname.':'.$udom;
 2971:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2972:     if ($cached) {
 2973: 	return %{$names};
 2974:     } else {
 2975: 	my %loadnames=&Apache::lonnet::get('environment',
 2976:                     ['firstname','middlename','lastname','generation','nickname'],
 2977: 					 $udom,$uname);
 2978: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2979: 	return %loadnames;
 2980:     }
 2981: }
 2982: 
 2983: # -------------------------------------------------------------------- getemails
 2984: 
 2985: =pod
 2986: 
 2987: =item * &getemails($uname,$udom)
 2988: 
 2989: Gets a user's email information and returns it as a hash with keys:
 2990: notification, critnotification, permanentemail
 2991: 
 2992: For notification and critnotification, values are comma-separated lists 
 2993: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2994:  
 2995: 
 2996: =cut
 2997: 
 2998: 
 2999: sub getemails {
 3000:     my ($uname,$udom)=@_;
 3001:     if ($udom eq 'public' && $uname eq 'public') {
 3002: 	return;
 3003:     }
 3004:     if (!$udom) { $udom=$env{'user.domain'}; }
 3005:     if (!$uname) { $uname=$env{'user.name'}; }
 3006:     my $id=$uname.':'.$udom;
 3007:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3008:     if ($cached) {
 3009: 	return %{$names};
 3010:     } else {
 3011: 	my %loadnames=&Apache::lonnet::get('environment',
 3012:                     			   ['notification','critnotification',
 3013: 					    'permanentemail'],
 3014: 					   $udom,$uname);
 3015: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3016: 	return %loadnames;
 3017:     }
 3018: }
 3019: 
 3020: sub flush_email_cache {
 3021:     my ($uname,$udom)=@_;
 3022:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3023:     if (!$uname) { $uname=$env{'user.name'};   }
 3024:     return if ($udom eq 'public' && $uname eq 'public');
 3025:     my $id=$uname.':'.$udom;
 3026:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3027: }
 3028: 
 3029: # -------------------------------------------------------------------- getlangs
 3030: 
 3031: =pod
 3032: 
 3033: =item * &getlangs($uname,$udom)
 3034: 
 3035: Gets a user's language preference and returns it as a hash with key:
 3036: language.
 3037: 
 3038: =cut
 3039: 
 3040: 
 3041: sub getlangs {
 3042:     my ($uname,$udom) = @_;
 3043:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3044:     if (!$uname) { $uname=$env{'user.name'};   }
 3045:     my $id=$uname.':'.$udom;
 3046:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3047:     if ($cached) {
 3048:         return %{$langs};
 3049:     } else {
 3050:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3051:                                            $udom,$uname);
 3052:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3053:         return %loadlangs;
 3054:     }
 3055: }
 3056: 
 3057: sub flush_langs_cache {
 3058:     my ($uname,$udom)=@_;
 3059:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3060:     if (!$uname) { $uname=$env{'user.name'};   }
 3061:     return if ($udom eq 'public' && $uname eq 'public');
 3062:     my $id=$uname.':'.$udom;
 3063:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3064: }
 3065: 
 3066: # ------------------------------------------------------------------ Screenname
 3067: 
 3068: =pod
 3069: 
 3070: =item * &screenname($uname,$udom)
 3071: 
 3072: Gets a users screenname and returns it as a string
 3073: 
 3074: =cut
 3075: 
 3076: sub screenname {
 3077:     my ($uname,$udom)=@_;
 3078:     if ($uname eq $env{'user.name'} &&
 3079: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3080:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3081:     return $names{'screenname'};
 3082: }
 3083: 
 3084: 
 3085: # ------------------------------------------------------------- Confirm Wrapper
 3086: =pod
 3087: 
 3088: =item confirmwrapper
 3089: 
 3090: Wrap messages about completion of operation in box
 3091: 
 3092: =cut
 3093: 
 3094: sub confirmwrapper {
 3095:     my ($message)=@_;
 3096:     if ($message) {
 3097:         return "\n".'<div class="LC_confirm_box">'."\n"
 3098:                .$message."\n"
 3099:                .'</div>'."\n";
 3100:     } else {
 3101:         return $message;
 3102:     }
 3103: }
 3104: 
 3105: # ------------------------------------------------------------- Message Wrapper
 3106: 
 3107: sub messagewrapper {
 3108:     my ($link,$username,$domain,$subject,$text)=@_;
 3109:     return 
 3110:         '<a href="/adm/email?compose=individual&amp;'.
 3111:         'recname='.$username.'&amp;recdom='.$domain.
 3112: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3113:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3114: }
 3115: 
 3116: # --------------------------------------------------------------- Notes Wrapper
 3117: 
 3118: sub noteswrapper {
 3119:     my ($link,$un,$do)=@_;
 3120:     return 
 3121: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3122: }
 3123: 
 3124: # ------------------------------------------------------------- Aboutme Wrapper
 3125: 
 3126: sub aboutmewrapper {
 3127:     my ($link,$username,$domain,$target)=@_;
 3128:     if (!defined($username)  && !defined($domain)) {
 3129:         return;
 3130:     }
 3131:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3132: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3133: }
 3134: 
 3135: # ------------------------------------------------------------ Syllabus Wrapper
 3136: 
 3137: sub syllabuswrapper {
 3138:     my ($linktext,$coursedir,$domain)=@_;
 3139:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3140: }
 3141: 
 3142: # -----------------------------------------------------------------------------
 3143: 
 3144: sub track_student_link {
 3145:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3146:     my $link ="/adm/trackstudent?";
 3147:     my $title = 'View recent activity';
 3148:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3149:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3150:         $link .= "selected_student=$sname:$sdom";
 3151:         $title .= ' of this student';
 3152:     } 
 3153:     if (defined($target) && $target !~ /^\s*$/) {
 3154:         $target = qq{target="$target"};
 3155:     } else {
 3156:         $target = '';
 3157:     }
 3158:     if ($start) { $link.='&amp;start='.$start; }
 3159:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3160:     $title = &mt($title);
 3161:     $linktext = &mt($linktext);
 3162:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3163: 	&help_open_topic('View_recent_activity');
 3164: }
 3165: 
 3166: sub slot_reservations_link {
 3167:     my ($linktext,$sname,$sdom,$target) = @_;
 3168:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3169:     my $title = 'View slot reservation history';
 3170:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3171:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3172:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3173:         $title .= ' of this student';
 3174:     }
 3175:     if (defined($target) && $target !~ /^\s*$/) {
 3176:         $target = qq{target="$target"};
 3177:     } else {
 3178:         $target = '';
 3179:     }
 3180:     $title = &mt($title);
 3181:     $linktext = &mt($linktext);
 3182:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3183: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3184: 
 3185: }
 3186: 
 3187: # ===================================================== Display a student photo
 3188: 
 3189: 
 3190: sub student_image_tag {
 3191:     my ($domain,$user)=@_;
 3192:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3193:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3194: 	return '<img src="'.$imgsrc.'" align="right" />';
 3195:     } else {
 3196: 	return '';
 3197:     }
 3198: }
 3199: 
 3200: =pod
 3201: 
 3202: =back
 3203: 
 3204: =head1 Access .tab File Data
 3205: 
 3206: =over 4
 3207: 
 3208: =item * &languageids() 
 3209: 
 3210: returns list of all language ids
 3211: 
 3212: =cut
 3213: 
 3214: sub languageids {
 3215:     return sort(keys(%language));
 3216: }
 3217: 
 3218: =pod
 3219: 
 3220: =item * &languagedescription() 
 3221: 
 3222: returns description of a specified language id
 3223: 
 3224: =cut
 3225: 
 3226: sub languagedescription {
 3227:     my $code=shift;
 3228:     return  ($supported_language{$code}?'* ':'').
 3229:             $language{$code}.
 3230: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3231: }
 3232: 
 3233: sub plainlanguagedescription {
 3234:     my $code=shift;
 3235:     return $language{$code};
 3236: }
 3237: 
 3238: sub supportedlanguagecode {
 3239:     my $code=shift;
 3240:     return $supported_language{$code};
 3241: }
 3242: 
 3243: =pod
 3244: 
 3245: =item * &copyrightids() 
 3246: 
 3247: returns list of all copyrights
 3248: 
 3249: =cut
 3250: 
 3251: sub copyrightids {
 3252:     return sort(keys(%cprtag));
 3253: }
 3254: 
 3255: =pod
 3256: 
 3257: =item * &copyrightdescription() 
 3258: 
 3259: returns description of a specified copyright id
 3260: 
 3261: =cut
 3262: 
 3263: sub copyrightdescription {
 3264:     return &mt($cprtag{shift(@_)});
 3265: }
 3266: 
 3267: =pod
 3268: 
 3269: =item * &source_copyrightids() 
 3270: 
 3271: returns list of all source copyrights
 3272: 
 3273: =cut
 3274: 
 3275: sub source_copyrightids {
 3276:     return sort(keys(%scprtag));
 3277: }
 3278: 
 3279: =pod
 3280: 
 3281: =item * &source_copyrightdescription() 
 3282: 
 3283: returns description of a specified source copyright id
 3284: 
 3285: =cut
 3286: 
 3287: sub source_copyrightdescription {
 3288:     return &mt($scprtag{shift(@_)});
 3289: }
 3290: 
 3291: =pod
 3292: 
 3293: =item * &filecategories() 
 3294: 
 3295: returns list of all file categories
 3296: 
 3297: =cut
 3298: 
 3299: sub filecategories {
 3300:     return sort(keys(%category_extensions));
 3301: }
 3302: 
 3303: =pod
 3304: 
 3305: =item * &filecategorytypes() 
 3306: 
 3307: returns list of file types belonging to a given file
 3308: category
 3309: 
 3310: =cut
 3311: 
 3312: sub filecategorytypes {
 3313:     my ($cat) = @_;
 3314:     return @{$category_extensions{lc($cat)}};
 3315: }
 3316: 
 3317: =pod
 3318: 
 3319: =item * &fileembstyle() 
 3320: 
 3321: returns embedding style for a specified file type
 3322: 
 3323: =cut
 3324: 
 3325: sub fileembstyle {
 3326:     return $fe{lc(shift(@_))};
 3327: }
 3328: 
 3329: sub filemimetype {
 3330:     return $fm{lc(shift(@_))};
 3331: }
 3332: 
 3333: 
 3334: sub filecategoryselect {
 3335:     my ($name,$value)=@_;
 3336:     return &select_form($value,$name,
 3337:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3338: }
 3339: 
 3340: =pod
 3341: 
 3342: =item * &filedescription() 
 3343: 
 3344: returns description for a specified file type
 3345: 
 3346: =cut
 3347: 
 3348: sub filedescription {
 3349:     my $file_description = $fd{lc(shift())};
 3350:     $file_description =~ s:([\[\]]):~$1:g;
 3351:     return &mt($file_description);
 3352: }
 3353: 
 3354: =pod
 3355: 
 3356: =item * &filedescriptionex() 
 3357: 
 3358: returns description for a specified file type with
 3359: extra formatting
 3360: 
 3361: =cut
 3362: 
 3363: sub filedescriptionex {
 3364:     my $ex=shift;
 3365:     my $file_description = $fd{lc($ex)};
 3366:     $file_description =~ s:([\[\]]):~$1:g;
 3367:     return '.'.$ex.' '.&mt($file_description);
 3368: }
 3369: 
 3370: # End of .tab access
 3371: =pod
 3372: 
 3373: =back
 3374: 
 3375: =cut
 3376: 
 3377: # ------------------------------------------------------------------ File Types
 3378: sub fileextensions {
 3379:     return sort(keys(%fe));
 3380: }
 3381: 
 3382: # ----------------------------------------------------------- Display Languages
 3383: # returns a hash with all desired display languages
 3384: #
 3385: 
 3386: sub display_languages {
 3387:     my %languages=();
 3388:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3389: 	$languages{$lang}=1;
 3390:     }
 3391:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3392:     if ($env{'form.displaylanguage'}) {
 3393: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3394: 	    $languages{$lang}=1;
 3395:         }
 3396:     }
 3397:     return %languages;
 3398: }
 3399: 
 3400: sub languages {
 3401:     my ($possible_langs) = @_;
 3402:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3403:     if (!ref($possible_langs)) {
 3404: 	if( wantarray ) {
 3405: 	    return @preferred_langs;
 3406: 	} else {
 3407: 	    return $preferred_langs[0];
 3408: 	}
 3409:     }
 3410:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3411:     my @preferred_possibilities;
 3412:     foreach my $preferred_lang (@preferred_langs) {
 3413: 	if (exists($possibilities{$preferred_lang})) {
 3414: 	    push(@preferred_possibilities, $preferred_lang);
 3415: 	}
 3416:     }
 3417:     if( wantarray ) {
 3418: 	return @preferred_possibilities;
 3419:     }
 3420:     return $preferred_possibilities[0];
 3421: }
 3422: 
 3423: sub user_lang {
 3424:     my ($touname,$toudom,$fromcid) = @_;
 3425:     my @userlangs;
 3426:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3427:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3428:                     $env{'course.'.$fromcid.'.languages'}));
 3429:     } else {
 3430:         my %langhash = &getlangs($touname,$toudom);
 3431:         if ($langhash{'languages'} ne '') {
 3432:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3433:         } else {
 3434:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3435:             if ($domdefs{'lang_def'} ne '') {
 3436:                 @userlangs = ($domdefs{'lang_def'});
 3437:             }
 3438:         }
 3439:     }
 3440:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3441:     my $user_lh = Apache::localize->get_handle(@languages);
 3442:     return $user_lh;
 3443: }
 3444: 
 3445: 
 3446: ###############################################################
 3447: ##               Student Answer Attempts                     ##
 3448: ###############################################################
 3449: 
 3450: =pod
 3451: 
 3452: =head1 Alternate Problem Views
 3453: 
 3454: =over 4
 3455: 
 3456: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3457:     $getattempt, $regexp, $gradesub)
 3458: 
 3459: Return string with previous attempt on problem. Arguments:
 3460: 
 3461: =over 4
 3462: 
 3463: =item * $symb: Problem, including path
 3464: 
 3465: =item * $username: username of the desired student
 3466: 
 3467: =item * $domain: domain of the desired student
 3468: 
 3469: =item * $course: Course ID
 3470: 
 3471: =item * $getattempt: Leave blank for all attempts, otherwise put
 3472:     something
 3473: 
 3474: =item * $regexp: if string matches this regexp, the string will be
 3475:     sent to $gradesub
 3476: 
 3477: =item * $gradesub: routine that processes the string if it matches $regexp
 3478: 
 3479: =back
 3480: 
 3481: The output string is a table containing all desired attempts, if any.
 3482: 
 3483: =cut
 3484: 
 3485: sub get_previous_attempt {
 3486:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3487:   my $prevattempts='';
 3488:   no strict 'refs';
 3489:   if ($symb) {
 3490:     my (%returnhash)=
 3491:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3492:     if ($returnhash{'version'}) {
 3493:       my %lasthash=();
 3494:       my $version;
 3495:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3496:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3497: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3498:         }
 3499:       }
 3500:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3501:       $prevattempts.='<th>'.&mt('History').'</th>';
 3502:       my (%typeparts,%lasthidden);
 3503:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3504:       foreach my $key (sort(keys(%lasthash))) {
 3505: 	my ($ign,@parts) = split(/\./,$key);
 3506: 	if ($#parts > 0) {
 3507: 	  my $data=$parts[-1];
 3508:           next if ($data eq 'foilorder');
 3509: 	  pop(@parts);
 3510:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3511:           if ($data eq 'type') {
 3512:               unless ($showsurv) {
 3513:                   my $id = join(',',@parts);
 3514:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3515:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3516:                       $lasthidden{$ign.'.'.$id} = 1;
 3517:                   }
 3518:               }
 3519:           } 
 3520: 	} else {
 3521: 	  if ($#parts == 0) {
 3522: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3523: 	  } else {
 3524: 	    $prevattempts.='<th>'.$ign.'</th>';
 3525: 	  }
 3526: 	}
 3527:       }
 3528:       $prevattempts.=&end_data_table_header_row();
 3529:       if ($getattempt eq '') {
 3530: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3531:             my @hidden;
 3532:             if (%typeparts) {
 3533:                 foreach my $id (keys(%typeparts)) {
 3534:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3535:                         push(@hidden,$id);
 3536:                     }
 3537:                 }
 3538:             }
 3539:             $prevattempts.=&start_data_table_row().
 3540:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3541:             if (@hidden) {
 3542:                 foreach my $key (sort(keys(%lasthash))) {
 3543:                     next if ($key =~ /\.foilorder$/);
 3544:                     my $hide;
 3545:                     foreach my $id (@hidden) {
 3546:                         if ($key =~ /^\Q$id\E/) {
 3547:                             $hide = 1;
 3548:                             last;
 3549:                         }
 3550:                     }
 3551:                     if ($hide) {
 3552:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3553:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3554:                             my $value = &format_previous_attempt_value($key,
 3555:                                              $returnhash{$version.':'.$key});
 3556:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3557:                         } else {
 3558:                             $prevattempts.='<td>&nbsp;</td>';
 3559:                         }
 3560:                     } else {
 3561:                         if ($key =~ /\./) {
 3562:                             my $value = &format_previous_attempt_value($key,
 3563:                                               $returnhash{$version.':'.$key});
 3564:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3565:                         } else {
 3566:                             $prevattempts.='<td>&nbsp;</td>';
 3567:                         }
 3568:                     }
 3569:                 }
 3570:             } else {
 3571: 	        foreach my $key (sort(keys(%lasthash))) {
 3572:                     next if ($key =~ /\.foilorder$/);
 3573: 		    my $value = &format_previous_attempt_value($key,
 3574: 			            $returnhash{$version.':'.$key});
 3575: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3576: 	        }
 3577:             }
 3578: 	    $prevattempts.=&end_data_table_row();
 3579: 	 }
 3580:       }
 3581:       my @currhidden = keys(%lasthidden);
 3582:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3583:       foreach my $key (sort(keys(%lasthash))) {
 3584:           next if ($key =~ /\.foilorder$/);
 3585:           if (%typeparts) {
 3586:               my $hidden;
 3587:               foreach my $id (@currhidden) {
 3588:                   if ($key =~ /^\Q$id\E/) {
 3589:                       $hidden = 1;
 3590:                       last;
 3591:                   }
 3592:               }
 3593:               if ($hidden) {
 3594:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3595:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3596:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3597:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3598:                           $value = &$gradesub($value);
 3599:                       }
 3600:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3601:                   } else {
 3602:                       $prevattempts.='<td>&nbsp;</td>';
 3603:                   }
 3604:               } else {
 3605:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3606:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3607:                       $value = &$gradesub($value);
 3608:                   }
 3609:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3610:               }
 3611:           } else {
 3612: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3613: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3614:                   $value = &$gradesub($value);
 3615:               }
 3616: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3617:           }
 3618:       }
 3619:       $prevattempts.= &end_data_table_row().&end_data_table();
 3620:     } else {
 3621:       $prevattempts=
 3622: 	  &start_data_table().&start_data_table_row().
 3623: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3624: 	  &end_data_table_row().&end_data_table();
 3625:     }
 3626:   } else {
 3627:     $prevattempts=
 3628: 	  &start_data_table().&start_data_table_row().
 3629: 	  '<td>'.&mt('No data.').'</td>'.
 3630: 	  &end_data_table_row().&end_data_table();
 3631:   }
 3632: }
 3633: 
 3634: sub format_previous_attempt_value {
 3635:     my ($key,$value) = @_;
 3636:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3637: 	$value = &Apache::lonlocal::locallocaltime($value);
 3638:     } elsif (ref($value) eq 'ARRAY') {
 3639: 	$value = '('.join(', ', @{ $value }).')';
 3640:     } elsif ($key =~ /answerstring$/) {
 3641:         my %answers = &Apache::lonnet::str2hash($value);
 3642:         my @anskeys = sort(keys(%answers));
 3643:         if (@anskeys == 1) {
 3644:             my $answer = $answers{$anskeys[0]};
 3645:             if ($answer =~ m{\0}) {
 3646:                 $answer =~ s{\0}{,}g;
 3647:             }
 3648:             my $tag_internal_answer_name = 'INTERNAL';
 3649:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3650:                 $value = $answer; 
 3651:             } else {
 3652:                 $value = $anskeys[0].'='.$answer;
 3653:             }
 3654:         } else {
 3655:             foreach my $ans (@anskeys) {
 3656:                 my $answer = $answers{$ans};
 3657:                 if ($answer =~ m{\0}) {
 3658:                     $answer =~ s{\0}{,}g;
 3659:                 }
 3660:                 $value .=  $ans.'='.$answer.'<br />';;
 3661:             } 
 3662:         }
 3663:     } else {
 3664: 	$value = &unescape($value);
 3665:     }
 3666:     return $value;
 3667: }
 3668: 
 3669: 
 3670: sub relative_to_absolute {
 3671:     my ($url,$output)=@_;
 3672:     my $parser=HTML::TokeParser->new(\$output);
 3673:     my $token;
 3674:     my $thisdir=$url;
 3675:     my @rlinks=();
 3676:     while ($token=$parser->get_token) {
 3677: 	if ($token->[0] eq 'S') {
 3678: 	    if ($token->[1] eq 'a') {
 3679: 		if ($token->[2]->{'href'}) {
 3680: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3681: 		}
 3682: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3683: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3684: 	    } elsif ($token->[1] eq 'base') {
 3685: 		$thisdir=$token->[2]->{'href'};
 3686: 	    }
 3687: 	}
 3688:     }
 3689:     $thisdir=~s-/[^/]*$--;
 3690:     foreach my $link (@rlinks) {
 3691: 	unless (($link=~/^https?\:\/\//i) ||
 3692: 		($link=~/^\//) ||
 3693: 		($link=~/^javascript:/i) ||
 3694: 		($link=~/^mailto:/i) ||
 3695: 		($link=~/^\#/)) {
 3696: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3697: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3698: 	}
 3699:     }
 3700: # -------------------------------------------------- Deal with Applet codebases
 3701:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3702:     return $output;
 3703: }
 3704: 
 3705: =pod
 3706: 
 3707: =item * &get_student_view()
 3708: 
 3709: show a snapshot of what student was looking at
 3710: 
 3711: =cut
 3712: 
 3713: sub get_student_view {
 3714:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3715:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3716:   my (%form);
 3717:   my @elements=('symb','courseid','domain','username');
 3718:   foreach my $element (@elements) {
 3719:       $form{'grade_'.$element}=eval '$'.$element #'
 3720:   }
 3721:   if (defined($moreenv)) {
 3722:       %form=(%form,%{$moreenv});
 3723:   }
 3724:   if (defined($target)) { $form{'grade_target'} = $target; }
 3725:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3726:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3727:   $userview=~s/\<body[^\>]*\>//gi;
 3728:   $userview=~s/\<\/body\>//gi;
 3729:   $userview=~s/\<html\>//gi;
 3730:   $userview=~s/\<\/html\>//gi;
 3731:   $userview=~s/\<head\>//gi;
 3732:   $userview=~s/\<\/head\>//gi;
 3733:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3734:   $userview=&relative_to_absolute($feedurl,$userview);
 3735:   if (wantarray) {
 3736:      return ($userview,$response);
 3737:   } else {
 3738:      return $userview;
 3739:   }
 3740: }
 3741: 
 3742: sub get_student_view_with_retries {
 3743:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3744: 
 3745:     my $ok = 0;                 # True if we got a good response.
 3746:     my $content;
 3747:     my $response;
 3748: 
 3749:     # Try to get the student_view done. within the retries count:
 3750:     
 3751:     do {
 3752:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3753:          $ok      = $response->is_success;
 3754:          if (!$ok) {
 3755:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3756:          }
 3757:          $retries--;
 3758:     } while (!$ok && ($retries > 0));
 3759:     
 3760:     if (!$ok) {
 3761:        $content = '';          # On error return an empty content.
 3762:     }
 3763:     if (wantarray) {
 3764:        return ($content, $response);
 3765:     } else {
 3766:        return $content;
 3767:     }
 3768: }
 3769: 
 3770: =pod
 3771: 
 3772: =item * &get_student_answers() 
 3773: 
 3774: show a snapshot of how student was answering problem
 3775: 
 3776: =cut
 3777: 
 3778: sub get_student_answers {
 3779:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3780:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3781:   my (%moreenv);
 3782:   my @elements=('symb','courseid','domain','username');
 3783:   foreach my $element (@elements) {
 3784:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3785:   }
 3786:   $moreenv{'grade_target'}='answer';
 3787:   %moreenv=(%form,%moreenv);
 3788:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3789:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3790:   return $userview;
 3791: }
 3792: 
 3793: =pod
 3794: 
 3795: =item * &submlink()
 3796: 
 3797: Inputs: $text $uname $udom $symb $target
 3798: 
 3799: Returns: A link to grades.pm such as to see the SUBM view of a student
 3800: 
 3801: =cut
 3802: 
 3803: ###############################################
 3804: sub submlink {
 3805:     my ($text,$uname,$udom,$symb,$target)=@_;
 3806:     if (!($uname && $udom)) {
 3807: 	(my $cursymb, my $courseid,$udom,$uname)=
 3808: 	    &Apache::lonnet::whichuser($symb);
 3809: 	if (!$symb) { $symb=$cursymb; }
 3810:     }
 3811:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3812:     $symb=&escape($symb);
 3813:     if ($target) { $target=" target=\"$target\""; }
 3814:     return
 3815:         '<a href="/adm/grades?command=submission'.
 3816:         '&amp;symb='.$symb.
 3817:         '&amp;student='.$uname.
 3818:         '&amp;userdom='.$udom.'"'.
 3819:         $target.'>'.$text.'</a>';
 3820: }
 3821: ##############################################
 3822: 
 3823: =pod
 3824: 
 3825: =item * &pgrdlink()
 3826: 
 3827: Inputs: $text $uname $udom $symb $target
 3828: 
 3829: Returns: A link to grades.pm such as to see the PGRD view of a student
 3830: 
 3831: =cut
 3832: 
 3833: ###############################################
 3834: sub pgrdlink {
 3835:     my $link=&submlink(@_);
 3836:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3837:     return $link;
 3838: }
 3839: ##############################################
 3840: 
 3841: =pod
 3842: 
 3843: =item * &pprmlink()
 3844: 
 3845: Inputs: $text $uname $udom $symb $target
 3846: 
 3847: Returns: A link to parmset.pm such as to see the PPRM view of a
 3848: student and a specific resource
 3849: 
 3850: =cut
 3851: 
 3852: ###############################################
 3853: sub pprmlink {
 3854:     my ($text,$uname,$udom,$symb,$target)=@_;
 3855:     if (!($uname && $udom)) {
 3856: 	(my $cursymb, my $courseid,$udom,$uname)=
 3857: 	    &Apache::lonnet::whichuser($symb);
 3858: 	if (!$symb) { $symb=$cursymb; }
 3859:     }
 3860:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3861:     $symb=&escape($symb);
 3862:     if ($target) { $target="target=\"$target\""; }
 3863:     return '<a href="/adm/parmset?command=set&amp;'.
 3864: 	'symb='.$symb.'&amp;uname='.$uname.
 3865: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3866: }
 3867: ##############################################
 3868: 
 3869: =pod
 3870: 
 3871: =back
 3872: 
 3873: =cut
 3874: 
 3875: ###############################################
 3876: 
 3877: 
 3878: sub timehash {
 3879:     my ($thistime) = @_;
 3880:     my $timezone = &Apache::lonlocal::gettimezone();
 3881:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3882:                      ->set_time_zone($timezone);
 3883:     my $wday = $dt->day_of_week();
 3884:     if ($wday == 7) { $wday = 0; }
 3885:     return ( 'second' => $dt->second(),
 3886:              'minute' => $dt->minute(),
 3887:              'hour'   => $dt->hour(),
 3888:              'day'     => $dt->day_of_month(),
 3889:              'month'   => $dt->month(),
 3890:              'year'    => $dt->year(),
 3891:              'weekday' => $wday,
 3892:              'dayyear' => $dt->day_of_year(),
 3893:              'dlsav'   => $dt->is_dst() );
 3894: }
 3895: 
 3896: sub utc_string {
 3897:     my ($date)=@_;
 3898:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3899: }
 3900: 
 3901: sub maketime {
 3902:     my %th=@_;
 3903:     my ($epoch_time,$timezone,$dt);
 3904:     $timezone = &Apache::lonlocal::gettimezone();
 3905:     eval {
 3906:         $dt = DateTime->new( year   => $th{'year'},
 3907:                              month  => $th{'month'},
 3908:                              day    => $th{'day'},
 3909:                              hour   => $th{'hour'},
 3910:                              minute => $th{'minute'},
 3911:                              second => $th{'second'},
 3912:                              time_zone => $timezone,
 3913:                          );
 3914:     };
 3915:     if (!$@) {
 3916:         $epoch_time = $dt->epoch;
 3917:         if ($epoch_time) {
 3918:             return $epoch_time;
 3919:         }
 3920:     }
 3921:     return POSIX::mktime(
 3922:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3923:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3924: }
 3925: 
 3926: #########################################
 3927: 
 3928: sub findallcourses {
 3929:     my ($roles,$uname,$udom) = @_;
 3930:     my %roles;
 3931:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3932:     my %courses;
 3933:     my $now=time;
 3934:     if (!defined($uname)) {
 3935:         $uname = $env{'user.name'};
 3936:     }
 3937:     if (!defined($udom)) {
 3938:         $udom = $env{'user.domain'};
 3939:     }
 3940:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3941:         my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 3942:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
 3943:                                               $extra);
 3944:         if (!%roles) {
 3945:             %roles = (
 3946:                        cc => 1,
 3947:                        co => 1,
 3948:                        in => 1,
 3949:                        ep => 1,
 3950:                        ta => 1,
 3951:                        cr => 1,
 3952:                        st => 1,
 3953:              );
 3954:         }
 3955:         foreach my $entry (keys(%roleshash)) {
 3956:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3957:             if ($trole =~ /^cr/) { 
 3958:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3959:             } else {
 3960:                 next if (!exists($roles{$trole}));
 3961:             }
 3962:             if ($tend) {
 3963:                 next if ($tend < $now);
 3964:             }
 3965:             if ($tstart) {
 3966:                 next if ($tstart > $now);
 3967:             }
 3968:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3969:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3970:             if ($secpart eq '') {
 3971:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3972:                 $sec = 'none';
 3973:                 $realsec = '';
 3974:             } else {
 3975:                 $cnum = $cnumpart;
 3976:                 ($sec,$role) = split(/_/,$secpart);
 3977:                 $realsec = $sec;
 3978:             }
 3979:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3980:         }
 3981:     } else {
 3982:         foreach my $key (keys(%env)) {
 3983: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3984:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3985: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3986: 	        next if ($role eq 'ca' || $role eq 'aa');
 3987: 	        next if (%roles && !exists($roles{$role}));
 3988: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3989:                 my $active=1;
 3990:                 if ($starttime) {
 3991: 		    if ($now<$starttime) { $active=0; }
 3992:                 }
 3993:                 if ($endtime) {
 3994:                     if ($now>$endtime) { $active=0; }
 3995:                 }
 3996:                 if ($active) {
 3997:                     if ($sec eq '') {
 3998:                         $sec = 'none';
 3999:                     }
 4000:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 4001:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 4002:                 }
 4003:             }
 4004:         }
 4005:     }
 4006:     return %courses;
 4007: }
 4008: 
 4009: ###############################################
 4010: 
 4011: sub blockcheck {
 4012:     my ($setters,$activity,$uname,$udom) = @_;
 4013: 
 4014:     if (!defined($udom)) {
 4015:         $udom = $env{'user.domain'};
 4016:     }
 4017:     if (!defined($uname)) {
 4018:         $uname = $env{'user.name'};
 4019:     }
 4020: 
 4021:     # If uname and udom are for a course, check for blocks in the course.
 4022: 
 4023:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4024:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 4025:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 4026:         return ($startblock,$endblock);
 4027:     }
 4028: 
 4029:     my $startblock = 0;
 4030:     my $endblock = 0;
 4031:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4032: 
 4033:     # If uname is for a user, and activity is course-specific, i.e.,
 4034:     # boards, chat or groups, check for blocking in current course only.
 4035: 
 4036:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4037:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4038:         foreach my $key (keys(%live_courses)) {
 4039:             if ($key ne $env{'request.course.id'}) {
 4040:                 delete($live_courses{$key});
 4041:             }
 4042:         }
 4043:     }
 4044: 
 4045:     my $otheruser = 0;
 4046:     my %own_courses;
 4047:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4048:         # Resource belongs to user other than current user.
 4049:         $otheruser = 1;
 4050:         # Gather courses for current user
 4051:         %own_courses = 
 4052:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4053:     }
 4054: 
 4055:     # Gather active course roles - course coordinator, instructor, 
 4056:     # exam proctor, ta, student, or custom role.
 4057: 
 4058:     foreach my $course (keys(%live_courses)) {
 4059:         my ($cdom,$cnum);
 4060:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4061:             $cdom = $env{'course.'.$course.'.domain'};
 4062:             $cnum = $env{'course.'.$course.'.num'};
 4063:         } else {
 4064:             ($cdom,$cnum) = split(/_/,$course); 
 4065:         }
 4066:         my $no_ownblock = 0;
 4067:         my $no_userblock = 0;
 4068:         if ($otheruser && $activity ne 'com') {
 4069:             # Check if current user has 'evb' priv for this
 4070:             if (defined($own_courses{$course})) {
 4071:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4072:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4073:                     if ($sec ne 'none') {
 4074:                         $checkrole .= '/'.$sec;
 4075:                     }
 4076:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4077:                         $no_ownblock = 1;
 4078:                         last;
 4079:                     }
 4080:                 }
 4081:             }
 4082:             # if they have 'evb' priv and are currently not playing student
 4083:             next if (($no_ownblock) &&
 4084:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4085:         }
 4086:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4087:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4088:             if ($sec ne 'none') {
 4089:                 $checkrole .= '/'.$sec;
 4090:             }
 4091:             if ($otheruser) {
 4092:                 # Resource belongs to user other than current user.
 4093:                 # Assemble privs for that user, and check for 'evb' priv.
 4094:                 my ($trole,$tdom,$tnum,$tsec);
 4095:                 my $entry = $live_courses{$course}{$sec};
 4096:                 if ($entry =~ /^cr/) {
 4097:                     ($trole,$tdom,$tnum,$tsec) = 
 4098:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4099:                 } else {
 4100:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4101:                 }
 4102:                 my ($spec,$area,$trest,%allroles,%userroles);
 4103:                 $area = '/'.$tdom.'/'.$tnum;
 4104:                 $trest = $tnum;
 4105:                 if ($tsec ne '') {
 4106:                     $area .= '/'.$tsec;
 4107:                     $trest .= '/'.$tsec;
 4108:                 }
 4109:                 $spec = $trole.'.'.$area;
 4110:                 if ($trole =~ /^cr/) {
 4111:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4112:                                                       $tdom,$spec,$trest,$area);
 4113:                 } else {
 4114:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4115:                                                        $tdom,$spec,$trest,$area);
 4116:                 }
 4117:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4118:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4119:                     if ($1) {
 4120:                         $no_userblock = 1;
 4121:                         last;
 4122:                     }
 4123:                 }
 4124:             } else {
 4125:                 # Resource belongs to current user
 4126:                 # Check for 'evb' priv via lonnet::allowed().
 4127:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4128:                     $no_ownblock = 1;
 4129:                     last;
 4130:                 }
 4131:             }
 4132:         }
 4133:         # if they have the evb priv and are currently not playing student
 4134:         next if (($no_ownblock) &&
 4135:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4136:         next if ($no_userblock);
 4137: 
 4138:         # Retrieve blocking times and identity of locker for course
 4139:         # of specified user, unless user has 'evb' privilege.
 4140:         
 4141:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 4142:         if (($start != 0) && 
 4143:             (($startblock == 0) || ($startblock > $start))) {
 4144:             $startblock = $start;
 4145:         }
 4146:         if (($end != 0)  &&
 4147:             (($endblock == 0) || ($endblock < $end))) {
 4148:             $endblock = $end;
 4149:         }
 4150:     }
 4151:     return ($startblock,$endblock);
 4152: }
 4153: 
 4154: sub get_blocks {
 4155:     my ($setters,$activity,$cdom,$cnum) = @_;
 4156:     my $startblock = 0;
 4157:     my $endblock = 0;
 4158:     my $course = $cdom.'_'.$cnum;
 4159:     $setters->{$course} = {};
 4160:     $setters->{$course}{'staff'} = [];
 4161:     $setters->{$course}{'times'} = [];
 4162:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 4163:     foreach my $record (keys(%records)) {
 4164:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 4165:         if ($start <= time && $end >= time) {
 4166:             my ($staff_name,$staff_dom,$title,$blocks) =
 4167:                 &parse_block_record($records{$record});
 4168:             if ($blocks->{$activity} eq 'on') {
 4169:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4170:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4171:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 4172:                     $startblock = $start;
 4173:                 }
 4174:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 4175:                     $endblock = $end;
 4176:                 }
 4177:             }
 4178:         }
 4179:     }
 4180:     return ($startblock,$endblock);
 4181: }
 4182: 
 4183: sub parse_block_record {
 4184:     my ($record) = @_;
 4185:     my ($setuname,$setudom,$title,$blocks);
 4186:     if (ref($record) eq 'HASH') {
 4187:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4188:         $title = &unescape($record->{'event'});
 4189:         $blocks = $record->{'blocks'};
 4190:     } else {
 4191:         my @data = split(/:/,$record,3);
 4192:         if (scalar(@data) eq 2) {
 4193:             $title = $data[1];
 4194:             ($setuname,$setudom) = split(/@/,$data[0]);
 4195:         } else {
 4196:             ($setuname,$setudom,$title) = @data;
 4197:         }
 4198:         $blocks = { 'com' => 'on' };
 4199:     }
 4200:     return ($setuname,$setudom,$title,$blocks);
 4201: }
 4202: 
 4203: sub blocking_status {
 4204:   my ($activity,$uname,$udom) = @_;
 4205:   my %setters;
 4206: 
 4207:   # check for active blocking
 4208:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 4209: 
 4210:   my $blocked = $startblock && $endblock ? 1 : 0;
 4211: 
 4212:   # caller just wants to know whether a block is active
 4213:   if (!wantarray) { return $blocked; }
 4214: 
 4215:   # build a link to a popup window containing the details
 4216:   my $querystring  = "?activity=$activity";
 4217:   # $uname and $udom decide whose portfolio the user is trying to look at
 4218:      $querystring .= "&amp;udom=$udom"      if $udom;
 4219:      $querystring .= "&amp;uname=$uname"    if $uname;
 4220: 
 4221:   my $output .= <<'END_MYBLOCK';
 4222:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4223:         var options = "width=" + w + ",height=" + h + ",";
 4224:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4225:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4226:         var newWin = window.open(url, wdwName, options);
 4227:         newWin.focus();
 4228:     }
 4229: END_MYBLOCK
 4230: 
 4231:   $output = Apache::lonhtmlcommon::scripttag($output);
 4232:   
 4233:   my $popupUrl = "/adm/blockingstatus/$querystring";
 4234:   my $text = mt('Communication Blocked');
 4235: 
 4236:   $output .= <<"END_BLOCK";
 4237: <div class='LC_comblock'>
 4238:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4239:   title='$text'>
 4240:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4241:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4242:   title='$text'>$text</a>
 4243: </div>
 4244: 
 4245: END_BLOCK
 4246: 
 4247:   return ($blocked, $output);
 4248: }
 4249: 
 4250: ###############################################
 4251: 
 4252: sub check_ip_acc {
 4253:     my ($acc)=@_;
 4254:     &Apache::lonxml::debug("acc is $acc");
 4255:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4256:         return 1;
 4257:     }
 4258:     my $allowed=0;
 4259:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4260: 
 4261:     my $name;
 4262:     foreach my $pattern (split(',',$acc)) {
 4263:         $pattern =~ s/^\s*//;
 4264:         $pattern =~ s/\s*$//;
 4265:         if ($pattern =~ /\*$/) {
 4266:             #35.8.*
 4267:             $pattern=~s/\*//;
 4268:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4269:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4270:             #35.8.3.[34-56]
 4271:             my $low=$2;
 4272:             my $high=$3;
 4273:             $pattern=$1;
 4274:             if ($ip =~ /^\Q$pattern\E/) {
 4275:                 my $last=(split(/\./,$ip))[3];
 4276:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4277:             }
 4278:         } elsif ($pattern =~ /^\*/) {
 4279:             #*.msu.edu
 4280:             $pattern=~s/\*//;
 4281:             if (!defined($name)) {
 4282:                 use Socket;
 4283:                 my $netaddr=inet_aton($ip);
 4284:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4285:             }
 4286:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4287:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4288:             #127.0.0.1
 4289:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4290:         } else {
 4291:             #some.name.com
 4292:             if (!defined($name)) {
 4293:                 use Socket;
 4294:                 my $netaddr=inet_aton($ip);
 4295:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4296:             }
 4297:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4298:         }
 4299:         if ($allowed) { last; }
 4300:     }
 4301:     return $allowed;
 4302: }
 4303: 
 4304: ###############################################
 4305: 
 4306: =pod
 4307: 
 4308: =head1 Domain Template Functions
 4309: 
 4310: =over 4
 4311: 
 4312: =item * &determinedomain()
 4313: 
 4314: Inputs: $domain (usually will be undef)
 4315: 
 4316: Returns: Determines which domain should be used for designs
 4317: 
 4318: =cut
 4319: 
 4320: ###############################################
 4321: sub determinedomain {
 4322:     my $domain=shift;
 4323:     if (! $domain) {
 4324:         # Determine domain if we have not been given one
 4325:         $domain = &Apache::lonnet::default_login_domain();
 4326:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4327:         if ($env{'request.role.domain'}) { 
 4328:             $domain=$env{'request.role.domain'}; 
 4329:         }
 4330:     }
 4331:     return $domain;
 4332: }
 4333: ###############################################
 4334: 
 4335: sub devalidate_domconfig_cache {
 4336:     my ($udom)=@_;
 4337:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4338: }
 4339: 
 4340: # ---------------------- Get domain configuration for a domain
 4341: sub get_domainconf {
 4342:     my ($udom) = @_;
 4343:     my $cachetime=1800;
 4344:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4345:     if (defined($cached)) { return %{$result}; }
 4346: 
 4347:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4348: 					     ['login','rolecolors','autoenroll'],$udom);
 4349:     my (%designhash,%legacy);
 4350:     if (keys(%domconfig) > 0) {
 4351:         if (ref($domconfig{'login'}) eq 'HASH') {
 4352:             if (keys(%{$domconfig{'login'}})) {
 4353:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4354:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4355:                         if ($key eq 'loginvia') {
 4356:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4357:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4358:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4359:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4360:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4361:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4362:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4363: 
 4364:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4365:                                             } else {
 4366:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4367:                                             }
 4368:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4369:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4370:                                             }
 4371:                                         }
 4372:                                     }
 4373:                                 }
 4374:                             }
 4375:                         } else {
 4376:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4377:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4378:                                     $domconfig{'login'}{$key}{$img};
 4379:                             }
 4380:                         }
 4381:                     } else {
 4382:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4383:                     }
 4384:                 }
 4385:             } else {
 4386:                 $legacy{'login'} = 1;
 4387:             }
 4388:         } else {
 4389:             $legacy{'login'} = 1;
 4390:         }
 4391:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4392:             if (keys(%{$domconfig{'rolecolors'}})) {
 4393:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4394:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4395:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4396:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4397:                         }
 4398:                     }
 4399:                 }
 4400:             } else {
 4401:                 $legacy{'rolecolors'} = 1;
 4402:             }
 4403:         } else {
 4404:             $legacy{'rolecolors'} = 1;
 4405:         }
 4406:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4407:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4408:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4409:             }
 4410:         }
 4411:         if (keys(%legacy) > 0) {
 4412:             my %legacyhash = &get_legacy_domconf($udom);
 4413:             foreach my $item (keys(%legacyhash)) {
 4414:                 if ($item =~ /^\Q$udom\E\.login/) {
 4415:                     if ($legacy{'login'}) { 
 4416:                         $designhash{$item} = $legacyhash{$item};
 4417:                     }
 4418:                 } else {
 4419:                     if ($legacy{'rolecolors'}) {
 4420:                         $designhash{$item} = $legacyhash{$item};
 4421:                     }
 4422:                 }
 4423:             }
 4424:         }
 4425:     } else {
 4426:         %designhash = &get_legacy_domconf($udom); 
 4427:     }
 4428:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4429: 				  $cachetime);
 4430:     return %designhash;
 4431: }
 4432: 
 4433: sub get_legacy_domconf {
 4434:     my ($udom) = @_;
 4435:     my %legacyhash;
 4436:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4437:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4438:     if (-e $designfile) {
 4439:         if ( open (my $fh,"<$designfile") ) {
 4440:             while (my $line = <$fh>) {
 4441:                 next if ($line =~ /^\#/);
 4442:                 chomp($line);
 4443:                 my ($key,$val)=(split(/\=/,$line));
 4444:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4445:             }
 4446:             close($fh);
 4447:         }
 4448:     }
 4449:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4450:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4451:     }
 4452:     return %legacyhash;
 4453: }
 4454: 
 4455: =pod
 4456: 
 4457: =item * &domainlogo()
 4458: 
 4459: Inputs: $domain (usually will be undef)
 4460: 
 4461: Returns: A link to a domain logo, if the domain logo exists.
 4462: If the domain logo does not exist, a description of the domain.
 4463: 
 4464: =cut
 4465: 
 4466: ###############################################
 4467: sub domainlogo {
 4468:     my $domain = &determinedomain(shift);
 4469:     my %designhash = &get_domainconf($domain);    
 4470:     # See if there is a logo
 4471:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4472:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4473:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4474: 	    if ($imgsrc =~ m{^/res/}) {
 4475: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4476: 		&Apache::lonnet::repcopy($local_name);
 4477: 	    }
 4478: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4479:         } 
 4480:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4481:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4482:         return &Apache::lonnet::domain($domain,'description');
 4483:     } else {
 4484:         return '';
 4485:     }
 4486: }
 4487: ##############################################
 4488: 
 4489: =pod
 4490: 
 4491: =item * &designparm()
 4492: 
 4493: Inputs: $which parameter; $domain (usually will be undef)
 4494: 
 4495: Returns: value of designparamter $which
 4496: 
 4497: =cut
 4498: 
 4499: 
 4500: ##############################################
 4501: sub designparm {
 4502:     my ($which,$domain)=@_;
 4503:     if (exists($env{'environment.color.'.$which})) {
 4504:         return $env{'environment.color.'.$which};
 4505:     }
 4506:     $domain=&determinedomain($domain);
 4507:     my %domdesign;
 4508:     unless ($domain eq 'public') {
 4509:         %domdesign = &get_domainconf($domain);
 4510:     }
 4511:     my $output;
 4512:     if ($domdesign{$domain.'.'.$which} ne '') {
 4513:         $output = $domdesign{$domain.'.'.$which};
 4514:     } else {
 4515:         $output = $defaultdesign{$which};
 4516:     }
 4517:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4518:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4519:         if ($output =~ m{^/(adm|res)/}) {
 4520:             if ($output =~ m{^/res/}) {
 4521:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4522:                 &Apache::lonnet::repcopy($local_name);
 4523:             }
 4524:             $output = &lonhttpdurl($output);
 4525:         }
 4526:     }
 4527:     return $output;
 4528: }
 4529: 
 4530: ##############################################
 4531: =pod
 4532: 
 4533: =item * &authorspace()
 4534: 
 4535: Inputs: $url (usually will be undef).
 4536: 
 4537: Returns: Path to Construction Space containing the resource or 
 4538:          directory being viewed (or for which action is being taken). 
 4539:          If $url is provided, and begins /priv/<domain>/<uname>
 4540:          the path will be that portion of the $context argument.
 4541:          Otherwise the path will be for the author space of the current
 4542:          user when the current role is author, or for that of the 
 4543:          co-author/assistant co-author space when the current role 
 4544:          is co-author or assistant co-author.
 4545: 
 4546: =cut
 4547: 
 4548: sub authorspace {
 4549:     my ($url) = @_;
 4550:     if ($url ne '') {
 4551:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4552:            return $1;
 4553:         }
 4554:     }
 4555:     my $caname = '';
 4556:     my $cadom = '';
 4557:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4558:         ($cadom,$caname) =
 4559:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4560:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4561:         $caname = $env{'user.name'};
 4562:         $cadom = $env{'user.domain'};
 4563:     }
 4564:     if (($caname ne '') && ($cadom ne '')) {
 4565:         return "/priv/$cadom/$caname/";
 4566:     }
 4567:     return;
 4568: }
 4569: 
 4570: ##############################################
 4571: =pod
 4572: 
 4573: =item * &head_subbox()
 4574: 
 4575: Inputs: $content (contains HTML code with page functions, etc.)
 4576: 
 4577: Returns: HTML div with $content
 4578:          To be included in page header
 4579: 
 4580: =cut
 4581: 
 4582: sub head_subbox {
 4583:     my ($content)=@_;
 4584:     my $output =
 4585:         '<div class="LC_head_subbox">'
 4586:        .$content
 4587:        .'</div>'
 4588: }
 4589: 
 4590: ##############################################
 4591: =pod
 4592: 
 4593: =item * &CSTR_pageheader()
 4594: 
 4595: Input: (optional) filename from which breadcrumb trail is built.
 4596:        In most cases no input as needed, as $env{'request.filename'}
 4597:        is appropriate for use in building the breadcrumb trail.
 4598: 
 4599: Returns: HTML div with CSTR path and recent box
 4600:          To be included on Construction Space pages
 4601: 
 4602: =cut
 4603: 
 4604: sub CSTR_pageheader {
 4605:     my ($trailfile) = @_;
 4606:     if ($trailfile eq '') {
 4607:         $trailfile = $env{'request.filename'};
 4608:     }
 4609: 
 4610: # this is for resources; directories have customtitle, and crumbs
 4611: # and select recent are created in lonpubdir.pm
 4612: 
 4613:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4614:     my ($udom,$uname,$thisdisfn)=
 4615:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
 4616:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4617:     $formaction =~ s{/+}{/}g;
 4618: 
 4619:     my $parentpath = '';
 4620:     my $lastitem = '';
 4621:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4622:         $parentpath = $1;
 4623:         $lastitem = $2;
 4624:     } else {
 4625:         $lastitem = $thisdisfn;
 4626:     }
 4627: 
 4628:     my $output =
 4629:          '<div>'
 4630:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4631:         .'<b>'.&mt('Construction Space:').'</b> '
 4632:         .'<form name="dirs" method="post" action="'.$formaction
 4633:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4634:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4635: 
 4636:     if ($lastitem) {
 4637:         $output .=
 4638:              '<span class="LC_filename">'
 4639:             .$lastitem
 4640:             .'</span>';
 4641:     }
 4642:     $output .=
 4643:          '<br />'
 4644:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4645:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4646:         .'</form>'
 4647:         .&Apache::lonmenu::constspaceform()
 4648:         .'</div>';
 4649: 
 4650:     return $output;
 4651: }
 4652: 
 4653: ###############################################
 4654: ###############################################
 4655: 
 4656: =pod
 4657: 
 4658: =back
 4659: 
 4660: =head1 HTML Helpers
 4661: 
 4662: =over 4
 4663: 
 4664: =item * &bodytag()
 4665: 
 4666: Returns a uniform header for LON-CAPA web pages.
 4667: 
 4668: Inputs: 
 4669: 
 4670: =over 4
 4671: 
 4672: =item * $title, A title to be displayed on the page.
 4673: 
 4674: =item * $function, the current role (can be undef).
 4675: 
 4676: =item * $addentries, extra parameters for the <body> tag.
 4677: 
 4678: =item * $bodyonly, if defined, only return the <body> tag.
 4679: 
 4680: =item * $domain, if defined, force a given domain.
 4681: 
 4682: =item * $forcereg, if page should register as content page (relevant for 
 4683:             text interface only)
 4684: 
 4685: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4686:                      navigational links
 4687: 
 4688: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4689: 
 4690: =item * $args, optional argument valid values are
 4691:             no_auto_mt_title -> prevents &mt()ing the title arg
 4692:             inherit_jsmath -> when creating popup window in a page,
 4693:                               should it have jsmath forced on by the
 4694:                               current page
 4695: 
 4696: =back
 4697: 
 4698: Returns: A uniform header for LON-CAPA web pages.  
 4699: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4700: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4701: other decorations will be returned.
 4702: 
 4703: =cut
 4704: 
 4705: sub bodytag {
 4706:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4707:         $no_nav_bar,$bgcolor,$args)=@_;
 4708: 
 4709:     my $public;
 4710:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4711:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4712:         $public = 1;
 4713:     }
 4714:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4715: 
 4716:     $function = &get_users_function() if (!$function);
 4717:     my $img =    &designparm($function.'.img',$domain);
 4718:     my $font =   &designparm($function.'.font',$domain);
 4719:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4720: 
 4721:     my %design = ( 'style'   => 'margin-top: 0',
 4722: 		   'bgcolor' => $pgbg,
 4723: 		   'text'    => $font,
 4724:                    'alink'   => &designparm($function.'.alink',$domain),
 4725: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4726: 		   'link'    => &designparm($function.'.link',$domain),);
 4727:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4728: 
 4729:  # role and realm
 4730:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4731:     if ($role  eq 'ca') {
 4732:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4733:         $realm = &plainname($rname,$rdom);
 4734:     } 
 4735: # realm
 4736:     if ($env{'request.course.id'}) {
 4737:         if ($env{'request.role'} !~ /^cr/) {
 4738:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4739:         }
 4740:         if ($env{'request.course.sec'}) {
 4741:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4742:         }   
 4743: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4744:     } else {
 4745:         $role = &Apache::lonnet::plaintext($role);
 4746:     }
 4747: 
 4748:     if (!$realm) { $realm='&nbsp;'; }
 4749: 
 4750:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4751: 
 4752: # construct main body tag
 4753:     my $bodytag = "<body $extra_body_attr>".
 4754: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4755: 
 4756:     if ($bodyonly) {
 4757:         return $bodytag;
 4758:     } 
 4759: 
 4760:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4761:     if ($public) {
 4762: 	undef($role);
 4763:     } else {
 4764: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4765:     }
 4766:     
 4767:     my $titleinfo = '<h1>'.$title.'</h1>';
 4768:     #
 4769:     # Extra info if you are the DC
 4770:     my $dc_info = '';
 4771:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4772:                         $env{'course.'.$env{'request.course.id'}.
 4773:                                  '.domain'}.'/'})) {
 4774:         my $cid = $env{'request.course.id'};
 4775:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4776:         $dc_info =~ s/\s+$//;
 4777:     }
 4778: 
 4779:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4780:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4781: 
 4782:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4783:             return $bodytag; 
 4784:         } 
 4785: 
 4786:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4787: 
 4788:         #    if ($env{'request.state'} eq 'construct') {
 4789:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4790:         #    }
 4791: 
 4792: 
 4793: 
 4794:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4795:              if ($dc_info) {
 4796:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4797:              }
 4798:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4799:                 <em>$realm</em> $dc_info</div>|;
 4800:             return $bodytag;
 4801:         }
 4802: 
 4803:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4804:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4805:         }
 4806: 
 4807:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4808:             Apache::lonmenu::utilityfunctions(), 'start');
 4809: 
 4810:         $bodytag .= Apache::lonmenu::primary_menu();
 4811: 
 4812:         if ($dc_info) {
 4813:             $dc_info = &dc_courseid_toggle($dc_info);
 4814:         }
 4815:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4816: 
 4817:         #don't show menus for public users
 4818:         if (!$public){
 4819:             $bodytag .= Apache::lonmenu::secondary_menu();
 4820:             $bodytag .= Apache::lonmenu::serverform();
 4821:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4822:             if ($env{'request.state'} eq 'construct') {
 4823:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 4824:                                 $args->{'bread_crumbs'});
 4825:             } elsif ($forcereg) { 
 4826:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 4827:             }
 4828:         }else{
 4829:             # this is to seperate menu from content when there's no secondary
 4830:             # menu. Especially needed for public accessible ressources.
 4831:             $bodytag .= '<hr style="clear:both" />';
 4832:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4833:         }
 4834: 
 4835:         return $bodytag;
 4836: }
 4837: 
 4838: sub dc_courseid_toggle {
 4839:     my ($dc_info) = @_;
 4840:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 4841:            '<a href="javascript:showCourseID();">'.
 4842:            &mt('(More ...)').'</a></span>'.
 4843:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 4844: }
 4845: 
 4846: sub make_attr_string {
 4847:     my ($register,$attr_ref) = @_;
 4848: 
 4849:     if ($attr_ref && !ref($attr_ref)) {
 4850: 	die("addentries Must be a hash ref ".
 4851: 	    join(':',caller(1))." ".
 4852: 	    join(':',caller(0))." ");
 4853:     }
 4854: 
 4855:     if ($register) {
 4856: 	my ($on_load,$on_unload);
 4857: 	foreach my $key (keys(%{$attr_ref})) {
 4858: 	    if      (lc($key) eq 'onload') {
 4859: 		$on_load.=$attr_ref->{$key}.';';
 4860: 		delete($attr_ref->{$key});
 4861: 
 4862: 	    } elsif (lc($key) eq 'onunload') {
 4863: 		$on_unload.=$attr_ref->{$key}.';';
 4864: 		delete($attr_ref->{$key});
 4865: 	    }
 4866: 	}
 4867: 	$attr_ref->{'onload'}  = $on_load;
 4868: 	$attr_ref->{'onunload'}= $on_unload;
 4869:     }
 4870: 
 4871:     my $attr_string;
 4872:     foreach my $attr (keys(%$attr_ref)) {
 4873: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4874:     }
 4875:     return $attr_string;
 4876: }
 4877: 
 4878: 
 4879: ###############################################
 4880: ###############################################
 4881: 
 4882: =pod
 4883: 
 4884: =item * &endbodytag()
 4885: 
 4886: Returns a uniform footer for LON-CAPA web pages.
 4887: 
 4888: Inputs: 1 - optional reference to an args hash
 4889: If in the hash, key for noredirectlink has a value which evaluates to true,
 4890: a 'Continue' link is not displayed if the page contains an
 4891: internal redirect in the <head></head> section,
 4892: i.e., $env{'internal.head.redirect'} exists   
 4893: 
 4894: =cut
 4895: 
 4896: sub endbodytag {
 4897:     my ($args) = @_;
 4898:     my $endbodytag='</body>';
 4899:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4900:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4901:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4902: 	    $endbodytag=
 4903: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4904: 	        &mt('Continue').'</a>'.
 4905: 	        $endbodytag;
 4906:         }
 4907:     }
 4908:     return $endbodytag;
 4909: }
 4910: 
 4911: =pod
 4912: 
 4913: =item * &standard_css()
 4914: 
 4915: Returns a style sheet
 4916: 
 4917: Inputs: (all optional)
 4918:             domain         -> force to color decorate a page for a specific
 4919:                                domain
 4920:             function       -> force usage of a specific rolish color scheme
 4921:             bgcolor        -> override the default page bgcolor
 4922: 
 4923: =cut
 4924: 
 4925: sub standard_css {
 4926:     my ($function,$domain,$bgcolor) = @_;
 4927:     $function  = &get_users_function() if (!$function);
 4928:     my $img    = &designparm($function.'.img',   $domain);
 4929:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4930:     my $font   = &designparm($function.'.font',  $domain);
 4931:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4932: #second colour for later usage
 4933:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4934:     my $pgbg_or_bgcolor =
 4935: 	         $bgcolor ||
 4936: 	         &designparm($function.'.pgbg',  $domain);
 4937:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4938:     my $alink  = &designparm($function.'.alink', $domain);
 4939:     my $vlink  = &designparm($function.'.vlink', $domain);
 4940:     my $link   = &designparm($function.'.link',  $domain);
 4941: 
 4942:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4943:     my $mono                 = 'monospace';
 4944:     my $data_table_head      = $sidebg;
 4945:     my $data_table_light     = '#FAFAFA';
 4946:     my $data_table_dark      = '#F0F0F0';
 4947:     my $data_table_darker    = '#CCCCCC';
 4948:     my $data_table_highlight = '#FFFF00';
 4949:     my $mail_new             = '#FFBB77';
 4950:     my $mail_new_hover       = '#DD9955';
 4951:     my $mail_read            = '#BBBB77';
 4952:     my $mail_read_hover      = '#999944';
 4953:     my $mail_replied         = '#AAAA88';
 4954:     my $mail_replied_hover   = '#888855';
 4955:     my $mail_other           = '#99BBBB';
 4956:     my $mail_other_hover     = '#669999';
 4957:     my $table_header         = '#DDDDDD';
 4958:     my $feedback_link_bg     = '#BBBBBB';
 4959:     my $lg_border_color      = '#C8C8C8';
 4960:     my $button_hover         = '#BF2317';
 4961: 
 4962:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4963:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4964:                                              : '0 3px 0 4px';
 4965: 
 4966: 
 4967:     return <<END;
 4968: 
 4969: /* needed for iframe to allow 100% height in FF */
 4970: body, html { 
 4971:     margin: 0;
 4972:     padding: 0 0.5%;
 4973:     height: 99%; /* to avoid scrollbars */
 4974: }
 4975: 
 4976: body {
 4977:   font-family: $sans;
 4978:   line-height:130%;
 4979:   font-size:0.83em;
 4980:   color:$font;
 4981: }
 4982: 
 4983: a:focus,
 4984: a:focus img {
 4985:   color: red;
 4986:   background: yellow;
 4987: }
 4988: 
 4989: form, .inline {
 4990:   display: inline;
 4991: }
 4992: 
 4993: .LC_right {
 4994:   text-align:right;
 4995: }
 4996: 
 4997: .LC_middle {
 4998:   vertical-align:middle;
 4999: }
 5000: 
 5001: .LC_400Box {
 5002:   width:400px;
 5003: }
 5004: 
 5005: .LC_iframecontainer {
 5006:     width: 98%;
 5007:     margin: 0;
 5008:     position: fixed;
 5009:     top: 8.5em;
 5010:     bottom: 0;
 5011: }
 5012: 
 5013: .LC_iframecontainer iframe{
 5014:     border: none;
 5015:     width: 100%;
 5016:     height: 100%;
 5017: }
 5018: 
 5019: .LC_filename {
 5020:   font-family: $mono;
 5021:   white-space:pre;
 5022:   font-size: 120%;
 5023: }
 5024: 
 5025: .LC_fileicon {
 5026:   border: none;
 5027:   height: 1.3em;
 5028:   vertical-align: text-bottom;
 5029:   margin-right: 0.3em;
 5030:   text-decoration:none;
 5031: }
 5032: 
 5033: .LC_setting {
 5034:   text-decoration:underline;
 5035: }
 5036: 
 5037: .LC_error {
 5038:   color: red;
 5039:   font-size: larger;
 5040: }
 5041: 
 5042: .LC_warning,
 5043: .LC_diff_removed {
 5044:   color: red;
 5045: }
 5046: 
 5047: .LC_info,
 5048: .LC_success,
 5049: .LC_diff_added {
 5050:   color: green;
 5051: }
 5052: 
 5053: div.LC_confirm_box {
 5054:   background-color: #FAFAFA;
 5055:   border: 1px solid $lg_border_color;
 5056:   margin-right: 0;
 5057:   padding: 5px;
 5058: }
 5059: 
 5060: div.LC_confirm_box .LC_error img,
 5061: div.LC_confirm_box .LC_success img {
 5062:   vertical-align: middle;
 5063: }
 5064: 
 5065: .LC_icon {
 5066:   border: none;
 5067:   vertical-align: middle;
 5068: }
 5069: 
 5070: .LC_docs_spacer {
 5071:   width: 25px;
 5072:   height: 1px;
 5073:   border: none;
 5074: }
 5075: 
 5076: .LC_internal_info {
 5077:   color: #999999;
 5078: }
 5079: 
 5080: .LC_discussion {
 5081:   background: $tabbg;
 5082:   border: 1px solid black;
 5083:   margin: 2px;
 5084: }
 5085: 
 5086: .LC_disc_action_links_bar {
 5087:   background: $tabbg;
 5088:   border: none;
 5089:   margin: 4px;
 5090: }
 5091: 
 5092: .LC_disc_action_left {
 5093:   text-align: left;
 5094: }
 5095: 
 5096: .LC_disc_action_right {
 5097:   text-align: right;
 5098: }
 5099: 
 5100: .LC_disc_new_item {
 5101:   background: white;
 5102:   border: 2px solid red;
 5103:   margin: 2px;
 5104: }
 5105: 
 5106: .LC_disc_old_item {
 5107:   background: white;
 5108:   border: 1px solid black;
 5109:   margin: 2px;
 5110: }
 5111: 
 5112: table.LC_pastsubmission {
 5113:   border: 1px solid black;
 5114:   margin: 2px;
 5115: }
 5116: 
 5117: table#LC_menubuttons {
 5118:   width: 100%;
 5119:   background: $pgbg;
 5120:   border: 2px;
 5121:   border-collapse: separate;
 5122:   padding: 0;
 5123: }
 5124: 
 5125: table#LC_title_bar a {
 5126:   color: $fontmenu;
 5127: }
 5128: 
 5129: table#LC_title_bar {
 5130:   clear: both;
 5131:   display: none;
 5132: }
 5133: 
 5134: table#LC_title_bar,
 5135: table.LC_breadcrumbs, /* obsolete? */
 5136: table#LC_title_bar.LC_with_remote {
 5137:   width: 100%;
 5138:   border-color: $pgbg;
 5139:   border-style: solid;
 5140:   border-width: $border;
 5141:   background: $pgbg;
 5142:   color: $fontmenu;
 5143:   border-collapse: collapse;
 5144:   padding: 0;
 5145:   margin: 0;
 5146: }
 5147: 
 5148: ul.LC_breadcrumb_tools_outerlist {
 5149:     margin: 0;
 5150:     padding: 0;
 5151:     position: relative;
 5152:     list-style: none;
 5153: }
 5154: ul.LC_breadcrumb_tools_outerlist li {
 5155:     display: inline;
 5156: }
 5157: 
 5158: .LC_breadcrumb_tools_navigation {
 5159:     padding: 0;
 5160:     margin: 0;
 5161:     float: left;
 5162: }
 5163: .LC_breadcrumb_tools_tools {
 5164:     padding: 0;
 5165:     margin: 0;
 5166:     float: right;
 5167: }
 5168: 
 5169: table#LC_title_bar td {
 5170:   background: $tabbg;
 5171: }
 5172: 
 5173: table#LC_menubuttons img {
 5174:   border: none;
 5175: }
 5176: 
 5177: .LC_breadcrumbs_component {
 5178:   float: right;
 5179:   margin: 0 1em;
 5180: }
 5181: .LC_breadcrumbs_component img {
 5182:   vertical-align: middle;
 5183: }
 5184: 
 5185: td.LC_table_cell_checkbox {
 5186:   text-align: center;
 5187: }
 5188: 
 5189: .LC_fontsize_small {
 5190:   font-size: 70%;
 5191: }
 5192: 
 5193: #LC_breadcrumbs {
 5194:   clear:both;
 5195:   background: $sidebg;
 5196:   border-bottom: 1px solid $lg_border_color;
 5197:   line-height: 2.5em;
 5198:   overflow: hidden;
 5199:   margin: 0;
 5200:   padding: 0;
 5201:   text-align: left;
 5202: }
 5203: 
 5204: .LC_head_subbox {
 5205:   clear:both;
 5206:   background: #F8F8F8; /* $sidebg; */
 5207:   border: 1px solid $sidebg;
 5208:   margin: 0 0 10px 0;      
 5209:   padding: 3px;
 5210:   text-align: left;
 5211: }
 5212: 
 5213: .LC_fontsize_medium {
 5214:   font-size: 85%;
 5215: }
 5216: 
 5217: .LC_fontsize_large {
 5218:   font-size: 120%;
 5219: }
 5220: 
 5221: .LC_menubuttons_inline_text {
 5222:   color: $font;
 5223:   font-size: 90%;
 5224:   padding-left:3px;
 5225: }
 5226: 
 5227: .LC_menubuttons_inline_text img{
 5228:   vertical-align: middle;
 5229: }
 5230: 
 5231: li.LC_menubuttons_inline_text img,a {
 5232:   cursor:pointer;
 5233:   text-decoration: none;
 5234: }
 5235: 
 5236: .LC_menubuttons_link {
 5237:   text-decoration: none;
 5238: }
 5239: 
 5240: .LC_menubuttons_category {
 5241:   color: $font;
 5242:   background: $pgbg;
 5243:   font-size: larger;
 5244:   font-weight: bold;
 5245: }
 5246: 
 5247: td.LC_menubuttons_text {
 5248:   color: $font;
 5249: }
 5250: 
 5251: .LC_current_location {
 5252:   background: $tabbg;
 5253: }
 5254: 
 5255: table.LC_data_table {
 5256:   border: 1px solid #000000;
 5257:   border-collapse: separate;
 5258:   border-spacing: 1px;
 5259:   background: $pgbg;
 5260: }
 5261: 
 5262: .LC_data_table_dense {
 5263:   font-size: small;
 5264: }
 5265: 
 5266: table.LC_nested_outer {
 5267:   border: 1px solid #000000;
 5268:   border-collapse: collapse;
 5269:   border-spacing: 0;
 5270:   width: 100%;
 5271: }
 5272: 
 5273: table.LC_innerpickbox,
 5274: table.LC_nested {
 5275:   border: none;
 5276:   border-collapse: collapse;
 5277:   border-spacing: 0;
 5278:   width: 100%;
 5279: }
 5280: 
 5281: table.LC_data_table tr th,
 5282: table.LC_calendar tr th,
 5283: table.LC_prior_tries tr th,
 5284: table.LC_innerpickbox tr th {
 5285:   font-weight: bold;
 5286:   background-color: $data_table_head;
 5287:   color:$fontmenu;
 5288:   font-size:90%;
 5289: }
 5290: 
 5291: table.LC_innerpickbox tr th,
 5292: table.LC_innerpickbox tr td {
 5293:   vertical-align: top;
 5294: }
 5295: 
 5296: table.LC_data_table tr.LC_info_row > td {
 5297:   background-color: #CCCCCC;
 5298:   font-weight: bold;
 5299:   text-align: left;
 5300: }
 5301: 
 5302: table.LC_data_table tr.LC_odd_row > td {
 5303:   background-color: $data_table_light;
 5304:   padding: 2px;
 5305:   vertical-align: top;
 5306: }
 5307: 
 5308: table.LC_pick_box tr > td.LC_odd_row {
 5309:   background-color: $data_table_light;
 5310:   vertical-align: top;
 5311: }
 5312: 
 5313: table.LC_data_table tr.LC_even_row > td {
 5314:   background-color: $data_table_dark;
 5315:   padding: 2px;
 5316:   vertical-align: top;
 5317: }
 5318: 
 5319: table.LC_pick_box tr > td.LC_even_row {
 5320:   background-color: $data_table_dark;
 5321:   vertical-align: top;
 5322: }
 5323: 
 5324: table.LC_data_table tr.LC_data_table_highlight td {
 5325:   background-color: $data_table_darker;
 5326: }
 5327: 
 5328: table.LC_data_table tr td.LC_leftcol_header {
 5329:   background-color: $data_table_head;
 5330:   font-weight: bold;
 5331: }
 5332: 
 5333: table.LC_data_table tr.LC_empty_row td,
 5334: table.LC_nested tr.LC_empty_row td {
 5335:   font-weight: bold;
 5336:   font-style: italic;
 5337:   text-align: center;
 5338:   padding: 8px;
 5339: }
 5340: 
 5341: table.LC_data_table tr.LC_empty_row td {
 5342:   background-color: $sidebg;
 5343: }
 5344: 
 5345: table.LC_nested tr.LC_empty_row td {
 5346:   background-color: #FFFFFF;
 5347: }
 5348: 
 5349: table.LC_caption {
 5350: }
 5351: 
 5352: table.LC_nested tr.LC_empty_row td {
 5353:   padding: 4ex
 5354: }
 5355: 
 5356: table.LC_nested_outer tr th {
 5357:   font-weight: bold;
 5358:   color:$fontmenu;
 5359:   background-color: $data_table_head;
 5360:   font-size: small;
 5361:   border-bottom: 1px solid #000000;
 5362: }
 5363: 
 5364: table.LC_nested_outer tr td.LC_subheader {
 5365:   background-color: $data_table_head;
 5366:   font-weight: bold;
 5367:   font-size: small;
 5368:   border-bottom: 1px solid #000000;
 5369:   text-align: right;
 5370: }
 5371: 
 5372: table.LC_nested tr.LC_info_row td {
 5373:   background-color: #CCCCCC;
 5374:   font-weight: bold;
 5375:   font-size: small;
 5376:   text-align: center;
 5377: }
 5378: 
 5379: table.LC_nested tr.LC_info_row td.LC_left_item,
 5380: table.LC_nested_outer tr th.LC_left_item {
 5381:   text-align: left;
 5382: }
 5383: 
 5384: table.LC_nested td {
 5385:   background-color: #FFFFFF;
 5386:   font-size: small;
 5387: }
 5388: 
 5389: table.LC_nested_outer tr th.LC_right_item,
 5390: table.LC_nested tr.LC_info_row td.LC_right_item,
 5391: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5392: table.LC_nested tr td.LC_right_item {
 5393:   text-align: right;
 5394: }
 5395: 
 5396: table.LC_nested tr.LC_odd_row td {
 5397:   background-color: #EEEEEE;
 5398: }
 5399: 
 5400: table.LC_createuser {
 5401: }
 5402: 
 5403: table.LC_createuser tr.LC_section_row td {
 5404:   font-size: small;
 5405: }
 5406: 
 5407: table.LC_createuser tr.LC_info_row td  {
 5408:   background-color: #CCCCCC;
 5409:   font-weight: bold;
 5410:   text-align: center;
 5411: }
 5412: 
 5413: table.LC_calendar {
 5414:   border: 1px solid #000000;
 5415:   border-collapse: collapse;
 5416:   width: 98%;
 5417: }
 5418: 
 5419: table.LC_calendar_pickdate {
 5420:   font-size: xx-small;
 5421: }
 5422: 
 5423: table.LC_calendar tr td {
 5424:   border: 1px solid #000000;
 5425:   vertical-align: top;
 5426:   width: 14%;
 5427: }
 5428: 
 5429: table.LC_calendar tr td.LC_calendar_day_empty {
 5430:   background-color: $data_table_dark;
 5431: }
 5432: 
 5433: table.LC_calendar tr td.LC_calendar_day_current {
 5434:   background-color: $data_table_highlight;
 5435: }
 5436: 
 5437: table.LC_data_table tr td.LC_mail_new {
 5438:   background-color: $mail_new;
 5439: }
 5440: 
 5441: table.LC_data_table tr.LC_mail_new:hover {
 5442:   background-color: $mail_new_hover;
 5443: }
 5444: 
 5445: table.LC_data_table tr td.LC_mail_read {
 5446:   background-color: $mail_read;
 5447: }
 5448: 
 5449: /*
 5450: table.LC_data_table tr.LC_mail_read:hover {
 5451:   background-color: $mail_read_hover;
 5452: }
 5453: */
 5454: 
 5455: table.LC_data_table tr td.LC_mail_replied {
 5456:   background-color: $mail_replied;
 5457: }
 5458: 
 5459: /*
 5460: table.LC_data_table tr.LC_mail_replied:hover {
 5461:   background-color: $mail_replied_hover;
 5462: }
 5463: */
 5464: 
 5465: table.LC_data_table tr td.LC_mail_other {
 5466:   background-color: $mail_other;
 5467: }
 5468: 
 5469: /*
 5470: table.LC_data_table tr.LC_mail_other:hover {
 5471:   background-color: $mail_other_hover;
 5472: }
 5473: */
 5474: 
 5475: table.LC_data_table tr > td.LC_browser_file,
 5476: table.LC_data_table tr > td.LC_browser_file_published {
 5477:   background: #AAEE77;
 5478: }
 5479: 
 5480: table.LC_data_table tr > td.LC_browser_file_locked,
 5481: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5482:   background: #FFAA99;
 5483: }
 5484: 
 5485: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5486:   background: #888888;
 5487: }
 5488: 
 5489: table.LC_data_table tr > td.LC_browser_file_modified,
 5490: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5491:   background: #F8F866;
 5492: }
 5493: 
 5494: table.LC_data_table tr.LC_browser_folder > td {
 5495:   background: #E0E8FF;
 5496: }
 5497: 
 5498: table.LC_data_table tr > td.LC_roles_is {
 5499:   /* background: #77FF77; */
 5500: }
 5501: 
 5502: table.LC_data_table tr > td.LC_roles_future {
 5503:   border-right: 8px solid #FFFF77;
 5504: }
 5505: 
 5506: table.LC_data_table tr > td.LC_roles_will {
 5507:   border-right: 8px solid #FFAA77;
 5508: }
 5509: 
 5510: table.LC_data_table tr > td.LC_roles_expired {
 5511:   border-right: 8px solid #FF7777;
 5512: }
 5513: 
 5514: table.LC_data_table tr > td.LC_roles_will_not {
 5515:   border-right: 8px solid #AAFF77;
 5516: }
 5517: 
 5518: table.LC_data_table tr > td.LC_roles_selected {
 5519:   border-right: 8px solid #11CC55;
 5520: }
 5521: 
 5522: span.LC_current_location {
 5523:   font-size:larger;
 5524:   background: $pgbg;
 5525: }
 5526: 
 5527: span.LC_current_nav_location {
 5528:   font-weight:bold;
 5529:   background: $sidebg;
 5530: }
 5531: 
 5532: span.LC_parm_menu_item {
 5533:   font-size: larger;
 5534: }
 5535: 
 5536: span.LC_parm_scope_all {
 5537:   color: red;
 5538: }
 5539: 
 5540: span.LC_parm_scope_folder {
 5541:   color: green;
 5542: }
 5543: 
 5544: span.LC_parm_scope_resource {
 5545:   color: orange;
 5546: }
 5547: 
 5548: span.LC_parm_part {
 5549:   color: blue;
 5550: }
 5551: 
 5552: span.LC_parm_folder,
 5553: span.LC_parm_symb {
 5554:   font-size: x-small;
 5555:   font-family: $mono;
 5556:   color: #AAAAAA;
 5557: }
 5558: 
 5559: ul.LC_parm_parmlist li {
 5560:   display: inline-block;
 5561:   padding: 0.3em 0.8em;
 5562:   vertical-align: top;
 5563:   width: 150px;
 5564:   border-top:1px solid $lg_border_color;
 5565: }
 5566: 
 5567: td.LC_parm_overview_level_menu,
 5568: td.LC_parm_overview_map_menu,
 5569: td.LC_parm_overview_parm_selectors,
 5570: td.LC_parm_overview_restrictions  {
 5571:   border: 1px solid black;
 5572:   border-collapse: collapse;
 5573: }
 5574: 
 5575: table.LC_parm_overview_restrictions td {
 5576:   border-width: 1px 4px 1px 4px;
 5577:   border-style: solid;
 5578:   border-color: $pgbg;
 5579:   text-align: center;
 5580: }
 5581: 
 5582: table.LC_parm_overview_restrictions th {
 5583:   background: $tabbg;
 5584:   border-width: 1px 4px 1px 4px;
 5585:   border-style: solid;
 5586:   border-color: $pgbg;
 5587: }
 5588: 
 5589: table#LC_helpmenu {
 5590:   border: none;
 5591:   height: 55px;
 5592:   border-spacing: 0;
 5593: }
 5594: 
 5595: table#LC_helpmenu fieldset legend {
 5596:   font-size: larger;
 5597: }
 5598: 
 5599: table#LC_helpmenu_links {
 5600:   width: 100%;
 5601:   border: 1px solid black;
 5602:   background: $pgbg;
 5603:   padding: 0;
 5604:   border-spacing: 1px;
 5605: }
 5606: 
 5607: table#LC_helpmenu_links tr td {
 5608:   padding: 1px;
 5609:   background: $tabbg;
 5610:   text-align: center;
 5611:   font-weight: bold;
 5612: }
 5613: 
 5614: table#LC_helpmenu_links a:link,
 5615: table#LC_helpmenu_links a:visited,
 5616: table#LC_helpmenu_links a:active {
 5617:   text-decoration: none;
 5618:   color: $font;
 5619: }
 5620: 
 5621: table#LC_helpmenu_links a:hover {
 5622:   text-decoration: underline;
 5623:   color: $vlink;
 5624: }
 5625: 
 5626: .LC_chrt_popup_exists {
 5627:   border: 1px solid #339933;
 5628:   margin: -1px;
 5629: }
 5630: 
 5631: .LC_chrt_popup_up {
 5632:   border: 1px solid yellow;
 5633:   margin: -1px;
 5634: }
 5635: 
 5636: .LC_chrt_popup {
 5637:   border: 1px solid #8888FF;
 5638:   background: #CCCCFF;
 5639: }
 5640: 
 5641: table.LC_pick_box {
 5642:   border-collapse: separate;
 5643:   background: white;
 5644:   border: 1px solid black;
 5645:   border-spacing: 1px;
 5646: }
 5647: 
 5648: table.LC_pick_box td.LC_pick_box_title {
 5649:   background: $sidebg;
 5650:   font-weight: bold;
 5651:   text-align: left;
 5652:   vertical-align: top;
 5653:   width: 184px;
 5654:   padding: 8px;
 5655: }
 5656: 
 5657: table.LC_pick_box td.LC_pick_box_value {
 5658:   text-align: left;
 5659:   padding: 8px;
 5660: }
 5661: 
 5662: table.LC_pick_box td.LC_pick_box_select {
 5663:   text-align: left;
 5664:   padding: 8px;
 5665: }
 5666: 
 5667: table.LC_pick_box td.LC_pick_box_separator {
 5668:   padding: 0;
 5669:   height: 1px;
 5670:   background: black;
 5671: }
 5672: 
 5673: table.LC_pick_box td.LC_pick_box_submit {
 5674:   text-align: right;
 5675: }
 5676: 
 5677: table.LC_pick_box td.LC_evenrow_value {
 5678:   text-align: left;
 5679:   padding: 8px;
 5680:   background-color: $data_table_light;
 5681: }
 5682: 
 5683: table.LC_pick_box td.LC_oddrow_value {
 5684:   text-align: left;
 5685:   padding: 8px;
 5686:   background-color: $data_table_light;
 5687: }
 5688: 
 5689: span.LC_helpform_receipt_cat {
 5690:   font-weight: bold;
 5691: }
 5692: 
 5693: table.LC_group_priv_box {
 5694:   background: white;
 5695:   border: 1px solid black;
 5696:   border-spacing: 1px;
 5697: }
 5698: 
 5699: table.LC_group_priv_box td.LC_pick_box_title {
 5700:   background: $tabbg;
 5701:   font-weight: bold;
 5702:   text-align: right;
 5703:   width: 184px;
 5704: }
 5705: 
 5706: table.LC_group_priv_box td.LC_groups_fixed {
 5707:   background: $data_table_light;
 5708:   text-align: center;
 5709: }
 5710: 
 5711: table.LC_group_priv_box td.LC_groups_optional {
 5712:   background: $data_table_dark;
 5713:   text-align: center;
 5714: }
 5715: 
 5716: table.LC_group_priv_box td.LC_groups_functionality {
 5717:   background: $data_table_darker;
 5718:   text-align: center;
 5719:   font-weight: bold;
 5720: }
 5721: 
 5722: table.LC_group_priv td {
 5723:   text-align: left;
 5724:   padding: 0;
 5725: }
 5726: 
 5727: .LC_navbuttons {
 5728:   margin: 2ex 0ex 2ex 0ex;
 5729: }
 5730: 
 5731: .LC_topic_bar {
 5732:   font-weight: bold;
 5733:   background: $tabbg;
 5734:   margin: 1em 0em 1em 2em;
 5735:   padding: 3px;
 5736:   font-size: 1.2em;
 5737: }
 5738: 
 5739: .LC_topic_bar span {
 5740:   left: 0.5em;
 5741:   position: absolute;
 5742:   vertical-align: middle;
 5743:   font-size: 1.2em;
 5744: }
 5745: 
 5746: table.LC_course_group_status {
 5747:   margin: 20px;
 5748: }
 5749: 
 5750: table.LC_status_selector td {
 5751:   vertical-align: top;
 5752:   text-align: center;
 5753:   padding: 4px;
 5754: }
 5755: 
 5756: div.LC_feedback_link {
 5757:   clear: both;
 5758:   background: $sidebg;
 5759:   width: 100%;
 5760:   padding-bottom: 10px;
 5761:   border: 1px $tabbg solid;
 5762:   height: 22px;
 5763:   line-height: 22px;
 5764:   padding-top: 5px;
 5765: }
 5766: 
 5767: div.LC_feedback_link img {
 5768:   height: 22px;
 5769:   vertical-align:middle;
 5770: }
 5771: 
 5772: div.LC_feedback_link a {
 5773:   text-decoration: none;
 5774: }
 5775: 
 5776: div.LC_comblock {
 5777:   display:inline;
 5778:   color:$font;
 5779:   font-size:90%;
 5780: }
 5781: 
 5782: div.LC_feedback_link div.LC_comblock {
 5783:   padding-left:5px;
 5784: }
 5785: 
 5786: div.LC_feedback_link div.LC_comblock a {
 5787:   color:$font;
 5788: }
 5789: 
 5790: span.LC_feedback_link {
 5791:   /* background: $feedback_link_bg; */
 5792:   font-size: larger;
 5793: }
 5794: 
 5795: span.LC_message_link {
 5796:   /* background: $feedback_link_bg; */
 5797:   font-size: larger;
 5798:   position: absolute;
 5799:   right: 1em;
 5800: }
 5801: 
 5802: table.LC_prior_tries {
 5803:   border: 1px solid #000000;
 5804:   border-collapse: separate;
 5805:   border-spacing: 1px;
 5806: }
 5807: 
 5808: table.LC_prior_tries td {
 5809:   padding: 2px;
 5810: }
 5811: 
 5812: .LC_answer_correct {
 5813:   background: lightgreen;
 5814:   color: darkgreen;
 5815:   padding: 6px;
 5816: }
 5817: 
 5818: .LC_answer_charged_try {
 5819:   background: #FFAAAA;
 5820:   color: darkred;
 5821:   padding: 6px;
 5822: }
 5823: 
 5824: .LC_answer_not_charged_try,
 5825: .LC_answer_no_grade,
 5826: .LC_answer_late {
 5827:   background: lightyellow;
 5828:   color: black;
 5829:   padding: 6px;
 5830: }
 5831: 
 5832: .LC_answer_previous {
 5833:   background: lightblue;
 5834:   color: darkblue;
 5835:   padding: 6px;
 5836: }
 5837: 
 5838: .LC_answer_no_message {
 5839:   background: #FFFFFF;
 5840:   color: black;
 5841:   padding: 6px;
 5842: }
 5843: 
 5844: .LC_answer_unknown {
 5845:   background: orange;
 5846:   color: black;
 5847:   padding: 6px;
 5848: }
 5849: 
 5850: span.LC_prior_numerical,
 5851: span.LC_prior_string,
 5852: span.LC_prior_custom,
 5853: span.LC_prior_reaction,
 5854: span.LC_prior_math {
 5855:   font-family: $mono;
 5856:   white-space: pre;
 5857: }
 5858: 
 5859: span.LC_prior_string {
 5860:   font-family: $mono;
 5861:   white-space: pre;
 5862: }
 5863: 
 5864: table.LC_prior_option {
 5865:   width: 100%;
 5866:   border-collapse: collapse;
 5867: }
 5868: 
 5869: table.LC_prior_rank,
 5870: table.LC_prior_match {
 5871:   border-collapse: collapse;
 5872: }
 5873: 
 5874: table.LC_prior_option tr td,
 5875: table.LC_prior_rank tr td,
 5876: table.LC_prior_match tr td {
 5877:   border: 1px solid #000000;
 5878: }
 5879: 
 5880: .LC_nobreak {
 5881:   white-space: nowrap;
 5882: }
 5883: 
 5884: span.LC_cusr_emph {
 5885:   font-style: italic;
 5886: }
 5887: 
 5888: span.LC_cusr_subheading {
 5889:   font-weight: normal;
 5890:   font-size: 85%;
 5891: }
 5892: 
 5893: div.LC_docs_entry_move {
 5894:   border: 1px solid #BBBBBB;
 5895:   background: #DDDDDD;
 5896:   width: 22px;
 5897:   padding: 1px;
 5898:   margin: 0;
 5899: }
 5900: 
 5901: table.LC_data_table tr > td.LC_docs_entry_commands,
 5902: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5903:   background: #DDDDDD;
 5904:   font-size: x-small;
 5905: }
 5906: 
 5907: .LC_docs_entry_parameter {
 5908:   white-space: nowrap;
 5909: }
 5910: 
 5911: .LC_docs_copy {
 5912:   color: #000099;
 5913: }
 5914: 
 5915: .LC_docs_cut {
 5916:   color: #550044;
 5917: }
 5918: 
 5919: .LC_docs_rename {
 5920:   color: #009900;
 5921: }
 5922: 
 5923: .LC_docs_remove {
 5924:   color: #990000;
 5925: }
 5926: 
 5927: .LC_docs_reinit_warn,
 5928: .LC_docs_ext_edit {
 5929:   font-size: x-small;
 5930: }
 5931: 
 5932: table.LC_docs_adddocs td,
 5933: table.LC_docs_adddocs th {
 5934:   border: 1px solid #BBBBBB;
 5935:   padding: 4px;
 5936:   background: #DDDDDD;
 5937: }
 5938: 
 5939: table.LC_sty_begin {
 5940:   background: #BBFFBB;
 5941: }
 5942: 
 5943: table.LC_sty_end {
 5944:   background: #FFBBBB;
 5945: }
 5946: 
 5947: table.LC_double_column {
 5948:   border-width: 0;
 5949:   border-collapse: collapse;
 5950:   width: 100%;
 5951:   padding: 2px;
 5952: }
 5953: 
 5954: table.LC_double_column tr td.LC_left_col {
 5955:   top: 2px;
 5956:   left: 2px;
 5957:   width: 47%;
 5958:   vertical-align: top;
 5959: }
 5960: 
 5961: table.LC_double_column tr td.LC_right_col {
 5962:   top: 2px;
 5963:   right: 2px;
 5964:   width: 47%;
 5965:   vertical-align: top;
 5966: }
 5967: 
 5968: div.LC_left_float {
 5969:   float: left;
 5970:   padding-right: 5%;
 5971:   padding-bottom: 4px;
 5972: }
 5973: 
 5974: div.LC_clear_float_header {
 5975:   padding-bottom: 2px;
 5976: }
 5977: 
 5978: div.LC_clear_float_footer {
 5979:   padding-top: 10px;
 5980:   clear: both;
 5981: }
 5982: 
 5983: div.LC_grade_show_user {
 5984: /*  border-left: 5px solid $sidebg; */
 5985:   border-top: 5px solid #000000;
 5986:   margin: 50px 0 0 0;
 5987:   padding: 15px 0 5px 10px;
 5988: }
 5989: 
 5990: div.LC_grade_show_user_odd_row {
 5991: /*  border-left: 5px solid #000000; */
 5992: }
 5993: 
 5994: div.LC_grade_show_user div.LC_Box {
 5995:   margin-right: 50px;
 5996: }
 5997: 
 5998: div.LC_grade_submissions,
 5999: div.LC_grade_message_center,
 6000: div.LC_grade_info_links {
 6001:   margin: 5px;
 6002:   width: 99%;
 6003:   background: #FFFFFF;
 6004: }
 6005: 
 6006: div.LC_grade_submissions_header,
 6007: div.LC_grade_message_center_header {
 6008:   font-weight: bold;
 6009:   font-size: large;
 6010: }
 6011: 
 6012: div.LC_grade_submissions_body,
 6013: div.LC_grade_message_center_body {
 6014:   border: 1px solid black;
 6015:   width: 99%;
 6016:   background: #FFFFFF;
 6017: }
 6018: 
 6019: table.LC_scantron_action {
 6020:   width: 100%;
 6021: }
 6022: 
 6023: table.LC_scantron_action tr th {
 6024:   font-weight:bold;
 6025:   font-style:normal;
 6026: }
 6027: 
 6028: .LC_edit_problem_header,
 6029: div.LC_edit_problem_footer {
 6030:   font-weight: normal;
 6031:   font-size:  medium;
 6032:   margin: 2px;
 6033: }
 6034: 
 6035: div.LC_edit_problem_header,
 6036: div.LC_edit_problem_header div,
 6037: div.LC_edit_problem_footer,
 6038: div.LC_edit_problem_footer div,
 6039: div.LC_edit_problem_editxml_header,
 6040: div.LC_edit_problem_editxml_header div {
 6041:   margin-top: 5px;
 6042: }
 6043: 
 6044: div.LC_edit_problem_header_title {
 6045:   font-weight: bold;
 6046:   font-size: larger;
 6047:   background: $tabbg;
 6048:   padding: 3px;
 6049: }
 6050: 
 6051: table.LC_edit_problem_header_title {
 6052:   width: 100%;
 6053:   background: $tabbg;
 6054: }
 6055: 
 6056: div.LC_edit_problem_discards {
 6057:   float: left;
 6058:   padding-bottom: 5px;
 6059: }
 6060: 
 6061: div.LC_edit_problem_saves {
 6062:   float: right;
 6063:   padding-bottom: 5px;
 6064: }
 6065: 
 6066: img.stift {
 6067:   border-width: 0;
 6068:   vertical-align: middle;
 6069: }
 6070: 
 6071: table td.LC_mainmenu_col_fieldset {
 6072:   vertical-align: top;
 6073: }
 6074: 
 6075: div.LC_createcourse {
 6076:   margin: 10px 10px 10px 10px;
 6077: }
 6078: 
 6079: .LC_dccid {
 6080:   margin: 0.2em 0 0 0;
 6081:   padding: 0;
 6082:   font-size: 90%;
 6083:   display:none;
 6084: }
 6085: 
 6086: a:hover,
 6087: ol.LC_primary_menu a:hover,
 6088: ol#LC_MenuBreadcrumbs a:hover,
 6089: ol#LC_PathBreadcrumbs a:hover,
 6090: ul#LC_secondary_menu a:hover,
 6091: .LC_FormSectionClearButton input:hover
 6092: ul.LC_TabContent   li:hover a {
 6093:   color:$button_hover;
 6094:   text-decoration:none;
 6095: }
 6096: 
 6097: h1 {
 6098:   padding: 0;
 6099:   line-height:130%;
 6100: }
 6101: 
 6102: h2,
 6103: h3,
 6104: h4,
 6105: h5,
 6106: h6 {
 6107:   margin: 5px 0 5px 0;
 6108:   padding: 0;
 6109:   line-height:130%;
 6110: }
 6111: 
 6112: .LC_hcell {
 6113:   padding:3px 15px 3px 15px;
 6114:   margin: 0;
 6115:   background-color:$tabbg;
 6116:   color:$fontmenu;
 6117:   border-bottom:solid 1px $lg_border_color;
 6118: }
 6119: 
 6120: .LC_Box > .LC_hcell {
 6121:   margin: 0 -10px 10px -10px;
 6122: }
 6123: 
 6124: .LC_noBorder {
 6125:   border: 0;
 6126: }
 6127: 
 6128: .LC_FormSectionClearButton input {
 6129:   background-color:transparent;
 6130:   border: none;
 6131:   cursor:pointer;
 6132:   text-decoration:underline;
 6133: }
 6134: 
 6135: .LC_help_open_topic {
 6136:   color: #FFFFFF;
 6137:   background-color: #EEEEFF;
 6138:   margin: 1px;
 6139:   padding: 4px;
 6140:   border: 1px solid #000033;
 6141:   white-space: nowrap;
 6142:   /* vertical-align: middle; */
 6143: }
 6144: 
 6145: dl,
 6146: ul,
 6147: div,
 6148: fieldset {
 6149:   margin: 10px 10px 10px 0;
 6150:   /* overflow: hidden; */
 6151: }
 6152: 
 6153: fieldset > legend {
 6154:   font-weight: bold;
 6155:   padding: 0 5px 0 5px;
 6156: }
 6157: 
 6158: #LC_nav_bar {
 6159:   float: left;
 6160:   background-color: $pgbg_or_bgcolor;
 6161:   margin: 0 0 2px 0;
 6162: }
 6163: 
 6164: #LC_realm {
 6165:   margin: 0.2em 0 0 0;
 6166:   padding: 0;
 6167:   font-weight: bold;
 6168:   text-align: center;
 6169:   background-color: $pgbg_or_bgcolor;
 6170: }
 6171: 
 6172: #LC_nav_bar em {
 6173:   font-weight: bold;
 6174:   font-style: normal;
 6175: }
 6176: 
 6177: ol.LC_primary_menu {
 6178:   float: right;
 6179:   margin: 0;
 6180:   background-color: $pgbg_or_bgcolor;
 6181: }
 6182: 
 6183: ol#LC_PathBreadcrumbs {
 6184:   margin: 0;
 6185: }
 6186: 
 6187: ol.LC_primary_menu li {
 6188:   display: inline;
 6189:   padding: 5px 5px 0 10px;
 6190:   vertical-align: top;
 6191: }
 6192: 
 6193: ol.LC_primary_menu li img {
 6194:   vertical-align: bottom;
 6195:   height: 1.1em;
 6196: }
 6197: 
 6198: ol.LC_primary_menu a {
 6199:   color: RGB(80, 80, 80);
 6200:   text-decoration: none;
 6201: }
 6202: 
 6203: ol.LC_primary_menu a.LC_new_message {
 6204:   font-weight:bold;
 6205:   color: darkred;
 6206: }
 6207: 
 6208: ol.LC_docs_parameters {
 6209:   margin-left: 0;
 6210:   padding: 0;
 6211:   list-style: none;
 6212: }
 6213: 
 6214: ol.LC_docs_parameters li {
 6215:   margin: 0;
 6216:   padding-right: 20px;
 6217:   display: inline;
 6218: }
 6219: 
 6220: ol.LC_docs_parameters li:before {
 6221:   content: "\\002022 \\0020";
 6222: }
 6223: 
 6224: li.LC_docs_parameters_title {
 6225:   font-weight: bold;
 6226: }
 6227: 
 6228: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6229:   content: "";
 6230: }
 6231: 
 6232: ul#LC_secondary_menu {
 6233:   clear: both;
 6234:   color: $fontmenu;
 6235:   background: $tabbg;
 6236:   list-style: none;
 6237:   padding: 0;
 6238:   margin: 0;
 6239:   width: 100%;
 6240:   text-align: left;
 6241: }
 6242: 
 6243: ul#LC_secondary_menu li {
 6244:   font-weight: bold;
 6245:   line-height: 1.8em;
 6246:   padding: 0 0.8em;
 6247:   border-right: 1px solid black;
 6248:   display: inline;
 6249:   vertical-align: middle;
 6250: }
 6251: 
 6252: ul.LC_TabContent {
 6253:   display:block;
 6254:   background: $sidebg;
 6255:   border-bottom: solid 1px $lg_border_color;
 6256:   list-style:none;
 6257:   margin: -1px -10px 0 -10px;
 6258:   padding: 0;
 6259: }
 6260: 
 6261: ul.LC_TabContent li,
 6262: ul.LC_TabContentBigger li {
 6263:   float:left;
 6264: }
 6265: 
 6266: ul#LC_secondary_menu li a {
 6267:   color: $fontmenu;
 6268:   text-decoration: none;
 6269: }
 6270: 
 6271: ul.LC_TabContent {
 6272:   min-height:20px;
 6273: }
 6274: 
 6275: ul.LC_TabContent li {
 6276:   vertical-align:middle;
 6277:   padding: 0 16px 0 10px;
 6278:   background-color:$tabbg;
 6279:   border-bottom:solid 1px $lg_border_color;
 6280:   border-left: solid 1px $font;
 6281: }
 6282: 
 6283: ul.LC_TabContent .right {
 6284:   float:right;
 6285: }
 6286: 
 6287: ul.LC_TabContent li a,
 6288: ul.LC_TabContent li {
 6289:   color:rgb(47,47,47);
 6290:   text-decoration:none;
 6291:   font-size:95%;
 6292:   font-weight:bold;
 6293:   min-height:20px;
 6294: }
 6295: 
 6296: ul.LC_TabContent li a:hover,
 6297: ul.LC_TabContent li a:focus {
 6298:   color: $button_hover;
 6299:   background:none;
 6300:   outline:none;
 6301: }
 6302: 
 6303: ul.LC_TabContent li:hover {
 6304:   color: $button_hover;
 6305:   cursor:pointer;
 6306: }
 6307: 
 6308: ul.LC_TabContent li.active {
 6309:   color: $font;
 6310:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6311:   border-bottom:solid 1px #FFFFFF;
 6312:   cursor: default;
 6313: }
 6314: 
 6315: ul.LC_TabContent li.active a {
 6316:   color:$font;
 6317:   background:#FFFFFF;
 6318:   outline: none;
 6319: }
 6320: #maincoursedoc {
 6321:   clear:both;
 6322: }
 6323: 
 6324: ul.LC_TabContentBigger {
 6325:   display:block;
 6326:   list-style:none;
 6327:   padding: 0;
 6328: }
 6329: 
 6330: ul.LC_TabContentBigger li {
 6331:   vertical-align:bottom;
 6332:   height: 30px;
 6333:   font-size:110%;
 6334:   font-weight:bold;
 6335:   color: #737373;
 6336: }
 6337: 
 6338: ul.LC_TabContentBigger li.active {
 6339:   position: relative;
 6340:   top: 1px;
 6341: }
 6342: 
 6343: ul.LC_TabContentBigger li a {
 6344:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6345:   height: 30px;
 6346:   line-height: 30px;
 6347:   text-align: center;
 6348:   display: block;
 6349:   text-decoration: none;
 6350:   outline: none;  
 6351: }
 6352: 
 6353: ul.LC_TabContentBigger li.active a {
 6354:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6355:   color:$font;
 6356: }
 6357: 
 6358: ul.LC_TabContentBigger li b {
 6359:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6360:   display: block;
 6361:   float: left;
 6362:   padding: 0 30px;
 6363:   border-bottom: 1px solid $lg_border_color;
 6364: }
 6365: 
 6366: ul.LC_TabContentBigger li:hover b {
 6367:   color:$button_hover;
 6368: }
 6369: 
 6370: ul.LC_TabContentBigger li.active b {
 6371:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6372:   color:$font;
 6373:   border: 0;
 6374: }
 6375: 
 6376: 
 6377: ul.LC_CourseBreadcrumbs {
 6378:   background: $sidebg;
 6379:   height: 2em;
 6380:   padding-left: 10px;
 6381:   margin: 0;
 6382:   list-style-position: inside;
 6383: }
 6384: 
 6385: ol#LC_MenuBreadcrumbs,
 6386: ol#LC_PathBreadcrumbs {
 6387:   padding-left: 10px;
 6388:   margin: 0;
 6389:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6390: }
 6391: 
 6392: ol#LC_MenuBreadcrumbs li,
 6393: ol#LC_PathBreadcrumbs li,
 6394: ul.LC_CourseBreadcrumbs li {
 6395:   display: inline;
 6396:   white-space: normal;  
 6397: }
 6398: 
 6399: ol#LC_MenuBreadcrumbs li a,
 6400: ul.LC_CourseBreadcrumbs li a {
 6401:   text-decoration: none;
 6402:   font-size:90%;
 6403: }
 6404: 
 6405: ol#LC_MenuBreadcrumbs h1 {
 6406:   display: inline;
 6407:   font-size: 90%;
 6408:   line-height: 2.5em;
 6409:   margin: 0;
 6410:   padding: 0;
 6411: }
 6412: 
 6413: ol#LC_PathBreadcrumbs li a {
 6414:   text-decoration:none;
 6415:   font-size:100%;
 6416:   font-weight:bold;
 6417: }
 6418: 
 6419: .LC_Box {
 6420:   border: solid 1px $lg_border_color;
 6421:   padding: 0 10px 10px 10px;
 6422: }
 6423: 
 6424: .LC_DocsBox {
 6425:   border: solid 1px $lg_border_color;
 6426:   padding: 0 0 10px 10px;
 6427: }
 6428: 
 6429: .LC_AboutMe_Image {
 6430:   float:left;
 6431:   margin-right:10px;
 6432: }
 6433: 
 6434: .LC_Clear_AboutMe_Image {
 6435:   clear:left;
 6436: }
 6437: 
 6438: dl.LC_ListStyleClean dt {
 6439:   padding-right: 5px;
 6440:   display: table-header-group;
 6441: }
 6442: 
 6443: dl.LC_ListStyleClean dd {
 6444:   display: table-row;
 6445: }
 6446: 
 6447: .LC_ListStyleClean,
 6448: .LC_ListStyleSimple,
 6449: .LC_ListStyleNormal,
 6450: .LC_ListStyleSpecial {
 6451:   /* display:block; */
 6452:   list-style-position: inside;
 6453:   list-style-type: none;
 6454:   overflow: hidden;
 6455:   padding: 0;
 6456: }
 6457: 
 6458: .LC_ListStyleSimple li,
 6459: .LC_ListStyleSimple dd,
 6460: .LC_ListStyleNormal li,
 6461: .LC_ListStyleNormal dd,
 6462: .LC_ListStyleSpecial li,
 6463: .LC_ListStyleSpecial dd {
 6464:   margin: 0;
 6465:   padding: 5px 5px 5px 10px;
 6466:   clear: both;
 6467: }
 6468: 
 6469: .LC_ListStyleClean li,
 6470: .LC_ListStyleClean dd {
 6471:   padding-top: 0;
 6472:   padding-bottom: 0;
 6473: }
 6474: 
 6475: .LC_ListStyleSimple dd,
 6476: .LC_ListStyleSimple li {
 6477:   border-bottom: solid 1px $lg_border_color;
 6478: }
 6479: 
 6480: .LC_ListStyleSpecial li,
 6481: .LC_ListStyleSpecial dd {
 6482:   list-style-type: none;
 6483:   background-color: RGB(220, 220, 220);
 6484:   margin-bottom: 4px;
 6485: }
 6486: 
 6487: table.LC_SimpleTable {
 6488:   margin:5px;
 6489:   border:solid 1px $lg_border_color;
 6490: }
 6491: 
 6492: table.LC_SimpleTable tr {
 6493:   padding: 0;
 6494:   border:solid 1px $lg_border_color;
 6495: }
 6496: 
 6497: table.LC_SimpleTable thead {
 6498:   background:rgb(220,220,220);
 6499: }
 6500: 
 6501: div.LC_columnSection {
 6502:   display: block;
 6503:   clear: both;
 6504:   overflow: hidden;
 6505:   margin: 0;
 6506: }
 6507: 
 6508: div.LC_columnSection>* {
 6509:   float: left;
 6510:   margin: 10px 20px 10px 0;
 6511:   overflow:hidden;
 6512: }
 6513: 
 6514: table em {
 6515:   font-weight: bold;
 6516:   font-style: normal;
 6517: }
 6518: 
 6519: table.LC_tableBrowseRes,
 6520: table.LC_tableOfContent {
 6521:   border:none;
 6522:   border-spacing: 1px;
 6523:   padding: 3px;
 6524:   background-color: #FFFFFF;
 6525:   font-size: 90%;
 6526: }
 6527: 
 6528: table.LC_tableOfContent {
 6529:   border-collapse: collapse;
 6530: }
 6531: 
 6532: table.LC_tableBrowseRes a,
 6533: table.LC_tableOfContent a {
 6534:   background-color: transparent;
 6535:   text-decoration: none;
 6536: }
 6537: 
 6538: table.LC_tableOfContent img {
 6539:   border: none;
 6540:   height: 1.3em;
 6541:   vertical-align: text-bottom;
 6542:   margin-right: 0.3em;
 6543: }
 6544: 
 6545: a#LC_content_toolbar_firsthomework {
 6546:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6547: }
 6548: 
 6549: a#LC_content_toolbar_everything {
 6550:   background-image:url(/res/adm/pages/show-all.gif);
 6551: }
 6552: 
 6553: a#LC_content_toolbar_uncompleted {
 6554:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6555: }
 6556: 
 6557: #LC_content_toolbar_clearbubbles {
 6558:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6559: }
 6560: 
 6561: a#LC_content_toolbar_changefolder {
 6562:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6563: }
 6564: 
 6565: a#LC_content_toolbar_changefolder_toggled {
 6566:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6567: }
 6568: 
 6569: ul#LC_toolbar li a:hover {
 6570:   background-position: bottom center;
 6571: }
 6572: 
 6573: ul#LC_toolbar {
 6574:   padding: 0;
 6575:   margin: 2px;
 6576:   list-style:none;
 6577:   position:relative;
 6578:   background-color:white;
 6579: }
 6580: 
 6581: ul#LC_toolbar li {
 6582:   border:1px solid white;
 6583:   padding: 0;
 6584:   margin: 0;
 6585:   float: left;
 6586:   display:inline;
 6587:   vertical-align:middle;
 6588: }
 6589: 
 6590: 
 6591: a.LC_toolbarItem {
 6592:   display:block;
 6593:   padding: 0;
 6594:   margin: 0;
 6595:   height: 32px;
 6596:   width: 32px;
 6597:   color:white;
 6598:   border: none;
 6599:   background-repeat:no-repeat;
 6600:   background-color:transparent;
 6601: }
 6602: 
 6603: ul.LC_funclist {
 6604:     margin: 0;
 6605:     padding: 0.5em 1em 0.5em 0;
 6606: }
 6607: 
 6608: ul.LC_funclist > li:first-child {
 6609:     font-weight:bold; 
 6610:     margin-left:0.8em;
 6611: }
 6612: 
 6613: ul.LC_funclist + ul.LC_funclist {
 6614:     /* 
 6615:        left border as a seperator if we have more than
 6616:        one list 
 6617:     */
 6618:     border-left: 1px solid $sidebg;
 6619:     /* 
 6620:        this hides the left border behind the border of the 
 6621:        outer box if element is wrapped to the next 'line' 
 6622:     */
 6623:     margin-left: -1px;
 6624: }
 6625: 
 6626: ul.LC_funclist li {
 6627:   display: inline;
 6628:   white-space: nowrap;
 6629:   margin: 0 0 0 25px;
 6630:   line-height: 150%;
 6631: }
 6632: 
 6633: .LC_hidden {
 6634:   display: none;
 6635: }
 6636: 
 6637: .LCmodal-overlay {
 6638: 		position:fixed;
 6639: 		top:0;
 6640: 		right:0;
 6641: 		bottom:0;
 6642: 		left:0;
 6643: 		height:100%;
 6644: 		width:100%;
 6645: 		margin:0;
 6646: 		padding:0;
 6647: 		background:#999;
 6648: 		opacity:.75;
 6649: 		filter: alpha(opacity=75);
 6650: 		-moz-opacity: 0.75;
 6651: 		z-index:101;
 6652: }
 6653: 
 6654: * html .LCmodal-overlay {   
 6655: 		position: absolute;
 6656: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 6657: }
 6658: 
 6659: .LCmodal-window {
 6660: 		position:fixed;
 6661: 		top:50%;
 6662: 		left:50%;
 6663: 		margin:0;
 6664: 		padding:0;
 6665: 		z-index:102;
 6666: 	}
 6667: 
 6668: * html .LCmodal-window {
 6669: 		position:absolute;
 6670: }
 6671: 
 6672: .LCclose-window {
 6673: 		position:absolute;
 6674: 		width:32px;
 6675: 		height:32px;
 6676: 		right:8px;
 6677: 		top:8px;
 6678: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 6679: 		text-indent:-99999px;
 6680: 		overflow:hidden;
 6681: 		cursor:pointer;
 6682: }
 6683: 
 6684: END
 6685: }
 6686: 
 6687: =pod
 6688: 
 6689: =item * &headtag()
 6690: 
 6691: Returns a uniform footer for LON-CAPA web pages.
 6692: 
 6693: Inputs: $title - optional title for the head
 6694:         $head_extra - optional extra HTML to put inside the <head>
 6695:         $args - optional arguments
 6696:             force_register - if is true call registerurl so the remote is 
 6697:                              informed
 6698:             redirect       -> array ref of
 6699:                                    1- seconds before redirect occurs
 6700:                                    2- url to redirect to
 6701:                                    3- whether the side effect should occur
 6702:                            (side effect of setting 
 6703:                                $env{'internal.head.redirect'} to the url 
 6704:                                redirected too)
 6705:             domain         -> force to color decorate a page for a specific
 6706:                                domain
 6707:             function       -> force usage of a specific rolish color scheme
 6708:             bgcolor        -> override the default page bgcolor
 6709:             no_auto_mt_title
 6710:                            -> prevent &mt()ing the title arg
 6711: 
 6712: =cut
 6713: 
 6714: sub headtag {
 6715:     my ($title,$head_extra,$args) = @_;
 6716:     
 6717:     my $function = $args->{'function'} || &get_users_function();
 6718:     my $domain   = $args->{'domain'}   || &determinedomain();
 6719:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6720:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6721: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6722: 		   #time(),
 6723: 		   $env{'environment.color.timestamp'},
 6724: 		   $function,$domain,$bgcolor);
 6725: 
 6726:     $url = '/adm/css/'.&escape($url).'.css';
 6727: 
 6728:     my $result =
 6729: 	'<head>'.
 6730: 	&font_settings();
 6731: 
 6732:     if (!$args->{'frameset'}) {
 6733: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6734:     }
 6735:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 6736:         $result .= Apache::lonxml::display_title();
 6737:     }
 6738:     if (!$args->{'no_nav_bar'} 
 6739: 	&& !$args->{'only_body'}
 6740: 	&& !$args->{'frameset'}) {
 6741: 	$result .= &help_menu_js();
 6742:         $result.=&modal_window();
 6743:         $result.=&wishlist_window();
 6744:     } else {
 6745:         if ($args->{'add_modal'}) {
 6746:            $result.=&modal_window();
 6747:         }
 6748:         if ($args->{'add_wishlist'}) {
 6749:            $result.=&wishlist_window();
 6750:         }
 6751:     }
 6752:     if (ref($args->{'redirect'})) {
 6753: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6754: 	$url = &Apache::lonenc::check_encrypt($url);
 6755: 	if (!$inhibit_continue) {
 6756: 	    $env{'internal.head.redirect'} = $url;
 6757: 	}
 6758: 	$result.=<<ADDMETA
 6759: <meta http-equiv="pragma" content="no-cache" />
 6760: <meta http-equiv="Refresh" content="$time; url=$url" />
 6761: ADDMETA
 6762:     }
 6763:     if (!defined($title)) {
 6764: 	$title = 'The LearningOnline Network with CAPA';
 6765:     }
 6766:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6767:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6768: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6769: 	.$head_extra;
 6770:     return $result.'</head>';
 6771: }
 6772: 
 6773: =pod
 6774: 
 6775: =item * &font_settings()
 6776: 
 6777: Returns neccessary <meta> to set the proper encoding
 6778: 
 6779: Inputs: none
 6780: 
 6781: =cut
 6782: 
 6783: sub font_settings {
 6784:     my $headerstring='';
 6785:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6786: 	$headerstring.=
 6787: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6788:     }
 6789:     return $headerstring;
 6790: }
 6791: 
 6792: =pod
 6793: 
 6794: =item * &xml_begin()
 6795: 
 6796: Returns the needed doctype and <html>
 6797: 
 6798: Inputs: none
 6799: 
 6800: =cut
 6801: 
 6802: sub xml_begin {
 6803:     my $output='';
 6804: 
 6805:     if ($env{'browser.mathml'}) {
 6806: 	$output='<?xml version="1.0"?>'
 6807:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6808: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6809:             
 6810: #	    .'<!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">] >'
 6811: 	    .'<!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">'
 6812:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6813: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6814:     } else {
 6815: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6816:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6817:     }
 6818:     return $output;
 6819: }
 6820: 
 6821: =pod
 6822: 
 6823: =item * &start_page()
 6824: 
 6825: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6826: 
 6827: Inputs:
 6828: 
 6829: =over 4
 6830: 
 6831: $title - optional title for the page
 6832: 
 6833: $head_extra - optional extra HTML to incude inside the <head>
 6834: 
 6835: $args - additional optional args supported are:
 6836: 
 6837: =over 8
 6838: 
 6839:              only_body      -> is true will set &bodytag() onlybodytag
 6840:                                     arg on
 6841:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6842:              add_entries    -> additional attributes to add to the  <body>
 6843:              domain         -> force to color decorate a page for a 
 6844:                                     specific domain
 6845:              function       -> force usage of a specific rolish color
 6846:                                     scheme
 6847:              redirect       -> see &headtag()
 6848:              bgcolor        -> override the default page bg color
 6849:              js_ready       -> return a string ready for being used in 
 6850:                                     a javascript writeln
 6851:              html_encode    -> return a string ready for being used in 
 6852:                                     a html attribute
 6853:              force_register -> if is true will turn on the &bodytag()
 6854:                                     $forcereg arg
 6855:              frameset       -> if true will start with a <frameset>
 6856:                                     rather than <body>
 6857:              skip_phases    -> hash ref of 
 6858:                                     head -> skip the <html><head> generation
 6859:                                     body -> skip all <body> generation
 6860:              no_auto_mt_title -> prevent &mt()ing the title arg
 6861:              inherit_jsmath -> when creating popup window in a page,
 6862:                                     should it have jsmath forced on by the
 6863:                                     current page
 6864:              bread_crumbs ->             Array containing breadcrumbs
 6865:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 6866: 
 6867: =back
 6868: 
 6869: =back
 6870: 
 6871: =cut
 6872: 
 6873: sub start_page {
 6874:     my ($title,$head_extra,$args) = @_;
 6875:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6876: 
 6877:     $env{'internal.start_page'}++;
 6878:     my $result;
 6879: 
 6880:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6881:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 6882:     }
 6883:     
 6884:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6885: 	if ($args->{'frameset'}) {
 6886: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6887: 						$args->{'add_entries'});
 6888: 	    $result .= "\n<frameset $attr_string>\n";
 6889:         } else {
 6890:             $result .=
 6891:                 &bodytag($title, 
 6892:                          $args->{'function'},       $args->{'add_entries'},
 6893:                          $args->{'only_body'},      $args->{'domain'},
 6894:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6895:                          $args->{'bgcolor'},        $args);
 6896:         }
 6897:     }
 6898: 
 6899:     if ($args->{'js_ready'}) {
 6900: 		$result = &js_ready($result);
 6901:     }
 6902:     if ($args->{'html_encode'}) {
 6903: 		$result = &html_encode($result);
 6904:     }
 6905: 
 6906:     # Preparation for new and consistent functionlist at top of screen
 6907:     # if ($args->{'functionlist'}) {
 6908:     #            $result .= &build_functionlist();
 6909:     #}
 6910: 
 6911:     # Don't add anything more if only_body wanted or in const space
 6912:     return $result if    $args->{'only_body'} 
 6913:                       || $env{'request.state'} eq 'construct';
 6914: 
 6915:     #Breadcrumbs
 6916:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6917: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6918: 		#if any br links exists, add them to the breadcrumbs
 6919: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6920: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6921: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6922: 			}
 6923: 		}
 6924: 
 6925: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6926: 		if(exists($args->{'bread_crumbs_component'})){
 6927: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6928: 		}else{
 6929: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6930: 		}
 6931:     }
 6932:     return $result;
 6933: }
 6934: 
 6935: sub end_page {
 6936:     my ($args) = @_;
 6937:     $env{'internal.end_page'}++;
 6938:     my $result;
 6939:     if ($args->{'discussion'}) {
 6940: 	my ($target,$parser);
 6941: 	if (ref($args->{'discussion'})) {
 6942: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6943: 				$args->{'discussion'}{'parser'});
 6944: 	}
 6945: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6946:     }
 6947:     if ($args->{'frameset'}) {
 6948: 	$result .= '</frameset>';
 6949:     } else {
 6950: 	$result .= &endbodytag($args);
 6951:     }
 6952:     $result .= "\n</html>";
 6953: 
 6954:     if ($args->{'js_ready'}) {
 6955: 	$result = &js_ready($result);
 6956:     }
 6957: 
 6958:     if ($args->{'html_encode'}) {
 6959: 	$result = &html_encode($result);
 6960:     }
 6961: 
 6962:     return $result;
 6963: }
 6964: 
 6965: sub wishlist_window {
 6966:     return(<<'ENDWISHLIST');
 6967: <script type="text/javascript" lang="javascript">
 6968: // <![CDATA[
 6969: // <!-- BEGIN LON-CAPA Internal
 6970: function set_wishlistlink(title, path) {
 6971:     if (!title) {
 6972:         title = document.title;
 6973:         title = title.replace(/^LON-CAPA /,'');
 6974:     }
 6975:     if (!path) {
 6976:         path = location.pathname;
 6977:     }
 6978:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 6979:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 6980: }
 6981: // END LON-CAPA Internal -->
 6982: // ]]>
 6983: </script>
 6984: ENDWISHLIST
 6985: }
 6986: 
 6987: sub modal_window {
 6988:     return(<<'ENDMODAL');
 6989: <script type="text/javascript" lang="javascript">
 6990: // <![CDATA[
 6991: // <!-- BEGIN LON-CAPA Internal
 6992: var modalWindow = {
 6993: 	parent:"body",
 6994: 	windowId:null,
 6995: 	content:null,
 6996: 	width:null,
 6997: 	height:null,
 6998: 	close:function()
 6999: 	{
 7000: 	        $(".LCmodal-window").remove();
 7001: 	        $(".LCmodal-overlay").remove();
 7002: 	},
 7003: 	open:function()
 7004: 	{
 7005: 		var modal = "";
 7006: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7007: 		modal += "<div id=\"" + this.windowId + "\" class=\"LCmodal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
 7008: 		modal += this.content;
 7009: 		modal += "</div>";	
 7010: 
 7011: 		$(this.parent).append(modal);
 7012: 
 7013: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7014: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7015: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7016: 	}
 7017: };
 7018: 	var openMyModal = function(source,width,height,scrolling)
 7019: 	{
 7020: 		modalWindow.windowId = "myModal";
 7021: 		modalWindow.width = width;
 7022: 		modalWindow.height = height;
 7023: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
 7024: 		modalWindow.open();
 7025: 	};	
 7026: // END LON-CAPA Internal -->
 7027: // ]]>
 7028: </script>
 7029: ENDMODAL
 7030: }
 7031: 
 7032: sub modal_link {
 7033:     my ($link,$linktext,$width,$height,$target,$scrolling)=@_;
 7034:     unless ($width) { $width=480; }
 7035:     unless ($height) { $height=400; }
 7036:     unless ($scrolling) { $scrolling='yes'; }
 7037:     return '<a href="'.$link.'" target="'.$target.'" onclick="openMyModal(\''.$link.'\','.$width.','.$height.',\''.$scrolling.'\'); return false;">'.
 7038:            $linktext.'</a>';
 7039: }
 7040: 
 7041: sub modal_adhoc_script {
 7042:     my ($funcname,$width,$height,$content)=@_;
 7043:     return (<<ENDADHOC);
 7044: <script type="text/javascript" lang="javascript">
 7045: // <![CDATA[
 7046:         var $funcname = function()
 7047:         {
 7048:                 modalWindow.windowId = "myModal";
 7049:                 modalWindow.width = $width;
 7050:                 modalWindow.height = $height;
 7051:                 modalWindow.content = '$content';
 7052:                 modalWindow.open();
 7053:         };  
 7054: // ]]>
 7055: </script>
 7056: ENDADHOC
 7057: }
 7058: 
 7059: sub html_encode {
 7060:     my ($result) = @_;
 7061: 
 7062:     $result = &HTML::Entities::encode($result,'<>&"');
 7063:     
 7064:     return $result;
 7065: }
 7066: sub js_ready {
 7067:     my ($result) = @_;
 7068: 
 7069:     $result =~ s/[\n\r]/ /xmsg;
 7070:     $result =~ s/\\/\\\\/xmsg;
 7071:     $result =~ s/'/\\'/xmsg;
 7072:     $result =~ s{</}{<\\/}xmsg;
 7073:     
 7074:     return $result;
 7075: }
 7076: 
 7077: sub validate_page {
 7078:     if (  exists($env{'internal.start_page'})
 7079: 	  &&     $env{'internal.start_page'} > 1) {
 7080: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7081: 				 $env{'internal.start_page'}.' '.
 7082: 				 $ENV{'request.filename'});
 7083:     }
 7084:     if (  exists($env{'internal.end_page'})
 7085: 	  &&     $env{'internal.end_page'} > 1) {
 7086: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7087: 				 $env{'internal.end_page'}.' '.
 7088: 				 $env{'request.filename'});
 7089:     }
 7090:     if (     exists($env{'internal.start_page'})
 7091: 	&& ! exists($env{'internal.end_page'})) {
 7092: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7093: 				 $env{'request.filename'});
 7094:     }
 7095:     if (   ! exists($env{'internal.start_page'})
 7096: 	&&   exists($env{'internal.end_page'})) {
 7097: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7098: 				 $env{'request.filename'});
 7099:     }
 7100: }
 7101: 
 7102: 
 7103: sub start_scrollbox {
 7104:     my ($outerwidth,$width,$height,$id)=@_;
 7105:     unless ($outerwidth) { $outerwidth='520px'; }
 7106:     unless ($width) { $width='500px'; }
 7107:     unless ($height) { $height='200px'; }
 7108:     my ($table_id,$div_id);
 7109:     if ($id ne '') {
 7110:         $table_id = " id='table_$id'";
 7111:         $div_id = " id='div_$id'";
 7112:     }
 7113:     return "<table style='width: $outerwidth; border: 1px solid none;'$table_id><tr><td style='width: $width;' bgcolor='#FFFFFF'><div style='overflow:auto; width:$width; height: $height;'$div_id>";
 7114: }
 7115: 
 7116: sub end_scrollbox {
 7117:     return '</td></tr></table>';
 7118: }
 7119: 
 7120: sub simple_error_page {
 7121:     my ($r,$title,$msg) = @_;
 7122:     my $page =
 7123: 	&Apache::loncommon::start_page($title).
 7124: 	&mt($msg).
 7125: 	&Apache::loncommon::end_page();
 7126:     if (ref($r)) {
 7127: 	$r->print($page);
 7128: 	return;
 7129:     }
 7130:     return $page;
 7131: }
 7132: 
 7133: {
 7134:     my @row_count;
 7135: 
 7136:     sub start_data_table_count {
 7137:         unshift(@row_count, 0);
 7138:         return;
 7139:     }
 7140: 
 7141:     sub end_data_table_count {
 7142:         shift(@row_count);
 7143:         return;
 7144:     }
 7145: 
 7146:     sub start_data_table {
 7147: 	my ($add_class,$id) = @_;
 7148: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7149:         my $table_id;
 7150:         if (defined($id)) {
 7151:             $table_id = ' id="'.$id.'"';
 7152:         }
 7153: 	&start_data_table_count();
 7154: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 7155:     }
 7156: 
 7157:     sub end_data_table {
 7158: 	&end_data_table_count();
 7159: 	return '</table>'."\n";;
 7160:     }
 7161: 
 7162:     sub start_data_table_row {
 7163: 	my ($add_class, $id) = @_;
 7164: 	$row_count[0]++;
 7165: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7166: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7167:         $id = (' id="'.$id.'"') unless ($id eq '');
 7168:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7169:     }
 7170:     
 7171:     sub continue_data_table_row {
 7172: 	my ($add_class, $id) = @_;
 7173: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7174: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7175:         $id = (' id="'.$id.'"') unless ($id eq '');
 7176:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7177:     }
 7178: 
 7179:     sub end_data_table_row {
 7180: 	return '</tr>'."\n";;
 7181:     }
 7182: 
 7183:     sub start_data_table_empty_row {
 7184: #	$row_count[0]++;
 7185: 	return  '<tr class="LC_empty_row" >'."\n";;
 7186:     }
 7187: 
 7188:     sub end_data_table_empty_row {
 7189: 	return '</tr>'."\n";;
 7190:     }
 7191: 
 7192:     sub start_data_table_header_row {
 7193: 	return  '<tr class="LC_header_row">'."\n";;
 7194:     }
 7195: 
 7196:     sub end_data_table_header_row {
 7197: 	return '</tr>'."\n";;
 7198:     }
 7199: 
 7200:     sub data_table_caption {
 7201:         my $caption = shift;
 7202:         return "<caption class=\"LC_caption\">$caption</caption>";
 7203:     }
 7204: }
 7205: 
 7206: =pod
 7207: 
 7208: =item * &inhibit_menu_check($arg)
 7209: 
 7210: Checks for a inhibitmenu state and generates output to preserve it
 7211: 
 7212: Inputs:         $arg - can be any of
 7213:                      - undef - in which case the return value is a string 
 7214:                                to add  into arguments list of a uri
 7215:                      - 'input' - in which case the return value is a HTML
 7216:                                  <form> <input> field of type hidden to
 7217:                                  preserve the value
 7218:                      - a url - in which case the return value is the url with
 7219:                                the neccesary cgi args added to preserve the
 7220:                                inhibitmenu state
 7221:                      - a ref to a url - no return value, but the string is
 7222:                                         updated to include the neccessary cgi
 7223:                                         args to preserve the inhibitmenu state
 7224: 
 7225: =cut
 7226: 
 7227: sub inhibit_menu_check {
 7228:     my ($arg) = @_;
 7229:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7230:     if ($arg eq 'input') {
 7231: 	if ($env{'form.inhibitmenu'}) {
 7232: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7233: 	} else {
 7234: 	    return
 7235: 	}
 7236:     }
 7237:     if ($env{'form.inhibitmenu'}) {
 7238: 	if (ref($arg)) {
 7239: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7240: 	} elsif ($arg eq '') {
 7241: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7242: 	} else {
 7243: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7244: 	}
 7245:     }
 7246:     if (!ref($arg)) {
 7247: 	return $arg;
 7248:     }
 7249: }
 7250: 
 7251: ###############################################
 7252: 
 7253: =pod
 7254: 
 7255: =back
 7256: 
 7257: =head1 User Information Routines
 7258: 
 7259: =over 4
 7260: 
 7261: =item * &get_users_function()
 7262: 
 7263: Used by &bodytag to determine the current users primary role.
 7264: Returns either 'student','coordinator','admin', or 'author'.
 7265: 
 7266: =cut
 7267: 
 7268: ###############################################
 7269: sub get_users_function {
 7270:     my $function = 'norole';
 7271:     if ($env{'request.role'}=~/^(st)/) {
 7272:         $function='student';
 7273:     }
 7274:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7275:         $function='coordinator';
 7276:     }
 7277:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7278:         $function='admin';
 7279:     }
 7280:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7281:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 7282:         $function='author';
 7283:     }
 7284:     return $function;
 7285: }
 7286: 
 7287: ###############################################
 7288: 
 7289: =pod
 7290: 
 7291: =item * &show_course()
 7292: 
 7293: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7294: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7295: 
 7296: Inputs:
 7297: None
 7298: 
 7299: Outputs:
 7300: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7301: 
 7302: =cut
 7303: 
 7304: ###############################################
 7305: sub show_course {
 7306:     my $course = !$env{'user.adv'};
 7307:     if (!$env{'user.adv'}) {
 7308:         foreach my $env (keys(%env)) {
 7309:             next if ($env !~ m/^user\.priv\./);
 7310:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7311:                 $course = 0;
 7312:                 last;
 7313:             }
 7314:         }
 7315:     }
 7316:     return $course;
 7317: }
 7318: 
 7319: ###############################################
 7320: 
 7321: =pod
 7322: 
 7323: =item * &check_user_status()
 7324: 
 7325: Determines current status of supplied role for a
 7326: specific user. Roles can be active, previous or future.
 7327: 
 7328: Inputs: 
 7329: user's domain, user's username, course's domain,
 7330: course's number, optional section ID.
 7331: 
 7332: Outputs:
 7333: role status: active, previous or future. 
 7334: 
 7335: =cut
 7336: 
 7337: sub check_user_status {
 7338:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7339:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 7340:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
 7341:     my @uroles = keys %userinfo;
 7342:     my $srchstr;
 7343:     my $active_chk = 'none';
 7344:     my $now = time;
 7345:     if (@uroles > 0) {
 7346:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7347:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7348:         } else {
 7349:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7350:         }
 7351:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7352:             my $role_end = 0;
 7353:             my $role_start = 0;
 7354:             $active_chk = 'active';
 7355:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7356:                 $role_end = $1;
 7357:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7358:                     $role_start = $1;
 7359:                 }
 7360:             }
 7361:             if ($role_start > 0) {
 7362:                 if ($now < $role_start) {
 7363:                     $active_chk = 'future';
 7364:                 }
 7365:             }
 7366:             if ($role_end > 0) {
 7367:                 if ($now > $role_end) {
 7368:                     $active_chk = 'previous';
 7369:                 }
 7370:             }
 7371:         }
 7372:     }
 7373:     return $active_chk;
 7374: }
 7375: 
 7376: ###############################################
 7377: 
 7378: =pod
 7379: 
 7380: =item * &get_sections()
 7381: 
 7382: Determines all the sections for a course including
 7383: sections with students and sections containing other roles.
 7384: Incoming parameters: 
 7385: 
 7386: 1. domain
 7387: 2. course number 
 7388: 3. reference to array containing roles for which sections should 
 7389: be gathered (optional).
 7390: 4. reference to array containing status types for which sections 
 7391: should be gathered (optional).
 7392: 
 7393: If the third argument is undefined, sections are gathered for any role. 
 7394: If the fourth argument is undefined, sections are gathered for any status.
 7395: Permissible values are 'active' or 'future' or 'previous'.
 7396:  
 7397: Returns section hash (keys are section IDs, values are
 7398: number of users in each section), subject to the
 7399: optional roles filter, optional status filter 
 7400: 
 7401: =cut
 7402: 
 7403: ###############################################
 7404: sub get_sections {
 7405:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7406:     if (!defined($cdom) || !defined($cnum)) {
 7407:         my $cid =  $env{'request.course.id'};
 7408: 
 7409: 	return if (!defined($cid));
 7410: 
 7411:         $cdom = $env{'course.'.$cid.'.domain'};
 7412:         $cnum = $env{'course.'.$cid.'.num'};
 7413:     }
 7414: 
 7415:     my %sectioncount;
 7416:     my $now = time;
 7417: 
 7418:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7419: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7420: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7421: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7422:         my $start_index = &Apache::loncoursedata::CL_START();
 7423:         my $end_index = &Apache::loncoursedata::CL_END();
 7424:         my $status;
 7425: 	while (my ($student,$data) = each(%$classlist)) {
 7426: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7427: 				                     $data->[$status_index],
 7428:                                                      $data->[$start_index],
 7429:                                                      $data->[$end_index]);
 7430:             if ($stu_status eq 'Active') {
 7431:                 $status = 'active';
 7432:             } elsif ($end < $now) {
 7433:                 $status = 'previous';
 7434:             } elsif ($start > $now) {
 7435:                 $status = 'future';
 7436:             } 
 7437: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7438:                 if ((!defined($possible_status)) || (($status ne '') && 
 7439:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7440: 		    $sectioncount{$section}++;
 7441:                 }
 7442: 	    }
 7443: 	}
 7444:     }
 7445:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7446:     foreach my $user (sort(keys(%courseroles))) {
 7447: 	if ($user !~ /^(\w{2})/) { next; }
 7448: 	my ($role) = ($user =~ /^(\w{2})/);
 7449: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7450: 	my ($section,$status);
 7451: 	if ($role eq 'cr' &&
 7452: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7453: 	    $section=$1;
 7454: 	}
 7455: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7456: 	if (!defined($section) || $section eq '-1') { next; }
 7457:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7458:         if ($end == -1 && $start == -1) {
 7459:             next; #deleted role
 7460:         }
 7461:         if (!defined($possible_status)) { 
 7462:             $sectioncount{$section}++;
 7463:         } else {
 7464:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7465:                 $status = 'active';
 7466:             } elsif ($end < $now) {
 7467:                 $status = 'future';
 7468:             } elsif ($start > $now) {
 7469:                 $status = 'previous';
 7470:             }
 7471:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7472:                 $sectioncount{$section}++;
 7473:             }
 7474:         }
 7475:     }
 7476:     return %sectioncount;
 7477: }
 7478: 
 7479: ###############################################
 7480: 
 7481: =pod
 7482: 
 7483: =item * &get_course_users()
 7484: 
 7485: Retrieves usernames:domains for users in the specified course
 7486: with specific role(s), and access status. 
 7487: 
 7488: Incoming parameters:
 7489: 1. course domain
 7490: 2. course number
 7491: 3. access status: users must have - either active, 
 7492: previous, future, or all.
 7493: 4. reference to array of permissible roles
 7494: 5. reference to array of section restrictions (optional)
 7495: 6. reference to results object (hash of hashes).
 7496: 7. reference to optional userdata hash
 7497: 8. reference to optional statushash
 7498: 9. flag if privileged users (except those set to unhide in
 7499:    course settings) should be excluded    
 7500: Keys of top level results hash are roles.
 7501: Keys of inner hashes are username:domain, with 
 7502: values set to access type.
 7503: Optional userdata hash returns an array with arguments in the 
 7504: same order as loncoursedata::get_classlist() for student data.
 7505: 
 7506: Optional statushash returns
 7507: 
 7508: Entries for end, start, section and status are blank because
 7509: of the possibility of multiple values for non-student roles.
 7510: 
 7511: =cut
 7512: 
 7513: ###############################################
 7514: 
 7515: sub get_course_users {
 7516:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7517:     my %idx = ();
 7518:     my %seclists;
 7519: 
 7520:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7521:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7522:     $idx{end} = &Apache::loncoursedata::CL_END();
 7523:     $idx{start} = &Apache::loncoursedata::CL_START();
 7524:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7525:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7526:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7527:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7528: 
 7529:     if (grep(/^st$/,@{$roles})) {
 7530:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7531:         my $now = time;
 7532:         foreach my $student (keys(%{$classlist})) {
 7533:             my $match = 0;
 7534:             my $secmatch = 0;
 7535:             my $section = $$classlist{$student}[$idx{section}];
 7536:             my $status = $$classlist{$student}[$idx{status}];
 7537:             if ($section eq '') {
 7538:                 $section = 'none';
 7539:             }
 7540:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7541:                 if (grep(/^all$/,@{$sections})) {
 7542:                     $secmatch = 1;
 7543:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7544:                     if (grep(/^none$/,@{$sections})) {
 7545:                         $secmatch = 1;
 7546:                     }
 7547:                 } else {  
 7548: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7549: 		        $secmatch = 1;
 7550:                     }
 7551: 		}
 7552:                 if (!$secmatch) {
 7553:                     next;
 7554:                 }
 7555:             }
 7556:             if (defined($$types{'active'})) {
 7557:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7558:                     push(@{$$users{st}{$student}},'active');
 7559:                     $match = 1;
 7560:                 }
 7561:             }
 7562:             if (defined($$types{'previous'})) {
 7563:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7564:                     push(@{$$users{st}{$student}},'previous');
 7565:                     $match = 1;
 7566:                 }
 7567:             }
 7568:             if (defined($$types{'future'})) {
 7569:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7570:                     push(@{$$users{st}{$student}},'future');
 7571:                     $match = 1;
 7572:                 }
 7573:             }
 7574:             if ($match) {
 7575:                 push(@{$seclists{$student}},$section);
 7576:                 if (ref($userdata) eq 'HASH') {
 7577:                     $$userdata{$student} = $$classlist{$student};
 7578:                 }
 7579:                 if (ref($statushash) eq 'HASH') {
 7580:                     $statushash->{$student}{'st'}{$section} = $status;
 7581:                 }
 7582:             }
 7583:         }
 7584:     }
 7585:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7586:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7587:         my $now = time;
 7588:         my %displaystatus = ( previous => 'Expired',
 7589:                               active   => 'Active',
 7590:                               future   => 'Future',
 7591:                             );
 7592:         my %nothide;
 7593:         if ($hidepriv) {
 7594:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7595:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7596:                 if ($user !~ /:/) {
 7597:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7598:                 } else {
 7599:                     $nothide{$user} = 1;
 7600:                 }
 7601:             }
 7602:         }
 7603:         foreach my $person (sort(keys(%coursepersonnel))) {
 7604:             my $match = 0;
 7605:             my $secmatch = 0;
 7606:             my $status;
 7607:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7608:             $user =~ s/:$//;
 7609:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7610:             if ($end == -1 || $start == -1) {
 7611:                 next;
 7612:             }
 7613:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7614:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7615:                 my ($uname,$udom) = split(/:/,$user);
 7616:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7617:                     if (grep(/^all$/,@{$sections})) {
 7618:                         $secmatch = 1;
 7619:                     } elsif ($usec eq '') {
 7620:                         if (grep(/^none$/,@{$sections})) {
 7621:                             $secmatch = 1;
 7622:                         }
 7623:                     } else {
 7624:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7625:                             $secmatch = 1;
 7626:                         }
 7627:                     }
 7628:                     if (!$secmatch) {
 7629:                         next;
 7630:                     }
 7631:                 }
 7632:                 if ($usec eq '') {
 7633:                     $usec = 'none';
 7634:                 }
 7635:                 if ($uname ne '' && $udom ne '') {
 7636:                     if ($hidepriv) {
 7637:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7638:                             (!$nothide{$uname.':'.$udom})) {
 7639:                             next;
 7640:                         }
 7641:                     }
 7642:                     if ($end > 0 && $end < $now) {
 7643:                         $status = 'previous';
 7644:                     } elsif ($start > $now) {
 7645:                         $status = 'future';
 7646:                     } else {
 7647:                         $status = 'active';
 7648:                     }
 7649:                     foreach my $type (keys(%{$types})) { 
 7650:                         if ($status eq $type) {
 7651:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7652:                                 push(@{$$users{$role}{$user}},$type);
 7653:                             }
 7654:                             $match = 1;
 7655:                         }
 7656:                     }
 7657:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7658:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7659: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7660:                         }
 7661:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7662:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7663:                         }
 7664:                         if (ref($statushash) eq 'HASH') {
 7665:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7666:                         }
 7667:                     }
 7668:                 }
 7669:             }
 7670:         }
 7671:         if (grep(/^ow$/,@{$roles})) {
 7672:             if ((defined($cdom)) && (defined($cnum))) {
 7673:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7674:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7675:                     my $owner = $csettings{'internal.courseowner'};
 7676:                     next if ($owner eq '');
 7677:                     my ($ownername,$ownerdom);
 7678:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7679:                         $ownername = $1;
 7680:                         $ownerdom = $2;
 7681:                     } else {
 7682:                         $ownername = $owner;
 7683:                         $ownerdom = $cdom;
 7684:                         $owner = $ownername.':'.$ownerdom;
 7685:                     }
 7686:                     @{$$users{'ow'}{$owner}} = 'any';
 7687:                     if (defined($userdata) && 
 7688: 			!exists($$userdata{$owner})) {
 7689: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7690:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7691:                             push(@{$seclists{$owner}},'none');
 7692:                         }
 7693:                         if (ref($statushash) eq 'HASH') {
 7694:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7695:                         }
 7696: 		    }
 7697:                 }
 7698:             }
 7699:         }
 7700:         foreach my $user (keys(%seclists)) {
 7701:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7702:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7703:         }
 7704:     }
 7705:     return;
 7706: }
 7707: 
 7708: sub get_user_info {
 7709:     my ($udom,$uname,$idx,$userdata) = @_;
 7710:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7711: 	&plainname($uname,$udom,'lastname');
 7712:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7713:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7714:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7715:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7716:     return;
 7717: }
 7718: 
 7719: ###############################################
 7720: 
 7721: =pod
 7722: 
 7723: =item * &get_user_quota()
 7724: 
 7725: Retrieves quota assigned for storage of portfolio files for a user  
 7726: 
 7727: Incoming parameters:
 7728: 1. user's username
 7729: 2. user's domain
 7730: 
 7731: Returns:
 7732: 1. Disk quota (in Mb) assigned to student.
 7733: 2. (Optional) Type of setting: custom or default
 7734:    (individually assigned or default for user's 
 7735:    institutional status).
 7736: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7737:    or student - types as defined in localenroll::inst_usertypes 
 7738:    for user's domain, which determines default quota for user.
 7739: 4. (Optional) - Default quota which would apply to the user.
 7740: 
 7741: If a value has been stored in the user's environment, 
 7742: it will return that, otherwise it returns the maximal default
 7743: defined for the user's instituional status(es) in the domain.
 7744: 
 7745: =cut
 7746: 
 7747: ###############################################
 7748: 
 7749: 
 7750: sub get_user_quota {
 7751:     my ($uname,$udom) = @_;
 7752:     my ($quota,$quotatype,$settingstatus,$defquota);
 7753:     if (!defined($udom)) {
 7754:         $udom = $env{'user.domain'};
 7755:     }
 7756:     if (!defined($uname)) {
 7757:         $uname = $env{'user.name'};
 7758:     }
 7759:     if (($udom eq '' || $uname eq '') ||
 7760:         ($udom eq 'public') && ($uname eq 'public')) {
 7761:         $quota = 0;
 7762:         $quotatype = 'default';
 7763:         $defquota = 0; 
 7764:     } else {
 7765:         my $inststatus;
 7766:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7767:             $quota = $env{'environment.portfolioquota'};
 7768:             $inststatus = $env{'environment.inststatus'};
 7769:         } else {
 7770:             my %userenv = 
 7771:                 &Apache::lonnet::get('environment',['portfolioquota',
 7772:                                      'inststatus'],$udom,$uname);
 7773:             my ($tmp) = keys(%userenv);
 7774:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7775:                 $quota = $userenv{'portfolioquota'};
 7776:                 $inststatus = $userenv{'inststatus'};
 7777:             } else {
 7778:                 undef(%userenv);
 7779:             }
 7780:         }
 7781:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7782:         if ($quota eq '') {
 7783:             $quota = $defquota;
 7784:             $quotatype = 'default';
 7785:         } else {
 7786:             $quotatype = 'custom';
 7787:         }
 7788:     }
 7789:     if (wantarray) {
 7790:         return ($quota,$quotatype,$settingstatus,$defquota);
 7791:     } else {
 7792:         return $quota;
 7793:     }
 7794: }
 7795: 
 7796: ###############################################
 7797: 
 7798: =pod
 7799: 
 7800: =item * &default_quota()
 7801: 
 7802: Retrieves default quota assigned for storage of user portfolio files,
 7803: given an (optional) user's institutional status.
 7804: 
 7805: Incoming parameters:
 7806: 1. domain
 7807: 2. (Optional) institutional status(es).  This is a : separated list of 
 7808:    status types (e.g., faculty, staff, student etc.)
 7809:    which apply to the user for whom the default is being retrieved.
 7810:    If the institutional status string in undefined, the domain
 7811:    default quota will be returned. 
 7812: 
 7813: Returns:
 7814: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7815: 2. (Optional) institutional type which determined the value of the
 7816:    default quota.
 7817: 
 7818: If a value has been stored in the domain's configuration db,
 7819: it will return that, otherwise it returns 20 (for backwards 
 7820: compatibility with domains which have not set up a configuration
 7821: db file; the original statically defined portfolio quota was 20 Mb). 
 7822: 
 7823: If the user's status includes multiple types (e.g., staff and student),
 7824: the largest default quota which applies to the user determines the
 7825: default quota returned.
 7826: 
 7827: =back
 7828: 
 7829: =cut
 7830: 
 7831: ###############################################
 7832: 
 7833: 
 7834: sub default_quota {
 7835:     my ($udom,$inststatus) = @_;
 7836:     my ($defquota,$settingstatus);
 7837:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7838:                                             ['quotas'],$udom);
 7839:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7840:         if ($inststatus ne '') {
 7841:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7842:             foreach my $item (@statuses) {
 7843:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7844:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7845:                         if ($defquota eq '') {
 7846:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7847:                             $settingstatus = $item;
 7848:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7849:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7850:                             $settingstatus = $item;
 7851:                         }
 7852:                     }
 7853:                 } else {
 7854:                     if ($quotahash{'quotas'}{$item} ne '') {
 7855:                         if ($defquota eq '') {
 7856:                             $defquota = $quotahash{'quotas'}{$item};
 7857:                             $settingstatus = $item;
 7858:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7859:                             $defquota = $quotahash{'quotas'}{$item};
 7860:                             $settingstatus = $item;
 7861:                         }
 7862:                     }
 7863:                 }
 7864:             }
 7865:         }
 7866:         if ($defquota eq '') {
 7867:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7868:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7869:             } else {
 7870:                 $defquota = $quotahash{'quotas'}{'default'};
 7871:             }
 7872:             $settingstatus = 'default';
 7873:         }
 7874:     } else {
 7875:         $settingstatus = 'default';
 7876:         $defquota = 20;
 7877:     }
 7878:     if (wantarray) {
 7879:         return ($defquota,$settingstatus);
 7880:     } else {
 7881:         return $defquota;
 7882:     }
 7883: }
 7884: 
 7885: sub get_secgrprole_info {
 7886:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7887:     my %sections_count = &get_sections($cdom,$cnum);
 7888:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7889:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7890:     my @groups = sort(keys(%curr_groups));
 7891:     my $allroles = [];
 7892:     my $rolehash;
 7893:     my $accesshash = {
 7894:                      active => 'Currently has access',
 7895:                      future => 'Will have future access',
 7896:                      previous => 'Previously had access',
 7897:                   };
 7898:     if ($needroles) {
 7899:         $rolehash = {'all' => 'all'};
 7900:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7901: 	if (&Apache::lonnet::error(%user_roles)) {
 7902: 	    undef(%user_roles);
 7903: 	}
 7904:         foreach my $item (keys(%user_roles)) {
 7905:             my ($role)=split(/\:/,$item,2);
 7906:             if ($role eq 'cr') { next; }
 7907:             if ($role =~ /^cr/) {
 7908:                 $$rolehash{$role} = (split('/',$role))[3];
 7909:             } else {
 7910:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7911:             }
 7912:         }
 7913:         foreach my $key (sort(keys(%{$rolehash}))) {
 7914:             push(@{$allroles},$key);
 7915:         }
 7916:         push (@{$allroles},'st');
 7917:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7918:     }
 7919:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7920: }
 7921: 
 7922: sub user_picker {
 7923:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 7924:     my $currdom = $dom;
 7925:     my %curr_selected = (
 7926:                         srchin => 'dom',
 7927:                         srchby => 'lastname',
 7928:                       );
 7929:     my $srchterm;
 7930:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7931:         if ($srch->{'srchby'} ne '') {
 7932:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7933:         }
 7934:         if ($srch->{'srchin'} ne '') {
 7935:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7936:         }
 7937:         if ($srch->{'srchtype'} ne '') {
 7938:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7939:         }
 7940:         if ($srch->{'srchdomain'} ne '') {
 7941:             $currdom = $srch->{'srchdomain'};
 7942:         }
 7943:         $srchterm = $srch->{'srchterm'};
 7944:     }
 7945:     my %lt=&Apache::lonlocal::texthash(
 7946:                     'usr'       => 'Search criteria',
 7947:                     'doma'      => 'Domain/institution to search',
 7948:                     'uname'     => 'username',
 7949:                     'lastname'  => 'last name',
 7950:                     'lastfirst' => 'last name, first name',
 7951:                     'crs'       => 'in this course',
 7952:                     'dom'       => 'in selected LON-CAPA domain', 
 7953:                     'alc'       => 'all LON-CAPA',
 7954:                     'instd'     => 'in institutional directory for selected domain',
 7955:                     'exact'     => 'is',
 7956:                     'contains'  => 'contains',
 7957:                     'begins'    => 'begins with',
 7958:                     'youm'      => "You must include some text to search for.",
 7959:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7960:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7961:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7962:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7963:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7964:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7965:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7966:                                        );
 7967:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7968:     my $srchinsel = ' <select name="srchin">';
 7969: 
 7970:     my @srchins = ('crs','dom','alc','instd');
 7971: 
 7972:     foreach my $option (@srchins) {
 7973:         # FIXME 'alc' option unavailable until 
 7974:         #       loncreateuser::print_user_query_page()
 7975:         #       has been completed.
 7976:         next if ($option eq 'alc');
 7977:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7978:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7979:         if ($curr_selected{'srchin'} eq $option) {
 7980:             $srchinsel .= ' 
 7981:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7982:         } else {
 7983:             $srchinsel .= '
 7984:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7985:         }
 7986:     }
 7987:     $srchinsel .= "\n  </select>\n";
 7988: 
 7989:     my $srchbysel =  ' <select name="srchby">';
 7990:     foreach my $option ('lastname','lastfirst','uname') {
 7991:         if ($curr_selected{'srchby'} eq $option) {
 7992:             $srchbysel .= '
 7993:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7994:         } else {
 7995:             $srchbysel .= '
 7996:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7997:          }
 7998:     }
 7999:     $srchbysel .= "\n  </select>\n";
 8000: 
 8001:     my $srchtypesel = ' <select name="srchtype">';
 8002:     foreach my $option ('begins','contains','exact') {
 8003:         if ($curr_selected{'srchtype'} eq $option) {
 8004:             $srchtypesel .= '
 8005:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8006:         } else {
 8007:             $srchtypesel .= '
 8008:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8009:         }
 8010:     }
 8011:     $srchtypesel .= "\n  </select>\n";
 8012: 
 8013:     my ($newuserscript,$new_user_create);
 8014:     my $context_dom = $env{'request.role.domain'};
 8015:     if ($context eq 'requestcrs') {
 8016:         if ($env{'form.coursedom'} ne '') { 
 8017:             $context_dom = $env{'form.coursedom'};
 8018:         }
 8019:     }
 8020:     if ($forcenewuser) {
 8021:         if (ref($srch) eq 'HASH') {
 8022:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 8023:                 if ($cancreate) {
 8024:                     $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>';
 8025:                 } else {
 8026:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 8027:                     my %usertypetext = (
 8028:                         official   => 'institutional',
 8029:                         unofficial => 'non-institutional',
 8030:                     );
 8031:                     $new_user_create = '<p class="LC_warning">'
 8032:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8033:                                       .' '
 8034:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8035:                                           ,'<a href="'.$helplink.'">','</a>')
 8036:                                       .'</p><br />';
 8037:                 }
 8038:             }
 8039:         }
 8040: 
 8041:         $newuserscript = <<"ENDSCRIPT";
 8042: 
 8043: function setSearch(createnew,callingForm) {
 8044:     if (createnew == 1) {
 8045:         for (var i=0; i<callingForm.srchby.length; i++) {
 8046:             if (callingForm.srchby.options[i].value == 'uname') {
 8047:                 callingForm.srchby.selectedIndex = i;
 8048:             }
 8049:         }
 8050:         for (var i=0; i<callingForm.srchin.length; i++) {
 8051:             if ( callingForm.srchin.options[i].value == 'dom') {
 8052: 		callingForm.srchin.selectedIndex = i;
 8053:             }
 8054:         }
 8055:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8056:             if (callingForm.srchtype.options[i].value == 'exact') {
 8057:                 callingForm.srchtype.selectedIndex = i;
 8058:             }
 8059:         }
 8060:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8061:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8062:                 callingForm.srchdomain.selectedIndex = i;
 8063:             }
 8064:         }
 8065:     }
 8066: }
 8067: ENDSCRIPT
 8068: 
 8069:     }
 8070: 
 8071:     my $output = <<"END_BLOCK";
 8072: <script type="text/javascript">
 8073: // <![CDATA[
 8074: function validateEntry(callingForm) {
 8075: 
 8076:     var checkok = 1;
 8077:     var srchin;
 8078:     for (var i=0; i<callingForm.srchin.length; i++) {
 8079: 	if ( callingForm.srchin[i].checked ) {
 8080: 	    srchin = callingForm.srchin[i].value;
 8081: 	}
 8082:     }
 8083: 
 8084:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8085:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8086:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8087:     var srchterm =  callingForm.srchterm.value;
 8088:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8089:     var msg = "";
 8090: 
 8091:     if (srchterm == "") {
 8092:         checkok = 0;
 8093:         msg += "$lt{'youm'}\\n";
 8094:     }
 8095: 
 8096:     if (srchtype== 'begins') {
 8097:         if (srchterm.length < 2) {
 8098:             checkok = 0;
 8099:             msg += "$lt{'thte'}\\n";
 8100:         }
 8101:     }
 8102: 
 8103:     if (srchtype== 'contains') {
 8104:         if (srchterm.length < 3) {
 8105:             checkok = 0;
 8106:             msg += "$lt{'thet'}\\n";
 8107:         }
 8108:     }
 8109:     if (srchin == 'instd') {
 8110:         if (srchdomain == '') {
 8111:             checkok = 0;
 8112:             msg += "$lt{'yomc'}\\n";
 8113:         }
 8114:     }
 8115:     if (srchin == 'dom') {
 8116:         if (srchdomain == '') {
 8117:             checkok = 0;
 8118:             msg += "$lt{'ymcd'}\\n";
 8119:         }
 8120:     }
 8121:     if (srchby == 'lastfirst') {
 8122:         if (srchterm.indexOf(",") == -1) {
 8123:             checkok = 0;
 8124:             msg += "$lt{'whus'}\\n";
 8125:         }
 8126:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8127:             checkok = 0;
 8128:             msg += "$lt{'whse'}\\n";
 8129:         }
 8130:     }
 8131:     if (checkok == 0) {
 8132:         alert("$lt{'thfo'}\\n"+msg);
 8133:         return;
 8134:     }
 8135:     if (checkok == 1) {
 8136:         callingForm.submit();
 8137:     }
 8138: }
 8139: 
 8140: $newuserscript
 8141: 
 8142: // ]]>
 8143: </script>
 8144: 
 8145: $new_user_create
 8146: 
 8147: END_BLOCK
 8148: 
 8149:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8150:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8151:                $domform.
 8152:                &Apache::lonhtmlcommon::row_closure().
 8153:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8154:                $srchbysel.
 8155:                $srchtypesel. 
 8156:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8157:                $srchinsel.
 8158:                &Apache::lonhtmlcommon::row_closure(1). 
 8159:                &Apache::lonhtmlcommon::end_pick_box().
 8160:                '<br />';
 8161:     return $output;
 8162: }
 8163: 
 8164: sub user_rule_check {
 8165:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8166:     my $response;
 8167:     if (ref($usershash) eq 'HASH') {
 8168:         foreach my $user (keys(%{$usershash})) {
 8169:             my ($uname,$udom) = split(/:/,$user);
 8170:             next if ($udom eq '' || $uname eq '');
 8171:             my ($id,$newuser);
 8172:             if (ref($usershash->{$user}) eq 'HASH') {
 8173:                 $newuser = $usershash->{$user}->{'newuser'};
 8174:                 $id = $usershash->{$user}->{'id'};
 8175:             }
 8176:             my $inst_response;
 8177:             if (ref($checks) eq 'HASH') {
 8178:                 if (defined($checks->{'username'})) {
 8179:                     ($inst_response,%{$inst_results->{$user}}) = 
 8180:                         &Apache::lonnet::get_instuser($udom,$uname);
 8181:                 } elsif (defined($checks->{'id'})) {
 8182:                     ($inst_response,%{$inst_results->{$user}}) =
 8183:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8184:                 }
 8185:             } else {
 8186:                 ($inst_response,%{$inst_results->{$user}}) =
 8187:                     &Apache::lonnet::get_instuser($udom,$uname);
 8188:                 return;
 8189:             }
 8190:             if (!$got_rules->{$udom}) {
 8191:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8192:                                                   ['usercreation'],$udom);
 8193:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8194:                     foreach my $item ('username','id') {
 8195:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8196:                             $$curr_rules{$udom}{$item} = 
 8197:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8198:                         }
 8199:                     }
 8200:                 }
 8201:                 $got_rules->{$udom} = 1;  
 8202:             }
 8203:             foreach my $item (keys(%{$checks})) {
 8204:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8205:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8206:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8207:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8208:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8209:                                 if ($rule_check{$rule}) {
 8210:                                     $$rulematch{$user}{$item} = $rule;
 8211:                                     if ($inst_response eq 'ok') {
 8212:                                         if (ref($inst_results) eq 'HASH') {
 8213:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8214:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8215:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8216:                                                 }
 8217:                                             }
 8218:                                         }
 8219:                                     }
 8220:                                     last;
 8221:                                 }
 8222:                             }
 8223:                         }
 8224:                     }
 8225:                 }
 8226:             }
 8227:         }
 8228:     }
 8229:     return;
 8230: }
 8231: 
 8232: sub user_rule_formats {
 8233:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8234:     my %text = ( 
 8235:                  'username' => 'Usernames',
 8236:                  'id'       => 'IDs',
 8237:                );
 8238:     my $output;
 8239:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8240:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8241:         if (@{$ruleorder} > 0) {
 8242:             $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>';
 8243:             foreach my $rule (@{$ruleorder}) {
 8244:                 if (ref($curr_rules) eq 'ARRAY') {
 8245:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8246:                         if (ref($rules->{$rule}) eq 'HASH') {
 8247:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8248:                                         $rules->{$rule}{'desc'}.'</li>';
 8249:                         }
 8250:                     }
 8251:                 }
 8252:             }
 8253:             $output .= '</ul>';
 8254:         }
 8255:     }
 8256:     return $output;
 8257: }
 8258: 
 8259: sub instrule_disallow_msg {
 8260:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8261:     my $response;
 8262:     my %text = (
 8263:                   item   => 'username',
 8264:                   items  => 'usernames',
 8265:                   match  => 'matches',
 8266:                   do     => 'does',
 8267:                   action => 'a username',
 8268:                   one    => 'one',
 8269:                );
 8270:     if ($count > 1) {
 8271:         $text{'item'} = 'usernames';
 8272:         $text{'match'} ='match';
 8273:         $text{'do'} = 'do';
 8274:         $text{'action'} = 'usernames',
 8275:         $text{'one'} = 'ones';
 8276:     }
 8277:     if ($checkitem eq 'id') {
 8278:         $text{'items'} = 'IDs';
 8279:         $text{'item'} = 'ID';
 8280:         $text{'action'} = 'an ID';
 8281:         if ($count > 1) {
 8282:             $text{'item'} = 'IDs';
 8283:             $text{'action'} = 'IDs';
 8284:         }
 8285:     }
 8286:     $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 />';
 8287:     if ($mode eq 'upload') {
 8288:         if ($checkitem eq 'username') {
 8289:             $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'}.");
 8290:         } elsif ($checkitem eq 'id') {
 8291:             $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.");
 8292:         }
 8293:     } elsif ($mode eq 'selfcreate') {
 8294:         if ($checkitem eq 'id') {
 8295:             $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.");
 8296:         }
 8297:     } else {
 8298:         if ($checkitem eq 'username') {
 8299:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8300:         } elsif ($checkitem eq 'id') {
 8301:             $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.");
 8302:         }
 8303:     }
 8304:     return $response;
 8305: }
 8306: 
 8307: sub personal_data_fieldtitles {
 8308:     my %fieldtitles = &Apache::lonlocal::texthash (
 8309:                         id => 'Student/Employee ID',
 8310:                         permanentemail => 'E-mail address',
 8311:                         lastname => 'Last Name',
 8312:                         firstname => 'First Name',
 8313:                         middlename => 'Middle Name',
 8314:                         generation => 'Generation',
 8315:                         gen => 'Generation',
 8316:                         inststatus => 'Affiliation',
 8317:                    );
 8318:     return %fieldtitles;
 8319: }
 8320: 
 8321: sub sorted_inst_types {
 8322:     my ($dom) = @_;
 8323:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8324:     my $othertitle = &mt('All users');
 8325:     if ($env{'request.course.id'}) {
 8326:         $othertitle  = &mt('Any users');
 8327:     }
 8328:     my @types;
 8329:     if (ref($order) eq 'ARRAY') {
 8330:         @types = @{$order};
 8331:     }
 8332:     if (@types == 0) {
 8333:         if (ref($usertypes) eq 'HASH') {
 8334:             @types = sort(keys(%{$usertypes}));
 8335:         }
 8336:     }
 8337:     if (keys(%{$usertypes}) > 0) {
 8338:         $othertitle = &mt('Other users');
 8339:     }
 8340:     return ($othertitle,$usertypes,\@types);
 8341: }
 8342: 
 8343: sub get_institutional_codes {
 8344:     my ($settings,$allcourses,$LC_code) = @_;
 8345: # Get complete list of course sections to update
 8346:     my @currsections = ();
 8347:     my @currxlists = ();
 8348:     my $coursecode = $$settings{'internal.coursecode'};
 8349: 
 8350:     if ($$settings{'internal.sectionnums'} ne '') {
 8351:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8352:     }
 8353: 
 8354:     if ($$settings{'internal.crosslistings'} ne '') {
 8355:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8356:     }
 8357: 
 8358:     if (@currxlists > 0) {
 8359:         foreach (@currxlists) {
 8360:             if (m/^([^:]+):(\w*)$/) {
 8361:                 unless (grep/^$1$/,@{$allcourses}) {
 8362:                     push @{$allcourses},$1;
 8363:                     $$LC_code{$1} = $2;
 8364:                 }
 8365:             }
 8366:         }
 8367:     }
 8368:  
 8369:     if (@currsections > 0) {
 8370:         foreach (@currsections) {
 8371:             if (m/^(\w+):(\w*)$/) {
 8372:                 my $sec = $coursecode.$1;
 8373:                 my $lc_sec = $2;
 8374:                 unless (grep/^$sec$/,@{$allcourses}) {
 8375:                     push @{$allcourses},$sec;
 8376:                     $$LC_code{$sec} = $lc_sec;
 8377:                 }
 8378:             }
 8379:         }
 8380:     }
 8381:     return;
 8382: }
 8383: 
 8384: sub get_standard_codeitems {
 8385:     return ('Year','Semester','Department','Number','Section');
 8386: }
 8387: 
 8388: =pod
 8389: 
 8390: =head1 Slot Helpers
 8391: 
 8392: =over 4
 8393: 
 8394: =item * sorted_slots()
 8395: 
 8396: Sorts an array of slot names in order of slot start time (earliest first). 
 8397: 
 8398: Inputs:
 8399: 
 8400: =over 4
 8401: 
 8402: slotsarr  - Reference to array of unsorted slot names.
 8403: 
 8404: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8405: 
 8406: =back
 8407: 
 8408: Returns:
 8409: 
 8410: =over 4
 8411: 
 8412: sorted   - An array of slot names sorted by the start time of the slot.
 8413: 
 8414: =back
 8415: 
 8416: =back
 8417: 
 8418: =cut
 8419: 
 8420: 
 8421: sub sorted_slots {
 8422:     my ($slotsarr,$slots) = @_;
 8423:     my @sorted;
 8424:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8425:         @sorted =
 8426:             sort {
 8427:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8428:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8429:                      }
 8430:                      if (ref($slots->{$a})) { return -1;}
 8431:                      if (ref($slots->{$b})) { return 1;}
 8432:                      return 0;
 8433:                  } @{$slotsarr};
 8434:     }
 8435:     return @sorted;
 8436: }
 8437: 
 8438: 
 8439: =pod
 8440: 
 8441: =head1 HTTP Helpers
 8442: 
 8443: =over 4
 8444: 
 8445: =item * &get_unprocessed_cgi($query,$possible_names)
 8446: 
 8447: Modify the %env hash to contain unprocessed CGI form parameters held in
 8448: $query.  The parameters listed in $possible_names (an array reference),
 8449: will be set in $env{'form.name'} if they do not already exist.
 8450: 
 8451: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8452: $possible_names is an ref to an array of form element names.  As an example:
 8453: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8454: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8455: 
 8456: =cut
 8457: 
 8458: sub get_unprocessed_cgi {
 8459:   my ($query,$possible_names)= @_;
 8460:   # $Apache::lonxml::debug=1;
 8461:   foreach my $pair (split(/&/,$query)) {
 8462:     my ($name, $value) = split(/=/,$pair);
 8463:     $name = &unescape($name);
 8464:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8465:       $value =~ tr/+/ /;
 8466:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8467:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8468:     }
 8469:   }
 8470: }
 8471: 
 8472: =pod
 8473: 
 8474: =item * &cacheheader() 
 8475: 
 8476: returns cache-controlling header code
 8477: 
 8478: =cut
 8479: 
 8480: sub cacheheader {
 8481:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8482:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8483:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8484:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8485:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8486:     return $output;
 8487: }
 8488: 
 8489: =pod
 8490: 
 8491: =item * &no_cache($r) 
 8492: 
 8493: specifies header code to not have cache
 8494: 
 8495: =cut
 8496: 
 8497: sub no_cache {
 8498:     my ($r) = @_;
 8499:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8500: 	$env{'request.method'} ne 'GET') { return ''; }
 8501:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8502:     $r->no_cache(1);
 8503:     $r->header_out("Expires" => $date);
 8504:     $r->header_out("Pragma" => "no-cache");
 8505: }
 8506: 
 8507: sub content_type {
 8508:     my ($r,$type,$charset) = @_;
 8509:     if ($r) {
 8510: 	#  Note that printout.pl calls this with undef for $r.
 8511: 	&no_cache($r);
 8512:     }
 8513:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8514:     unless ($charset) {
 8515: 	$charset=&Apache::lonlocal::current_encoding;
 8516:     }
 8517:     if ($charset) { $type.='; charset='.$charset; }
 8518:     if ($r) {
 8519: 	$r->content_type($type);
 8520:     } else {
 8521: 	print("Content-type: $type\n\n");
 8522:     }
 8523: }
 8524: 
 8525: =pod
 8526: 
 8527: =item * &add_to_env($name,$value) 
 8528: 
 8529: adds $name to the %env hash with value
 8530: $value, if $name already exists, the entry is converted to an array
 8531: reference and $value is added to the array.
 8532: 
 8533: =cut
 8534: 
 8535: sub add_to_env {
 8536:   my ($name,$value)=@_;
 8537:   if (defined($env{$name})) {
 8538:     if (ref($env{$name})) {
 8539:       #already have multiple values
 8540:       push(@{ $env{$name} },$value);
 8541:     } else {
 8542:       #first time seeing multiple values, convert hash entry to an arrayref
 8543:       my $first=$env{$name};
 8544:       undef($env{$name});
 8545:       push(@{ $env{$name} },$first,$value);
 8546:     }
 8547:   } else {
 8548:     $env{$name}=$value;
 8549:   }
 8550: }
 8551: 
 8552: =pod
 8553: 
 8554: =item * &get_env_multiple($name) 
 8555: 
 8556: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8557: values may be defined and end up as an array ref.
 8558: 
 8559: returns an array of values
 8560: 
 8561: =cut
 8562: 
 8563: sub get_env_multiple {
 8564:     my ($name) = @_;
 8565:     my @values;
 8566:     if (defined($env{$name})) {
 8567:         # exists is it an array
 8568:         if (ref($env{$name})) {
 8569:             @values=@{ $env{$name} };
 8570:         } else {
 8571:             $values[0]=$env{$name};
 8572:         }
 8573:     }
 8574:     return(@values);
 8575: }
 8576: 
 8577: sub ask_for_embedded_content {
 8578:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8579:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
 8580:     my $num = 0;
 8581:     my $numremref = 0;
 8582:     my $numinvalid = 0;
 8583:     my $numpathchg = 0;
 8584:     my $numexisting = 0;
 8585:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
 8586:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8587:         my $current_path='/';
 8588:         if ($env{'form.currentpath'}) {
 8589:             $current_path = $env{'form.currentpath'};
 8590:         }
 8591:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 8592:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8593:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 8594:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 8595:         } else {
 8596:             $udom = $env{'user.domain'};
 8597:             $uname = $env{'user.name'};
 8598:             $url = '/userfiles/portfolio';
 8599:         }
 8600:         $toplevel = $url.'/';
 8601:         $url .= $current_path;
 8602:         $getpropath = 1;
 8603:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 8604:              ($actionurl eq '/adm/imsimport')) { 
 8605:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 8606:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 8607:         $toplevel = $url;
 8608:         if ($rest ne '') {
 8609:             $url .= $rest;
 8610:         }
 8611:     } elsif ($actionurl eq '/adm/coursedocs') {
 8612:         if (ref($args) eq 'HASH') {
 8613:            $url = $args->{'docs_url'};
 8614:            $toplevel = $url;
 8615:         }
 8616:     }
 8617:     my $now = time();
 8618:     foreach my $embed_file (keys(%{$allfiles})) {
 8619:         my $absolutepath;
 8620:         if ($embed_file =~ m{^\w+://}) {
 8621:             $newfiles{$embed_file} = 1;
 8622:             $mapping{$embed_file} = $embed_file;
 8623:         } else {
 8624:             if ($embed_file =~ m{^/}) {
 8625:                 $absolutepath = $embed_file;
 8626:                 $embed_file =~ s{^(/+)}{};
 8627:             }
 8628:             if ($embed_file =~ m{/}) {
 8629:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 8630:                 $path = &check_for_traversal($path,$url,$toplevel);
 8631:                 my $item = $fname;
 8632:                 if ($path ne '') {
 8633:                     $item = $path.'/'.$fname;
 8634:                     $subdependencies{$path}{$fname} = 1;
 8635:                 } else {
 8636:                     $dependencies{$item} = 1;
 8637:                 }
 8638:                 if ($absolutepath) {
 8639:                     $mapping{$item} = $absolutepath;
 8640:                 } else {
 8641:                     $mapping{$item} = $embed_file;
 8642:                 }
 8643:             } else {
 8644:                 $dependencies{$embed_file} = 1;
 8645:                 if ($absolutepath) {
 8646:                     $mapping{$embed_file} = $absolutepath;
 8647:                 } else {
 8648:                     $mapping{$embed_file} = $embed_file;
 8649:                 }
 8650:             }
 8651:         }
 8652:     }
 8653:     foreach my $path (keys(%subdependencies)) {
 8654:         my %currsubfile;
 8655:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 8656:             my ($sublistref,$listerror) =
 8657:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 8658:             if (ref($sublistref) eq 'ARRAY') {
 8659:                 foreach my $line (@{$sublistref}) {
 8660:                     my ($file_name,$rest) = split(/\&/,$line,2);
 8661:                     $currsubfile{$file_name} = 1;
 8662:                 }
 8663:             }
 8664:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8665:             if (opendir(my $dir,$url.'/'.$path)) {
 8666:                 my @subdir_list = grep(!/^\./,readdir($dir));
 8667:                 map {$currsubfile{$_} = 1;} @subdir_list;
 8668:             }
 8669:         }
 8670:         foreach my $file (keys(%{$subdependencies{$path}})) {
 8671:             if ($currsubfile{$file}) {
 8672:                 my $item = $path.'/'.$file;
 8673:                 unless ($mapping{$item} eq $item) {
 8674:                     $pathchanges{$item} = 1;
 8675:                 }
 8676:                 $existing{$item} = 1;
 8677:                 $numexisting ++;
 8678:             } else {
 8679:                 $newfiles{$path.'/'.$file} = 1;
 8680:             }
 8681:         }
 8682:     }
 8683:     my %currfile;
 8684:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8685:         my ($dirlistref,$listerror) =
 8686:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 8687:         if (ref($dirlistref) eq 'ARRAY') {
 8688:             foreach my $line (@{$dirlistref}) {
 8689:                 my ($file_name,$rest) = split(/\&/,$line,2);
 8690:                 $currfile{$file_name} = 1;
 8691:             }
 8692:         }
 8693:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8694:         if (opendir(my $dir,$url)) {
 8695:             my @dir_list = grep(!/^\./,readdir($dir));
 8696:             map {$currfile{$_} = 1;} @dir_list;
 8697:         }
 8698:     }
 8699:     foreach my $file (keys(%dependencies)) {
 8700:         if ($currfile{$file}) {
 8701:             unless ($mapping{$file} eq $file) {
 8702:                 $pathchanges{$file} = 1;
 8703:             }
 8704:             $existing{$file} = 1;
 8705:             $numexisting ++;
 8706:         } else {
 8707:             $newfiles{$file} = 1;
 8708:         }
 8709:     }
 8710:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 8711:         $upload_output .= &start_data_table_row().
 8712:                           '<td><span class="LC_filename">'.$embed_file.'</span>';
 8713:         unless ($mapping{$embed_file} eq $embed_file) {
 8714:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 8715:         }
 8716:         $upload_output .= '</td><td>';
 8717:         if ($args->{'ignore_remote_references'}
 8718:             && $embed_file =~ m{^\w+://}) {
 8719:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8720:             $numremref++;
 8721:         } elsif ($args->{'error_on_invalid_names'}
 8722:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8723: 
 8724:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 8725:             $numinvalid++;
 8726:         } else {
 8727:             $upload_output .= &embedded_file_element('upload_embedded',$num,
 8728:                                                      $embed_file,\%mapping,
 8729:                                                      $allfiles,$codebase);
 8730:             $num++;
 8731:         }
 8732:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 8733:     }
 8734:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 8735:         $upload_output .= &start_data_table_row().
 8736:                           '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
 8737:                           '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 8738:                           &Apache::loncommon::end_data_table_row()."\n";
 8739:     }
 8740:     if ($upload_output) {
 8741:         $upload_output = &start_data_table().
 8742:                          $upload_output.
 8743:                          &end_data_table()."\n";
 8744:     }
 8745:     my $applies = 0;
 8746:     if ($numremref) {
 8747:         $applies ++;
 8748:     }
 8749:     if ($numinvalid) {
 8750:         $applies ++;
 8751:     }
 8752:     if ($numexisting) {
 8753:         $applies ++;
 8754:     }
 8755:     if ($num) {
 8756:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 8757:                   ' method="post" enctype="multipart/form-data">'."\n".
 8758:                   $state.
 8759:                   '<h3>'.&mt('Upload embedded files').
 8760:                   ':</h3>'.$upload_output.'<br />'."\n".
 8761:                   '<input type ="hidden" name="number_embedded_items" value="'.
 8762:                   $num.'" />'."\n";
 8763:         if ($actionurl eq '') {
 8764:             $output .=  '<input type="hidden" name="phase" value="three" />';
 8765:         }
 8766:     } elsif ($applies) {
 8767:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 8768:         if ($applies > 1) {
 8769:             $output .=  
 8770:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 8771:             if ($numremref) {
 8772:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 8773:             }
 8774:             if ($numinvalid) {
 8775:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 8776:             }
 8777:             if ($numexisting) {
 8778:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 8779:             }
 8780:             $output .= '</ul><br />';
 8781:         } elsif ($numremref) {
 8782:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 8783:         } elsif ($numinvalid) {
 8784:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 8785:         } elsif ($numexisting) {
 8786:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 8787:         }
 8788:         $output .= $upload_output.'<br />';
 8789:     }
 8790:     my ($pathchange_output,$chgcount);
 8791:     $chgcount = $num;
 8792:     if (keys(%pathchanges) > 0) {
 8793:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 8794:             if ($num) {
 8795:                 $output .= &embedded_file_element('pathchange',$chgcount,
 8796:                                                   $embed_file,\%mapping,
 8797:                                                   $allfiles,$codebase);
 8798:             } else {
 8799:                 $pathchange_output .= 
 8800:                     &start_data_table_row().
 8801:                     '<td><input type ="checkbox" name="namechange" value="'.
 8802:                     $chgcount.'" checked="checked" /></td>'.
 8803:                     '<td>'.$mapping{$embed_file}.'</td>'.
 8804:                     '<td>'.$embed_file.
 8805:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 8806:                                            \%mapping,$allfiles,$codebase).
 8807:                     '</td>'.&end_data_table_row();
 8808:             }
 8809:             $numpathchg ++;
 8810:             $chgcount ++;
 8811:         }
 8812:     }
 8813:     if ($num) {
 8814:         if ($numpathchg) {
 8815:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 8816:                        $numpathchg.'" />'."\n";
 8817:         }
 8818:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 8819:             ($actionurl eq '/adm/imsimport')) {
 8820:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 8821:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 8822:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 8823:         }
 8824:         $output .=  '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
 8825:                     &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
 8826:     } elsif ($numpathchg) {
 8827:         my %pathchange = ();
 8828:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 8829:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8830:             $output .= '<p>'.&mt('or').'</p>'; 
 8831:         } 
 8832:     }
 8833:     return ($output,$num,$numpathchg);
 8834: }
 8835: 
 8836: sub embedded_file_element {
 8837:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
 8838:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 8839:                    (ref($codebase) eq 'HASH'));
 8840:     my $output;
 8841:     if ($context eq 'upload_embedded') {
 8842:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 8843:     }
 8844:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 8845:                &escape($embed_file).'" />';
 8846:     unless (($context eq 'upload_embedded') && 
 8847:             ($mapping->{$embed_file} eq $embed_file)) {
 8848:         $output .='
 8849:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 8850:     }
 8851:     my $attrib;
 8852:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 8853:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 8854:     }
 8855:     $output .=
 8856:         "\n\t\t".
 8857:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8858:         $attrib.'" />';
 8859:     if (exists($codebase->{$mapping->{$embed_file}})) {
 8860:         $output .=
 8861:             "\n\t\t".
 8862:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 8863:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 8864:     }
 8865:     return $output;
 8866: }
 8867: 
 8868: sub upload_embedded {
 8869:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8870:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 8871:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 8872:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8873:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8874:         my $orig_uploaded_filename =
 8875:             $env{'form.embedded_item_'.$i.'.filename'};
 8876:         foreach my $type ('orig','ref','attrib','codebase') {
 8877:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 8878:                 $env{'form.embedded_'.$type.'_'.$i} =
 8879:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 8880:             }
 8881:         }
 8882:         my ($path,$fname) =
 8883:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8884:         # no path, whole string is fname
 8885:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8886:         $fname = &Apache::lonnet::clean_filename($fname);
 8887:         # See if there is anything left
 8888:         next if ($fname eq '');
 8889: 
 8890:         # Check if file already exists as a file or directory.
 8891:         my ($state,$msg);
 8892:         if ($context eq 'portfolio') {
 8893:             my $port_path = $dirpath;
 8894:             if ($group ne '') {
 8895:                 $port_path = "groups/$group/$port_path";
 8896:             }
 8897:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 8898:                                               $fname,$group,'embedded_item_'.$i,
 8899:                                               $dir_root,$port_path,$disk_quota,
 8900:                                               $current_disk_usage,$uname,$udom);
 8901:             if ($state eq 'will_exceed_quota'
 8902:                 || $state eq 'file_locked') {
 8903:                 $output .= $msg;
 8904:                 next;
 8905:             }
 8906:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8907:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8908:             if ($state eq 'exists') {
 8909:                 $output .= $msg;
 8910:                 next;
 8911:             }
 8912:         }
 8913:         # Check if extension is valid
 8914:         if (($fname =~ /\.(\w+)$/) &&
 8915:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8916:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 8917:             next;
 8918:         } elsif (($fname =~ /\.(\w+)$/) &&
 8919:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8920:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
 8921:             next;
 8922:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8923:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
 8924:             next;
 8925:         }
 8926: 
 8927:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8928:         if ($context eq 'portfolio') {
 8929:             my $result;
 8930:             if ($state eq 'existingfile') {
 8931:                 $result=
 8932:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
 8933:                                                     $dirpath.$env{'form.currentpath'}.$path);
 8934:             } else {
 8935:                 $result=
 8936:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8937:                                                     $dirpath.
 8938:                                                     $env{'form.currentpath'}.$path);
 8939:                 if ($result !~ m|^/uploaded/|) {
 8940:                     $output .= '<span class="LC_error">'
 8941:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8942:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8943:                                .'</span><br />';
 8944:                     next;
 8945:                 } else {
 8946:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8947:                                $path.$fname.'</span>').'<br />';     
 8948:                 }
 8949:             }
 8950:         } elsif ($context eq 'coursedoc') {
 8951:             my $result =
 8952:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
 8953:                                                 $dirpath.'/'.$path);
 8954:             if ($result !~ m|^/uploaded/|) {
 8955:                 $output .= '<span class="LC_error">'
 8956:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8957:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8958:                            .'</span><br />';
 8959:                     next;
 8960:             } else {
 8961:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8962:                            $path.$fname.'</span>').'<br />';
 8963:             }
 8964:         } else {
 8965: # Save the file
 8966:             my $target = $env{'form.embedded_item_'.$i};
 8967:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8968:             my $dest = $fullpath.$fname;
 8969:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8970:             my @parts=split(/\//,"$dirpath/$path");
 8971:             my $count;
 8972:             my $filepath = $dir_root;
 8973:             foreach my $subdir (@parts) {
 8974:                 $filepath .= "/$subdir";
 8975:                 if (!-e $filepath) {
 8976:                     mkdir($filepath,0770);
 8977:                 }
 8978:             }
 8979:             my $fh;
 8980:             if (!open($fh,'>'.$dest)) {
 8981:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8982:                 $output .= '<span class="LC_error">'.
 8983:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8984:                            '</span><br />';
 8985:             } else {
 8986:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8987:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8988:                     $output .= '<span class="LC_error">'.
 8989:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8990:                               '</span><br />';
 8991:                 } else {
 8992:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8993:                                $url.'</span>').'<br />';
 8994:                     unless ($context eq 'testbank') {
 8995:                         $footer .= &mt('View embedded file: [_1]',
 8996:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
 8997:                     }
 8998:                 }
 8999:                 close($fh);
 9000:             }
 9001:         }
 9002:         if ($env{'form.embedded_ref_'.$i}) {
 9003:             $pathchange{$i} = 1;
 9004:         }
 9005:     }
 9006:     if ($output) {
 9007:         $output = '<p>'.$output.'</p>';
 9008:     }
 9009:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
 9010:     $returnflag = 'ok';
 9011:     if (keys(%pathchange) > 0) {
 9012:         if ($context eq 'portfolio') {
 9013:             $output .= '<p>'.&mt('or').'</p>';
 9014:         } elsif ($context eq 'testbank') {
 9015:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
 9016:             $returnflag = 'modify_orightml';
 9017:         }
 9018:     }
 9019:     return ($output.$footer,$returnflag);
 9020: }
 9021: 
 9022: sub modify_html_form {
 9023:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
 9024:     my $end = 0;
 9025:     my $modifyform;
 9026:     if ($context eq 'upload_embedded') {
 9027:         return unless (ref($pathchange) eq 'HASH');
 9028:         if ($env{'form.number_embedded_items'}) {
 9029:             $end += $env{'form.number_embedded_items'};
 9030:         }
 9031:         if ($env{'form.number_pathchange_items'}) {
 9032:             $end += $env{'form.number_pathchange_items'};
 9033:         }
 9034:         if ($end) {
 9035:             for (my $i=0; $i<$end; $i++) {
 9036:                 if ($i < $env{'form.number_embedded_items'}) {
 9037:                     next unless($pathchange->{$i});
 9038:                 }
 9039:                 $modifyform .=
 9040:                     &start_data_table_row().
 9041:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
 9042:                     'checked="checked" /></td>'.
 9043:                     '<td>'.$env{'form.embedded_ref_'.$i}.
 9044:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
 9045:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
 9046:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
 9047:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
 9048:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
 9049:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
 9050:                     '<td>'.$env{'form.embedded_orig_'.$i}.
 9051:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
 9052:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
 9053:                     &end_data_table_row();
 9054:             } 
 9055:         }
 9056:     } else {
 9057:         $modifyform = $pathchgtable;
 9058:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9059:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
 9060:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9061:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
 9062:         }
 9063:     }
 9064:     if ($modifyform) {
 9065:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
 9066:                '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
 9067:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
 9068:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
 9069:                '</ol></p>'."\n".'<p>'.
 9070:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
 9071:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
 9072:                &start_data_table()."\n".
 9073:                &start_data_table_header_row().
 9074:                '<th>'.&mt('Change?').'</th>'.
 9075:                '<th>'.&mt('Current reference').'</th>'.
 9076:                '<th>'.&mt('Required reference').'</th>'.
 9077:                &end_data_table_header_row()."\n".
 9078:                $modifyform.
 9079:                &end_data_table().'<br />'."\n".$hiddenstate.
 9080:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
 9081:                '</form>'."\n";
 9082:     }
 9083:     return;
 9084: }
 9085: 
 9086: sub modify_html_refs {
 9087:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
 9088:     my $container;
 9089:     if ($context eq 'portfolio') {
 9090:         $container = $env{'form.container'};
 9091:     } elsif ($context eq 'coursedoc') {
 9092:         $container = $env{'form.primaryurl'};
 9093:     } else {
 9094:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
 9095:     }
 9096:     my (%allfiles,%codebase,$output,$content);
 9097:     my @changes = &get_env_multiple('form.namechange');
 9098:     return unless (@changes > 0);
 9099:     if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
 9100:         return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
 9101:         $content = &Apache::lonnet::getfile($container);
 9102:         return if ($content eq '-1');
 9103:     } else {
 9104:         return unless ($container =~ /^\Q$dir_root\E/); 
 9105:         if (open(my $fh,"<$container")) {
 9106:             $content = join('', <$fh>);
 9107:             close($fh);
 9108:         } else {
 9109:             return;
 9110:         }
 9111:     }
 9112:     my ($count,$codebasecount) = (0,0);
 9113:     my $mm = new File::MMagic;
 9114:     my $mime_type = $mm->checktype_contents($content);
 9115:     if ($mime_type eq 'text/html') {
 9116:         my $parse_result = 
 9117:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
 9118:                                                     \%codebase,\$content);
 9119:         if ($parse_result eq 'ok') {
 9120:             foreach my $i (@changes) {
 9121:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
 9122:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
 9123:                 if ($allfiles{$ref}) {
 9124:                     my $newname =  $orig;
 9125:                     my ($attrib_regexp,$codebase);
 9126:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
 9127:                     if ($attrib_regexp =~ /:/) {
 9128:                         $attrib_regexp =~ s/\:/|/g;
 9129:                     }
 9130:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
 9131:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
 9132:                         $count += $numchg;
 9133:                     }
 9134:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
 9135:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
 9136:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
 9137:                         $codebasecount ++;
 9138:                     }
 9139:                 }
 9140:             }
 9141:             if ($count || $codebasecount) {
 9142:                 my $saveresult;
 9143:                 if ($context eq 'portfolio' || $context eq 'coursedoc') {
 9144:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
 9145:                     if ($url eq $container) {
 9146:                         my ($fname) = ($container =~ m{/([^/]+)$});
 9147:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9148:                                             $count,'<span class="LC_filename">'.
 9149:                                             $fname.'</span>').'</p>'; 
 9150:                     } else {
 9151:                          $output = '<p class="LC_error">'.
 9152:                                    &mt('Error: update failed for: [_1].',
 9153:                                    '<span class="LC_filename">'.
 9154:                                    $container.'</span>').'</p>';
 9155:                     }
 9156:                 } else {
 9157:                     if (open(my $fh,">$container")) {
 9158:                         print $fh $content;
 9159:                         close($fh);
 9160:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9161:                                   $count,'<span class="LC_filename">'.
 9162:                                   $container.'</span>').'</p>';
 9163:                     } else {
 9164:                          $output = '<p class="LC_error">'.
 9165:                                    &mt('Error: could not update [_1].',
 9166:                                    '<span class="LC_filename">'.
 9167:                                    $container.'</span>').'</p>';
 9168:                     }
 9169:                 }
 9170:             }
 9171:         } else {
 9172:             &logthis('Failed to parse '.$container.
 9173:                      ' to modify references: '.$parse_result);
 9174:         }
 9175:     }
 9176:     return $output;
 9177: }
 9178: 
 9179: sub check_for_existing {
 9180:     my ($path,$fname,$element) = @_;
 9181:     my ($state,$msg);
 9182:     if (-d $path.'/'.$fname) {
 9183:         $state = 'exists';
 9184:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 9185:     } elsif (-e $path.'/'.$fname) {
 9186:         $state = 'exists';
 9187:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 9188:     }
 9189:     if ($state eq 'exists') {
 9190:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 9191:     }
 9192:     return ($state,$msg);
 9193: }
 9194: 
 9195: sub check_for_upload {
 9196:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 9197:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 9198:     my $filesize = length($env{'form.'.$element});
 9199:     if (!$filesize) {
 9200:         my $msg = '<span class="LC_error">'.
 9201:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
 9202:                       '<span class="LC_filename">'.$fname.'</span>',
 9203:                       $filesize).'<br />'.
 9204:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
 9205:                   '</span>';
 9206:         return ('zero_bytes',$msg);
 9207:     }
 9208:     $filesize =  $filesize/1000; #express in k (1024?)
 9209:     my $getpropath = 1;
 9210:     my ($dirlistref,$listerror) =
 9211:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
 9212:     my $found_file = 0;
 9213:     my $locked_file = 0;
 9214:     my @lockers;
 9215:     my $navmap;
 9216:     if ($env{'request.course.id'}) {
 9217:         $navmap = Apache::lonnavmaps::navmap->new();
 9218:     }
 9219:     if (ref($dirlistref) eq 'ARRAY') {
 9220:         foreach my $line (@{$dirlistref}) {
 9221:             my ($file_name,$rest)=split(/\&/,$line,2);
 9222:             if ($file_name eq $fname){
 9223:                 $file_name = $path.$file_name;
 9224:                 if ($group ne '') {
 9225:                     $file_name = $group.$file_name;
 9226:                 }
 9227:                 $found_file = 1;
 9228:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
 9229:                     foreach my $lock (@lockers) {
 9230:                         if (ref($lock) eq 'ARRAY') {
 9231:                             my ($symb,$crsid) = @{$lock};
 9232:                             if ($crsid eq $env{'request.course.id'}) {
 9233:                                 if (ref($navmap)) {
 9234:                                     my $res = $navmap->getBySymb($symb);
 9235:                                     foreach my $part (@{$res->parts()}) { 
 9236:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
 9237:                                         unless (($slot_status == $res->RESERVED) ||
 9238:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
 9239:                                             $locked_file = 1;
 9240:                                         }
 9241:                                     }
 9242:                                 } else {
 9243:                                     $locked_file = 1;
 9244:                                 }
 9245:                             } else {
 9246:                                 $locked_file = 1;
 9247:                             }
 9248:                         }
 9249:                    }
 9250:                 } else {
 9251:                     my @info = split(/\&/,$rest);
 9252:                     my $currsize = $info[6]/1000;
 9253:                     if ($currsize < $filesize) {
 9254:                         my $extra = $filesize - $currsize;
 9255:                         if (($current_disk_usage + $extra) > $disk_quota) {
 9256:                             my $msg = '<span class="LC_error">'.
 9257:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
 9258:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
 9259:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9260:                                                    $disk_quota,$current_disk_usage);
 9261:                             return ('will_exceed_quota',$msg);
 9262:                         }
 9263:                     }
 9264:                 }
 9265:             }
 9266:         }
 9267:     }
 9268:     if (($current_disk_usage + $filesize) > $disk_quota){
 9269:         my $msg = '<span class="LC_error">'.
 9270:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 9271:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 9272:         return ('will_exceed_quota',$msg);
 9273:     } elsif ($found_file) {
 9274:         if ($locked_file) {
 9275:             my $msg = '<span class="LC_error">';
 9276:             $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>');
 9277:             $msg .= '</span><br />';
 9278:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 9279:             return ('file_locked',$msg);
 9280:         } else {
 9281:             my $msg = '<span class="LC_error">';
 9282:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 9283:             $msg .= '</span>';
 9284:             return ('existingfile',$msg);
 9285:         }
 9286:     }
 9287: }
 9288: 
 9289: sub check_for_traversal {
 9290:     my ($path,$url,$toplevel) = @_;
 9291:     my @parts=split(/\//,$path);
 9292:     my $cleanpath;
 9293:     my $fullpath = $url;
 9294:     for (my $i=0;$i<@parts;$i++) {
 9295:         next if ($parts[$i] eq '.');
 9296:         if ($parts[$i] eq '..') {
 9297:             $fullpath =~ s{([^/]+/)$}{};
 9298:         } else {
 9299:             $fullpath .= $parts[$i].'/';
 9300:         }
 9301:     }
 9302:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
 9303:         $cleanpath = $1;
 9304:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
 9305:         my $curr_toprel = $1;
 9306:         my @parts = split(/\//,$curr_toprel);
 9307:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
 9308:         my @urlparts = split(/\//,$url_toprel);
 9309:         my $doubledots;
 9310:         my $startdiff = -1;
 9311:         for (my $i=0; $i<@urlparts; $i++) {
 9312:             if ($startdiff == -1) {
 9313:                 unless ($urlparts[$i] eq $parts[$i]) {
 9314:                     $startdiff = $i;
 9315:                     $doubledots .= '../';
 9316:                 }
 9317:             } else {
 9318:                 $doubledots .= '../';
 9319:             }
 9320:         }
 9321:         if ($startdiff > -1) {
 9322:             $cleanpath = $doubledots;
 9323:             for (my $i=$startdiff; $i<@parts; $i++) {
 9324:                 $cleanpath .= $parts[$i].'/';
 9325:             }
 9326:         }
 9327:     }
 9328:     $cleanpath =~ s{(/)$}{};
 9329:     return $cleanpath;
 9330: }
 9331: 
 9332: =pod
 9333: 
 9334: =item * &get_turnedin_filepath()
 9335: 
 9336: Determines path in a user's portfolio file for storage of files uploaded
 9337: to a specific essayresponse or dropbox item.
 9338: 
 9339: Inputs: 3 required + 1 optional.
 9340: $symb is symb for resource, $uname and $udom are for current user (required).
 9341: $caller is optional (can be "submission", if routine is called when storing
 9342: an upoaded file when "Submit Answer" button was pressed).
 9343: 
 9344: Returns array containing $path and $multiresp. 
 9345: $path is path in portfolio.  $multiresp is 1 if this resource contains more
 9346: than one file upload item.  Callers of routine should append partid as a 
 9347: subdirectory to $path in cases where $multiresp is 1.
 9348: 
 9349: Called by: homework/essayresponse.pm and homework/structuretags.pm
 9350: 
 9351: =cut
 9352: 
 9353: sub get_turnedin_filepath {
 9354:     my ($symb,$uname,$udom,$caller) = @_;
 9355:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
 9356:     my $turnindir;
 9357:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
 9358:     $turnindir = $userhash{'turnindir'};
 9359:     my ($path,$multiresp);
 9360:     if ($turnindir eq '') {
 9361:         if ($caller eq 'submission') {
 9362:             $turnindir = &mt('turned in');
 9363:             $turnindir =~ s/\W+/_/g;
 9364:             my %newhash = (
 9365:                             'turnindir' => $turnindir,
 9366:                           );
 9367:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
 9368:         }
 9369:     }
 9370:     if ($turnindir ne '') {
 9371:         $path = '/'.$turnindir.'/';
 9372:         my ($multipart,$turnin,@pathitems);
 9373:         my $navmap = Apache::lonnavmaps::navmap->new();
 9374:         if (defined($navmap)) {
 9375:             my $mapres = $navmap->getResourceByUrl($map);
 9376:             if (ref($mapres)) {
 9377:                 my $pcslist = $mapres->map_hierarchy();
 9378:                 if ($pcslist ne '') {
 9379:                     foreach my $pc (split(/,/,$pcslist)) {
 9380:                         my $res = $navmap->getByMapPc($pc);
 9381:                         if (ref($res)) {
 9382:                             my $title = $res->compTitle();
 9383:                             $title =~ s/\W+/_/g;
 9384:                             if ($title ne '') {
 9385:                                 push(@pathitems,$title);
 9386:                             }
 9387:                         }
 9388:                     }
 9389:                 }
 9390:                 my $maptitle = $mapres->compTitle();
 9391:                 $maptitle =~ s/\W+/_/g;
 9392:                 if ($maptitle ne '') {
 9393:                     push(@pathitems,$maptitle);
 9394:                 }
 9395:                 unless ($env{'request.state'} eq 'construct') {
 9396:                     my $res = $navmap->getBySymb($symb);
 9397:                     if (ref($res)) {
 9398:                         my $partlist = $res->parts();
 9399:                         my $totaluploads = 0;
 9400:                         if (ref($partlist) eq 'ARRAY') {
 9401:                             foreach my $part (@{$partlist}) {
 9402:                                 my @types = $res->responseType($part);
 9403:                                 my @ids = $res->responseIds($part);
 9404:                                 for (my $i=0; $i < scalar(@ids); $i++) {
 9405:                                     if ($types[$i] eq 'essay') {
 9406:                                         my $partid = $part.'_'.$ids[$i];
 9407:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
 9408:                                             $totaluploads ++;
 9409:                                         }
 9410:                                     }
 9411:                                 }
 9412:                             }
 9413:                             if ($totaluploads > 1) {
 9414:                                 $multiresp = 1;
 9415:                             }
 9416:                         }
 9417:                     }
 9418:                 }
 9419:             } else {
 9420:                 return;
 9421:             }
 9422:         } else {
 9423:             return;
 9424:         }
 9425:         my $restitle=&Apache::lonnet::gettitle($symb);
 9426:         $restitle =~ s/\W+/_/g;
 9427:         if ($restitle eq '') {
 9428:             $restitle = ($resurl =~ m{/[^/]+$});
 9429:             if ($restitle eq '') {
 9430:                 $restitle = time;
 9431:             }
 9432:         }
 9433:         push(@pathitems,$restitle);
 9434:         $path .= join('/',@pathitems);
 9435:     }
 9436:     return ($path,$multiresp);
 9437: }
 9438: 
 9439: =pod
 9440: 
 9441: =back
 9442: 
 9443: =head1 CSV Upload/Handling functions
 9444: 
 9445: =over 4
 9446: 
 9447: =item * &upfile_store($r)
 9448: 
 9449: Store uploaded file, $r should be the HTTP Request object,
 9450: needs $env{'form.upfile'}
 9451: returns $datatoken to be put into hidden field
 9452: 
 9453: =cut
 9454: 
 9455: sub upfile_store {
 9456:     my $r=shift;
 9457:     $env{'form.upfile'}=~s/\r/\n/gs;
 9458:     $env{'form.upfile'}=~s/\f/\n/gs;
 9459:     $env{'form.upfile'}=~s/\n+/\n/gs;
 9460:     $env{'form.upfile'}=~s/\n+$//gs;
 9461: 
 9462:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 9463: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 9464:     {
 9465:         my $datafile = $r->dir_config('lonDaemons').
 9466:                            '/tmp/'.$datatoken.'.tmp';
 9467:         if ( open(my $fh,">$datafile") ) {
 9468:             print $fh $env{'form.upfile'};
 9469:             close($fh);
 9470:         }
 9471:     }
 9472:     return $datatoken;
 9473: }
 9474: 
 9475: =pod
 9476: 
 9477: =item * &load_tmp_file($r)
 9478: 
 9479: Load uploaded file from tmp, $r should be the HTTP Request object,
 9480: needs $env{'form.datatoken'},
 9481: sets $env{'form.upfile'} to the contents of the file
 9482: 
 9483: =cut
 9484: 
 9485: sub load_tmp_file {
 9486:     my $r=shift;
 9487:     my @studentdata=();
 9488:     {
 9489:         my $studentfile = $r->dir_config('lonDaemons').
 9490:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 9491:         if ( open(my $fh,"<$studentfile") ) {
 9492:             @studentdata=<$fh>;
 9493:             close($fh);
 9494:         }
 9495:     }
 9496:     $env{'form.upfile'}=join('',@studentdata);
 9497: }
 9498: 
 9499: =pod
 9500: 
 9501: =item * &upfile_record_sep()
 9502: 
 9503: Separate uploaded file into records
 9504: returns array of records,
 9505: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 9506: 
 9507: =cut
 9508: 
 9509: sub upfile_record_sep {
 9510:     if ($env{'form.upfiletype'} eq 'xml') {
 9511:     } else {
 9512: 	my @records;
 9513: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 9514: 	    if ($line=~/^\s*$/) { next; }
 9515: 	    push(@records,$line);
 9516: 	}
 9517: 	return @records;
 9518:     }
 9519: }
 9520: 
 9521: =pod
 9522: 
 9523: =item * &record_sep($record)
 9524: 
 9525: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 9526: 
 9527: =cut
 9528: 
 9529: sub takeleft {
 9530:     my $index=shift;
 9531:     return substr('0000'.$index,-4,4);
 9532: }
 9533: 
 9534: sub record_sep {
 9535:     my $record=shift;
 9536:     my %components=();
 9537:     if ($env{'form.upfiletype'} eq 'xml') {
 9538:     } elsif ($env{'form.upfiletype'} eq 'space') {
 9539:         my $i=0;
 9540:         foreach my $field (split(/\s+/,$record)) {
 9541:             $field=~s/^(\"|\')//;
 9542:             $field=~s/(\"|\')$//;
 9543:             $components{&takeleft($i)}=$field;
 9544:             $i++;
 9545:         }
 9546:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 9547:         my $i=0;
 9548:         foreach my $field (split(/\t/,$record)) {
 9549:             $field=~s/^(\"|\')//;
 9550:             $field=~s/(\"|\')$//;
 9551:             $components{&takeleft($i)}=$field;
 9552:             $i++;
 9553:         }
 9554:     } else {
 9555:         my $separator=',';
 9556:         if ($env{'form.upfiletype'} eq 'semisv') {
 9557:             $separator=';';
 9558:         }
 9559:         my $i=0;
 9560: # the character we are looking for to indicate the end of a quote or a record 
 9561:         my $looking_for=$separator;
 9562: # do not add the characters to the fields
 9563:         my $ignore=0;
 9564: # we just encountered a separator (or the beginning of the record)
 9565:         my $just_found_separator=1;
 9566: # store the field we are working on here
 9567:         my $field='';
 9568: # work our way through all characters in record
 9569:         foreach my $character ($record=~/(.)/g) {
 9570:             if ($character eq $looking_for) {
 9571:                if ($character ne $separator) {
 9572: # Found the end of a quote, again looking for separator
 9573:                   $looking_for=$separator;
 9574:                   $ignore=1;
 9575:                } else {
 9576: # Found a separator, store away what we got
 9577:                   $components{&takeleft($i)}=$field;
 9578: 	          $i++;
 9579:                   $just_found_separator=1;
 9580:                   $ignore=0;
 9581:                   $field='';
 9582:                }
 9583:                next;
 9584:             }
 9585: # single or double quotation marks after a separator indicate beginning of a quote
 9586: # we are now looking for the end of the quote and need to ignore separators
 9587:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 9588:                $looking_for=$character;
 9589:                next;
 9590:             }
 9591: # ignore would be true after we reached the end of a quote
 9592:             if ($ignore) { next; }
 9593:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 9594:             $field.=$character;
 9595:             $just_found_separator=0; 
 9596:         }
 9597: # catch the very last entry, since we never encountered the separator
 9598:         $components{&takeleft($i)}=$field;
 9599:     }
 9600:     return %components;
 9601: }
 9602: 
 9603: ######################################################
 9604: ######################################################
 9605: 
 9606: =pod
 9607: 
 9608: =item * &upfile_select_html()
 9609: 
 9610: Return HTML code to select a file from the users machine and specify 
 9611: the file type.
 9612: 
 9613: =cut
 9614: 
 9615: ######################################################
 9616: ######################################################
 9617: sub upfile_select_html {
 9618:     my %Types = (
 9619:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 9620:                  semisv => &mt('Semicolon separated values'),
 9621:                  space => &mt('Space separated'),
 9622:                  tab   => &mt('Tabulator separated'),
 9623: #                 xml   => &mt('HTML/XML'),
 9624:                  );
 9625:     my $Str = '<input type="file" name="upfile" size="50" />'.
 9626:         '<br />'.&mt('Type').': <select name="upfiletype">';
 9627:     foreach my $type (sort(keys(%Types))) {
 9628:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 9629:     }
 9630:     $Str .= "</select>\n";
 9631:     return $Str;
 9632: }
 9633: 
 9634: sub get_samples {
 9635:     my ($records,$toget) = @_;
 9636:     my @samples=({});
 9637:     my $got=0;
 9638:     foreach my $rec (@$records) {
 9639: 	my %temp = &record_sep($rec);
 9640: 	if (! grep(/\S/, values(%temp))) { next; }
 9641: 	if (%temp) {
 9642: 	    $samples[$got]=\%temp;
 9643: 	    $got++;
 9644: 	    if ($got == $toget) { last; }
 9645: 	}
 9646:     }
 9647:     return \@samples;
 9648: }
 9649: 
 9650: ######################################################
 9651: ######################################################
 9652: 
 9653: =pod
 9654: 
 9655: =item * &csv_print_samples($r,$records)
 9656: 
 9657: Prints a table of sample values from each column uploaded $r is an
 9658: Apache Request ref, $records is an arrayref from
 9659: &Apache::loncommon::upfile_record_sep
 9660: 
 9661: =cut
 9662: 
 9663: ######################################################
 9664: ######################################################
 9665: sub csv_print_samples {
 9666:     my ($r,$records) = @_;
 9667:     my $samples = &get_samples($records,5);
 9668: 
 9669:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 9670:               &start_data_table_header_row());
 9671:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 9672:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 9673:     $r->print(&end_data_table_header_row());
 9674:     foreach my $hash (@$samples) {
 9675: 	$r->print(&start_data_table_row());
 9676: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9677: 	    $r->print('<td>');
 9678: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 9679: 	    $r->print('</td>');
 9680: 	}
 9681: 	$r->print(&end_data_table_row());
 9682:     }
 9683:     $r->print(&end_data_table().'<br />'."\n");
 9684: }
 9685: 
 9686: ######################################################
 9687: ######################################################
 9688: 
 9689: =pod
 9690: 
 9691: =item * &csv_print_select_table($r,$records,$d)
 9692: 
 9693: Prints a table to create associations between values and table columns.
 9694: 
 9695: $r is an Apache Request ref,
 9696: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9697: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 9698: 
 9699: =cut
 9700: 
 9701: ######################################################
 9702: ######################################################
 9703: sub csv_print_select_table {
 9704:     my ($r,$records,$d) = @_;
 9705:     my $i=0;
 9706:     my $samples = &get_samples($records,1);
 9707:     $r->print(&mt('Associate columns with student attributes.')."\n".
 9708: 	      &start_data_table().&start_data_table_header_row().
 9709:               '<th>'.&mt('Attribute').'</th>'.
 9710:               '<th>'.&mt('Column').'</th>'.
 9711:               &end_data_table_header_row()."\n");
 9712:     foreach my $array_ref (@$d) {
 9713: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 9714: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 9715: 
 9716: 	$r->print('<td><select name="f'.$i.'"'.
 9717: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9718: 	$r->print('<option value="none"></option>');
 9719: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9720: 	    $r->print('<option value="'.$sample.'"'.
 9721:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 9722:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 9723: 	}
 9724: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 9725: 	$i++;
 9726:     }
 9727:     $r->print(&end_data_table());
 9728:     $i--;
 9729:     return $i;
 9730: }
 9731: 
 9732: ######################################################
 9733: ######################################################
 9734: 
 9735: =pod
 9736: 
 9737: =item * &csv_samples_select_table($r,$records,$d)
 9738: 
 9739: Prints a table of sample values from the upload and can make associate samples to internal names.
 9740: 
 9741: $r is an Apache Request ref,
 9742: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9743: $d is an array of 2 element arrays (internal name, displayed name)
 9744: 
 9745: =cut
 9746: 
 9747: ######################################################
 9748: ######################################################
 9749: sub csv_samples_select_table {
 9750:     my ($r,$records,$d) = @_;
 9751:     my $i=0;
 9752:     #
 9753:     my $max_samples = 5;
 9754:     my $samples = &get_samples($records,$max_samples);
 9755:     $r->print(&start_data_table().
 9756:               &start_data_table_header_row().'<th>'.
 9757:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 9758:               &end_data_table_header_row());
 9759: 
 9760:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 9761: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 9762: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9763: 	foreach my $option (@$d) {
 9764: 	    my ($value,$display,$defaultcol)=@{ $option };
 9765: 	    $r->print('<option value="'.$value.'"'.
 9766:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 9767:                       $display.'</option>');
 9768: 	}
 9769: 	$r->print('</select></td><td>');
 9770: 	foreach my $line (0..($max_samples-1)) {
 9771: 	    if (defined($samples->[$line]{$key})) { 
 9772: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 9773: 	    }
 9774: 	}
 9775: 	$r->print('</td>'.&end_data_table_row());
 9776: 	$i++;
 9777:     }
 9778:     $r->print(&end_data_table());
 9779:     $i--;
 9780:     return($i);
 9781: }
 9782: 
 9783: ######################################################
 9784: ######################################################
 9785: 
 9786: =pod
 9787: 
 9788: =item * &clean_excel_name($name)
 9789: 
 9790: Returns a replacement for $name which does not contain any illegal characters.
 9791: 
 9792: =cut
 9793: 
 9794: ######################################################
 9795: ######################################################
 9796: sub clean_excel_name {
 9797:     my ($name) = @_;
 9798:     $name =~ s/[:\*\?\/\\]//g;
 9799:     if (length($name) > 31) {
 9800:         $name = substr($name,0,31);
 9801:     }
 9802:     return $name;
 9803: }
 9804: 
 9805: =pod
 9806: 
 9807: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 9808: 
 9809: Returns either 1 or undef
 9810: 
 9811: 1 if the part is to be hidden, undef if it is to be shown
 9812: 
 9813: Arguments are:
 9814: 
 9815: $id the id of the part to be checked
 9816: $symb, optional the symb of the resource to check
 9817: $udom, optional the domain of the user to check for
 9818: $uname, optional the username of the user to check for
 9819: 
 9820: =cut
 9821: 
 9822: sub check_if_partid_hidden {
 9823:     my ($id,$symb,$udom,$uname) = @_;
 9824:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 9825: 					 $symb,$udom,$uname);
 9826:     my $truth=1;
 9827:     #if the string starts with !, then the list is the list to show not hide
 9828:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 9829:     my @hiddenlist=split(/,/,$hiddenparts);
 9830:     foreach my $checkid (@hiddenlist) {
 9831: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 9832:     }
 9833:     return !$truth;
 9834: }
 9835: 
 9836: 
 9837: ############################################################
 9838: ############################################################
 9839: 
 9840: =pod
 9841: 
 9842: =back 
 9843: 
 9844: =head1 cgi-bin script and graphing routines
 9845: 
 9846: =over 4
 9847: 
 9848: =item * &get_cgi_id()
 9849: 
 9850: Inputs: none
 9851: 
 9852: Returns an id which can be used to pass environment variables
 9853: to various cgi-bin scripts.  These environment variables will
 9854: be removed from the users environment after a given time by
 9855: the routine &Apache::lonnet::transfer_profile_to_env.
 9856: 
 9857: =cut
 9858: 
 9859: ############################################################
 9860: ############################################################
 9861: my $uniq=0;
 9862: sub get_cgi_id {
 9863:     $uniq=($uniq+1)%100000;
 9864:     return (time.'_'.$$.'_'.$uniq);
 9865: }
 9866: 
 9867: ############################################################
 9868: ############################################################
 9869: 
 9870: =pod
 9871: 
 9872: =item * &DrawBarGraph()
 9873: 
 9874: Facilitates the plotting of data in a (stacked) bar graph.
 9875: Puts plot definition data into the users environment in order for 
 9876: graph.png to plot it.  Returns an <img> tag for the plot.
 9877: The bars on the plot are labeled '1','2',...,'n'.
 9878: 
 9879: Inputs:
 9880: 
 9881: =over 4
 9882: 
 9883: =item $Title: string, the title of the plot
 9884: 
 9885: =item $xlabel: string, text describing the X-axis of the plot
 9886: 
 9887: =item $ylabel: string, text describing the Y-axis of the plot
 9888: 
 9889: =item $Max: scalar, the maximum Y value to use in the plot
 9890: If $Max is < any data point, the graph will not be rendered.
 9891: 
 9892: =item $colors: array ref holding the colors to be used for the data sets when
 9893: they are plotted.  If undefined, default values will be used.
 9894: 
 9895: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 9896: 
 9897: =item @Values: An array of array references.  Each array reference holds data
 9898: to be plotted in a stacked bar chart.
 9899: 
 9900: =item If the final element of @Values is a hash reference the key/value
 9901: pairs will be added to the graph definition.
 9902: 
 9903: =back
 9904: 
 9905: Returns:
 9906: 
 9907: An <img> tag which references graph.png and the appropriate identifying
 9908: information for the plot.
 9909: 
 9910: =cut
 9911: 
 9912: ############################################################
 9913: ############################################################
 9914: sub DrawBarGraph {
 9915:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 9916:     #
 9917:     if (! defined($colors)) {
 9918:         $colors = ['#33ff00', 
 9919:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 9920:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 9921:                   ]; 
 9922:     }
 9923:     my $extra_settings = {};
 9924:     if (ref($Values[-1]) eq 'HASH') {
 9925:         $extra_settings = pop(@Values);
 9926:     }
 9927:     #
 9928:     my $identifier = &get_cgi_id();
 9929:     my $id = 'cgi.'.$identifier;        
 9930:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 9931:         return '';
 9932:     }
 9933:     #
 9934:     my @Labels;
 9935:     if (defined($labels)) {
 9936:         @Labels = @$labels;
 9937:     } else {
 9938:         for (my $i=0;$i<@{$Values[0]};$i++) {
 9939:             push (@Labels,$i+1);
 9940:         }
 9941:     }
 9942:     #
 9943:     my $NumBars = scalar(@{$Values[0]});
 9944:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 9945:     my %ValuesHash;
 9946:     my $NumSets=1;
 9947:     foreach my $array (@Values) {
 9948:         next if (! ref($array));
 9949:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 9950:             join(',',@$array);
 9951:     }
 9952:     #
 9953:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 9954:     if ($NumBars < 3) {
 9955:         $width = 120+$NumBars*32;
 9956:         $xskip = 1;
 9957:         $bar_width = 30;
 9958:     } elsif ($NumBars < 5) {
 9959:         $width = 120+$NumBars*20;
 9960:         $xskip = 1;
 9961:         $bar_width = 20;
 9962:     } elsif ($NumBars < 10) {
 9963:         $width = 120+$NumBars*15;
 9964:         $xskip = 1;
 9965:         $bar_width = 15;
 9966:     } elsif ($NumBars <= 25) {
 9967:         $width = 120+$NumBars*11;
 9968:         $xskip = 5;
 9969:         $bar_width = 8;
 9970:     } elsif ($NumBars <= 50) {
 9971:         $width = 120+$NumBars*8;
 9972:         $xskip = 5;
 9973:         $bar_width = 4;
 9974:     } else {
 9975:         $width = 120+$NumBars*8;
 9976:         $xskip = 5;
 9977:         $bar_width = 4;
 9978:     }
 9979:     #
 9980:     $Max = 1 if ($Max < 1);
 9981:     if ( int($Max) < $Max ) {
 9982:         $Max++;
 9983:         $Max = int($Max);
 9984:     }
 9985:     $Title  = '' if (! defined($Title));
 9986:     $xlabel = '' if (! defined($xlabel));
 9987:     $ylabel = '' if (! defined($ylabel));
 9988:     $ValuesHash{$id.'.title'}    = &escape($Title);
 9989:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 9990:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 9991:     $ValuesHash{$id.'.y_max_value'} = $Max;
 9992:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 9993:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 9994:     $ValuesHash{$id.'.PlotType'} = 'bar';
 9995:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9996:     $ValuesHash{$id.'.height'}   = $height;
 9997:     $ValuesHash{$id.'.width'}    = $width;
 9998:     $ValuesHash{$id.'.xskip'}    = $xskip;
 9999:     $ValuesHash{$id.'.bar_width'} = $bar_width;
10000:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
10001:     #
10002:     # Deal with other parameters
10003:     while (my ($key,$value) = each(%$extra_settings)) {
10004:         $ValuesHash{$id.'.'.$key} = $value;
10005:     }
10006:     #
10007:     &Apache::lonnet::appenv(\%ValuesHash);
10008:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
10009: }
10010: 
10011: ############################################################
10012: ############################################################
10013: 
10014: =pod
10015: 
10016: =item * &DrawXYGraph()
10017: 
10018: Facilitates the plotting of data in an XY graph.
10019: Puts plot definition data into the users environment in order for 
10020: graph.png to plot it.  Returns an <img> tag for the plot.
10021: 
10022: Inputs:
10023: 
10024: =over 4
10025: 
10026: =item $Title: string, the title of the plot
10027: 
10028: =item $xlabel: string, text describing the X-axis of the plot
10029: 
10030: =item $ylabel: string, text describing the Y-axis of the plot
10031: 
10032: =item $Max: scalar, the maximum Y value to use in the plot
10033: If $Max is < any data point, the graph will not be rendered.
10034: 
10035: =item $colors: Array ref containing the hex color codes for the data to be 
10036: plotted in.  If undefined, default values will be used.
10037: 
10038: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
10039: 
10040: =item $Ydata: Array ref containing Array refs.  
10041: Each of the contained arrays will be plotted as a separate curve.
10042: 
10043: =item %Values: hash indicating or overriding any default values which are 
10044: passed to graph.png.  
10045: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
10046: 
10047: =back
10048: 
10049: Returns:
10050: 
10051: An <img> tag which references graph.png and the appropriate identifying
10052: information for the plot.
10053: 
10054: =cut
10055: 
10056: ############################################################
10057: ############################################################
10058: sub DrawXYGraph {
10059:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
10060:     #
10061:     # Create the identifier for the graph
10062:     my $identifier = &get_cgi_id();
10063:     my $id = 'cgi.'.$identifier;
10064:     #
10065:     $Title  = '' if (! defined($Title));
10066:     $xlabel = '' if (! defined($xlabel));
10067:     $ylabel = '' if (! defined($ylabel));
10068:     my %ValuesHash = 
10069:         (
10070:          $id.'.title'  => &escape($Title),
10071:          $id.'.xlabel' => &escape($xlabel),
10072:          $id.'.ylabel' => &escape($ylabel),
10073:          $id.'.y_max_value'=> $Max,
10074:          $id.'.labels'     => join(',',@$Xlabels),
10075:          $id.'.PlotType'   => 'XY',
10076:          );
10077:     #
10078:     if (defined($colors) && ref($colors) eq 'ARRAY') {
10079:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
10080:     }
10081:     #
10082:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
10083:         return '';
10084:     }
10085:     my $NumSets=1;
10086:     foreach my $array (@{$Ydata}){
10087:         next if (! ref($array));
10088:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
10089:     }
10090:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
10091:     #
10092:     # Deal with other parameters
10093:     while (my ($key,$value) = each(%Values)) {
10094:         $ValuesHash{$id.'.'.$key} = $value;
10095:     }
10096:     #
10097:     &Apache::lonnet::appenv(\%ValuesHash);
10098:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
10099: }
10100: 
10101: ############################################################
10102: ############################################################
10103: 
10104: =pod
10105: 
10106: =item * &DrawXYYGraph()
10107: 
10108: Facilitates the plotting of data in an XY graph with two Y axes.
10109: Puts plot definition data into the users environment in order for 
10110: graph.png to plot it.  Returns an <img> tag for the plot.
10111: 
10112: Inputs:
10113: 
10114: =over 4
10115: 
10116: =item $Title: string, the title of the plot
10117: 
10118: =item $xlabel: string, text describing the X-axis of the plot
10119: 
10120: =item $ylabel: string, text describing the Y-axis of the plot
10121: 
10122: =item $colors: Array ref containing the hex color codes for the data to be 
10123: plotted in.  If undefined, default values will be used.
10124: 
10125: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
10126: 
10127: =item $Ydata1: The first data set
10128: 
10129: =item $Min1: The minimum value of the left Y-axis
10130: 
10131: =item $Max1: The maximum value of the left Y-axis
10132: 
10133: =item $Ydata2: The second data set
10134: 
10135: =item $Min2: The minimum value of the right Y-axis
10136: 
10137: =item $Max2: The maximum value of the left Y-axis
10138: 
10139: =item %Values: hash indicating or overriding any default values which are 
10140: passed to graph.png.  
10141: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
10142: 
10143: =back
10144: 
10145: Returns:
10146: 
10147: An <img> tag which references graph.png and the appropriate identifying
10148: information for the plot.
10149: 
10150: =cut
10151: 
10152: ############################################################
10153: ############################################################
10154: sub DrawXYYGraph {
10155:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
10156:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
10157:     #
10158:     # Create the identifier for the graph
10159:     my $identifier = &get_cgi_id();
10160:     my $id = 'cgi.'.$identifier;
10161:     #
10162:     $Title  = '' if (! defined($Title));
10163:     $xlabel = '' if (! defined($xlabel));
10164:     $ylabel = '' if (! defined($ylabel));
10165:     my %ValuesHash = 
10166:         (
10167:          $id.'.title'  => &escape($Title),
10168:          $id.'.xlabel' => &escape($xlabel),
10169:          $id.'.ylabel' => &escape($ylabel),
10170:          $id.'.labels' => join(',',@$Xlabels),
10171:          $id.'.PlotType' => 'XY',
10172:          $id.'.NumSets' => 2,
10173:          $id.'.two_axes' => 1,
10174:          $id.'.y1_max_value' => $Max1,
10175:          $id.'.y1_min_value' => $Min1,
10176:          $id.'.y2_max_value' => $Max2,
10177:          $id.'.y2_min_value' => $Min2,
10178:          );
10179:     #
10180:     if (defined($colors) && ref($colors) eq 'ARRAY') {
10181:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
10182:     }
10183:     #
10184:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
10185:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
10186:         return '';
10187:     }
10188:     my $NumSets=1;
10189:     foreach my $array ($Ydata1,$Ydata2){
10190:         next if (! ref($array));
10191:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
10192:     }
10193:     #
10194:     # Deal with other parameters
10195:     while (my ($key,$value) = each(%Values)) {
10196:         $ValuesHash{$id.'.'.$key} = $value;
10197:     }
10198:     #
10199:     &Apache::lonnet::appenv(\%ValuesHash);
10200:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
10201: }
10202: 
10203: ############################################################
10204: ############################################################
10205: 
10206: =pod
10207: 
10208: =back 
10209: 
10210: =head1 Statistics helper routines?  
10211: 
10212: Bad place for them but what the hell.
10213: 
10214: =over 4
10215: 
10216: =item * &chartlink()
10217: 
10218: Returns a link to the chart for a specific student.  
10219: 
10220: Inputs:
10221: 
10222: =over 4
10223: 
10224: =item $linktext: The text of the link
10225: 
10226: =item $sname: The students username
10227: 
10228: =item $sdomain: The students domain
10229: 
10230: =back
10231: 
10232: =back
10233: 
10234: =cut
10235: 
10236: ############################################################
10237: ############################################################
10238: sub chartlink {
10239:     my ($linktext, $sname, $sdomain) = @_;
10240:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
10241:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
10242:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
10243:        '">'.$linktext.'</a>';
10244: }
10245: 
10246: #######################################################
10247: #######################################################
10248: 
10249: =pod
10250: 
10251: =head1 Course Environment Routines
10252: 
10253: =over 4
10254: 
10255: =item * &restore_course_settings()
10256: 
10257: =item * &store_course_settings()
10258: 
10259: Restores/Store indicated form parameters from the course environment.
10260: Will not overwrite existing values of the form parameters.
10261: 
10262: Inputs: 
10263: a scalar describing the data (e.g. 'chart', 'problem_analysis')
10264: 
10265: a hash ref describing the data to be stored.  For example:
10266:    
10267: %Save_Parameters = ('Status' => 'scalar',
10268:     'chartoutputmode' => 'scalar',
10269:     'chartoutputdata' => 'scalar',
10270:     'Section' => 'array',
10271:     'Group' => 'array',
10272:     'StudentData' => 'array',
10273:     'Maps' => 'array');
10274: 
10275: Returns: both routines return nothing
10276: 
10277: =back
10278: 
10279: =cut
10280: 
10281: #######################################################
10282: #######################################################
10283: sub store_course_settings {
10284:     return &store_settings($env{'request.course.id'},@_);
10285: }
10286: 
10287: sub store_settings {
10288:     # save to the environment
10289:     # appenv the same items, just to be safe
10290:     my $udom  = $env{'user.domain'};
10291:     my $uname = $env{'user.name'};
10292:     my ($context,$prefix,$Settings) = @_;
10293:     my %SaveHash;
10294:     my %AppHash;
10295:     while (my ($setting,$type) = each(%$Settings)) {
10296:         my $basename = join('.','internal',$context,$prefix,$setting);
10297:         my $envname = 'environment.'.$basename;
10298:         if (exists($env{'form.'.$setting})) {
10299:             # Save this value away
10300:             if ($type eq 'scalar' &&
10301:                 (! exists($env{$envname}) || 
10302:                  $env{$envname} ne $env{'form.'.$setting})) {
10303:                 $SaveHash{$basename} = $env{'form.'.$setting};
10304:                 $AppHash{$envname}   = $env{'form.'.$setting};
10305:             } elsif ($type eq 'array') {
10306:                 my $stored_form;
10307:                 if (ref($env{'form.'.$setting})) {
10308:                     $stored_form = join(',',
10309:                                         map {
10310:                                             &escape($_);
10311:                                         } sort(@{$env{'form.'.$setting}}));
10312:                 } else {
10313:                     $stored_form = 
10314:                         &escape($env{'form.'.$setting});
10315:                 }
10316:                 # Determine if the array contents are the same.
10317:                 if ($stored_form ne $env{$envname}) {
10318:                     $SaveHash{$basename} = $stored_form;
10319:                     $AppHash{$envname}   = $stored_form;
10320:                 }
10321:             }
10322:         }
10323:     }
10324:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
10325:                                           $udom,$uname);
10326:     if ($put_result !~ /^(ok|delayed)/) {
10327:         &Apache::lonnet::logthis('unable to save form parameters, '.
10328:                                  'got error:'.$put_result);
10329:     }
10330:     # Make sure these settings stick around in this session, too
10331:     &Apache::lonnet::appenv(\%AppHash);
10332:     return;
10333: }
10334: 
10335: sub restore_course_settings {
10336:     return &restore_settings($env{'request.course.id'},@_);
10337: }
10338: 
10339: sub restore_settings {
10340:     my ($context,$prefix,$Settings) = @_;
10341:     while (my ($setting,$type) = each(%$Settings)) {
10342:         next if (exists($env{'form.'.$setting}));
10343:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
10344:             '.'.$setting;
10345:         if (exists($env{$envname})) {
10346:             if ($type eq 'scalar') {
10347:                 $env{'form.'.$setting} = $env{$envname};
10348:             } elsif ($type eq 'array') {
10349:                 $env{'form.'.$setting} = [ 
10350:                                            map { 
10351:                                                &unescape($_); 
10352:                                            } split(',',$env{$envname})
10353:                                            ];
10354:             }
10355:         }
10356:     }
10357: }
10358: 
10359: #######################################################
10360: #######################################################
10361: 
10362: =pod
10363: 
10364: =head1 Domain E-mail Routines  
10365: 
10366: =over 4
10367: 
10368: =item * &build_recipient_list()
10369: 
10370: Build recipient lists for five types of e-mail:
10371: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
10372: (d) Help requests, (e) Course requests needing approval,  generated by
10373: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
10374: loncoursequeueadmin.pm respectively.
10375: 
10376: Inputs:
10377: defmail (scalar - email address of default recipient), 
10378: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
10379: defdom (domain for which to retrieve configuration settings),
10380: origmail (scalar - email address of recipient from loncapa.conf, 
10381: i.e., predates configuration by DC via domainprefs.pm 
10382: 
10383: Returns: comma separated list of addresses to which to send e-mail.
10384: 
10385: =back
10386: 
10387: =cut
10388: 
10389: ############################################################
10390: ############################################################
10391: sub build_recipient_list {
10392:     my ($defmail,$mailing,$defdom,$origmail) = @_;
10393:     my @recipients;
10394:     my $otheremails;
10395:     my %domconfig =
10396:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
10397:     if (ref($domconfig{'contacts'}) eq 'HASH') {
10398:         if (exists($domconfig{'contacts'}{$mailing})) {
10399:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
10400:                 my @contacts = ('adminemail','supportemail');
10401:                 foreach my $item (@contacts) {
10402:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
10403:                         my $addr = $domconfig{'contacts'}{$item}; 
10404:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
10405:                             push(@recipients,$addr);
10406:                         }
10407:                     }
10408:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
10409:                 }
10410:             }
10411:         } elsif ($origmail ne '') {
10412:             push(@recipients,$origmail);
10413:         }
10414:     } elsif ($origmail ne '') {
10415:         push(@recipients,$origmail);
10416:     }
10417:     if (defined($defmail)) {
10418:         if ($defmail ne '') {
10419:             push(@recipients,$defmail);
10420:         }
10421:     }
10422:     if ($otheremails) {
10423:         my @others;
10424:         if ($otheremails =~ /,/) {
10425:             @others = split(/,/,$otheremails);
10426:         } else {
10427:             push(@others,$otheremails);
10428:         }
10429:         foreach my $addr (@others) {
10430:             if (!grep(/^\Q$addr\E$/,@recipients)) {
10431:                 push(@recipients,$addr);
10432:             }
10433:         }
10434:     }
10435:     my $recipientlist = join(',',@recipients); 
10436:     return $recipientlist;
10437: }
10438: 
10439: ############################################################
10440: ############################################################
10441: 
10442: =pod
10443: 
10444: =head1 Course Catalog Routines
10445: 
10446: =over 4
10447: 
10448: =item * &gather_categories()
10449: 
10450: Converts category definitions - keys of categories hash stored in  
10451: coursecategories in configuration.db on the primary library server in a 
10452: domain - to an array.  Also generates javascript and idx hash used to 
10453: generate Domain Coordinator interface for editing Course Categories.
10454: 
10455: Inputs:
10456: 
10457: categories (reference to hash of category definitions).
10458: 
10459: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10460:       categories and subcategories).
10461: 
10462: idx (reference to hash of counters used in Domain Coordinator interface for 
10463:       editing Course Categories).
10464: 
10465: jsarray (reference to array of categories used to create Javascript arrays for
10466:          Domain Coordinator interface for editing Course Categories).
10467: 
10468: Returns: nothing
10469: 
10470: Side effects: populates cats, idx and jsarray. 
10471: 
10472: =cut
10473: 
10474: sub gather_categories {
10475:     my ($categories,$cats,$idx,$jsarray) = @_;
10476:     my %counters;
10477:     my $num = 0;
10478:     foreach my $item (keys(%{$categories})) {
10479:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
10480:         if ($container eq '' && $depth == 0) {
10481:             $cats->[$depth][$categories->{$item}] = $cat;
10482:         } else {
10483:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
10484:         }
10485:         my ($escitem,$tail) = split(/:/,$item,2);
10486:         if ($counters{$tail} eq '') {
10487:             $counters{$tail} = $num;
10488:             $num ++;
10489:         }
10490:         if (ref($idx) eq 'HASH') {
10491:             $idx->{$item} = $counters{$tail};
10492:         }
10493:         if (ref($jsarray) eq 'ARRAY') {
10494:             push(@{$jsarray->[$counters{$tail}]},$item);
10495:         }
10496:     }
10497:     return;
10498: }
10499: 
10500: =pod
10501: 
10502: =item * &extract_categories()
10503: 
10504: Used to generate breadcrumb trails for course categories.
10505: 
10506: Inputs:
10507: 
10508: categories (reference to hash of category definitions).
10509: 
10510: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10511:       categories and subcategories).
10512: 
10513: trails (reference to array of breacrumb trails for each category).
10514: 
10515: allitems (reference to hash - key is category key 
10516:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10517: 
10518: idx (reference to hash of counters used in Domain Coordinator interface for
10519:       editing Course Categories).
10520: 
10521: jsarray (reference to array of categories used to create Javascript arrays for
10522:          Domain Coordinator interface for editing Course Categories).
10523: 
10524: subcats (reference to hash of arrays containing all subcategories within each 
10525:          category, -recursive)
10526: 
10527: Returns: nothing
10528: 
10529: Side effects: populates trails and allitems hash references.
10530: 
10531: =cut
10532: 
10533: sub extract_categories {
10534:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
10535:     if (ref($categories) eq 'HASH') {
10536:         &gather_categories($categories,$cats,$idx,$jsarray);
10537:         if (ref($cats->[0]) eq 'ARRAY') {
10538:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
10539:                 my $name = $cats->[0][$i];
10540:                 my $item = &escape($name).'::0';
10541:                 my $trailstr;
10542:                 if ($name eq 'instcode') {
10543:                     $trailstr = &mt('Official courses (with institutional codes)');
10544:                 } elsif ($name eq 'communities') {
10545:                     $trailstr = &mt('Communities');
10546:                 } else {
10547:                     $trailstr = $name;
10548:                 }
10549:                 if ($allitems->{$item} eq '') {
10550:                     push(@{$trails},$trailstr);
10551:                     $allitems->{$item} = scalar(@{$trails})-1;
10552:                 }
10553:                 my @parents = ($name);
10554:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
10555:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
10556:                         my $category = $cats->[1]{$name}[$j];
10557:                         if (ref($subcats) eq 'HASH') {
10558:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
10559:                         }
10560:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
10561:                     }
10562:                 } else {
10563:                     if (ref($subcats) eq 'HASH') {
10564:                         $subcats->{$item} = [];
10565:                     }
10566:                 }
10567:             }
10568:         }
10569:     }
10570:     return;
10571: }
10572: 
10573: =pod
10574: 
10575: =item *&recurse_categories()
10576: 
10577: Recursively used to generate breadcrumb trails for course categories.
10578: 
10579: Inputs:
10580: 
10581: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10582:       categories and subcategories).
10583: 
10584: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
10585: 
10586: category (current course category, for which breadcrumb trail is being generated).
10587: 
10588: trails (reference to array of breadcrumb trails for each category).
10589: 
10590: allitems (reference to hash - key is category key
10591:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10592: 
10593: parents (array containing containers directories for current category, 
10594:          back to top level). 
10595: 
10596: Returns: nothing
10597: 
10598: Side effects: populates trails and allitems hash references
10599: 
10600: =cut
10601: 
10602: sub recurse_categories {
10603:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
10604:     my $shallower = $depth - 1;
10605:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
10606:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
10607:             my $name = $cats->[$depth]{$category}[$k];
10608:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10609:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
10610:             if ($allitems->{$item} eq '') {
10611:                 push(@{$trails},$trailstr);
10612:                 $allitems->{$item} = scalar(@{$trails})-1;
10613:             }
10614:             my $deeper = $depth+1;
10615:             push(@{$parents},$category);
10616:             if (ref($subcats) eq 'HASH') {
10617:                 my $subcat = &escape($name).':'.$category.':'.$depth;
10618:                 for (my $j=@{$parents}; $j>=0; $j--) {
10619:                     my $higher;
10620:                     if ($j > 0) {
10621:                         $higher = &escape($parents->[$j]).':'.
10622:                                   &escape($parents->[$j-1]).':'.$j;
10623:                     } else {
10624:                         $higher = &escape($parents->[$j]).'::'.$j;
10625:                     }
10626:                     push(@{$subcats->{$higher}},$subcat);
10627:                 }
10628:             }
10629:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
10630:                                 $subcats);
10631:             pop(@{$parents});
10632:         }
10633:     } else {
10634:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10635:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
10636:         if ($allitems->{$item} eq '') {
10637:             push(@{$trails},$trailstr);
10638:             $allitems->{$item} = scalar(@{$trails})-1;
10639:         }
10640:     }
10641:     return;
10642: }
10643: 
10644: =pod
10645: 
10646: =item *&assign_categories_table()
10647: 
10648: Create a datatable for display of hierarchical categories in a domain,
10649: with checkboxes to allow a course to be categorized. 
10650: 
10651: Inputs:
10652: 
10653: cathash - reference to hash of categories defined for the domain (from
10654:           configuration.db)
10655: 
10656: currcat - scalar with an & separated list of categories assigned to a course. 
10657: 
10658: type    - scalar contains course type (Course or Community).
10659: 
10660: Returns: $output (markup to be displayed) 
10661: 
10662: =cut
10663: 
10664: sub assign_categories_table {
10665:     my ($cathash,$currcat,$type) = @_;
10666:     my $output;
10667:     if (ref($cathash) eq 'HASH') {
10668:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
10669:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
10670:         $maxdepth = scalar(@cats);
10671:         if (@cats > 0) {
10672:             my $itemcount = 0;
10673:             if (ref($cats[0]) eq 'ARRAY') {
10674:                 my @currcategories;
10675:                 if ($currcat ne '') {
10676:                     @currcategories = split('&',$currcat);
10677:                 }
10678:                 my $table;
10679:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
10680:                     my $parent = $cats[0][$i];
10681:                     next if ($parent eq 'instcode');
10682:                     if ($type eq 'Community') {
10683:                         next unless ($parent eq 'communities');
10684:                     } else {
10685:                         next if ($parent eq 'communities');
10686:                     }
10687:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10688:                     my $item = &escape($parent).'::0';
10689:                     my $checked = '';
10690:                     if (@currcategories > 0) {
10691:                         if (grep(/^\Q$item\E$/,@currcategories)) {
10692:                             $checked = ' checked="checked"';
10693:                         }
10694:                     }
10695:                     my $parent_title = $parent;
10696:                     if ($parent eq 'communities') {
10697:                         $parent_title = &mt('Communities');
10698:                     }
10699:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
10700:                               '<input type="checkbox" name="usecategory" value="'.
10701:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
10702:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
10703:                     my $depth = 1;
10704:                     push(@path,$parent);
10705:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
10706:                     pop(@path);
10707:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10708:                     $itemcount ++;
10709:                 }
10710:                 if ($itemcount) {
10711:                     $output = &Apache::loncommon::start_data_table().
10712:                               $table.
10713:                               &Apache::loncommon::end_data_table();
10714:                 }
10715:             }
10716:         }
10717:     }
10718:     return $output;
10719: }
10720: 
10721: =pod
10722: 
10723: =item *&assign_category_rows()
10724: 
10725: Create a datatable row for display of nested categories in a domain,
10726: with checkboxes to allow a course to be categorized,called recursively.
10727: 
10728: Inputs:
10729: 
10730: itemcount - track row number for alternating colors
10731: 
10732: cats - reference to array of arrays/hashes which encapsulates hierarchy of
10733:       categories and subcategories.
10734: 
10735: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
10736: 
10737: parent - parent of current category item
10738: 
10739: path - Array containing all categories back up through the hierarchy from the
10740:        current category to the top level.
10741: 
10742: currcategories - reference to array of current categories assigned to the course
10743: 
10744: Returns: $output (markup to be displayed).
10745: 
10746: =cut
10747: 
10748: sub assign_category_rows {
10749:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
10750:     my ($text,$name,$item,$chgstr);
10751:     if (ref($cats) eq 'ARRAY') {
10752:         my $maxdepth = scalar(@{$cats});
10753:         if (ref($cats->[$depth]) eq 'HASH') {
10754:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10755:                 my $numchildren = @{$cats->[$depth]{$parent}};
10756:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10757:                 $text .= '<td><table class="LC_datatable">';
10758:                 for (my $j=0; $j<$numchildren; $j++) {
10759:                     $name = $cats->[$depth]{$parent}[$j];
10760:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
10761:                     my $deeper = $depth+1;
10762:                     my $checked = '';
10763:                     if (ref($currcategories) eq 'ARRAY') {
10764:                         if (@{$currcategories} > 0) {
10765:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
10766:                                 $checked = ' checked="checked"';
10767:                             }
10768:                         }
10769:                     }
10770:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
10771:                              '<input type="checkbox" name="usecategory" value="'.
10772:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
10773:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
10774:                              '</td><td>';
10775:                     if (ref($path) eq 'ARRAY') {
10776:                         push(@{$path},$name);
10777:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
10778:                         pop(@{$path});
10779:                     }
10780:                     $text .= '</td></tr>';
10781:                 }
10782:                 $text .= '</table></td>';
10783:             }
10784:         }
10785:     }
10786:     return $text;
10787: }
10788: 
10789: ############################################################
10790: ############################################################
10791: 
10792: 
10793: sub commit_customrole {
10794:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
10795:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
10796:                          ($start?', '.&mt('starting').' '.localtime($start):'').
10797:                          ($end?', ending '.localtime($end):'').': <b>'.
10798:               &Apache::lonnet::assigncustomrole(
10799:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
10800:                  '</b><br />';
10801:     return $output;
10802: }
10803: 
10804: sub commit_standardrole {
10805:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10806:     my ($output,$logmsg,$linefeed);
10807:     if ($context eq 'auto') {
10808:         $linefeed = "\n";
10809:     } else {
10810:         $linefeed = "<br />\n";
10811:     }  
10812:     if ($three eq 'st') {
10813:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
10814:                                          $one,$two,$sec,$context);
10815:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
10816:             ($result eq 'unknown_course') || ($result eq 'refused')) {
10817:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
10818:         } else {
10819:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
10820:                ($start?', '.&mt('starting').' '.localtime($start):'').
10821:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10822:             if ($context eq 'auto') {
10823:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
10824:             } else {
10825:                $output .= '<b>'.$result.'</b>'.$linefeed.
10826:                &mt('Add to classlist').': <b>ok</b>';
10827:             }
10828:             $output .= $linefeed;
10829:         }
10830:     } else {
10831:         $output = &mt('Assigning').' '.$three.' in '.$url.
10832:                ($start?', '.&mt('starting').' '.localtime($start):'').
10833:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10834:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10835:         if ($context eq 'auto') {
10836:             $output .= $result.$linefeed;
10837:         } else {
10838:             $output .= '<b>'.$result.'</b>'.$linefeed;
10839:         }
10840:     }
10841:     return $output;
10842: }
10843: 
10844: sub commit_studentrole {
10845:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10846:     my ($result,$linefeed,$oldsecurl,$newsecurl);
10847:     if ($context eq 'auto') {
10848:         $linefeed = "\n";
10849:     } else {
10850:         $linefeed = '<br />'."\n";
10851:     }
10852:     if (defined($one) && defined($two)) {
10853:         my $cid=$one.'_'.$two;
10854:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10855:         my $secchange = 0;
10856:         my $expire_role_result;
10857:         my $modify_section_result;
10858:         if ($oldsec ne '-1') { 
10859:             if ($oldsec ne $sec) {
10860:                 $secchange = 1;
10861:                 my $now = time;
10862:                 my $uurl='/'.$cid;
10863:                 $uurl=~s/\_/\//g;
10864:                 if ($oldsec) {
10865:                     $uurl.='/'.$oldsec;
10866:                 }
10867:                 $oldsecurl = $uurl;
10868:                 $expire_role_result = 
10869:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10870:                 if ($env{'request.course.sec'} ne '') { 
10871:                     if ($expire_role_result eq 'refused') {
10872:                         my @roles = ('st');
10873:                         my @statuses = ('previous');
10874:                         my @roledoms = ($one);
10875:                         my $withsec = 1;
10876:                         my %roleshash = 
10877:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10878:                                               \@statuses,\@roles,\@roledoms,$withsec);
10879:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10880:                             my ($oldstart,$oldend) = 
10881:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10882:                             if ($oldend > 0 && $oldend <= $now) {
10883:                                 $expire_role_result = 'ok';
10884:                             }
10885:                         }
10886:                     }
10887:                 }
10888:                 $result = $expire_role_result;
10889:             }
10890:         }
10891:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10892:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10893:             if ($modify_section_result =~ /^ok/) {
10894:                 if ($secchange == 1) {
10895:                     if ($sec eq '') {
10896:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10897:                     } else {
10898:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10899:                     }
10900:                 } elsif ($oldsec eq '-1') {
10901:                     if ($sec eq '') {
10902:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10903:                     } else {
10904:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10905:                     }
10906:                 } else {
10907:                     if ($sec eq '') {
10908:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10909:                     } else {
10910:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10911:                     }
10912:                 }
10913:             } else {
10914:                 if ($secchange) {       
10915:                     $$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;
10916:                 } else {
10917:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10918:                 }
10919:             }
10920:             $result = $modify_section_result;
10921:         } elsif ($secchange == 1) {
10922:             if ($oldsec eq '') {
10923:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10924:             } else {
10925:                 $$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;
10926:             }
10927:             if ($expire_role_result eq 'refused') {
10928:                 my $newsecurl = '/'.$cid;
10929:                 $newsecurl =~ s/\_/\//g;
10930:                 if ($sec ne '') {
10931:                     $newsecurl.='/'.$sec;
10932:                 }
10933:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10934:                     if ($sec eq '') {
10935:                         $$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;
10936:                     } else {
10937:                         $$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;
10938:                     }
10939:                 }
10940:             }
10941:         }
10942:     } else {
10943:         $$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;
10944:         $result = "error: incomplete course id\n";
10945:     }
10946:     return $result;
10947: }
10948: 
10949: ############################################################
10950: ############################################################
10951: 
10952: sub check_clone {
10953:     my ($args,$linefeed) = @_;
10954:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10955:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10956:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10957:     my $clonemsg;
10958:     my $can_clone = 0;
10959:     my $lctype = lc($args->{'crstype'});
10960:     if ($lctype ne 'community') {
10961:         $lctype = 'course';
10962:     }
10963:     if ($clonehome eq 'no_host') {
10964:         if ($args->{'crstype'} eq 'Community') {
10965:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10966:         } else {
10967:             $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'});
10968:         }     
10969:     } else {
10970: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10971:         if ($args->{'crstype'} eq 'Community') {
10972:             if ($clonedesc{'type'} ne 'Community') {
10973:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10974:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
10975:             }
10976:         }
10977: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
10978:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10979: 	    $can_clone = 1;
10980: 	} else {
10981: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10982: 						 $args->{'clonedomain'},$args->{'clonecourse'});
10983: 	    my @cloners = split(/,/,$clonehash{'cloners'});
10984:             if (grep(/^\*$/,@cloners)) {
10985:                 $can_clone = 1;
10986:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10987:                 $can_clone = 1;
10988:             } else {
10989:                 my $ccrole = 'cc';
10990:                 if ($args->{'crstype'} eq 'Community') {
10991:                     $ccrole = 'co';
10992:                 }
10993: 	        my %roleshash =
10994: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
10995: 					 $args->{'ccdomain'},
10996:                                          'userroles',['active'],[$ccrole],
10997: 					 [$args->{'clonedomain'}]);
10998: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10999:                     $can_clone = 1;
11000:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
11001:                     $can_clone = 1;
11002:                 } else {
11003:                     if ($args->{'crstype'} eq 'Community') {
11004:                         $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
11005:                     } else {
11006:                         $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'});
11007:                     }
11008: 	        }
11009: 	    }
11010:         }
11011:     }
11012:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
11013: }
11014: 
11015: sub construct_course {
11016:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
11017:     my $outcome;
11018:     my $linefeed =  '<br />'."\n";
11019:     if ($context eq 'auto') {
11020:         $linefeed = "\n";
11021:     }
11022: 
11023: #
11024: # Are we cloning?
11025: #
11026:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
11027:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
11028: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
11029: 	if ($context ne 'auto') {
11030:             if ($clonemsg ne '') {
11031: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
11032:             }
11033: 	}
11034: 	$outcome .= $clonemsg.$linefeed;
11035: 
11036:         if (!$can_clone) {
11037: 	    return (0,$outcome);
11038: 	}
11039:     }
11040: 
11041: #
11042: # Open course
11043: #
11044:     my $crstype = lc($args->{'crstype'});
11045:     my %cenv=();
11046:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
11047:                                              $args->{'cdescr'},
11048:                                              $args->{'curl'},
11049:                                              $args->{'course_home'},
11050:                                              $args->{'nonstandard'},
11051:                                              $args->{'crscode'},
11052:                                              $args->{'ccuname'}.':'.
11053:                                              $args->{'ccdomain'},
11054:                                              $args->{'crstype'},
11055:                                              $cnum,$context,$category);
11056: 
11057:     # Note: The testing routines depend on this being output; see 
11058:     # Utils::Course. This needs to at least be output as a comment
11059:     # if anyone ever decides to not show this, and Utils::Course::new
11060:     # will need to be suitably modified.
11061:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
11062:     if ($$courseid =~ /^error:/) {
11063:         return (0,$outcome);
11064:     }
11065: 
11066: #
11067: # Check if created correctly
11068: #
11069:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
11070:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
11071:     if ($crsuhome eq 'no_host') {
11072:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
11073:         return (0,$outcome);
11074:     }
11075:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
11076: 
11077: #
11078: # Do the cloning
11079: #   
11080:     if ($can_clone && $cloneid) {
11081: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
11082: 	if ($context ne 'auto') {
11083: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
11084: 	}
11085: 	$outcome .= $clonemsg.$linefeed;
11086: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
11087: # Copy all files
11088: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
11089: # Restore URL
11090: 	$cenv{'url'}=$oldcenv{'url'};
11091: # Restore title
11092: 	$cenv{'description'}=$oldcenv{'description'};
11093: # Restore creation date, creator and creation context.
11094:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
11095:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
11096:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
11097: # Mark as cloned
11098: 	$cenv{'clonedfrom'}=$cloneid;
11099: # Need to clone grading mode
11100:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
11101:         $cenv{'grading'}=$newenv{'grading'};
11102: # Do not clone these environment entries
11103:         &Apache::lonnet::del('environment',
11104:                   ['default_enrollment_start_date',
11105:                    'default_enrollment_end_date',
11106:                    'question.email',
11107:                    'policy.email',
11108:                    'comment.email',
11109:                    'pch.users.denied',
11110:                    'plc.users.denied',
11111:                    'hidefromcat',
11112:                    'categories'],
11113:                    $$crsudom,$$crsunum);
11114:     }
11115: 
11116: #
11117: # Set environment (will override cloned, if existing)
11118: #
11119:     my @sections = ();
11120:     my @xlists = ();
11121:     if ($args->{'crstype'}) {
11122:         $cenv{'type'}=$args->{'crstype'};
11123:     }
11124:     if ($args->{'crsid'}) {
11125:         $cenv{'courseid'}=$args->{'crsid'};
11126:     }
11127:     if ($args->{'crscode'}) {
11128:         $cenv{'internal.coursecode'}=$args->{'crscode'};
11129:     }
11130:     if ($args->{'crsquota'} ne '') {
11131:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
11132:     } else {
11133:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
11134:     }
11135:     if ($args->{'ccuname'}) {
11136:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
11137:                                         ':'.$args->{'ccdomain'};
11138:     } else {
11139:         $cenv{'internal.courseowner'} = $args->{'curruser'};
11140:     }
11141:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
11142:     if ($args->{'crssections'}) {
11143:         $cenv{'internal.sectionnums'} = '';
11144:         if ($args->{'crssections'} =~ m/,/) {
11145:             @sections = split/,/,$args->{'crssections'};
11146:         } else {
11147:             $sections[0] = $args->{'crssections'};
11148:         }
11149:         if (@sections > 0) {
11150:             foreach my $item (@sections) {
11151:                 my ($sec,$gp) = split/:/,$item;
11152:                 my $class = $args->{'crscode'}.$sec;
11153:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
11154:                 $cenv{'internal.sectionnums'} .= $item.',';
11155:                 unless ($addcheck eq 'ok') {
11156:                     push @badclasses, $class;
11157:                 }
11158:             }
11159:             $cenv{'internal.sectionnums'} =~ s/,$//;
11160:         }
11161:     }
11162: # do not hide course coordinator from staff listing, 
11163: # even if privileged
11164:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11165: # add crosslistings
11166:     if ($args->{'crsxlist'}) {
11167:         $cenv{'internal.crosslistings'}='';
11168:         if ($args->{'crsxlist'} =~ m/,/) {
11169:             @xlists = split/,/,$args->{'crsxlist'};
11170:         } else {
11171:             $xlists[0] = $args->{'crsxlist'};
11172:         }
11173:         if (@xlists > 0) {
11174:             foreach my $item (@xlists) {
11175:                 my ($xl,$gp) = split/:/,$item;
11176:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
11177:                 $cenv{'internal.crosslistings'} .= $item.',';
11178:                 unless ($addcheck eq 'ok') {
11179:                     push @badclasses, $xl;
11180:                 }
11181:             }
11182:             $cenv{'internal.crosslistings'} =~ s/,$//;
11183:         }
11184:     }
11185:     if ($args->{'autoadds'}) {
11186:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
11187:     }
11188:     if ($args->{'autodrops'}) {
11189:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
11190:     }
11191: # check for notification of enrollment changes
11192:     my @notified = ();
11193:     if ($args->{'notify_owner'}) {
11194:         if ($args->{'ccuname'} ne '') {
11195:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
11196:         }
11197:     }
11198:     if ($args->{'notify_dc'}) {
11199:         if ($uname ne '') { 
11200:             push(@notified,$uname.':'.$udom);
11201:         }
11202:     }
11203:     if (@notified > 0) {
11204:         my $notifylist;
11205:         if (@notified > 1) {
11206:             $notifylist = join(',',@notified);
11207:         } else {
11208:             $notifylist = $notified[0];
11209:         }
11210:         $cenv{'internal.notifylist'} = $notifylist;
11211:     }
11212:     if (@badclasses > 0) {
11213:         my %lt=&Apache::lonlocal::texthash(
11214:                 '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',
11215:                 'dnhr' => 'does not have rights to access enrollment in these classes',
11216:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
11217:         );
11218:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
11219:                            ' ('.$lt{'adby'}.')';
11220:         if ($context eq 'auto') {
11221:             $outcome .= $badclass_msg.$linefeed;
11222:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
11223:             foreach my $item (@badclasses) {
11224:                 if ($context eq 'auto') {
11225:                     $outcome .= " - $item\n";
11226:                 } else {
11227:                     $outcome .= "<li>$item</li>\n";
11228:                 }
11229:             }
11230:             if ($context eq 'auto') {
11231:                 $outcome .= $linefeed;
11232:             } else {
11233:                 $outcome .= "</ul><br /><br /></div>\n";
11234:             }
11235:         } 
11236:     }
11237:     if ($args->{'no_end_date'}) {
11238:         $args->{'endaccess'} = 0;
11239:     }
11240:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
11241:     $cenv{'internal.autoend'}=$args->{'enrollend'};
11242:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
11243:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
11244:     if ($args->{'showphotos'}) {
11245:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
11246:     }
11247:     $cenv{'internal.authtype'} = $args->{'authtype'};
11248:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
11249:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
11250:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
11251:             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'); 
11252:             if ($context eq 'auto') {
11253:                 $outcome .= $krb_msg;
11254:             } else {
11255:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
11256:             }
11257:             $outcome .= $linefeed;
11258:         }
11259:     }
11260:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
11261:        if ($args->{'setpolicy'}) {
11262:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11263:        }
11264:        if ($args->{'setcontent'}) {
11265:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11266:        }
11267:     }
11268:     if ($args->{'reshome'}) {
11269: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
11270: 	$cenv{'reshome'}=~s/\/+$/\//;
11271:     }
11272: #
11273: # course has keyed access
11274: #
11275:     if ($args->{'setkeys'}) {
11276:        $cenv{'keyaccess'}='yes';
11277:     }
11278: # if specified, key authority is not course, but user
11279: # only active if keyaccess is yes
11280:     if ($args->{'keyauth'}) {
11281: 	my ($user,$domain) = split(':',$args->{'keyauth'});
11282: 	$user = &LONCAPA::clean_username($user);
11283: 	$domain = &LONCAPA::clean_username($domain);
11284: 	if ($user ne '' && $domain ne '') {
11285: 	    $cenv{'keyauth'}=$user.':'.$domain;
11286: 	}
11287:     }
11288: 
11289:     if ($args->{'disresdis'}) {
11290:         $cenv{'pch.roles.denied'}='st';
11291:     }
11292:     if ($args->{'disablechat'}) {
11293:         $cenv{'plc.roles.denied'}='st';
11294:     }
11295: 
11296:     # Record we've not yet viewed the Course Initialization Helper for this 
11297:     # course
11298:     $cenv{'course.helper.not.run'} = 1;
11299:     #
11300:     # Use new Randomseed
11301:     #
11302:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
11303:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
11304:     #
11305:     # The encryption code and receipt prefix for this course
11306:     #
11307:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
11308:     $cenv{'internal.encpref'}=100+int(9*rand(99));
11309:     #
11310:     # By default, use standard grading
11311:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
11312: 
11313:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
11314:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
11315: #
11316: # Open all assignments
11317: #
11318:     if ($args->{'openall'}) {
11319:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
11320:        my %storecontent = ($storeunder         => time,
11321:                            $storeunder.'.type' => 'date_start');
11322:        
11323:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
11324:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
11325:    }
11326: #
11327: # Set first page
11328: #
11329:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
11330: 	    || ($cloneid)) {
11331: 	use LONCAPA::map;
11332: 	$outcome .= &mt('Setting first resource').': ';
11333: 
11334: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
11335:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
11336: 
11337:         $outcome .= ($fatal?$errtext:'read ok').' - ';
11338:         my $title; my $url;
11339:         if ($args->{'firstres'} eq 'syl') {
11340: 	    $title=&mt('Syllabus');
11341:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
11342:         } else {
11343:             $title=&mt('Table of Contents');
11344:             $url='/adm/navmaps';
11345:         }
11346: 
11347:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
11348: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
11349: 
11350: 	if ($errtext) { $fatal=2; }
11351:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
11352:     }
11353: 
11354:     return (1,$outcome);
11355: }
11356: 
11357: ############################################################
11358: ############################################################
11359: 
11360: #SD
11361: # only Community and Course, or anything else?
11362: sub course_type {
11363:     my ($cid) = @_;
11364:     if (!defined($cid)) {
11365:         $cid = $env{'request.course.id'};
11366:     }
11367:     if (defined($env{'course.'.$cid.'.type'})) {
11368:         return $env{'course.'.$cid.'.type'};
11369:     } else {
11370:         return 'Course';
11371:     }
11372: }
11373: 
11374: sub group_term {
11375:     my $crstype = &course_type();
11376:     my %names = (
11377:                   'Course' => 'group',
11378:                   'Community' => 'group',
11379:                 );
11380:     return $names{$crstype};
11381: }
11382: 
11383: sub course_types {
11384:     my @types = ('official','unofficial','community');
11385:     my %typename = (
11386:                          official   => 'Official course',
11387:                          unofficial => 'Unofficial course',
11388:                          community  => 'Community',
11389:                    );
11390:     return (\@types,\%typename);
11391: }
11392: 
11393: sub icon {
11394:     my ($file)=@_;
11395:     my $curfext = lc((split(/\./,$file))[-1]);
11396:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
11397:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
11398:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
11399: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
11400: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11401: 	            $curfext.".gif") {
11402: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11403: 		$curfext.".gif";
11404: 	}
11405:     }
11406:     return &lonhttpdurl($iconname);
11407: } 
11408: 
11409: sub lonhttpdurl {
11410: #
11411: # Had been used for "small fry" static images on separate port 8080.
11412: # Modify here if lightweight http functionality desired again.
11413: # Currently eliminated due to increasing firewall issues.
11414: #
11415:     my ($url)=@_;
11416:     return $url;
11417: }
11418: 
11419: sub connection_aborted {
11420:     my ($r)=@_;
11421:     $r->print(" ");$r->rflush();
11422:     my $c = $r->connection;
11423:     return $c->aborted();
11424: }
11425: 
11426: #    Escapes strings that may have embedded 's that will be put into
11427: #    strings as 'strings'.
11428: sub escape_single {
11429:     my ($input) = @_;
11430:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
11431:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
11432:     return $input;
11433: }
11434: 
11435: #  Same as escape_single, but escape's "'s  This 
11436: #  can be used for  "strings"
11437: sub escape_double {
11438:     my ($input) = @_;
11439:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
11440:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
11441:     return $input;
11442: }
11443:  
11444: #   Escapes the last element of a full URL.
11445: sub escape_url {
11446:     my ($url)   = @_;
11447:     my @urlslices = split(/\//, $url,-1);
11448:     my $lastitem = &escape(pop(@urlslices));
11449:     return join('/',@urlslices).'/'.$lastitem;
11450: }
11451: 
11452: sub compare_arrays {
11453:     my ($arrayref1,$arrayref2) = @_;
11454:     my (@difference,%count);
11455:     @difference = ();
11456:     %count = ();
11457:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
11458:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
11459:         foreach my $element (keys(%count)) {
11460:             if ($count{$element} == 1) {
11461:                 push(@difference,$element);
11462:             }
11463:         }
11464:     }
11465:     return @difference;
11466: }
11467: 
11468: # -------------------------------------------------------- Initialize user login
11469: sub init_user_environment {
11470:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
11471:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
11472: 
11473:     my $public=($username eq 'public' && $domain eq 'public');
11474: 
11475: # See if old ID present, if so, remove
11476: 
11477:     my ($filename,$cookie,$userroles);
11478:     my $now=time;
11479: 
11480:     if ($public) {
11481: 	my $max_public=100;
11482: 	my $oldest;
11483: 	my $oldest_time=0;
11484: 	for(my $next=1;$next<=$max_public;$next++) {
11485: 	    if (-e $lonids."/publicuser_$next.id") {
11486: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
11487: 		if ($mtime<$oldest_time || !$oldest_time) {
11488: 		    $oldest_time=$mtime;
11489: 		    $oldest=$next;
11490: 		}
11491: 	    } else {
11492: 		$cookie="publicuser_$next";
11493: 		last;
11494: 	    }
11495: 	}
11496: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
11497:     } else {
11498: 	# if this isn't a robot, kill any existing non-robot sessions
11499: 	if (!$args->{'robot'}) {
11500: 	    opendir(DIR,$lonids);
11501: 	    while ($filename=readdir(DIR)) {
11502: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
11503: 		    unlink($lonids.'/'.$filename);
11504: 		}
11505: 	    }
11506: 	    closedir(DIR);
11507: 	}
11508: # Give them a new cookie
11509: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
11510: 		                   : $now.$$.int(rand(10000)));
11511: 	$cookie="$username\_$id\_$domain\_$authhost";
11512:     
11513: # Initialize roles
11514: 
11515: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
11516:     }
11517: # ------------------------------------ Check browser type and MathML capability
11518: 
11519:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
11520:         $clientunicode,$clientos) = &decode_user_agent($r);
11521: 
11522: # ------------------------------------------------------------- Get environment
11523: 
11524:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
11525:     my ($tmp) = keys(%userenv);
11526:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11527:     } else {
11528: 	undef(%userenv);
11529:     }
11530:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
11531: 	$form->{'interface'}=$userenv{'interface'};
11532:     }
11533:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
11534: 
11535: # --------------- Do not trust query string to be put directly into environment
11536:     foreach my $option ('interface','localpath','localres') {
11537:         $form->{$option}=~s/[\n\r\=]//gs;
11538:     }
11539: # --------------------------------------------------------- Write first profile
11540: 
11541:     {
11542: 	my %initial_env = 
11543: 	    ("user.name"          => $username,
11544: 	     "user.domain"        => $domain,
11545: 	     "user.home"          => $authhost,
11546: 	     "browser.type"       => $clientbrowser,
11547: 	     "browser.version"    => $clientversion,
11548: 	     "browser.mathml"     => $clientmathml,
11549: 	     "browser.unicode"    => $clientunicode,
11550: 	     "browser.os"         => $clientos,
11551: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
11552: 	     "request.course.fn"  => '',
11553: 	     "request.course.uri" => '',
11554: 	     "request.course.sec" => '',
11555: 	     "request.role"       => 'cm',
11556: 	     "request.role.adv"   => $env{'user.adv'},
11557: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
11558: 
11559:         if ($form->{'localpath'}) {
11560: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
11561: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
11562:         }
11563: 	
11564: 	if ($form->{'interface'}) {
11565: 	    $form->{'interface'}=~s/\W//gs;
11566: 	    $initial_env{"browser.interface"} = $form->{'interface'};
11567: 	    $env{'browser.interface'}=$form->{'interface'};
11568: 	}
11569: 
11570:         my %is_adv = ( is_adv => $env{'user.adv'} );
11571:         my %domdef;
11572:         unless ($domain eq 'public') {
11573:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
11574:         }
11575: 
11576:         foreach my $tool ('aboutme','blog','portfolio') {
11577:             $userenv{'availabletools.'.$tool} = 
11578:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
11579:                                                   undef,\%userenv,\%domdef,\%is_adv);
11580:         }
11581: 
11582:         foreach my $crstype ('official','unofficial','community') {
11583:             $userenv{'canrequest.'.$crstype} =
11584:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
11585:                                                   'reload','requestcourses',
11586:                                                   \%userenv,\%domdef,\%is_adv);
11587:         }
11588: 
11589: 	$env{'user.environment'} = "$lonids/$cookie.id";
11590: 	
11591: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
11592: 		 &GDBM_WRCREAT(),0640)) {
11593: 	    &_add_to_env(\%disk_env,\%initial_env);
11594: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
11595: 	    &_add_to_env(\%disk_env,$userroles);
11596: 	    if (ref($args->{'extra_env'})) {
11597: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
11598: 	    }
11599: 	    untie(%disk_env);
11600: 	} else {
11601: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
11602: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
11603: 	    return 'error: '.$!;
11604: 	}
11605:     }
11606:     $env{'request.role'}='cm';
11607:     $env{'request.role.adv'}=$env{'user.adv'};
11608:     $env{'browser.type'}=$clientbrowser;
11609: 
11610:     return $cookie;
11611: 
11612: }
11613: 
11614: sub _add_to_env {
11615:     my ($idf,$env_data,$prefix) = @_;
11616:     if (ref($env_data) eq 'HASH') {
11617:         while (my ($key,$value) = each(%$env_data)) {
11618: 	    $idf->{$prefix.$key} = $value;
11619: 	    $env{$prefix.$key}   = $value;
11620:         }
11621:     }
11622: }
11623: 
11624: # --- Get the symbolic name of a problem and the url
11625: sub get_symb {
11626:     my ($request,$silent) = @_;
11627:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11628:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
11629:     if ($symb eq '') {
11630:         if (!$silent) {
11631:             $request->print("Unable to handle ambiguous references:$url:.");
11632:             return ();
11633:         }
11634:     }
11635:     &Apache::lonenc::check_decrypt(\$symb);
11636:     return ($symb);
11637: }
11638: 
11639: # --------------------------------------------------------------Get annotation
11640: 
11641: sub get_annotation {
11642:     my ($symb,$enc) = @_;
11643: 
11644:     my $key = $symb;
11645:     if (!$enc) {
11646:         $key =
11647:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
11648:     }
11649:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
11650:     return $annotation{$key};
11651: }
11652: 
11653: sub clean_symb {
11654:     my ($symb,$delete_enc) = @_;
11655: 
11656:     &Apache::lonenc::check_decrypt(\$symb);
11657:     my $enc = $env{'request.enc'};
11658:     if ($delete_enc) {
11659:         delete($env{'request.enc'});
11660:     }
11661: 
11662:     return ($symb,$enc);
11663: }
11664: 
11665: sub build_release_hashes {
11666:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
11667:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
11668:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
11669:                   (ref($randomizetry) eq 'HASH'));
11670:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
11671:         my ($item,$name,$value) = split(/:/,$key);
11672:         if ($item eq 'parameter') {
11673:             if (ref($checkparms->{$name}) eq 'ARRAY') {
11674:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
11675:                     push(@{$checkparms->{$name}},$value);
11676:                 }
11677:             } else {
11678:                 push(@{$checkparms->{$name}},$value);
11679:             }
11680:         } elsif ($item eq 'resourcetag') {
11681:             if ($name eq 'responsetype') {
11682:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
11683:             }
11684:         } elsif ($item eq 'course') {
11685:             if ($name eq 'crstype') {
11686:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
11687:             }
11688:         }
11689:     }
11690:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
11691:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
11692:     return;
11693: }
11694: 
11695: =pod
11696: 
11697: =back
11698: 
11699: =cut
11700: 
11701: 1;
11702: __END__;
11703: 

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