File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.12: download - view: text, annotated - select for diffs
Fri Aug 3 17:35:32 2012 UTC (11 years, 9 months ago) by raeburn
Branches: version_2_11_X
- For 2.11.
  - Remote Control retained in 2.11.
  - Reverse part of changes in loncommon.pm rev 1.949, 1.953, 1.962, 1.964.
  - Reverse part of changes in lonmenu.pm rev 1.316, 1.318, 1.321.
  - Reverse part of changes in lonroles.pm rev 1.245.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.12 2012/08/03 17:35:32 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %latex_language;		# For choosing hyphenation in <transl..>
  158: my %latex_language_bykey;	# for choosing hyphenation from metadata
  159: my %cprtag;
  160: my %scprtag;
  161: my %fe; my %fd; my %fm;
  162: my %category_extensions;
  163: 
  164: # ---------------------------------------------- Thesaurus variables
  165: #
  166: # %Keywords:
  167: #      A hash used by &keyword to determine if a word is considered a keyword.
  168: # $thesaurus_db_file 
  169: #      Scalar containing the full path to the thesaurus database.
  170: 
  171: my %Keywords;
  172: my $thesaurus_db_file;
  173: 
  174: #
  175: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  176: # thesaurus.tab, and filecategories.tab.
  177: #
  178: BEGIN {
  179:     # Variable initialization
  180:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  181:     #
  182:     unless ($readit) {
  183: # ------------------------------------------------------------------- languages
  184:     {
  185:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  186:                                    '/language.tab';
  187:         if ( open(my $fh,"<$langtabfile") ) {
  188:             while (my $line = <$fh>) {
  189:                 next if ($line=~/^\#/);
  190:                 chomp($line);
  191:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  192:                 $language{$key}=$val.' - '.$enc;
  193:                 if ($sup) {
  194:                     $supported_language{$key}=$sup;
  195:                 }
  196: 		if ($latex) {
  197: 		    $latex_language_bykey{$key} = $latex;
  198: 		    $latex_language{$two} = $latex;
  199: 		}
  200:             }
  201:             close($fh);
  202:         }
  203:     }
  204: # ------------------------------------------------------------------ copyrights
  205:     {
  206:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  207:                                   '/copyright.tab';
  208:         if ( open (my $fh,"<$copyrightfile") ) {
  209:             while (my $line = <$fh>) {
  210:                 next if ($line=~/^\#/);
  211:                 chomp($line);
  212:                 my ($key,$val)=(split(/\s+/,$line,2));
  213:                 $cprtag{$key}=$val;
  214:             }
  215:             close($fh);
  216:         }
  217:     }
  218: # ----------------------------------------------------------- source copyrights
  219:     {
  220:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  221:                                   '/source_copyright.tab';
  222:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  223:             while (my $line = <$fh>) {
  224:                 next if ($line =~ /^\#/);
  225:                 chomp($line);
  226:                 my ($key,$val)=(split(/\s+/,$line,2));
  227:                 $scprtag{$key}=$val;
  228:             }
  229:             close($fh);
  230:         }
  231:     }
  232: 
  233: # -------------------------------------------------------------- default domain designs
  234:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  235:     my $designfile = $designdir.'/default.tab';
  236:     if ( open (my $fh,"<$designfile") ) {
  237:         while (my $line = <$fh>) {
  238:             next if ($line =~ /^\#/);
  239:             chomp($line);
  240:             my ($key,$val)=(split(/\=/,$line));
  241:             if ($val) { $defaultdesign{$key}=$val; }
  242:         }
  243:         close($fh);
  244:     }
  245: 
  246: # ------------------------------------------------------------- file categories
  247:     {
  248:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  249:                                   '/filecategories.tab';
  250:         if ( open (my $fh,"<$categoryfile") ) {
  251: 	    while (my $line = <$fh>) {
  252: 		next if ($line =~ /^\#/);
  253: 		chomp($line);
  254:                 my ($extension,$category)=(split(/\s+/,$line,2));
  255:                 push @{$category_extensions{lc($category)}},$extension;
  256:             }
  257:             close($fh);
  258:         }
  259: 
  260:     }
  261: # ------------------------------------------------------------------ file types
  262:     {
  263:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  264:                '/filetypes.tab';
  265:         if ( open (my $fh,"<$typesfile") ) {
  266:             while (my $line = <$fh>) {
  267: 		next if ($line =~ /^\#/);
  268: 		chomp($line);
  269:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  270:                 if ($descr ne '') {
  271:                     $fe{$ending}=lc($emb);
  272:                     $fd{$ending}=$descr;
  273:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  274:                 }
  275:             }
  276:             close($fh);
  277:         }
  278:     }
  279:     &Apache::lonnet::logthis(
  280:              "<span style='color:yellow;'>INFO: Read file types</span>");
  281:     $readit=1;
  282:     }  # end of unless($readit) 
  283:     
  284: }
  285: 
  286: ###############################################################
  287: ##           HTML and Javascript Helper Functions            ##
  288: ###############################################################
  289: 
  290: =pod 
  291: 
  292: =head1 HTML and Javascript Functions
  293: 
  294: =over 4
  295: 
  296: =item * &browser_and_searcher_javascript()
  297: 
  298: X<browsing, javascript>X<searching, javascript>Returns a string
  299: containing javascript with two functions, C<openbrowser> and
  300: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  301: tags.
  302: 
  303: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  304: 
  305: inputs: formname, elementname, only, omit
  306: 
  307: formname and elementname indicate the name of the html form and name of
  308: the element that the results of the browsing selection are to be placed in. 
  309: 
  310: Specifying 'only' will restrict the browser to displaying only files
  311: with the given extension.  Can be a comma separated list.
  312: 
  313: Specifying 'omit' will restrict the browser to NOT displaying files
  314: with the given extension.  Can be a comma separated list.
  315: 
  316: =item * &opensearcher(formname,elementname) [javascript]
  317: 
  318: Inputs: formname, elementname
  319: 
  320: formname and elementname specify the name of the html form and the name
  321: of the element the selection from the search results will be placed in.
  322: 
  323: =cut
  324: 
  325: sub browser_and_searcher_javascript {
  326:     my ($mode)=@_;
  327:     if (!defined($mode)) { $mode='edit'; }
  328:     my $resurl=&escape_single(&lastresurl());
  329:     return <<END;
  330: // <!-- BEGIN LON-CAPA Internal
  331:     var editbrowser = null;
  332:     function openbrowser(formname,elementname,only,omit,titleelement) {
  333:         var url = '$resurl/?';
  334:         if (editbrowser == null) {
  335:             url += 'launch=1&';
  336:         }
  337:         url += 'catalogmode=interactive&';
  338:         url += 'mode=$mode&';
  339:         url += 'inhibitmenu=yes&';
  340:         url += 'form=' + formname + '&';
  341:         if (only != null) {
  342:             url += 'only=' + only + '&';
  343:         } else {
  344:             url += 'only=&';
  345: 	}
  346:         if (omit != null) {
  347:             url += 'omit=' + omit + '&';
  348:         } else {
  349:             url += 'omit=&';
  350: 	}
  351:         if (titleelement != null) {
  352:             url += 'titleelement=' + titleelement + '&';
  353:         } else {
  354: 	    url += 'titleelement=&';
  355: 	}
  356:         url += 'element=' + elementname + '';
  357:         var title = 'Browser';
  358:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  359:         options += ',width=700,height=600';
  360:         editbrowser = open(url,title,options,'1');
  361:         editbrowser.focus();
  362:     }
  363:     var editsearcher;
  364:     function opensearcher(formname,elementname,titleelement) {
  365:         var url = '/adm/searchcat?';
  366:         if (editsearcher == null) {
  367:             url += 'launch=1&';
  368:         }
  369:         url += 'catalogmode=interactive&';
  370:         url += 'mode=$mode&';
  371:         url += 'form=' + formname + '&';
  372:         if (titleelement != null) {
  373:             url += 'titleelement=' + titleelement + '&';
  374:         } else {
  375: 	    url += 'titleelement=&';
  376: 	}
  377:         url += 'element=' + elementname + '';
  378:         var title = 'Search';
  379:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  380:         options += ',width=700,height=600';
  381:         editsearcher = open(url,title,options,'1');
  382:         editsearcher.focus();
  383:     }
  384: // END LON-CAPA Internal -->
  385: END
  386: }
  387: 
  388: sub lastresurl {
  389:     if ($env{'environment.lastresurl'}) {
  390: 	return $env{'environment.lastresurl'}
  391:     } else {
  392: 	return '/res';
  393:     }
  394: }
  395: 
  396: sub storeresurl {
  397:     my $resurl=&Apache::lonnet::clutter(shift);
  398:     unless ($resurl=~/^\/res/) { return 0; }
  399:     $resurl=~s/\/$//;
  400:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  401:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  402:     return 1;
  403: }
  404: 
  405: sub studentbrowser_javascript {
  406:    unless (
  407:             (($env{'request.course.id'}) && 
  408:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  409: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  410: 					  '/'.$env{'request.course.sec'})
  411: 	      ))
  412:          || ($env{'request.role'}=~/^(au|dc|su)/)
  413:           ) { return ''; }  
  414:    return (<<'ENDSTDBRW');
  415: <script type="text/javascript" language="Javascript">
  416: // <![CDATA[
  417:     var stdeditbrowser;
  418:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  419:         var url = '/adm/pickstudent?';
  420:         var filter;
  421: 	if (!ignorefilter) {
  422: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  423: 	}
  424:         if (filter != null) {
  425:            if (filter != '') {
  426:                url += 'filter='+filter+'&';
  427: 	   }
  428:         }
  429:         url += 'form=' + formname + '&unameelement='+uname+
  430:                                     '&udomelement='+udom+
  431:                                     '&clicker='+clicker;
  432: 	if (roleflag) { url+="&roles=1"; }
  433:         if (courseadvonly) { url+="&courseadvonly=1"; }
  434:         var title = 'Student_Browser';
  435:         var options = 'scrollbars=1,resizable=1,menubar=0';
  436:         options += ',width=700,height=600';
  437:         stdeditbrowser = open(url,title,options,'1');
  438:         stdeditbrowser.focus();
  439:     }
  440: // ]]>
  441: </script>
  442: ENDSTDBRW
  443: }
  444: 
  445: sub resourcebrowser_javascript {
  446:    unless ($env{'request.course.id'}) { return ''; }
  447:    return (<<'ENDRESBRW');
  448: <script type="text/javascript" language="Javascript">
  449: // <![CDATA[
  450:     var reseditbrowser;
  451:     function openresbrowser(formname,reslink) {
  452:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  453:         var title = 'Resource_Browser';
  454:         var options = 'scrollbars=1,resizable=1,menubar=0';
  455:         options += ',width=700,height=500';
  456:         reseditbrowser = open(url,title,options,'1');
  457:         reseditbrowser.focus();
  458:     }
  459: // ]]>
  460: </script>
  461: ENDRESBRW
  462: }
  463: 
  464: sub selectstudent_link {
  465:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  466:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  467:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  468:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  469:    if ($env{'request.course.id'}) {  
  470:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  471: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  472: 					'/'.$env{'request.course.sec'})) {
  473: 	   return '';
  474:        }
  475:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  476:        if ($courseadvonly)  {
  477:            $callargs .= ",'',1,1";
  478:        }
  479:        return '<span class="LC_nobreak">'.
  480:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  481:               &mt('Select User').'</a></span>';
  482:    }
  483:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  484:        $callargs .= ",'',1"; 
  485:        return '<span class="LC_nobreak">'.
  486:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  487:               &mt('Select User').'</a></span>';
  488:    }
  489:    return '';
  490: }
  491: 
  492: sub selectresource_link {
  493:    my ($form,$reslink,$arg)=@_;
  494:    
  495:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  496:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  497:    unless ($env{'request.course.id'}) { return $arg; }
  498:    return '<span class="LC_nobreak">'.
  499:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  500:               $arg.'</a></span>';
  501: }
  502: 
  503: 
  504: 
  505: sub authorbrowser_javascript {
  506:     return <<"ENDAUTHORBRW";
  507: <script type="text/javascript" language="JavaScript">
  508: // <![CDATA[
  509: var stdeditbrowser;
  510: 
  511: function openauthorbrowser(formname,udom) {
  512:     var url = '/adm/pickauthor?';
  513:     url += 'form='+formname+'&roledom='+udom;
  514:     var title = 'Author_Browser';
  515:     var options = 'scrollbars=1,resizable=1,menubar=0';
  516:     options += ',width=700,height=600';
  517:     stdeditbrowser = open(url,title,options,'1');
  518:     stdeditbrowser.focus();
  519: }
  520: 
  521: // ]]>
  522: </script>
  523: ENDAUTHORBRW
  524: }
  525: 
  526: sub coursebrowser_javascript {
  527:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  528:     my $wintitle = 'Course_Browser';
  529:     if ($crstype eq 'Community') {
  530:         $wintitle = 'Community_Browser';
  531:     }
  532:     my $id_functions = &javascript_index_functions();
  533:     my $output = '
  534: <script type="text/javascript" language="JavaScript">
  535: // <![CDATA[
  536:     var stdeditbrowser;'."\n";
  537: 
  538:     $output .= <<"ENDSTDBRW";
  539:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  540:         var url = '/adm/pickcourse?';
  541:         var formid = getFormIdByName(formname);
  542:         var domainfilter = getDomainFromSelectbox(formname,udom);
  543:         if (domainfilter != null) {
  544:            if (domainfilter != '') {
  545:                url += 'domainfilter='+domainfilter+'&';
  546: 	   }
  547:         }
  548:         url += 'form=' + formname + '&cnumelement='+uname+
  549: 	                            '&cdomelement='+udom+
  550:                                     '&cnameelement='+desc;
  551:         if (extra_element !=null && extra_element != '') {
  552:             if (formname == 'rolechoice' || formname == 'studentform') {
  553:                 url += '&roleelement='+extra_element;
  554:                 if (domainfilter == null || domainfilter == '') {
  555:                     url += '&domainfilter='+extra_element;
  556:                 }
  557:             }
  558:             else {
  559:                 if (formname == 'portform') {
  560:                     url += '&setroles='+extra_element;
  561:                 } else {
  562:                     if (formname == 'rules') {
  563:                         url += '&fixeddom='+extra_element; 
  564:                     }
  565:                 }
  566:             }     
  567:         }
  568:         if (type != null && type != '') {
  569:             url += '&type='+type;
  570:         }
  571:         if (type_elem != null && type_elem != '') {
  572:             url += '&typeelement='+type_elem;
  573:         }
  574:         if (formname == 'ccrs') {
  575:             var ownername = document.forms[formid].ccuname.value;
  576:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  577:             url += '&cloner='+ownername+':'+ownerdom;
  578:         }
  579:         if (multflag !=null && multflag != '') {
  580:             url += '&multiple='+multflag;
  581:         }
  582:         var title = '$wintitle';
  583:         var options = 'scrollbars=1,resizable=1,menubar=0';
  584:         options += ',width=700,height=600';
  585:         stdeditbrowser = open(url,title,options,'1');
  586:         stdeditbrowser.focus();
  587:     }
  588: $id_functions
  589: ENDSTDBRW
  590:     if (($sec_element ne '') || ($role_element ne '')) {
  591:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  592:     }
  593:     $output .= '
  594: // ]]>
  595: </script>';
  596:     return $output;
  597: }
  598: 
  599: sub javascript_index_functions {
  600:     return <<"ENDJS";
  601: 
  602: function getFormIdByName(formname) {
  603:     for (var i=0;i<document.forms.length;i++) {
  604:         if (document.forms[i].name == formname) {
  605:             return i;
  606:         }
  607:     }
  608:     return -1;
  609: }
  610: 
  611: function getIndexByName(formid,item) {
  612:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  613:         if (document.forms[formid].elements[i].name == item) {
  614:             return i;
  615:         }
  616:     }
  617:     return -1;
  618: }
  619: 
  620: function getDomainFromSelectbox(formname,udom) {
  621:     var userdom;
  622:     var formid = getFormIdByName(formname);
  623:     if (formid > -1) {
  624:         var domid = getIndexByName(formid,udom);
  625:         if (domid > -1) {
  626:             if (document.forms[formid].elements[domid].type == 'select-one') {
  627:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  628:             }
  629:             if (document.forms[formid].elements[domid].type == 'hidden') {
  630:                 userdom=document.forms[formid].elements[domid].value;
  631:             }
  632:         }
  633:     }
  634:     return userdom;
  635: }
  636: 
  637: ENDJS
  638: 
  639: }
  640: 
  641: sub javascript_array_indexof {
  642:     return <<ENDJS;
  643: <script type="text/javascript" language="JavaScript">
  644: // <![CDATA[
  645: 
  646: if (!Array.prototype.indexOf) {
  647:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  648:         "use strict";
  649:         if (this === void 0 || this === null) {
  650:             throw new TypeError();
  651:         }
  652:         var t = Object(this);
  653:         var len = t.length >>> 0;
  654:         if (len === 0) {
  655:             return -1;
  656:         }
  657:         var n = 0;
  658:         if (arguments.length > 0) {
  659:             n = Number(arguments[1]);
  660:             if (n !== n) { // shortcut for verifying if it's NaN
  661:                 n = 0;
  662:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  663:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  664:             }
  665:         }
  666:         if (n >= len) {
  667:             return -1;
  668:         }
  669:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  670:         for (; k < len; k++) {
  671:             if (k in t && t[k] === searchElement) {
  672:                 return k;
  673:             }
  674:         }
  675:         return -1;
  676:     }
  677: }
  678: 
  679: // ]]>
  680: </script>
  681: 
  682: ENDJS
  683: 
  684: }
  685: 
  686: sub userbrowser_javascript {
  687:     my $id_functions = &javascript_index_functions();
  688:     return <<"ENDUSERBRW";
  689: 
  690: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  691:     var url = '/adm/pickuser?';
  692:     var userdom = getDomainFromSelectbox(formname,udom);
  693:     if (userdom != null) {
  694:        if (userdom != '') {
  695:            url += 'srchdom='+userdom+'&';
  696:        }
  697:     }
  698:     url += 'form=' + formname + '&unameelement='+uname+
  699:                                 '&udomelement='+udom+
  700:                                 '&ulastelement='+ulast+
  701:                                 '&ufirstelement='+ufirst+
  702:                                 '&uemailelement='+uemail+
  703:                                 '&hideudomelement='+hideudom+
  704:                                 '&coursedom='+crsdom;
  705:     if ((caller != null) && (caller != undefined)) {
  706:         url += '&caller='+caller;
  707:     }
  708:     var title = 'User_Browser';
  709:     var options = 'scrollbars=1,resizable=1,menubar=0';
  710:     options += ',width=700,height=600';
  711:     var stdeditbrowser = open(url,title,options,'1');
  712:     stdeditbrowser.focus();
  713: }
  714: 
  715: function fix_domain (formname,udom,origdom,uname) {
  716:     var formid = getFormIdByName(formname);
  717:     if (formid > -1) {
  718:         var unameid = getIndexByName(formid,uname);
  719:         var domid = getIndexByName(formid,udom);
  720:         var hidedomid = getIndexByName(formid,origdom);
  721:         if (hidedomid > -1) {
  722:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  723:             var unameval = document.forms[formid].elements[unameid].value;
  724:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  725:                 if (domid > -1) {
  726:                     var slct = document.forms[formid].elements[domid];
  727:                     if (slct.type == 'select-one') {
  728:                         var i;
  729:                         for (i=0;i<slct.length;i++) {
  730:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  731:                         }
  732:                     }
  733:                     if (slct.type == 'hidden') {
  734:                         slct.value = fixeddom;
  735:                     }
  736:                 }
  737:             }
  738:         }
  739:     }
  740:     return;
  741: }
  742: 
  743: $id_functions
  744: ENDUSERBRW
  745: }
  746: 
  747: sub setsec_javascript {
  748:     my ($sec_element,$formname,$role_element) = @_;
  749:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  750:         $communityrolestr);
  751:     if ($role_element ne '') {
  752:         my @allroles = ('st','ta','ep','in','ad');
  753:         foreach my $crstype ('Course','Community') {
  754:             if ($crstype eq 'Community') {
  755:                 foreach my $role (@allroles) {
  756:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  757:                 }
  758:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  759:             } else {
  760:                 foreach my $role (@allroles) {
  761:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  762:                 }
  763:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  764:             }
  765:         }
  766:         $rolestr = '"'.join('","',@allroles).'"';
  767:         $courserolestr = '"'.join('","',@courserolenames).'"';
  768:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  769:     }
  770:     my $setsections = qq|
  771: function setSect(sectionlist) {
  772:     var sectionsArray = new Array();
  773:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  774:         sectionsArray = sectionlist.split(",");
  775:     }
  776:     var numSections = sectionsArray.length;
  777:     document.$formname.$sec_element.length = 0;
  778:     if (numSections == 0) {
  779:         document.$formname.$sec_element.multiple=false;
  780:         document.$formname.$sec_element.size=1;
  781:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  782:     } else {
  783:         if (numSections == 1) {
  784:             document.$formname.$sec_element.multiple=false;
  785:             document.$formname.$sec_element.size=1;
  786:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  787:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  788:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  789:         } else {
  790:             for (var i=0; i<numSections; i++) {
  791:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  792:             }
  793:             document.$formname.$sec_element.multiple=true
  794:             if (numSections < 3) {
  795:                 document.$formname.$sec_element.size=numSections;
  796:             } else {
  797:                 document.$formname.$sec_element.size=3;
  798:             }
  799:             document.$formname.$sec_element.options[0].selected = false
  800:         }
  801:     }
  802: }
  803: 
  804: function setRole(crstype) {
  805: |;
  806:     if ($role_element eq '') {
  807:         $setsections .= '    return;
  808: }
  809: ';
  810:     } else {
  811:         $setsections .= qq|
  812:     var elementLength = document.$formname.$role_element.length;
  813:     var allroles = Array($rolestr);
  814:     var courserolenames = Array($courserolestr);
  815:     var communityrolenames = Array($communityrolestr);
  816:     if (elementLength != undefined) {
  817:         if (document.$formname.$role_element.options[5].value == 'cc') {
  818:             if (crstype == 'Course') {
  819:                 return;
  820:             } else {
  821:                 allroles[5] = 'co';
  822:                 for (var i=0; i<6; i++) {
  823:                     document.$formname.$role_element.options[i].value = allroles[i];
  824:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  825:                 }
  826:             }
  827:         } else {
  828:             if (crstype == 'Community') {
  829:                 return;
  830:             } else {
  831:                 allroles[5] = 'cc';
  832:                 for (var i=0; i<6; i++) {
  833:                     document.$formname.$role_element.options[i].value = allroles[i];
  834:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  835:                 }
  836:             }
  837:         }
  838:     }
  839:     return;
  840: }
  841: |;
  842:     }
  843:     return $setsections;
  844: }
  845: 
  846: sub selectcourse_link {
  847:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  848:        $typeelement) = @_;
  849:    my $type = $selecttype;
  850:    my $linktext = &mt('Select Course');
  851:    if ($selecttype eq 'Community') {
  852:        $linktext = &mt('Select Community');
  853:    } elsif ($selecttype eq 'Course/Community') {
  854:        $linktext = &mt('Select Course/Community');
  855:        $type = '';
  856:    } elsif ($selecttype eq 'Select') {
  857:        $linktext = &mt('Select');
  858:        $type = '';
  859:    }
  860:    return '<span class="LC_nobreak">'
  861:          ."<a href='"
  862:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  863:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  864:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  865:          ."'>".$linktext.'</a>'
  866:          .'</span>';
  867: }
  868: 
  869: sub selectauthor_link {
  870:    my ($form,$udom)=@_;
  871:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  872:           &mt('Select Author').'</a>';
  873: }
  874: 
  875: sub selectuser_link {
  876:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  877:         $coursedom,$linktext,$caller) = @_;
  878:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  879:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  880:            ');">'.$linktext.'</a>';
  881: }
  882: 
  883: sub check_uncheck_jscript {
  884:     my $jscript = <<"ENDSCRT";
  885: function checkAll(field) {
  886:     if (field.length > 0) {
  887:         for (i = 0; i < field.length; i++) {
  888:             field[i].checked = true ;
  889:         }
  890:     } else {
  891:         field.checked = true
  892:     }
  893: }
  894:  
  895: function uncheckAll(field) {
  896:     if (field.length > 0) {
  897:         for (i = 0; i < field.length; i++) {
  898:             field[i].checked = false ;
  899:         }
  900:     } else {
  901:         field.checked = false ;
  902:     }
  903: }
  904: ENDSCRT
  905:     return $jscript;
  906: }
  907: 
  908: sub select_timezone {
  909:    my ($name,$selected,$onchange,$includeempty)=@_;
  910:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  911:    if ($includeempty) {
  912:        $output .= '<option value=""';
  913:        if (($selected eq '') || ($selected eq 'local')) {
  914:            $output .= ' selected="selected" ';
  915:        }
  916:        $output .= '> </option>';
  917:    }
  918:    my @timezones = DateTime::TimeZone->all_names;
  919:    foreach my $tzone (@timezones) {
  920:        $output.= '<option value="'.$tzone.'"';
  921:        if ($tzone eq $selected) {
  922:            $output.=' selected="selected"';
  923:        }
  924:        $output.=">$tzone</option>\n";
  925:    }
  926:    $output.="</select>";
  927:    return $output;
  928: }
  929: 
  930: sub select_datelocale {
  931:     my ($name,$selected,$onchange,$includeempty)=@_;
  932:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  933:     if ($includeempty) {
  934:         $output .= '<option value=""';
  935:         if ($selected eq '') {
  936:             $output .= ' selected="selected" ';
  937:         }
  938:         $output .= '> </option>';
  939:     }
  940:     my (@possibles,%locale_names);
  941:     my @locales = DateTime::Locale::Catalog::Locales;
  942:     foreach my $locale (@locales) {
  943:         if (ref($locale) eq 'HASH') {
  944:             my $id = $locale->{'id'};
  945:             if ($id ne '') {
  946:                 my $en_terr = $locale->{'en_territory'};
  947:                 my $native_terr = $locale->{'native_territory'};
  948:                 my @languages = &Apache::lonlocal::preferred_languages();
  949:                 if (grep(/^en$/,@languages) || !@languages) {
  950:                     if ($en_terr ne '') {
  951:                         $locale_names{$id} = '('.$en_terr.')';
  952:                     } elsif ($native_terr ne '') {
  953:                         $locale_names{$id} = $native_terr;
  954:                     }
  955:                 } else {
  956:                     if ($native_terr ne '') {
  957:                         $locale_names{$id} = $native_terr.' ';
  958:                     } elsif ($en_terr ne '') {
  959:                         $locale_names{$id} = '('.$en_terr.')';
  960:                     }
  961:                 }
  962:                 push (@possibles,$id);
  963:             }
  964:         }
  965:     }
  966:     foreach my $item (sort(@possibles)) {
  967:         $output.= '<option value="'.$item.'"';
  968:         if ($item eq $selected) {
  969:             $output.=' selected="selected"';
  970:         }
  971:         $output.=">$item";
  972:         if ($locale_names{$item} ne '') {
  973:             $output.="  $locale_names{$item}</option>\n";
  974:         }
  975:         $output.="</option>\n";
  976:     }
  977:     $output.="</select>";
  978:     return $output;
  979: }
  980: 
  981: sub select_language {
  982:     my ($name,$selected,$includeempty) = @_;
  983:     my %langchoices;
  984:     if ($includeempty) {
  985:         %langchoices = ('' => 'No language preference');
  986:     }
  987:     foreach my $id (&languageids()) {
  988:         my $code = &supportedlanguagecode($id);
  989:         if ($code) {
  990:             $langchoices{$code} = &plainlanguagedescription($id);
  991:         }
  992:     }
  993:     return &select_form($selected,$name,\%langchoices);
  994: }
  995: 
  996: =pod
  997: 
  998: =item * &linked_select_forms(...)
  999: 
 1000: linked_select_forms returns a string containing a <script></script> block
 1001: and html for two <select> menus.  The select menus will be linked in that
 1002: changing the value of the first menu will result in new values being placed
 1003: in the second menu.  The values in the select menu will appear in alphabetical
 1004: order unless a defined order is provided.
 1005: 
 1006: linked_select_forms takes the following ordered inputs:
 1007: 
 1008: =over 4
 1009: 
 1010: =item * $formname, the name of the <form> tag
 1011: 
 1012: =item * $middletext, the text which appears between the <select> tags
 1013: 
 1014: =item * $firstdefault, the default value for the first menu
 1015: 
 1016: =item * $firstselectname, the name of the first <select> tag
 1017: 
 1018: =item * $secondselectname, the name of the second <select> tag
 1019: 
 1020: =item * $hashref, a reference to a hash containing the data for the menus.
 1021: 
 1022: =item * $menuorder, the order of values in the first menu
 1023: 
 1024: =back 
 1025: 
 1026: Below is an example of such a hash.  Only the 'text', 'default', and 
 1027: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1028: values for the first select menu.  The text that coincides with the 
 1029: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1030: and text for the second menu are given in the hash pointed to by 
 1031: $menu{$choice1}->{'select2'}.  
 1032: 
 1033:  my %menu = ( A1 => { text =>"Choice A1" ,
 1034:                        default => "B3",
 1035:                        select2 => { 
 1036:                            B1 => "Choice B1",
 1037:                            B2 => "Choice B2",
 1038:                            B3 => "Choice B3",
 1039:                            B4 => "Choice B4"
 1040:                            },
 1041:                        order => ['B4','B3','B1','B2'],
 1042:                    },
 1043:                A2 => { text =>"Choice A2" ,
 1044:                        default => "C2",
 1045:                        select2 => { 
 1046:                            C1 => "Choice C1",
 1047:                            C2 => "Choice C2",
 1048:                            C3 => "Choice C3"
 1049:                            },
 1050:                        order => ['C2','C1','C3'],
 1051:                    },
 1052:                A3 => { text =>"Choice A3" ,
 1053:                        default => "D6",
 1054:                        select2 => { 
 1055:                            D1 => "Choice D1",
 1056:                            D2 => "Choice D2",
 1057:                            D3 => "Choice D3",
 1058:                            D4 => "Choice D4",
 1059:                            D5 => "Choice D5",
 1060:                            D6 => "Choice D6",
 1061:                            D7 => "Choice D7"
 1062:                            },
 1063:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1064:                    }
 1065:                );
 1066: 
 1067: =cut
 1068: 
 1069: sub linked_select_forms {
 1070:     my ($formname,
 1071:         $middletext,
 1072:         $firstdefault,
 1073:         $firstselectname,
 1074:         $secondselectname, 
 1075:         $hashref,
 1076:         $menuorder,
 1077:         ) = @_;
 1078:     my $second = "document.$formname.$secondselectname";
 1079:     my $first = "document.$formname.$firstselectname";
 1080:     # output the javascript to do the changing
 1081:     my $result = '';
 1082:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1083:     $result.="// <![CDATA[\n";
 1084:     $result.="var select2data = new Object();\n";
 1085:     $" = '","';
 1086:     my $debug = '';
 1087:     foreach my $s1 (sort(keys(%$hashref))) {
 1088:         $result.="select2data.d_$s1 = new Object();\n";        
 1089:         $result.="select2data.d_$s1.def = new String('".
 1090:             $hashref->{$s1}->{'default'}."');\n";
 1091:         $result.="select2data.d_$s1.values = new Array(";
 1092:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1093:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1094:             @s2values = @{$hashref->{$s1}->{'order'}};
 1095:         }
 1096:         $result.="\"@s2values\");\n";
 1097:         $result.="select2data.d_$s1.texts = new Array(";        
 1098:         my @s2texts;
 1099:         foreach my $value (@s2values) {
 1100:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1101:         }
 1102:         $result.="\"@s2texts\");\n";
 1103:     }
 1104:     $"=' ';
 1105:     $result.= <<"END";
 1106: 
 1107: function select1_changed() {
 1108:     // Determine new choice
 1109:     var newvalue = "d_" + $first.value;
 1110:     // update select2
 1111:     var values     = select2data[newvalue].values;
 1112:     var texts      = select2data[newvalue].texts;
 1113:     var select2def = select2data[newvalue].def;
 1114:     var i;
 1115:     // out with the old
 1116:     for (i = 0; i < $second.options.length; i++) {
 1117:         $second.options[i] = null;
 1118:     }
 1119:     // in with the nuclear
 1120:     for (i=0;i<values.length; i++) {
 1121:         $second.options[i] = new Option(values[i]);
 1122:         $second.options[i].value = values[i];
 1123:         $second.options[i].text = texts[i];
 1124:         if (values[i] == select2def) {
 1125:             $second.options[i].selected = true;
 1126:         }
 1127:     }
 1128: }
 1129: // ]]>
 1130: </script>
 1131: END
 1132:     # output the initial values for the selection lists
 1133:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1134:     my @order = sort(keys(%{$hashref}));
 1135:     if (ref($menuorder) eq 'ARRAY') {
 1136:         @order = @{$menuorder};
 1137:     }
 1138:     foreach my $value (@order) {
 1139:         $result.="    <option value=\"$value\" ";
 1140:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1141:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1142:     }
 1143:     $result .= "</select>\n";
 1144:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1145:     $result .= $middletext;
 1146:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1147:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1148:     
 1149:     my @secondorder = sort(keys(%select2));
 1150:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1151:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1152:     }
 1153:     foreach my $value (@secondorder) {
 1154:         $result.="    <option value=\"$value\" ";        
 1155:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1156:         $result.=">".&mt($select2{$value})."</option>\n";
 1157:     }
 1158:     $result .= "</select>\n";
 1159:     #    return $debug;
 1160:     return $result;
 1161: }   #  end of sub linked_select_forms {
 1162: 
 1163: =pod
 1164: 
 1165: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1166: 
 1167: Returns a string corresponding to an HTML link to the given help
 1168: $topic, where $topic corresponds to the name of a .tex file in
 1169: /home/httpd/html/adm/help/tex, with underscores replaced by
 1170: spaces. 
 1171: 
 1172: $text will optionally be linked to the same topic, allowing you to
 1173: link text in addition to the graphic. If you do not want to link
 1174: text, but wish to specify one of the later parameters, pass an
 1175: empty string. 
 1176: 
 1177: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1178: the link will not open a new window. If false, the link will open
 1179: a new window using Javascript. (Default is false.) 
 1180: 
 1181: $width and $height are optional numerical parameters that will
 1182: override the width and height of the popped up window, which may
 1183: be useful for certain help topics with big pictures included.
 1184: 
 1185: $imgid is the id of the img tag used for the help icon. This may be
 1186: used in a javascript call to switch the image src.  See 
 1187: lonhtmlcommon::htmlareaselectactive() for an example.
 1188: 
 1189: =cut
 1190: 
 1191: sub help_open_topic {
 1192:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1193:     $text = "" if (not defined $text);
 1194:     $stayOnPage = 0 if (not defined $stayOnPage);
 1195:     $width = 500 if (not defined $width);
 1196:     $height = 400 if (not defined $height);
 1197:     my $filename = $topic;
 1198:     $filename =~ s/ /_/g;
 1199: 
 1200:     my $template = "";
 1201:     my $link;
 1202:     
 1203:     $topic=~s/\W/\_/g;
 1204: 
 1205:     if (!$stayOnPage) {
 1206: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1207:     } elsif ($stayOnPage eq 'popup') {
 1208:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1209:     } else {
 1210: 	$link = "/adm/help/${filename}.hlp";
 1211:     }
 1212: 
 1213:     # Add the text
 1214:     if ($text ne "") {	
 1215: 	$template.='<span class="LC_help_open_topic">'
 1216:                   .'<a target="_top" href="'.$link.'">'
 1217:                   .$text.'</a>';
 1218:     }
 1219: 
 1220:     # (Always) Add the graphic
 1221:     my $title = &mt('Online Help');
 1222:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1223:     if ($imgid ne '') {
 1224:         $imgid = ' id="'.$imgid.'"';
 1225:     }
 1226:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1227:               .'<img src="'.$helpicon.'" border="0"'
 1228:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1229:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1230:               .' /></a>';
 1231:     if ($text ne "") {	
 1232:         $template.='</span>';
 1233:     }
 1234:     return $template;
 1235: 
 1236: }
 1237: 
 1238: # This is a quicky function for Latex cheatsheet editing, since it 
 1239: # appears in at least four places
 1240: sub helpLatexCheatsheet {
 1241:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1242:     my $out;
 1243:     my $addOther = '';
 1244:     if ($topic) {
 1245: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1246:     }
 1247:     $out = '<span>' # Start cheatsheet
 1248: 	  .$addOther
 1249:           .'<span>'
 1250: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1251: 	  .'</span> <span>'
 1252: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1253: 	  .'</span>';
 1254:     unless ($not_author) {
 1255:         $out .= ' <span>'
 1256: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1257: 	       .'</span>';
 1258:     }
 1259:     $out .= '</span>'; # End cheatsheet
 1260:     return $out;
 1261: }
 1262: 
 1263: sub general_help {
 1264:     my $helptopic='Student_Intro';
 1265:     if ($env{'request.role'}=~/^(ca|au)/) {
 1266: 	$helptopic='Authoring_Intro';
 1267:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1268: 	$helptopic='Course_Coordination_Intro';
 1269:     } elsif ($env{'request.role'}=~/^dc/) {
 1270:         $helptopic='Domain_Coordination_Intro';
 1271:     }
 1272:     return $helptopic;
 1273: }
 1274: 
 1275: sub update_help_link {
 1276:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1277:     my $origurl = $ENV{'REQUEST_URI'};
 1278:     $origurl=~s|^/~|/priv/|;
 1279:     my $timestamp = time;
 1280:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1281:         $$datum = &escape($$datum);
 1282:     }
 1283: 
 1284:     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";
 1285:     my $output .= <<"ENDOUTPUT";
 1286: <script type="text/javascript">
 1287: // <![CDATA[
 1288: banner_link = '$banner_link';
 1289: // ]]>
 1290: </script>
 1291: ENDOUTPUT
 1292:     return $output;
 1293: }
 1294: 
 1295: # now just updates the help link and generates a blue icon
 1296: sub help_open_menu {
 1297:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1298: 	= @_;    
 1299:     $stayOnPage = 1;
 1300:     my $output;
 1301:     if ($component_help) {
 1302: 	if (!$text) {
 1303: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1304: 				       $width,$height);
 1305: 	} else {
 1306: 	    my $help_text;
 1307: 	    $help_text=&unescape($topic);
 1308: 	    $output='<table><tr><td>'.
 1309: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1310: 				 $width,$height).'</td></tr></table>';
 1311: 	}
 1312:     }
 1313:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1314:     return $output.$banner_link;
 1315: }
 1316: 
 1317: sub top_nav_help {
 1318:     my ($text) = @_;
 1319:     $text = &mt($text);
 1320:     my $stay_on_page = 1;
 1321: 
 1322:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1323: 	                     : "javascript:helpMenu('open')";
 1324:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1325: 
 1326:     my $title = &mt('Get help');
 1327: 
 1328:     return <<"END";
 1329: $banner_link
 1330:  <a href="$link" title="$title">$text</a>
 1331: END
 1332: }
 1333: 
 1334: sub help_menu_js {
 1335:     my ($text) = @_;
 1336:     my $stayOnPage = 1;
 1337:     my $width = 620;
 1338:     my $height = 600;
 1339:     my $helptopic=&general_help();
 1340:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1341:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1342:     my $start_page =
 1343:         &Apache::loncommon::start_page('Help Menu', undef,
 1344: 				       {'frameset'    => 1,
 1345: 					'js_ready'    => 1,
 1346: 					'add_entries' => {
 1347: 					    'border' => '0',
 1348: 					    'rows'   => "110,*",},});
 1349:     my $end_page =
 1350:         &Apache::loncommon::end_page({'frameset' => 1,
 1351: 				      'js_ready' => 1,});
 1352: 
 1353:     my $template .= <<"ENDTEMPLATE";
 1354: <script type="text/javascript">
 1355: // <![CDATA[
 1356: // <!-- BEGIN LON-CAPA Internal
 1357: var banner_link = '';
 1358: function helpMenu(target) {
 1359:     var caller = this;
 1360:     if (target == 'open') {
 1361:         var newWindow = null;
 1362:         try {
 1363:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1364:         }
 1365:         catch(error) {
 1366:             writeHelp(caller);
 1367:             return;
 1368:         }
 1369:         if (newWindow) {
 1370:             caller = newWindow;
 1371:         }
 1372:     }
 1373:     writeHelp(caller);
 1374:     return;
 1375: }
 1376: function writeHelp(caller) {
 1377:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1378:     caller.document.close()
 1379:     caller.focus()
 1380: }
 1381: // END LON-CAPA Internal -->
 1382: // ]]>
 1383: </script>
 1384: ENDTEMPLATE
 1385:     return $template;
 1386: }
 1387: 
 1388: sub help_open_bug {
 1389:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1390:     unless ($env{'user.adv'}) { return ''; }
 1391:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1392:     $text = "" if (not defined $text);
 1393: 	$stayOnPage=1;
 1394:     $width = 600 if (not defined $width);
 1395:     $height = 600 if (not defined $height);
 1396: 
 1397:     $topic=~s/\W+/\+/g;
 1398:     my $link='';
 1399:     my $template='';
 1400:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1401: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1402:     if (!$stayOnPage)
 1403:     {
 1404: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1405:     }
 1406:     else
 1407:     {
 1408: 	$link = $url;
 1409:     }
 1410:     # Add the text
 1411:     if ($text ne "")
 1412:     {
 1413: 	$template .= 
 1414:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1415:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1416:     }
 1417: 
 1418:     # Add the graphic
 1419:     my $title = &mt('Report a Bug');
 1420:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1421:     $template .= <<"ENDTEMPLATE";
 1422:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1423: ENDTEMPLATE
 1424:     if ($text ne '') { $template.='</td></tr></table>' };
 1425:     return $template;
 1426: 
 1427: }
 1428: 
 1429: sub help_open_faq {
 1430:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1431:     unless ($env{'user.adv'}) { return ''; }
 1432:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1433:     $text = "" if (not defined $text);
 1434: 	$stayOnPage=1;
 1435:     $width = 350 if (not defined $width);
 1436:     $height = 400 if (not defined $height);
 1437: 
 1438:     $topic=~s/\W+/\+/g;
 1439:     my $link='';
 1440:     my $template='';
 1441:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1442:     if (!$stayOnPage)
 1443:     {
 1444: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1445:     }
 1446:     else
 1447:     {
 1448: 	$link = $url;
 1449:     }
 1450: 
 1451:     # Add the text
 1452:     if ($text ne "")
 1453:     {
 1454: 	$template .= 
 1455:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1456:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1457:     }
 1458: 
 1459:     # Add the graphic
 1460:     my $title = &mt('View the FAQ');
 1461:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1462:     $template .= <<"ENDTEMPLATE";
 1463:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1464: ENDTEMPLATE
 1465:     if ($text ne '') { $template.='</td></tr></table>' };
 1466:     return $template;
 1467: 
 1468: }
 1469: 
 1470: ###############################################################
 1471: ###############################################################
 1472: 
 1473: =pod
 1474: 
 1475: =item * &change_content_javascript():
 1476: 
 1477: This and the next function allow you to create small sections of an
 1478: otherwise static HTML page that you can update on the fly with
 1479: Javascript, even in Netscape 4.
 1480: 
 1481: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1482: must be written to the HTML page once. It will prove the Javascript
 1483: function "change(name, content)". Calling the change function with the
 1484: name of the section 
 1485: you want to update, matching the name passed to C<changable_area>, and
 1486: the new content you want to put in there, will put the content into
 1487: that area.
 1488: 
 1489: B<Note>: Netscape 4 only reserves enough space for the changable area
 1490: to contain room for the original contents. You need to "make space"
 1491: for whatever changes you wish to make, and be B<sure> to check your
 1492: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1493: it's adequate for updating a one-line status display, but little more.
 1494: This script will set the space to 100% width, so you only need to
 1495: worry about height in Netscape 4.
 1496: 
 1497: Modern browsers are much less limiting, and if you can commit to the
 1498: user not using Netscape 4, this feature may be used freely with
 1499: pretty much any HTML.
 1500: 
 1501: =cut
 1502: 
 1503: sub change_content_javascript {
 1504:     # If we're on Netscape 4, we need to use Layer-based code
 1505:     if ($env{'browser.type'} eq 'netscape' &&
 1506: 	$env{'browser.version'} =~ /^4\./) {
 1507: 	return (<<NETSCAPE4);
 1508: 	function change(name, content) {
 1509: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1510: 	    doc.open();
 1511: 	    doc.write(content);
 1512: 	    doc.close();
 1513: 	}
 1514: NETSCAPE4
 1515:     } else {
 1516: 	# Otherwise, we need to use semi-standards-compliant code
 1517: 	# (technically, "innerHTML" isn't standard but the equivalent
 1518: 	# is really scary, and every useful browser supports it
 1519: 	return (<<DOMBASED);
 1520: 	function change(name, content) {
 1521: 	    element = document.getElementById(name);
 1522: 	    element.innerHTML = content;
 1523: 	}
 1524: DOMBASED
 1525:     }
 1526: }
 1527: 
 1528: =pod
 1529: 
 1530: =item * &changable_area($name,$origContent):
 1531: 
 1532: This provides a "changable area" that can be modified on the fly via
 1533: the Javascript code provided in C<change_content_javascript>. $name is
 1534: the name you will use to reference the area later; do not repeat the
 1535: same name on a given HTML page more then once. $origContent is what
 1536: the area will originally contain, which can be left blank.
 1537: 
 1538: =cut
 1539: 
 1540: sub changable_area {
 1541:     my ($name, $origContent) = @_;
 1542: 
 1543:     if ($env{'browser.type'} eq 'netscape' &&
 1544: 	$env{'browser.version'} =~ /^4\./) {
 1545: 	# If this is netscape 4, we need to use the Layer tag
 1546: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1547:     } else {
 1548: 	return "<span id='$name'>$origContent</span>";
 1549:     }
 1550: }
 1551: 
 1552: =pod
 1553: 
 1554: =item * &viewport_geometry_js 
 1555: 
 1556: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1557: 
 1558: =cut
 1559: 
 1560: 
 1561: sub viewport_geometry_js { 
 1562:     return <<"GEOMETRY";
 1563: var Geometry = {};
 1564: function init_geometry() {
 1565:     if (Geometry.init) { return };
 1566:     Geometry.init=1;
 1567:     if (window.innerHeight) {
 1568:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1569:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1570:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1571:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1572:     }
 1573:     else if (document.documentElement && document.documentElement.clientHeight) {
 1574:         Geometry.getViewportHeight =
 1575:             function() { return document.documentElement.clientHeight; };
 1576:         Geometry.getViewportWidth =
 1577:             function() { return document.documentElement.clientWidth; };
 1578: 
 1579:         Geometry.getHorizontalScroll =
 1580:             function() { return document.documentElement.scrollLeft; };
 1581:         Geometry.getVerticalScroll =
 1582:             function() { return document.documentElement.scrollTop; };
 1583:     }
 1584:     else if (document.body.clientHeight) {
 1585:         Geometry.getViewportHeight =
 1586:             function() { return document.body.clientHeight; };
 1587:         Geometry.getViewportWidth =
 1588:             function() { return document.body.clientWidth; };
 1589:         Geometry.getHorizontalScroll =
 1590:             function() { return document.body.scrollLeft; };
 1591:         Geometry.getVerticalScroll =
 1592:             function() { return document.body.scrollTop; };
 1593:     }
 1594: }
 1595: 
 1596: GEOMETRY
 1597: }
 1598: 
 1599: =pod
 1600: 
 1601: =item * &viewport_size_js()
 1602: 
 1603: 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. 
 1604: 
 1605: =cut
 1606: 
 1607: sub viewport_size_js {
 1608:     my $geometry = &viewport_geometry_js();
 1609:     return <<"DIMS";
 1610: 
 1611: $geometry
 1612: 
 1613: function getViewportDims(width,height) {
 1614:     init_geometry();
 1615:     width.value = Geometry.getViewportWidth();
 1616:     height.value = Geometry.getViewportHeight();
 1617:     return;
 1618: }
 1619: 
 1620: DIMS
 1621: }
 1622: 
 1623: =pod
 1624: 
 1625: =item * &resize_textarea_js()
 1626: 
 1627: emits the needed javascript to resize a textarea to be as big as possible
 1628: 
 1629: creates a function resize_textrea that takes two IDs first should be
 1630: the id of the element to resize, second should be the id of a div that
 1631: surrounds everything that comes after the textarea, this routine needs
 1632: to be attached to the <body> for the onload and onresize events.
 1633: 
 1634: =back
 1635: 
 1636: =cut
 1637: 
 1638: sub resize_textarea_js {
 1639:     my $geometry = &viewport_geometry_js();
 1640:     return <<"RESIZE";
 1641:     <script type="text/javascript">
 1642: // <![CDATA[
 1643: $geometry
 1644: 
 1645: function getX(element) {
 1646:     var x = 0;
 1647:     while (element) {
 1648: 	x += element.offsetLeft;
 1649: 	element = element.offsetParent;
 1650:     }
 1651:     return x;
 1652: }
 1653: function getY(element) {
 1654:     var y = 0;
 1655:     while (element) {
 1656: 	y += element.offsetTop;
 1657: 	element = element.offsetParent;
 1658:     }
 1659:     return y;
 1660: }
 1661: 
 1662: 
 1663: function resize_textarea(textarea_id,bottom_id) {
 1664:     init_geometry();
 1665:     var textarea        = document.getElementById(textarea_id);
 1666:     //alert(textarea);
 1667: 
 1668:     var textarea_top    = getY(textarea);
 1669:     var textarea_height = textarea.offsetHeight;
 1670:     var bottom          = document.getElementById(bottom_id);
 1671:     var bottom_top      = getY(bottom);
 1672:     var bottom_height   = bottom.offsetHeight;
 1673:     var window_height   = Geometry.getViewportHeight();
 1674:     var fudge           = 23;
 1675:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1676:     if (new_height < 300) {
 1677: 	new_height = 300;
 1678:     }
 1679:     textarea.style.height=new_height+'px';
 1680: }
 1681: // ]]>
 1682: </script>
 1683: RESIZE
 1684: 
 1685: }
 1686: 
 1687: =pod
 1688: 
 1689: =head1 Excel and CSV file utility routines
 1690: 
 1691: =over 4
 1692: 
 1693: =cut
 1694: 
 1695: ###############################################################
 1696: ###############################################################
 1697: 
 1698: =pod
 1699: 
 1700: =item * &csv_translate($text) 
 1701: 
 1702: Translate $text to allow it to be output as a 'comma separated values' 
 1703: format.
 1704: 
 1705: =cut
 1706: 
 1707: ###############################################################
 1708: ###############################################################
 1709: sub csv_translate {
 1710:     my $text = shift;
 1711:     $text =~ s/\"/\"\"/g;
 1712:     $text =~ s/\n/ /g;
 1713:     return $text;
 1714: }
 1715: 
 1716: ###############################################################
 1717: ###############################################################
 1718: 
 1719: =pod
 1720: 
 1721: =item * &define_excel_formats()
 1722: 
 1723: Define some commonly used Excel cell formats.
 1724: 
 1725: Currently supported formats:
 1726: 
 1727: =over 4
 1728: 
 1729: =item header
 1730: 
 1731: =item bold
 1732: 
 1733: =item h1
 1734: 
 1735: =item h2
 1736: 
 1737: =item h3
 1738: 
 1739: =item h4
 1740: 
 1741: =item i
 1742: 
 1743: =item date
 1744: 
 1745: =back
 1746: 
 1747: Inputs: $workbook
 1748: 
 1749: Returns: $format, a hash reference.
 1750: 
 1751: 
 1752: =cut
 1753: 
 1754: ###############################################################
 1755: ###############################################################
 1756: sub define_excel_formats {
 1757:     my ($workbook) = @_;
 1758:     my $format;
 1759:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1760:                                                 bottom    => 1,
 1761:                                                 align     => 'center');
 1762:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1763:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1764:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1765:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1766:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1767:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1768:     $format->{'date'} = $workbook->add_format(num_format=>
 1769:                                             'mm/dd/yyyy hh:mm:ss');
 1770:     return $format;
 1771: }
 1772: 
 1773: ###############################################################
 1774: ###############################################################
 1775: 
 1776: =pod
 1777: 
 1778: =item * &create_workbook()
 1779: 
 1780: Create an Excel worksheet.  If it fails, output message on the
 1781: request object and return undefs.
 1782: 
 1783: Inputs: Apache request object
 1784: 
 1785: Returns (undef) on failure, 
 1786:     Excel worksheet object, scalar with filename, and formats 
 1787:     from &Apache::loncommon::define_excel_formats on success
 1788: 
 1789: =cut
 1790: 
 1791: ###############################################################
 1792: ###############################################################
 1793: sub create_workbook {
 1794:     my ($r) = @_;
 1795:         #
 1796:     # Create the excel spreadsheet
 1797:     my $filename = '/prtspool/'.
 1798:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1799:         time.'_'.rand(1000000000).'.xls';
 1800:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1801:     if (! defined($workbook)) {
 1802:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1803:         $r->print(
 1804:             '<p class="LC_error">'
 1805:            .&mt('Problems occurred in creating the new Excel file.')
 1806:            .' '.&mt('This error has been logged.')
 1807:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1808:            .'</p>'
 1809:         );
 1810:         return (undef);
 1811:     }
 1812:     #
 1813:     $workbook->set_tempdir(LONCAPA::tempdir());
 1814:     #
 1815:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1816:     return ($workbook,$filename,$format);
 1817: }
 1818: 
 1819: ###############################################################
 1820: ###############################################################
 1821: 
 1822: =pod
 1823: 
 1824: =item * &create_text_file()
 1825: 
 1826: Create a file to write to and eventually make available to the user.
 1827: If file creation fails, outputs an error message on the request object and 
 1828: return undefs.
 1829: 
 1830: Inputs: Apache request object, and file suffix
 1831: 
 1832: Returns (undef) on failure, 
 1833:     Filehandle and filename on success.
 1834: 
 1835: =cut
 1836: 
 1837: ###############################################################
 1838: ###############################################################
 1839: sub create_text_file {
 1840:     my ($r,$suffix) = @_;
 1841:     if (! defined($suffix)) { $suffix = 'txt'; };
 1842:     my $fh;
 1843:     my $filename = '/prtspool/'.
 1844:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1845:         time.'_'.rand(1000000000).'.'.$suffix;
 1846:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1847:     if (! defined($fh)) {
 1848:         $r->log_error("Couldn't open $filename for output $!");
 1849:         $r->print(
 1850:             '<p class="LC_error">'
 1851:            .&mt('Problems occurred in creating the output file.')
 1852:            .' '.&mt('This error has been logged.')
 1853:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1854:            .'</p>'
 1855:         );
 1856:     }
 1857:     return ($fh,$filename)
 1858: }
 1859: 
 1860: 
 1861: =pod 
 1862: 
 1863: =back
 1864: 
 1865: =cut
 1866: 
 1867: ###############################################################
 1868: ##        Home server <option> list generating code          ##
 1869: ###############################################################
 1870: 
 1871: # ------------------------------------------
 1872: 
 1873: sub domain_select {
 1874:     my ($name,$value,$multiple)=@_;
 1875:     my %domains=map { 
 1876: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1877:     } &Apache::lonnet::all_domains();
 1878:     if ($multiple) {
 1879: 	$domains{''}=&mt('Any domain');
 1880: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1881: 	return &multiple_select_form($name,$value,4,\%domains);
 1882:     } else {
 1883: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1884: 	return &select_form($name,$value,\%domains);
 1885:     }
 1886: }
 1887: 
 1888: #-------------------------------------------
 1889: 
 1890: =pod
 1891: 
 1892: =head1 Routines for form select boxes
 1893: 
 1894: =over 4
 1895: 
 1896: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1897: 
 1898: Returns a string containing a <select> element int multiple mode
 1899: 
 1900: 
 1901: Args:
 1902:   $name - name of the <select> element
 1903:   $value - scalar or array ref of values that should already be selected
 1904:   $size - number of rows long the select element is
 1905:   $hash - the elements should be 'option' => 'shown text'
 1906:           (shown text should already have been &mt())
 1907:   $order - (optional) array ref of the order to show the elements in
 1908: 
 1909: =cut
 1910: 
 1911: #-------------------------------------------
 1912: sub multiple_select_form {
 1913:     my ($name,$value,$size,$hash,$order)=@_;
 1914:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1915:     my $output='';
 1916:     if (! defined($size)) {
 1917:         $size = 4;
 1918:         if (scalar(keys(%$hash))<4) {
 1919:             $size = scalar(keys(%$hash));
 1920:         }
 1921:     }
 1922:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1923:     my @order;
 1924:     if (ref($order) eq 'ARRAY')  {
 1925:         @order = @{$order};
 1926:     } else {
 1927:         @order = sort(keys(%$hash));
 1928:     }
 1929:     if (exists($$hash{'select_form_order'})) {
 1930:         @order = @{$$hash{'select_form_order'}};
 1931:     }
 1932:         
 1933:     foreach my $key (@order) {
 1934:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1935:         $output.='selected="selected" ' if ($selected{$key});
 1936:         $output.='>'.$hash->{$key}."</option>\n";
 1937:     }
 1938:     $output.="</select>\n";
 1939:     return $output;
 1940: }
 1941: 
 1942: #-------------------------------------------
 1943: 
 1944: =pod
 1945: 
 1946: =item * &select_form($defdom,$name,$hashref,$onchange)
 1947: 
 1948: Returns a string containing a <select name='$name' size='1'> form to 
 1949: allow a user to select options from a ref to a hash containing:
 1950: option_name => displayed text. An optional $onchange can include
 1951: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1952: 
 1953: See lonrights.pm for an example invocation and use.
 1954: 
 1955: =cut
 1956: 
 1957: #-------------------------------------------
 1958: sub select_form {
 1959:     my ($def,$name,$hashref,$onchange) = @_;
 1960:     return unless (ref($hashref) eq 'HASH');
 1961:     if ($onchange) {
 1962:         $onchange = ' onchange="'.$onchange.'"';
 1963:     }
 1964:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1965:     my @keys;
 1966:     if (exists($hashref->{'select_form_order'})) {
 1967: 	@keys=@{$hashref->{'select_form_order'}};
 1968:     } else {
 1969: 	@keys=sort(keys(%{$hashref}));
 1970:     }
 1971:     foreach my $key (@keys) {
 1972:         $selectform.=
 1973: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1974:             ($key eq $def ? 'selected="selected" ' : '').
 1975:                 ">".$hashref->{$key}."</option>\n";
 1976:     }
 1977:     $selectform.="</select>";
 1978:     return $selectform;
 1979: }
 1980: 
 1981: # For display filters
 1982: 
 1983: sub display_filter {
 1984:     my ($context) = @_;
 1985:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1986:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1987:     my $phraseinput = 'hidden';
 1988:     my $includeinput = 'hidden';
 1989:     my ($checked,$includetypestext);
 1990:     if ($env{'form.displayfilter'} eq 'containing') {
 1991:         $phraseinput = 'text'; 
 1992:         if ($context eq 'parmslog') {
 1993:             $includeinput = 'checkbox';
 1994:             if ($env{'form.includetypes'}) {
 1995:                 $checked = ' checked="checked"';
 1996:             }
 1997:             $includetypestext = &mt('Include parameter types');
 1998:         }
 1999:     } else {
 2000:         $includetypestext = '&nbsp;';
 2001:     }
 2002:     my ($additional,$secondid,$thirdid);
 2003:     if ($context eq 'parmslog') {
 2004:         $additional = 
 2005:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2006:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2007:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2008:             '</label>';
 2009:         $secondid = 'includetypes';
 2010:         $thirdid = 'includetypestext';
 2011:     }
 2012:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2013:                                                     '$secondid','$thirdid')";
 2014:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2015: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2016: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2017: 	   '</label></span> <span class="LC_nobreak">'.
 2018:            &mt('Filter: [_1]',
 2019: 	   &select_form($env{'form.displayfilter'},
 2020: 			'displayfilter',
 2021: 			{'currentfolder' => 'Current folder/page',
 2022: 			 'containing' => 'Containing phrase',
 2023: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2024: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2025:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2026:                          '" />'.$additional;
 2027: }
 2028: 
 2029: sub display_filter_js {
 2030:     my $includetext = &mt('Include parameter types');
 2031:     return <<"ENDJS";
 2032:   
 2033: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2034:     var firstType = 'hidden';
 2035:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2036:         firstType = 'text';
 2037:     }
 2038:     firstObject = document.getElementById(firstid);
 2039:     if (typeof(firstObject) == 'object') {
 2040:         if (firstObject.type != firstType) {
 2041:             changeInputType(firstObject,firstType);
 2042:         }
 2043:     }
 2044:     if (context == 'parmslog') {
 2045:         var secondType = 'hidden';
 2046:         if (firstType == 'text') {
 2047:             secondType = 'checkbox';
 2048:         }
 2049:         secondObject = document.getElementById(secondid);  
 2050:         if (typeof(secondObject) == 'object') {
 2051:             if (secondObject.type != secondType) {
 2052:                 changeInputType(secondObject,secondType);
 2053:             }
 2054:         }
 2055:         var textItem = document.getElementById(thirdid);
 2056:         var currtext = textItem.innerHTML;
 2057:         var newtext;
 2058:         if (firstType == 'text') {
 2059:             newtext = '$includetext';
 2060:         } else {
 2061:             newtext = '&nbsp;';
 2062:         }
 2063:         if (currtext != newtext) {
 2064:             textItem.innerHTML = newtext;
 2065:         }
 2066:     }
 2067:     return;
 2068: }
 2069: 
 2070: function changeInputType(oldObject,newType) {
 2071:     var newObject = document.createElement('input');
 2072:     newObject.type = newType;
 2073:     if (oldObject.size) {
 2074:         newObject.size = oldObject.size;
 2075:     }
 2076:     if (oldObject.value) {
 2077:         newObject.value = oldObject.value;
 2078:     }
 2079:     if (oldObject.name) {
 2080:         newObject.name = oldObject.name;
 2081:     }
 2082:     if (oldObject.id) {
 2083:         newObject.id = oldObject.id;
 2084:     }
 2085:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2086:     return;
 2087: }
 2088: 
 2089: ENDJS
 2090: }
 2091: 
 2092: sub gradeleveldescription {
 2093:     my $gradelevel=shift;
 2094:     my %gradelevels=(0 => 'Not specified',
 2095: 		     1 => 'Grade 1',
 2096: 		     2 => 'Grade 2',
 2097: 		     3 => 'Grade 3',
 2098: 		     4 => 'Grade 4',
 2099: 		     5 => 'Grade 5',
 2100: 		     6 => 'Grade 6',
 2101: 		     7 => 'Grade 7',
 2102: 		     8 => 'Grade 8',
 2103: 		     9 => 'Grade 9',
 2104: 		     10 => 'Grade 10',
 2105: 		     11 => 'Grade 11',
 2106: 		     12 => 'Grade 12',
 2107: 		     13 => 'Grade 13',
 2108: 		     14 => '100 Level',
 2109: 		     15 => '200 Level',
 2110: 		     16 => '300 Level',
 2111: 		     17 => '400 Level',
 2112: 		     18 => 'Graduate Level');
 2113:     return &mt($gradelevels{$gradelevel});
 2114: }
 2115: 
 2116: sub select_level_form {
 2117:     my ($deflevel,$name)=@_;
 2118:     unless ($deflevel) { $deflevel=0; }
 2119:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2120:     for (my $i=0; $i<=18; $i++) {
 2121:         $selectform.="<option value=\"$i\" ".
 2122:             ($i==$deflevel ? 'selected="selected" ' : '').
 2123:                 ">".&gradeleveldescription($i)."</option>\n";
 2124:     }
 2125:     $selectform.="</select>";
 2126:     return $selectform;
 2127: }
 2128: 
 2129: #-------------------------------------------
 2130: 
 2131: =pod
 2132: 
 2133: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2134: 
 2135: Returns a string containing a <select name='$name' size='1'> form to 
 2136: allow a user to select the domain to preform an operation in.  
 2137: See loncreateuser.pm for an example invocation and use.
 2138: 
 2139: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2140: selected");
 2141: 
 2142: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2143: 
 2144: 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.
 2145: 
 2146: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2147: 
 2148: =cut
 2149: 
 2150: #-------------------------------------------
 2151: sub select_dom_form {
 2152:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2153:     if ($onchange) {
 2154:         $onchange = ' onchange="'.$onchange.'"';
 2155:     }
 2156:     my @domains;
 2157:     if (ref($incdoms) eq 'ARRAY') {
 2158:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2159:     } else {
 2160:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2161:     }
 2162:     if ($includeempty) { @domains=('',@domains); }
 2163:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2164:     foreach my $dom (@domains) {
 2165:         $selectdomain.="<option value=\"$dom\" ".
 2166:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2167:         if ($showdomdesc) {
 2168:             if ($dom ne '') {
 2169:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2170:                 if ($domdesc ne '') {
 2171:                     $selectdomain .= ' ('.$domdesc.')';
 2172:                 }
 2173:             } 
 2174:         }
 2175:         $selectdomain .= "</option>\n";
 2176:     }
 2177:     $selectdomain.="</select>";
 2178:     return $selectdomain;
 2179: }
 2180: 
 2181: #-------------------------------------------
 2182: 
 2183: =pod
 2184: 
 2185: =item * &home_server_form_item($domain,$name,$defaultflag)
 2186: 
 2187: input: 4 arguments (two required, two optional) - 
 2188:     $domain - domain of new user
 2189:     $name - name of form element
 2190:     $default - Value of 'default' causes a default item to be first 
 2191:                             option, and selected by default. 
 2192:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2193:                             if 1 server found, or default, if 0 found.
 2194: output: returns 2 items: 
 2195: (a) form element which contains either:
 2196:    (i) <select name="$name">
 2197:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2198:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2199:        </select>
 2200:        form item if there are multiple library servers in $domain, or
 2201:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2202:        if there is only one library server in $domain.
 2203: 
 2204: (b) number of library servers found.
 2205: 
 2206: See loncreateuser.pm for example of use.
 2207: 
 2208: =cut
 2209: 
 2210: #-------------------------------------------
 2211: sub home_server_form_item {
 2212:     my ($domain,$name,$default,$hide) = @_;
 2213:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2214:     my $result;
 2215:     my $numlib = keys(%servers);
 2216:     if ($numlib > 1) {
 2217:         $result .= '<select name="'.$name.'" />'."\n";
 2218:         if ($default) {
 2219:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2220:                        '</option>'."\n";
 2221:         }
 2222:         foreach my $hostid (sort(keys(%servers))) {
 2223:             $result.= '<option value="'.$hostid.'">'.
 2224: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2225:         }
 2226:         $result .= '</select>'."\n";
 2227:     } elsif ($numlib == 1) {
 2228:         my $hostid;
 2229:         foreach my $item (keys(%servers)) {
 2230:             $hostid = $item;
 2231:         }
 2232:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2233:                    $hostid.'" />';
 2234:                    if (!$hide) {
 2235:                        $result .= $hostid.' '.$servers{$hostid};
 2236:                    }
 2237:                    $result .= "\n";
 2238:     } elsif ($default) {
 2239:         $result .= '<input type="hidden" name="'.$name.
 2240:                    '" value="default" />';
 2241:                    if (!$hide) {
 2242:                        $result .= &mt('default');
 2243:                    }
 2244:                    $result .= "\n";
 2245:     }
 2246:     return ($result,$numlib);
 2247: }
 2248: 
 2249: =pod
 2250: 
 2251: =back 
 2252: 
 2253: =cut
 2254: 
 2255: ###############################################################
 2256: ##                  Decoding User Agent                      ##
 2257: ###############################################################
 2258: 
 2259: =pod
 2260: 
 2261: =head1 Decoding the User Agent
 2262: 
 2263: =over 4
 2264: 
 2265: =item * &decode_user_agent()
 2266: 
 2267: Inputs: $r
 2268: 
 2269: Outputs:
 2270: 
 2271: =over 4
 2272: 
 2273: =item * $httpbrowser
 2274: 
 2275: =item * $clientbrowser
 2276: 
 2277: =item * $clientversion
 2278: 
 2279: =item * $clientmathml
 2280: 
 2281: =item * $clientunicode
 2282: 
 2283: =item * $clientos
 2284: 
 2285: =back
 2286: 
 2287: =back 
 2288: 
 2289: =cut
 2290: 
 2291: ###############################################################
 2292: ###############################################################
 2293: sub decode_user_agent {
 2294:     my ($r)=@_;
 2295:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2296:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2297:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2298:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2299:     my $clientbrowser='unknown';
 2300:     my $clientversion='0';
 2301:     my $clientmathml='';
 2302:     my $clientunicode='0';
 2303:     for (my $i=0;$i<=$#browsertype;$i++) {
 2304:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2305: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2306: 	    $clientbrowser=$bname;
 2307:             $httpbrowser=~/$vreg/i;
 2308: 	    $clientversion=$1;
 2309:             $clientmathml=($clientversion>=$minv);
 2310:             $clientunicode=($clientversion>=$univ);
 2311: 	}
 2312:     }
 2313:     my $clientos='unknown';
 2314:     if (($httpbrowser=~/linux/i) ||
 2315:         ($httpbrowser=~/unix/i) ||
 2316:         ($httpbrowser=~/ux/i) ||
 2317:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2318:     if (($httpbrowser=~/vax/i) ||
 2319:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2320:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2321:     if (($httpbrowser=~/mac/i) ||
 2322:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2323:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2324:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2325:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2326:             $clientunicode,$clientos,);
 2327: }
 2328: 
 2329: ###############################################################
 2330: ##    Authentication changing form generation subroutines    ##
 2331: ###############################################################
 2332: ##
 2333: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2334: ## hash, and have reasonable default values.
 2335: ##
 2336: ##    formname = the name given in the <form> tag.
 2337: #-------------------------------------------
 2338: 
 2339: =pod
 2340: 
 2341: =head1 Authentication Routines
 2342: 
 2343: =over 4
 2344: 
 2345: =item * &authform_xxxxxx()
 2346: 
 2347: The authform_xxxxxx subroutines provide javascript and html forms which 
 2348: handle some of the conveniences required for authentication forms.  
 2349: This is not an optimal method, but it works.  
 2350: 
 2351: =over 4
 2352: 
 2353: =item * authform_header
 2354: 
 2355: =item * authform_authorwarning
 2356: 
 2357: =item * authform_nochange
 2358: 
 2359: =item * authform_kerberos
 2360: 
 2361: =item * authform_internal
 2362: 
 2363: =item * authform_filesystem
 2364: 
 2365: =back
 2366: 
 2367: See loncreateuser.pm for invocation and use examples.
 2368: 
 2369: =cut
 2370: 
 2371: #-------------------------------------------
 2372: sub authform_header{  
 2373:     my %in = (
 2374:         formname => 'cu',
 2375:         kerb_def_dom => '',
 2376:         @_,
 2377:     );
 2378:     $in{'formname'} = 'document.' . $in{'formname'};
 2379:     my $result='';
 2380: 
 2381: #---------------------------------------------- Code for upper case translation
 2382:     my $Javascript_toUpperCase;
 2383:     unless ($in{kerb_def_dom}) {
 2384:         $Javascript_toUpperCase =<<"END";
 2385:         switch (choice) {
 2386:            case 'krb': currentform.elements[choicearg].value =
 2387:                currentform.elements[choicearg].value.toUpperCase();
 2388:                break;
 2389:            default:
 2390:         }
 2391: END
 2392:     } else {
 2393:         $Javascript_toUpperCase = "";
 2394:     }
 2395: 
 2396:     my $radioval = "'nochange'";
 2397:     if (defined($in{'curr_authtype'})) {
 2398:         if ($in{'curr_authtype'} ne '') {
 2399:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2400:         }
 2401:     }
 2402:     my $argfield = 'null';
 2403:     if (defined($in{'mode'})) {
 2404:         if ($in{'mode'} eq 'modifycourse')  {
 2405:             if (defined($in{'curr_autharg'})) {
 2406:                 if ($in{'curr_autharg'} ne '') {
 2407:                     $argfield = "'$in{'curr_autharg'}'";
 2408:                 }
 2409:             }
 2410:         }
 2411:     }
 2412: 
 2413:     $result.=<<"END";
 2414: var current = new Object();
 2415: current.radiovalue = $radioval;
 2416: current.argfield = $argfield;
 2417: 
 2418: function changed_radio(choice,currentform) {
 2419:     var choicearg = choice + 'arg';
 2420:     // If a radio button in changed, we need to change the argfield
 2421:     if (current.radiovalue != choice) {
 2422:         current.radiovalue = choice;
 2423:         if (current.argfield != null) {
 2424:             currentform.elements[current.argfield].value = '';
 2425:         }
 2426:         if (choice == 'nochange') {
 2427:             current.argfield = null;
 2428:         } else {
 2429:             current.argfield = choicearg;
 2430:             switch(choice) {
 2431:                 case 'krb': 
 2432:                     currentform.elements[current.argfield].value = 
 2433:                         "$in{'kerb_def_dom'}";
 2434:                 break;
 2435:               default:
 2436:                 break;
 2437:             }
 2438:         }
 2439:     }
 2440:     return;
 2441: }
 2442: 
 2443: function changed_text(choice,currentform) {
 2444:     var choicearg = choice + 'arg';
 2445:     if (currentform.elements[choicearg].value !='') {
 2446:         $Javascript_toUpperCase
 2447:         // clear old field
 2448:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2449:             currentform.elements[current.argfield].value = '';
 2450:         }
 2451:         current.argfield = choicearg;
 2452:     }
 2453:     set_auth_radio_buttons(choice,currentform);
 2454:     return;
 2455: }
 2456: 
 2457: function set_auth_radio_buttons(newvalue,currentform) {
 2458:     var numauthchoices = currentform.login.length;
 2459:     if (typeof numauthchoices  == "undefined") {
 2460:         return;
 2461:     } 
 2462:     var i=0;
 2463:     while (i < numauthchoices) {
 2464:         if (currentform.login[i].value == newvalue) { break; }
 2465:         i++;
 2466:     }
 2467:     if (i == numauthchoices) {
 2468:         return;
 2469:     }
 2470:     current.radiovalue = newvalue;
 2471:     currentform.login[i].checked = true;
 2472:     return;
 2473: }
 2474: END
 2475:     return $result;
 2476: }
 2477: 
 2478: sub authform_authorwarning{
 2479:     my $result='';
 2480:     $result='<i>'.
 2481:         &mt('As a general rule, only authors or co-authors should be '.
 2482:             'filesystem authenticated '.
 2483:             '(which allows access to the server filesystem).')."</i>\n";
 2484:     return $result;
 2485: }
 2486: 
 2487: sub authform_nochange{  
 2488:     my %in = (
 2489:               formname => 'document.cu',
 2490:               kerb_def_dom => 'MSU.EDU',
 2491:               @_,
 2492:           );
 2493:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2494:     my $result;
 2495:     if (keys(%can_assign) == 0) {
 2496:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2497:     } else {
 2498:         $result = '<label>'.&mt('[_1] Do not change login data',
 2499:                   '<input type="radio" name="login" value="nochange" '.
 2500:                   'checked="checked" onclick="'.
 2501:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2502: 	    '</label>';
 2503:     }
 2504:     return $result;
 2505: }
 2506: 
 2507: sub authform_kerberos {
 2508:     my %in = (
 2509:               formname => 'document.cu',
 2510:               kerb_def_dom => 'MSU.EDU',
 2511:               kerb_def_auth => 'krb4',
 2512:               @_,
 2513:               );
 2514:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2515:         $autharg,$jscall);
 2516:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2517:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2518:        $check5 = ' checked="checked"';
 2519:     } else {
 2520:        $check4 = ' checked="checked"';
 2521:     }
 2522:     $krbarg = $in{'kerb_def_dom'};
 2523:     if (defined($in{'curr_authtype'})) {
 2524:         if ($in{'curr_authtype'} eq 'krb') {
 2525:             $krbcheck = ' checked="checked"';
 2526:             if (defined($in{'mode'})) {
 2527:                 if ($in{'mode'} eq 'modifyuser') {
 2528:                     $krbcheck = '';
 2529:                 }
 2530:             }
 2531:             if (defined($in{'curr_kerb_ver'})) {
 2532:                 if ($in{'curr_krb_ver'} eq '5') {
 2533:                     $check5 = ' checked="checked"';
 2534:                     $check4 = '';
 2535:                 } else {
 2536:                     $check4 = ' checked="checked"';
 2537:                     $check5 = '';
 2538:                 }
 2539:             }
 2540:             if (defined($in{'curr_autharg'})) {
 2541:                 $krbarg = $in{'curr_autharg'};
 2542:             }
 2543:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2544:                 if (defined($in{'curr_autharg'})) {
 2545:                     $result = 
 2546:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2547:         $in{'curr_autharg'},$krbver);
 2548:                 } else {
 2549:                     $result =
 2550:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2551:                 }
 2552:                 return $result; 
 2553:             }
 2554:         }
 2555:     } else {
 2556:         if ($authnum == 1) {
 2557:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2558:         }
 2559:     }
 2560:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2561:         return;
 2562:     } elsif ($authtype eq '') {
 2563:         if (defined($in{'mode'})) {
 2564:             if ($in{'mode'} eq 'modifycourse') {
 2565:                 if ($authnum == 1) {
 2566:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2567:                 }
 2568:             }
 2569:         }
 2570:     }
 2571:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2572:     if ($authtype eq '') {
 2573:         $authtype = '<input type="radio" name="login" value="krb" '.
 2574:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2575:                     $krbcheck.' />';
 2576:     }
 2577:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2578:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2579:          $in{'curr_authtype'} eq 'krb5') ||
 2580:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2581:          $in{'curr_authtype'} eq 'krb4')) {
 2582:         $result .= &mt
 2583:         ('[_1] Kerberos authenticated with domain [_2] '.
 2584:          '[_3] Version 4 [_4] Version 5 [_5]',
 2585:          '<label>'.$authtype,
 2586:          '</label><input type="text" size="10" name="krbarg" '.
 2587:              'value="'.$krbarg.'" '.
 2588:              'onchange="'.$jscall.'" />',
 2589:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2590:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2591: 	 '</label>');
 2592:     } elsif ($can_assign{'krb4'}) {
 2593:         $result .= &mt
 2594:         ('[_1] Kerberos authenticated with domain [_2] '.
 2595:          '[_3] Version 4 [_4]',
 2596:          '<label>'.$authtype,
 2597:          '</label><input type="text" size="10" name="krbarg" '.
 2598:              'value="'.$krbarg.'" '.
 2599:              'onchange="'.$jscall.'" />',
 2600:          '<label><input type="hidden" name="krbver" value="4" />',
 2601:          '</label>');
 2602:     } elsif ($can_assign{'krb5'}) {
 2603:         $result .= &mt
 2604:         ('[_1] Kerberos authenticated with domain [_2] '.
 2605:          '[_3] Version 5 [_4]',
 2606:          '<label>'.$authtype,
 2607:          '</label><input type="text" size="10" name="krbarg" '.
 2608:              'value="'.$krbarg.'" '.
 2609:              'onchange="'.$jscall.'" />',
 2610:          '<label><input type="hidden" name="krbver" value="5" />',
 2611:          '</label>');
 2612:     }
 2613:     return $result;
 2614: }
 2615: 
 2616: sub authform_internal{  
 2617:     my %in = (
 2618:                 formname => 'document.cu',
 2619:                 kerb_def_dom => 'MSU.EDU',
 2620:                 @_,
 2621:                 );
 2622:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2623:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2624:     if (defined($in{'curr_authtype'})) {
 2625:         if ($in{'curr_authtype'} eq 'int') {
 2626:             if ($can_assign{'int'}) {
 2627:                 $intcheck = 'checked="checked" ';
 2628:                 if (defined($in{'mode'})) {
 2629:                     if ($in{'mode'} eq 'modifyuser') {
 2630:                         $intcheck = '';
 2631:                     }
 2632:                 }
 2633:                 if (defined($in{'curr_autharg'})) {
 2634:                     $intarg = $in{'curr_autharg'};
 2635:                 }
 2636:             } else {
 2637:                 $result = &mt('Currently internally authenticated.');
 2638:                 return $result;
 2639:             }
 2640:         }
 2641:     } else {
 2642:         if ($authnum == 1) {
 2643:             $authtype = '<input type="hidden" name="login" value="int" />';
 2644:         }
 2645:     }
 2646:     if (!$can_assign{'int'}) {
 2647:         return;
 2648:     } elsif ($authtype eq '') {
 2649:         if (defined($in{'mode'})) {
 2650:             if ($in{'mode'} eq 'modifycourse') {
 2651:                 if ($authnum == 1) {
 2652:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2653:                 }
 2654:             }
 2655:         }
 2656:     }
 2657:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2658:     if ($authtype eq '') {
 2659:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2660:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2661:     }
 2662:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2663:                $intarg.'" onchange="'.$jscall.'" />';
 2664:     $result = &mt
 2665:         ('[_1] Internally authenticated (with initial password [_2])',
 2666:          '<label>'.$authtype,'</label>'.$autharg);
 2667:     $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>';
 2668:     return $result;
 2669: }
 2670: 
 2671: sub authform_local{  
 2672:     my %in = (
 2673:               formname => 'document.cu',
 2674:               kerb_def_dom => 'MSU.EDU',
 2675:               @_,
 2676:               );
 2677:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2678:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2679:     if (defined($in{'curr_authtype'})) {
 2680:         if ($in{'curr_authtype'} eq 'loc') {
 2681:             if ($can_assign{'loc'}) {
 2682:                 $loccheck = 'checked="checked" ';
 2683:                 if (defined($in{'mode'})) {
 2684:                     if ($in{'mode'} eq 'modifyuser') {
 2685:                         $loccheck = '';
 2686:                     }
 2687:                 }
 2688:                 if (defined($in{'curr_autharg'})) {
 2689:                     $locarg = $in{'curr_autharg'};
 2690:                 }
 2691:             } else {
 2692:                 $result = &mt('Currently using local (institutional) authentication.');
 2693:                 return $result;
 2694:             }
 2695:         }
 2696:     } else {
 2697:         if ($authnum == 1) {
 2698:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2699:         }
 2700:     }
 2701:     if (!$can_assign{'loc'}) {
 2702:         return;
 2703:     } elsif ($authtype eq '') {
 2704:         if (defined($in{'mode'})) {
 2705:             if ($in{'mode'} eq 'modifycourse') {
 2706:                 if ($authnum == 1) {
 2707:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2708:                 }
 2709:             }
 2710:         }
 2711:     }
 2712:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2713:     if ($authtype eq '') {
 2714:         $authtype = '<input type="radio" name="login" value="loc" '.
 2715:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2716:                     $jscall.'" />';
 2717:     }
 2718:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2719:                $locarg.'" onchange="'.$jscall.'" />';
 2720:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2721:                   '<label>'.$authtype,'</label>'.$autharg);
 2722:     return $result;
 2723: }
 2724: 
 2725: sub authform_filesystem{  
 2726:     my %in = (
 2727:               formname => 'document.cu',
 2728:               kerb_def_dom => 'MSU.EDU',
 2729:               @_,
 2730:               );
 2731:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2732:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2733:     if (defined($in{'curr_authtype'})) {
 2734:         if ($in{'curr_authtype'} eq 'fsys') {
 2735:             if ($can_assign{'fsys'}) {
 2736:                 $fsyscheck = 'checked="checked" ';
 2737:                 if (defined($in{'mode'})) {
 2738:                     if ($in{'mode'} eq 'modifyuser') {
 2739:                         $fsyscheck = '';
 2740:                     }
 2741:                 }
 2742:             } else {
 2743:                 $result = &mt('Currently Filesystem Authenticated.');
 2744:                 return $result;
 2745:             }           
 2746:         }
 2747:     } else {
 2748:         if ($authnum == 1) {
 2749:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2750:         }
 2751:     }
 2752:     if (!$can_assign{'fsys'}) {
 2753:         return;
 2754:     } elsif ($authtype eq '') {
 2755:         if (defined($in{'mode'})) {
 2756:             if ($in{'mode'} eq 'modifycourse') {
 2757:                 if ($authnum == 1) {
 2758:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2759:                 }
 2760:             }
 2761:         }
 2762:     }
 2763:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2764:     if ($authtype eq '') {
 2765:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2766:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2767:                     $jscall.'" />';
 2768:     }
 2769:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2770:                ' onchange="'.$jscall.'" />';
 2771:     $result = &mt
 2772:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2773:          '<label><input type="radio" name="login" value="fsys" '.
 2774:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2775:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2776:                   'onchange="'.$jscall.'" />');
 2777:     return $result;
 2778: }
 2779: 
 2780: sub get_assignable_auth {
 2781:     my ($dom) = @_;
 2782:     if ($dom eq '') {
 2783:         $dom = $env{'request.role.domain'};
 2784:     }
 2785:     my %can_assign = (
 2786:                           krb4 => 1,
 2787:                           krb5 => 1,
 2788:                           int  => 1,
 2789:                           loc  => 1,
 2790:                      );
 2791:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2792:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2793:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2794:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2795:             my $context;
 2796:             if ($env{'request.role'} =~ /^au/) {
 2797:                 $context = 'author';
 2798:             } elsif ($env{'request.role'} =~ /^dc/) {
 2799:                 $context = 'domain';
 2800:             } elsif ($env{'request.course.id'}) {
 2801:                 $context = 'course';
 2802:             }
 2803:             if ($context) {
 2804:                 if (ref($authhash->{$context}) eq 'HASH') {
 2805:                    %can_assign = %{$authhash->{$context}}; 
 2806:                 }
 2807:             }
 2808:         }
 2809:     }
 2810:     my $authnum = 0;
 2811:     foreach my $key (keys(%can_assign)) {
 2812:         if ($can_assign{$key}) {
 2813:             $authnum ++;
 2814:         }
 2815:     }
 2816:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2817:         $authnum --;
 2818:     }
 2819:     return ($authnum,%can_assign);
 2820: }
 2821: 
 2822: ###############################################################
 2823: ##    Get Kerberos Defaults for Domain                 ##
 2824: ###############################################################
 2825: ##
 2826: ## Returns default kerberos version and an associated argument
 2827: ## as listed in file domain.tab. If not listed, provides
 2828: ## appropriate default domain and kerberos version.
 2829: ##
 2830: #-------------------------------------------
 2831: 
 2832: =pod
 2833: 
 2834: =item * &get_kerberos_defaults()
 2835: 
 2836: get_kerberos_defaults($target_domain) returns the default kerberos
 2837: version and domain. If not found, it defaults to version 4 and the 
 2838: domain of the server.
 2839: 
 2840: =over 4
 2841: 
 2842: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2843: 
 2844: =back
 2845: 
 2846: =back
 2847: 
 2848: =cut
 2849: 
 2850: #-------------------------------------------
 2851: sub get_kerberos_defaults {
 2852:     my $domain=shift;
 2853:     my ($krbdef,$krbdefdom);
 2854:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2855:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2856:         $krbdef = $domdefaults{'auth_def'};
 2857:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2858:     } else {
 2859:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2860:         my $krbdefdom=$1;
 2861:         $krbdefdom=~tr/a-z/A-Z/;
 2862:         $krbdef = "krb4";
 2863:     }
 2864:     return ($krbdef,$krbdefdom);
 2865: }
 2866: 
 2867: 
 2868: ###############################################################
 2869: ##                Thesaurus Functions                        ##
 2870: ###############################################################
 2871: 
 2872: =pod
 2873: 
 2874: =head1 Thesaurus Functions
 2875: 
 2876: =over 4
 2877: 
 2878: =item * &initialize_keywords()
 2879: 
 2880: Initializes the package variable %Keywords if it is empty.  Uses the
 2881: package variable $thesaurus_db_file.
 2882: 
 2883: =cut
 2884: 
 2885: ###################################################
 2886: 
 2887: sub initialize_keywords {
 2888:     return 1 if (scalar keys(%Keywords));
 2889:     # If we are here, %Keywords is empty, so fill it up
 2890:     #   Make sure the file we need exists...
 2891:     if (! -e $thesaurus_db_file) {
 2892:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2893:                                  " failed because it does not exist");
 2894:         return 0;
 2895:     }
 2896:     #   Set up the hash as a database
 2897:     my %thesaurus_db;
 2898:     if (! tie(%thesaurus_db,'GDBM_File',
 2899:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2900:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2901:                                  $thesaurus_db_file);
 2902:         return 0;
 2903:     } 
 2904:     #  Get the average number of appearances of a word.
 2905:     my $avecount = $thesaurus_db{'average.count'};
 2906:     #  Put keywords (those that appear > average) into %Keywords
 2907:     while (my ($word,$data)=each (%thesaurus_db)) {
 2908:         my ($count,undef) = split /:/,$data;
 2909:         $Keywords{$word}++ if ($count > $avecount);
 2910:     }
 2911:     untie %thesaurus_db;
 2912:     # Remove special values from %Keywords.
 2913:     foreach my $value ('total.count','average.count') {
 2914:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2915:   }
 2916:     return 1;
 2917: }
 2918: 
 2919: ###################################################
 2920: 
 2921: =pod
 2922: 
 2923: =item * &keyword($word)
 2924: 
 2925: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2926: than the average number of times in the thesaurus database.  Calls 
 2927: &initialize_keywords
 2928: 
 2929: =cut
 2930: 
 2931: ###################################################
 2932: 
 2933: sub keyword {
 2934:     return if (!&initialize_keywords());
 2935:     my $word=lc(shift());
 2936:     $word=~s/\W//g;
 2937:     return exists($Keywords{$word});
 2938: }
 2939: 
 2940: ###############################################################
 2941: 
 2942: =pod 
 2943: 
 2944: =item * &get_related_words()
 2945: 
 2946: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2947: an array of words.  If the keyword is not in the thesaurus, an empty array
 2948: will be returned.  The order of the words returned is determined by the
 2949: database which holds them.
 2950: 
 2951: Uses global $thesaurus_db_file.
 2952: 
 2953: 
 2954: =cut
 2955: 
 2956: ###############################################################
 2957: sub get_related_words {
 2958:     my $keyword = shift;
 2959:     my %thesaurus_db;
 2960:     if (! -e $thesaurus_db_file) {
 2961:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2962:                                  "failed because the file does not exist");
 2963:         return ();
 2964:     }
 2965:     if (! tie(%thesaurus_db,'GDBM_File',
 2966:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2967:         return ();
 2968:     } 
 2969:     my @Words=();
 2970:     my $count=0;
 2971:     if (exists($thesaurus_db{$keyword})) {
 2972: 	# The first element is the number of times
 2973: 	# the word appears.  We do not need it now.
 2974: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2975: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2976: 	my $threshold=$mostfrequentcount/10;
 2977:         foreach my $possibleword (@RelatedWords) {
 2978:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2979:             if ($wordcount>$threshold) {
 2980: 		push(@Words,$word);
 2981:                 $count++;
 2982:                 if ($count>10) { last; }
 2983: 	    }
 2984:         }
 2985:     }
 2986:     untie %thesaurus_db;
 2987:     return @Words;
 2988: }
 2989: 
 2990: =pod
 2991: 
 2992: =back
 2993: 
 2994: =cut
 2995: 
 2996: # -------------------------------------------------------------- Plaintext name
 2997: =pod
 2998: 
 2999: =head1 User Name Functions
 3000: 
 3001: =over 4
 3002: 
 3003: =item * &plainname($uname,$udom,$first)
 3004: 
 3005: Takes a users logon name and returns it as a string in
 3006: "first middle last generation" form 
 3007: if $first is set to 'lastname' then it returns it as
 3008: 'lastname generation, firstname middlename' if their is a lastname
 3009: 
 3010: =cut
 3011: 
 3012: 
 3013: ###############################################################
 3014: sub plainname {
 3015:     my ($uname,$udom,$first)=@_;
 3016:     return if (!defined($uname) || !defined($udom));
 3017:     my %names=&getnames($uname,$udom);
 3018:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3019: 					  $names{'middlename'},
 3020: 					  $names{'lastname'},
 3021: 					  $names{'generation'},$first);
 3022:     $name=~s/^\s+//;
 3023:     $name=~s/\s+$//;
 3024:     $name=~s/\s+/ /g;
 3025:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3026:     return $name;
 3027: }
 3028: 
 3029: # -------------------------------------------------------------------- Nickname
 3030: =pod
 3031: 
 3032: =item * &nickname($uname,$udom)
 3033: 
 3034: Gets a users name and returns it as a string as
 3035: 
 3036: "&quot;nickname&quot;"
 3037: 
 3038: if the user has a nickname or
 3039: 
 3040: "first middle last generation"
 3041: 
 3042: if the user does not
 3043: 
 3044: =cut
 3045: 
 3046: sub nickname {
 3047:     my ($uname,$udom)=@_;
 3048:     return if (!defined($uname) || !defined($udom));
 3049:     my %names=&getnames($uname,$udom);
 3050:     my $name=$names{'nickname'};
 3051:     if ($name) {
 3052:        $name='&quot;'.$name.'&quot;'; 
 3053:     } else {
 3054:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3055: 	     $names{'lastname'}.' '.$names{'generation'};
 3056:        $name=~s/\s+$//;
 3057:        $name=~s/\s+/ /g;
 3058:     }
 3059:     return $name;
 3060: }
 3061: 
 3062: sub getnames {
 3063:     my ($uname,$udom)=@_;
 3064:     return if (!defined($uname) || !defined($udom));
 3065:     if ($udom eq 'public' && $uname eq 'public') {
 3066: 	return ('lastname' => &mt('Public'));
 3067:     }
 3068:     my $id=$uname.':'.$udom;
 3069:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3070:     if ($cached) {
 3071: 	return %{$names};
 3072:     } else {
 3073: 	my %loadnames=&Apache::lonnet::get('environment',
 3074:                     ['firstname','middlename','lastname','generation','nickname'],
 3075: 					 $udom,$uname);
 3076: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3077: 	return %loadnames;
 3078:     }
 3079: }
 3080: 
 3081: # -------------------------------------------------------------------- getemails
 3082: 
 3083: =pod
 3084: 
 3085: =item * &getemails($uname,$udom)
 3086: 
 3087: Gets a user's email information and returns it as a hash with keys:
 3088: notification, critnotification, permanentemail
 3089: 
 3090: For notification and critnotification, values are comma-separated lists 
 3091: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3092:  
 3093: 
 3094: =cut
 3095: 
 3096: 
 3097: sub getemails {
 3098:     my ($uname,$udom)=@_;
 3099:     if ($udom eq 'public' && $uname eq 'public') {
 3100: 	return;
 3101:     }
 3102:     if (!$udom) { $udom=$env{'user.domain'}; }
 3103:     if (!$uname) { $uname=$env{'user.name'}; }
 3104:     my $id=$uname.':'.$udom;
 3105:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3106:     if ($cached) {
 3107: 	return %{$names};
 3108:     } else {
 3109: 	my %loadnames=&Apache::lonnet::get('environment',
 3110:                     			   ['notification','critnotification',
 3111: 					    'permanentemail'],
 3112: 					   $udom,$uname);
 3113: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3114: 	return %loadnames;
 3115:     }
 3116: }
 3117: 
 3118: sub flush_email_cache {
 3119:     my ($uname,$udom)=@_;
 3120:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3121:     if (!$uname) { $uname=$env{'user.name'};   }
 3122:     return if ($udom eq 'public' && $uname eq 'public');
 3123:     my $id=$uname.':'.$udom;
 3124:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3125: }
 3126: 
 3127: # -------------------------------------------------------------------- getlangs
 3128: 
 3129: =pod
 3130: 
 3131: =item * &getlangs($uname,$udom)
 3132: 
 3133: Gets a user's language preference and returns it as a hash with key:
 3134: language.
 3135: 
 3136: =cut
 3137: 
 3138: 
 3139: sub getlangs {
 3140:     my ($uname,$udom) = @_;
 3141:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3142:     if (!$uname) { $uname=$env{'user.name'};   }
 3143:     my $id=$uname.':'.$udom;
 3144:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3145:     if ($cached) {
 3146:         return %{$langs};
 3147:     } else {
 3148:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3149:                                            $udom,$uname);
 3150:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3151:         return %loadlangs;
 3152:     }
 3153: }
 3154: 
 3155: sub flush_langs_cache {
 3156:     my ($uname,$udom)=@_;
 3157:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3158:     if (!$uname) { $uname=$env{'user.name'};   }
 3159:     return if ($udom eq 'public' && $uname eq 'public');
 3160:     my $id=$uname.':'.$udom;
 3161:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3162: }
 3163: 
 3164: # ------------------------------------------------------------------ Screenname
 3165: 
 3166: =pod
 3167: 
 3168: =item * &screenname($uname,$udom)
 3169: 
 3170: Gets a users screenname and returns it as a string
 3171: 
 3172: =cut
 3173: 
 3174: sub screenname {
 3175:     my ($uname,$udom)=@_;
 3176:     if ($uname eq $env{'user.name'} &&
 3177: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3178:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3179:     return $names{'screenname'};
 3180: }
 3181: 
 3182: 
 3183: # ------------------------------------------------------------- Confirm Wrapper
 3184: =pod
 3185: 
 3186: =item confirmwrapper
 3187: 
 3188: Wrap messages about completion of operation in box
 3189: 
 3190: =cut
 3191: 
 3192: sub confirmwrapper {
 3193:     my ($message)=@_;
 3194:     if ($message) {
 3195:         return "\n".'<div class="LC_confirm_box">'."\n"
 3196:                .$message."\n"
 3197:                .'</div>'."\n";
 3198:     } else {
 3199:         return $message;
 3200:     }
 3201: }
 3202: 
 3203: # ------------------------------------------------------------- Message Wrapper
 3204: 
 3205: sub messagewrapper {
 3206:     my ($link,$username,$domain,$subject,$text)=@_;
 3207:     return 
 3208:         '<a href="/adm/email?compose=individual&amp;'.
 3209:         'recname='.$username.'&amp;recdom='.$domain.
 3210: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3211:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3212: }
 3213: 
 3214: # --------------------------------------------------------------- Notes Wrapper
 3215: 
 3216: sub noteswrapper {
 3217:     my ($link,$un,$do)=@_;
 3218:     return 
 3219: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3220: }
 3221: 
 3222: # ------------------------------------------------------------- Aboutme Wrapper
 3223: 
 3224: sub aboutmewrapper {
 3225:     my ($link,$username,$domain,$target,$class)=@_;
 3226:     if (!defined($username)  && !defined($domain)) {
 3227:         return;
 3228:     }
 3229:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3230: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3231: }
 3232: 
 3233: # ------------------------------------------------------------ Syllabus Wrapper
 3234: 
 3235: sub syllabuswrapper {
 3236:     my ($linktext,$coursedir,$domain)=@_;
 3237:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3238: }
 3239: 
 3240: # -----------------------------------------------------------------------------
 3241: 
 3242: sub track_student_link {
 3243:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3244:     my $link ="/adm/trackstudent?";
 3245:     my $title = 'View recent activity';
 3246:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3247:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3248:         $link .= "selected_student=$sname:$sdom";
 3249:         $title .= ' of this student';
 3250:     } 
 3251:     if (defined($target) && $target !~ /^\s*$/) {
 3252:         $target = qq{target="$target"};
 3253:     } else {
 3254:         $target = '';
 3255:     }
 3256:     if ($start) { $link.='&amp;start='.$start; }
 3257:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3258:     $title = &mt($title);
 3259:     $linktext = &mt($linktext);
 3260:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3261: 	&help_open_topic('View_recent_activity');
 3262: }
 3263: 
 3264: sub slot_reservations_link {
 3265:     my ($linktext,$sname,$sdom,$target) = @_;
 3266:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3267:     my $title = 'View slot reservation history';
 3268:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3269:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3270:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3271:         $title .= ' of this student';
 3272:     }
 3273:     if (defined($target) && $target !~ /^\s*$/) {
 3274:         $target = qq{target="$target"};
 3275:     } else {
 3276:         $target = '';
 3277:     }
 3278:     $title = &mt($title);
 3279:     $linktext = &mt($linktext);
 3280:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3281: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3282: 
 3283: }
 3284: 
 3285: # ===================================================== Display a student photo
 3286: 
 3287: 
 3288: sub student_image_tag {
 3289:     my ($domain,$user)=@_;
 3290:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3291:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3292: 	return '<img src="'.$imgsrc.'" align="right" />';
 3293:     } else {
 3294: 	return '';
 3295:     }
 3296: }
 3297: 
 3298: =pod
 3299: 
 3300: =back
 3301: 
 3302: =head1 Access .tab File Data
 3303: 
 3304: =over 4
 3305: 
 3306: =item * &languageids() 
 3307: 
 3308: returns list of all language ids
 3309: 
 3310: =cut
 3311: 
 3312: sub languageids {
 3313:     return sort(keys(%language));
 3314: }
 3315: 
 3316: =pod
 3317: 
 3318: =item * &languagedescription() 
 3319: 
 3320: returns description of a specified language id
 3321: 
 3322: =cut
 3323: 
 3324: sub languagedescription {
 3325:     my $code=shift;
 3326:     return  ($supported_language{$code}?'* ':'').
 3327:             $language{$code}.
 3328: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3329: }
 3330: 
 3331: =pod
 3332: 
 3333: =item * &plainlanguagedescription
 3334: 
 3335: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3336: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3337: 
 3338: =cut
 3339: 
 3340: sub plainlanguagedescription {
 3341:     my $code=shift;
 3342:     return $language{$code};
 3343: }
 3344: 
 3345: =pod
 3346: 
 3347: =item * &supportedlanguagecode
 3348: 
 3349: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3350: code.
 3351: 
 3352: =cut
 3353: 
 3354: sub supportedlanguagecode {
 3355:     my $code=shift;
 3356:     return $supported_language{$code};
 3357: }
 3358: 
 3359: =pod
 3360: 
 3361: =item * &latexlanguage()
 3362: 
 3363: Given a language key code returns the correspondnig language to use
 3364: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3365: is no supported hyphenation for the language code.
 3366: 
 3367: =cut
 3368: 
 3369: sub latexlanguage {
 3370:     my $code = shift;
 3371:     return $latex_language{$code};
 3372: }
 3373: 
 3374: =pod
 3375: 
 3376: =item * &latexhyphenation()
 3377: 
 3378: Same as above but what's supplied is the language as it might be stored
 3379: in the metadata.
 3380: 
 3381: =cut
 3382: 
 3383: sub latexhyphenation {
 3384:     my $key = shift;
 3385:     return $latex_language_bykey{$key};
 3386: }
 3387: 
 3388: =pod
 3389: 
 3390: =item * &copyrightids() 
 3391: 
 3392: returns list of all copyrights
 3393: 
 3394: =cut
 3395: 
 3396: sub copyrightids {
 3397:     return sort(keys(%cprtag));
 3398: }
 3399: 
 3400: =pod
 3401: 
 3402: =item * &copyrightdescription() 
 3403: 
 3404: returns description of a specified copyright id
 3405: 
 3406: =cut
 3407: 
 3408: sub copyrightdescription {
 3409:     return &mt($cprtag{shift(@_)});
 3410: }
 3411: 
 3412: =pod
 3413: 
 3414: =item * &source_copyrightids() 
 3415: 
 3416: returns list of all source copyrights
 3417: 
 3418: =cut
 3419: 
 3420: sub source_copyrightids {
 3421:     return sort(keys(%scprtag));
 3422: }
 3423: 
 3424: =pod
 3425: 
 3426: =item * &source_copyrightdescription() 
 3427: 
 3428: returns description of a specified source copyright id
 3429: 
 3430: =cut
 3431: 
 3432: sub source_copyrightdescription {
 3433:     return &mt($scprtag{shift(@_)});
 3434: }
 3435: 
 3436: =pod
 3437: 
 3438: =item * &filecategories() 
 3439: 
 3440: returns list of all file categories
 3441: 
 3442: =cut
 3443: 
 3444: sub filecategories {
 3445:     return sort(keys(%category_extensions));
 3446: }
 3447: 
 3448: =pod
 3449: 
 3450: =item * &filecategorytypes() 
 3451: 
 3452: returns list of file types belonging to a given file
 3453: category
 3454: 
 3455: =cut
 3456: 
 3457: sub filecategorytypes {
 3458:     my ($cat) = @_;
 3459:     return @{$category_extensions{lc($cat)}};
 3460: }
 3461: 
 3462: =pod
 3463: 
 3464: =item * &fileembstyle() 
 3465: 
 3466: returns embedding style for a specified file type
 3467: 
 3468: =cut
 3469: 
 3470: sub fileembstyle {
 3471:     return $fe{lc(shift(@_))};
 3472: }
 3473: 
 3474: sub filemimetype {
 3475:     return $fm{lc(shift(@_))};
 3476: }
 3477: 
 3478: 
 3479: sub filecategoryselect {
 3480:     my ($name,$value)=@_;
 3481:     return &select_form($value,$name,
 3482:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3483: }
 3484: 
 3485: =pod
 3486: 
 3487: =item * &filedescription() 
 3488: 
 3489: returns description for a specified file type
 3490: 
 3491: =cut
 3492: 
 3493: sub filedescription {
 3494:     my $file_description = $fd{lc(shift())};
 3495:     $file_description =~ s:([\[\]]):~$1:g;
 3496:     return &mt($file_description);
 3497: }
 3498: 
 3499: =pod
 3500: 
 3501: =item * &filedescriptionex() 
 3502: 
 3503: returns description for a specified file type with
 3504: extra formatting
 3505: 
 3506: =cut
 3507: 
 3508: sub filedescriptionex {
 3509:     my $ex=shift;
 3510:     my $file_description = $fd{lc($ex)};
 3511:     $file_description =~ s:([\[\]]):~$1:g;
 3512:     return '.'.$ex.' '.&mt($file_description);
 3513: }
 3514: 
 3515: # End of .tab access
 3516: =pod
 3517: 
 3518: =back
 3519: 
 3520: =cut
 3521: 
 3522: # ------------------------------------------------------------------ File Types
 3523: sub fileextensions {
 3524:     return sort(keys(%fe));
 3525: }
 3526: 
 3527: # ----------------------------------------------------------- Display Languages
 3528: # returns a hash with all desired display languages
 3529: #
 3530: 
 3531: sub display_languages {
 3532:     my %languages=();
 3533:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3534: 	$languages{$lang}=1;
 3535:     }
 3536:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3537:     if ($env{'form.displaylanguage'}) {
 3538: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3539: 	    $languages{$lang}=1;
 3540:         }
 3541:     }
 3542:     return %languages;
 3543: }
 3544: 
 3545: sub languages {
 3546:     my ($possible_langs) = @_;
 3547:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3548:     if (!ref($possible_langs)) {
 3549: 	if( wantarray ) {
 3550: 	    return @preferred_langs;
 3551: 	} else {
 3552: 	    return $preferred_langs[0];
 3553: 	}
 3554:     }
 3555:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3556:     my @preferred_possibilities;
 3557:     foreach my $preferred_lang (@preferred_langs) {
 3558: 	if (exists($possibilities{$preferred_lang})) {
 3559: 	    push(@preferred_possibilities, $preferred_lang);
 3560: 	}
 3561:     }
 3562:     if( wantarray ) {
 3563: 	return @preferred_possibilities;
 3564:     }
 3565:     return $preferred_possibilities[0];
 3566: }
 3567: 
 3568: sub user_lang {
 3569:     my ($touname,$toudom,$fromcid) = @_;
 3570:     my @userlangs;
 3571:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3572:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3573:                     $env{'course.'.$fromcid.'.languages'}));
 3574:     } else {
 3575:         my %langhash = &getlangs($touname,$toudom);
 3576:         if ($langhash{'languages'} ne '') {
 3577:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3578:         } else {
 3579:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3580:             if ($domdefs{'lang_def'} ne '') {
 3581:                 @userlangs = ($domdefs{'lang_def'});
 3582:             }
 3583:         }
 3584:     }
 3585:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3586:     my $user_lh = Apache::localize->get_handle(@languages);
 3587:     return $user_lh;
 3588: }
 3589: 
 3590: 
 3591: ###############################################################
 3592: ##               Student Answer Attempts                     ##
 3593: ###############################################################
 3594: 
 3595: =pod
 3596: 
 3597: =head1 Alternate Problem Views
 3598: 
 3599: =over 4
 3600: 
 3601: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3602:     $getattempt, $regexp, $gradesub)
 3603: 
 3604: Return string with previous attempt on problem. Arguments:
 3605: 
 3606: =over 4
 3607: 
 3608: =item * $symb: Problem, including path
 3609: 
 3610: =item * $username: username of the desired student
 3611: 
 3612: =item * $domain: domain of the desired student
 3613: 
 3614: =item * $course: Course ID
 3615: 
 3616: =item * $getattempt: Leave blank for all attempts, otherwise put
 3617:     something
 3618: 
 3619: =item * $regexp: if string matches this regexp, the string will be
 3620:     sent to $gradesub
 3621: 
 3622: =item * $gradesub: routine that processes the string if it matches $regexp
 3623: 
 3624: =back
 3625: 
 3626: The output string is a table containing all desired attempts, if any.
 3627: 
 3628: =cut
 3629: 
 3630: sub get_previous_attempt {
 3631:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3632:   my $prevattempts='';
 3633:   no strict 'refs';
 3634:   if ($symb) {
 3635:     my (%returnhash)=
 3636:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3637:     if ($returnhash{'version'}) {
 3638:       my %lasthash=();
 3639:       my $version;
 3640:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3641:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3642: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3643:         }
 3644:       }
 3645:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3646:       $prevattempts.='<th>'.&mt('History').'</th>';
 3647:       my (%typeparts,%lasthidden);
 3648:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3649:       foreach my $key (sort(keys(%lasthash))) {
 3650: 	my ($ign,@parts) = split(/\./,$key);
 3651: 	if ($#parts > 0) {
 3652: 	  my $data=$parts[-1];
 3653:           next if ($data eq 'foilorder');
 3654: 	  pop(@parts);
 3655:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3656:           if ($data eq 'type') {
 3657:               unless ($showsurv) {
 3658:                   my $id = join(',',@parts);
 3659:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3660:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3661:                       $lasthidden{$ign.'.'.$id} = 1;
 3662:                   }
 3663:               }
 3664:           } 
 3665: 	} else {
 3666: 	  if ($#parts == 0) {
 3667: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3668: 	  } else {
 3669: 	    $prevattempts.='<th>'.$ign.'</th>';
 3670: 	  }
 3671: 	}
 3672:       }
 3673:       $prevattempts.=&end_data_table_header_row();
 3674:       if ($getattempt eq '') {
 3675: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3676:             my @hidden;
 3677:             if (%typeparts) {
 3678:                 foreach my $id (keys(%typeparts)) {
 3679:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3680:                         push(@hidden,$id);
 3681:                     }
 3682:                 }
 3683:             }
 3684:             $prevattempts.=&start_data_table_row().
 3685:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3686:             if (@hidden) {
 3687:                 foreach my $key (sort(keys(%lasthash))) {
 3688:                     next if ($key =~ /\.foilorder$/);
 3689:                     my $hide;
 3690:                     foreach my $id (@hidden) {
 3691:                         if ($key =~ /^\Q$id\E/) {
 3692:                             $hide = 1;
 3693:                             last;
 3694:                         }
 3695:                     }
 3696:                     if ($hide) {
 3697:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3698:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3699:                             my $value = &format_previous_attempt_value($key,
 3700:                                              $returnhash{$version.':'.$key});
 3701:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3702:                         } else {
 3703:                             $prevattempts.='<td>&nbsp;</td>';
 3704:                         }
 3705:                     } else {
 3706:                         if ($key =~ /\./) {
 3707:                             my $value = &format_previous_attempt_value($key,
 3708:                                               $returnhash{$version.':'.$key});
 3709:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3710:                         } else {
 3711:                             $prevattempts.='<td>&nbsp;</td>';
 3712:                         }
 3713:                     }
 3714:                 }
 3715:             } else {
 3716: 	        foreach my $key (sort(keys(%lasthash))) {
 3717:                     next if ($key =~ /\.foilorder$/);
 3718: 		    my $value = &format_previous_attempt_value($key,
 3719: 			            $returnhash{$version.':'.$key});
 3720: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3721: 	        }
 3722:             }
 3723: 	    $prevattempts.=&end_data_table_row();
 3724: 	 }
 3725:       }
 3726:       my @currhidden = keys(%lasthidden);
 3727:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3728:       foreach my $key (sort(keys(%lasthash))) {
 3729:           next if ($key =~ /\.foilorder$/);
 3730:           if (%typeparts) {
 3731:               my $hidden;
 3732:               foreach my $id (@currhidden) {
 3733:                   if ($key =~ /^\Q$id\E/) {
 3734:                       $hidden = 1;
 3735:                       last;
 3736:                   }
 3737:               }
 3738:               if ($hidden) {
 3739:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3740:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3741:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3742:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3743:                           $value = &$gradesub($value);
 3744:                       }
 3745:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3746:                   } else {
 3747:                       $prevattempts.='<td>&nbsp;</td>';
 3748:                   }
 3749:               } else {
 3750:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3751:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3752:                       $value = &$gradesub($value);
 3753:                   }
 3754:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3755:               }
 3756:           } else {
 3757: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3758: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3759:                   $value = &$gradesub($value);
 3760:               }
 3761: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3762:           }
 3763:       }
 3764:       $prevattempts.= &end_data_table_row().&end_data_table();
 3765:     } else {
 3766:       $prevattempts=
 3767: 	  &start_data_table().&start_data_table_row().
 3768: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3769: 	  &end_data_table_row().&end_data_table();
 3770:     }
 3771:   } else {
 3772:     $prevattempts=
 3773: 	  &start_data_table().&start_data_table_row().
 3774: 	  '<td>'.&mt('No data.').'</td>'.
 3775: 	  &end_data_table_row().&end_data_table();
 3776:   }
 3777: }
 3778: 
 3779: sub format_previous_attempt_value {
 3780:     my ($key,$value) = @_;
 3781:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3782: 	$value = &Apache::lonlocal::locallocaltime($value);
 3783:     } elsif (ref($value) eq 'ARRAY') {
 3784: 	$value = '('.join(', ', @{ $value }).')';
 3785:     } elsif ($key =~ /answerstring$/) {
 3786:         my %answers = &Apache::lonnet::str2hash($value);
 3787:         my @anskeys = sort(keys(%answers));
 3788:         if (@anskeys == 1) {
 3789:             my $answer = $answers{$anskeys[0]};
 3790:             if ($answer =~ m{\0}) {
 3791:                 $answer =~ s{\0}{,}g;
 3792:             }
 3793:             my $tag_internal_answer_name = 'INTERNAL';
 3794:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3795:                 $value = $answer; 
 3796:             } else {
 3797:                 $value = $anskeys[0].'='.$answer;
 3798:             }
 3799:         } else {
 3800:             foreach my $ans (@anskeys) {
 3801:                 my $answer = $answers{$ans};
 3802:                 if ($answer =~ m{\0}) {
 3803:                     $answer =~ s{\0}{,}g;
 3804:                 }
 3805:                 $value .=  $ans.'='.$answer.'<br />';;
 3806:             } 
 3807:         }
 3808:     } else {
 3809: 	$value = &unescape($value);
 3810:     }
 3811:     return $value;
 3812: }
 3813: 
 3814: 
 3815: sub relative_to_absolute {
 3816:     my ($url,$output)=@_;
 3817:     my $parser=HTML::TokeParser->new(\$output);
 3818:     my $token;
 3819:     my $thisdir=$url;
 3820:     my @rlinks=();
 3821:     while ($token=$parser->get_token) {
 3822: 	if ($token->[0] eq 'S') {
 3823: 	    if ($token->[1] eq 'a') {
 3824: 		if ($token->[2]->{'href'}) {
 3825: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3826: 		}
 3827: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3828: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3829: 	    } elsif ($token->[1] eq 'base') {
 3830: 		$thisdir=$token->[2]->{'href'};
 3831: 	    }
 3832: 	}
 3833:     }
 3834:     $thisdir=~s-/[^/]*$--;
 3835:     foreach my $link (@rlinks) {
 3836: 	unless (($link=~/^https?\:\/\//i) ||
 3837: 		($link=~/^\//) ||
 3838: 		($link=~/^javascript:/i) ||
 3839: 		($link=~/^mailto:/i) ||
 3840: 		($link=~/^\#/)) {
 3841: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3842: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3843: 	}
 3844:     }
 3845: # -------------------------------------------------- Deal with Applet codebases
 3846:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3847:     return $output;
 3848: }
 3849: 
 3850: =pod
 3851: 
 3852: =item * &get_student_view()
 3853: 
 3854: show a snapshot of what student was looking at
 3855: 
 3856: =cut
 3857: 
 3858: sub get_student_view {
 3859:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3860:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3861:   my (%form);
 3862:   my @elements=('symb','courseid','domain','username');
 3863:   foreach my $element (@elements) {
 3864:       $form{'grade_'.$element}=eval '$'.$element #'
 3865:   }
 3866:   if (defined($moreenv)) {
 3867:       %form=(%form,%{$moreenv});
 3868:   }
 3869:   if (defined($target)) { $form{'grade_target'} = $target; }
 3870:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3871:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3872:   $userview=~s/\<body[^\>]*\>//gi;
 3873:   $userview=~s/\<\/body\>//gi;
 3874:   $userview=~s/\<html\>//gi;
 3875:   $userview=~s/\<\/html\>//gi;
 3876:   $userview=~s/\<head\>//gi;
 3877:   $userview=~s/\<\/head\>//gi;
 3878:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3879:   $userview=&relative_to_absolute($feedurl,$userview);
 3880:   if (wantarray) {
 3881:      return ($userview,$response);
 3882:   } else {
 3883:      return $userview;
 3884:   }
 3885: }
 3886: 
 3887: sub get_student_view_with_retries {
 3888:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3889: 
 3890:     my $ok = 0;                 # True if we got a good response.
 3891:     my $content;
 3892:     my $response;
 3893: 
 3894:     # Try to get the student_view done. within the retries count:
 3895:     
 3896:     do {
 3897:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3898:          $ok      = $response->is_success;
 3899:          if (!$ok) {
 3900:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3901:          }
 3902:          $retries--;
 3903:     } while (!$ok && ($retries > 0));
 3904:     
 3905:     if (!$ok) {
 3906:        $content = '';          # On error return an empty content.
 3907:     }
 3908:     if (wantarray) {
 3909:        return ($content, $response);
 3910:     } else {
 3911:        return $content;
 3912:     }
 3913: }
 3914: 
 3915: =pod
 3916: 
 3917: =item * &get_student_answers() 
 3918: 
 3919: show a snapshot of how student was answering problem
 3920: 
 3921: =cut
 3922: 
 3923: sub get_student_answers {
 3924:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3925:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3926:   my (%moreenv);
 3927:   my @elements=('symb','courseid','domain','username');
 3928:   foreach my $element (@elements) {
 3929:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3930:   }
 3931:   $moreenv{'grade_target'}='answer';
 3932:   %moreenv=(%form,%moreenv);
 3933:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3934:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3935:   return $userview;
 3936: }
 3937: 
 3938: =pod
 3939: 
 3940: =item * &submlink()
 3941: 
 3942: Inputs: $text $uname $udom $symb $target
 3943: 
 3944: Returns: A link to grades.pm such as to see the SUBM view of a student
 3945: 
 3946: =cut
 3947: 
 3948: ###############################################
 3949: sub submlink {
 3950:     my ($text,$uname,$udom,$symb,$target)=@_;
 3951:     if (!($uname && $udom)) {
 3952: 	(my $cursymb, my $courseid,$udom,$uname)=
 3953: 	    &Apache::lonnet::whichuser($symb);
 3954: 	if (!$symb) { $symb=$cursymb; }
 3955:     }
 3956:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3957:     $symb=&escape($symb);
 3958:     if ($target) { $target=" target=\"$target\""; }
 3959:     return
 3960:         '<a href="/adm/grades?command=submission'.
 3961:         '&amp;symb='.$symb.
 3962:         '&amp;student='.$uname.
 3963:         '&amp;userdom='.$udom.'"'.
 3964:         $target.'>'.$text.'</a>';
 3965: }
 3966: ##############################################
 3967: 
 3968: =pod
 3969: 
 3970: =item * &pgrdlink()
 3971: 
 3972: Inputs: $text $uname $udom $symb $target
 3973: 
 3974: Returns: A link to grades.pm such as to see the PGRD view of a student
 3975: 
 3976: =cut
 3977: 
 3978: ###############################################
 3979: sub pgrdlink {
 3980:     my $link=&submlink(@_);
 3981:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3982:     return $link;
 3983: }
 3984: ##############################################
 3985: 
 3986: =pod
 3987: 
 3988: =item * &pprmlink()
 3989: 
 3990: Inputs: $text $uname $udom $symb $target
 3991: 
 3992: Returns: A link to parmset.pm such as to see the PPRM view of a
 3993: student and a specific resource
 3994: 
 3995: =cut
 3996: 
 3997: ###############################################
 3998: sub pprmlink {
 3999:     my ($text,$uname,$udom,$symb,$target)=@_;
 4000:     if (!($uname && $udom)) {
 4001: 	(my $cursymb, my $courseid,$udom,$uname)=
 4002: 	    &Apache::lonnet::whichuser($symb);
 4003: 	if (!$symb) { $symb=$cursymb; }
 4004:     }
 4005:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4006:     $symb=&escape($symb);
 4007:     if ($target) { $target="target=\"$target\""; }
 4008:     return '<a href="/adm/parmset?command=set&amp;'.
 4009: 	'symb='.$symb.'&amp;uname='.$uname.
 4010: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4011: }
 4012: ##############################################
 4013: 
 4014: =pod
 4015: 
 4016: =back
 4017: 
 4018: =cut
 4019: 
 4020: ###############################################
 4021: 
 4022: 
 4023: sub timehash {
 4024:     my ($thistime) = @_;
 4025:     my $timezone = &Apache::lonlocal::gettimezone();
 4026:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4027:                      ->set_time_zone($timezone);
 4028:     my $wday = $dt->day_of_week();
 4029:     if ($wday == 7) { $wday = 0; }
 4030:     return ( 'second' => $dt->second(),
 4031:              'minute' => $dt->minute(),
 4032:              'hour'   => $dt->hour(),
 4033:              'day'     => $dt->day_of_month(),
 4034:              'month'   => $dt->month(),
 4035:              'year'    => $dt->year(),
 4036:              'weekday' => $wday,
 4037:              'dayyear' => $dt->day_of_year(),
 4038:              'dlsav'   => $dt->is_dst() );
 4039: }
 4040: 
 4041: sub utc_string {
 4042:     my ($date)=@_;
 4043:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4044: }
 4045: 
 4046: sub maketime {
 4047:     my %th=@_;
 4048:     my ($epoch_time,$timezone,$dt);
 4049:     $timezone = &Apache::lonlocal::gettimezone();
 4050:     eval {
 4051:         $dt = DateTime->new( year   => $th{'year'},
 4052:                              month  => $th{'month'},
 4053:                              day    => $th{'day'},
 4054:                              hour   => $th{'hour'},
 4055:                              minute => $th{'minute'},
 4056:                              second => $th{'second'},
 4057:                              time_zone => $timezone,
 4058:                          );
 4059:     };
 4060:     if (!$@) {
 4061:         $epoch_time = $dt->epoch;
 4062:         if ($epoch_time) {
 4063:             return $epoch_time;
 4064:         }
 4065:     }
 4066:     return POSIX::mktime(
 4067:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4068:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4069: }
 4070: 
 4071: #########################################
 4072: 
 4073: sub findallcourses {
 4074:     my ($roles,$uname,$udom) = @_;
 4075:     my %roles;
 4076:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4077:     my %courses;
 4078:     my $now=time;
 4079:     if (!defined($uname)) {
 4080:         $uname = $env{'user.name'};
 4081:     }
 4082:     if (!defined($udom)) {
 4083:         $udom = $env{'user.domain'};
 4084:     }
 4085:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4086:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4087:         if (!%roles) {
 4088:             %roles = (
 4089:                        cc => 1,
 4090:                        co => 1,
 4091:                        in => 1,
 4092:                        ep => 1,
 4093:                        ta => 1,
 4094:                        cr => 1,
 4095:                        st => 1,
 4096:              );
 4097:         }
 4098:         foreach my $entry (keys(%roleshash)) {
 4099:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4100:             if ($trole =~ /^cr/) { 
 4101:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4102:             } else {
 4103:                 next if (!exists($roles{$trole}));
 4104:             }
 4105:             if ($tend) {
 4106:                 next if ($tend < $now);
 4107:             }
 4108:             if ($tstart) {
 4109:                 next if ($tstart > $now);
 4110:             }
 4111:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4112:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4113:             my $value = $trole.'/'.$cdom.'/';
 4114:             if ($secpart eq '') {
 4115:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4116:                 $sec = 'none';
 4117:                 $value .= $cnum.'/';
 4118:             } else {
 4119:                 $cnum = $cnumpart;
 4120:                 ($sec,$role) = split(/_/,$secpart);
 4121:                 $value .= $cnum.'/'.$sec;
 4122:             }
 4123:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4124:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4125:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4126:                 }
 4127:             } else {
 4128:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4129:             }
 4130:         }
 4131:     } else {
 4132:         foreach my $key (keys(%env)) {
 4133: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4134:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4135: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4136: 	        next if ($role eq 'ca' || $role eq 'aa');
 4137: 	        next if (%roles && !exists($roles{$role}));
 4138: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4139:                 my $active=1;
 4140:                 if ($starttime) {
 4141: 		    if ($now<$starttime) { $active=0; }
 4142:                 }
 4143:                 if ($endtime) {
 4144:                     if ($now>$endtime) { $active=0; }
 4145:                 }
 4146:                 if ($active) {
 4147:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4148:                     if ($sec eq '') {
 4149:                         $sec = 'none';
 4150:                     } else {
 4151:                         $value .= $sec;
 4152:                     }
 4153:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4154:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4155:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4156:                         }
 4157:                     } else {
 4158:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4159:                     }
 4160:                 }
 4161:             }
 4162:         }
 4163:     }
 4164:     return %courses;
 4165: }
 4166: 
 4167: ###############################################
 4168: 
 4169: sub blockcheck {
 4170:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4171: 
 4172:     if (!defined($udom)) {
 4173:         $udom = $env{'user.domain'};
 4174:     }
 4175:     if (!defined($uname)) {
 4176:         $uname = $env{'user.name'};
 4177:     }
 4178: 
 4179:     # If uname and udom are for a course, check for blocks in the course.
 4180: 
 4181:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4182:         my ($startblock,$endblock,$triggerblock) = 
 4183:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4184:         return ($startblock,$endblock,$triggerblock);
 4185:     }
 4186: 
 4187:     my $startblock = 0;
 4188:     my $endblock = 0;
 4189:     my $triggerblock = '';
 4190:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4191: 
 4192:     # If uname is for a user, and activity is course-specific, i.e.,
 4193:     # boards, chat or groups, check for blocking in current course only.
 4194: 
 4195:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4196:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4197:         foreach my $key (keys(%live_courses)) {
 4198:             if ($key ne $env{'request.course.id'}) {
 4199:                 delete($live_courses{$key});
 4200:             }
 4201:         }
 4202:     }
 4203: 
 4204:     my $otheruser = 0;
 4205:     my %own_courses;
 4206:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4207:         # Resource belongs to user other than current user.
 4208:         $otheruser = 1;
 4209:         # Gather courses for current user
 4210:         %own_courses = 
 4211:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4212:     }
 4213: 
 4214:     # Gather active course roles - course coordinator, instructor, 
 4215:     # exam proctor, ta, student, or custom role.
 4216: 
 4217:     foreach my $course (keys(%live_courses)) {
 4218:         my ($cdom,$cnum);
 4219:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4220:             $cdom = $env{'course.'.$course.'.domain'};
 4221:             $cnum = $env{'course.'.$course.'.num'};
 4222:         } else {
 4223:             ($cdom,$cnum) = split(/_/,$course); 
 4224:         }
 4225:         my $no_ownblock = 0;
 4226:         my $no_userblock = 0;
 4227:         if ($otheruser && $activity ne 'com') {
 4228:             # Check if current user has 'evb' priv for this
 4229:             if (defined($own_courses{$course})) {
 4230:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4231:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4232:                     if ($sec ne 'none') {
 4233:                         $checkrole .= '/'.$sec;
 4234:                     }
 4235:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4236:                         $no_ownblock = 1;
 4237:                         last;
 4238:                     }
 4239:                 }
 4240:             }
 4241:             # if they have 'evb' priv and are currently not playing student
 4242:             next if (($no_ownblock) &&
 4243:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4244:         }
 4245:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4246:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4247:             if ($sec ne 'none') {
 4248:                 $checkrole .= '/'.$sec;
 4249:             }
 4250:             if ($otheruser) {
 4251:                 # Resource belongs to user other than current user.
 4252:                 # Assemble privs for that user, and check for 'evb' priv.
 4253:                 my (%allroles,%userroles);
 4254:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4255:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4256:                         my ($trole,$tdom,$tnum,$tsec);
 4257:                         if ($entry =~ /^cr/) {
 4258:                             ($trole,$tdom,$tnum,$tsec) = 
 4259:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4260:                         } else {
 4261:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4262:                         }
 4263:                         my ($spec,$area,$trest);
 4264:                         $area = '/'.$tdom.'/'.$tnum;
 4265:                         $trest = $tnum;
 4266:                         if ($tsec ne '') {
 4267:                             $area .= '/'.$tsec;
 4268:                             $trest .= '/'.$tsec;
 4269:                         }
 4270:                         $spec = $trole.'.'.$area;
 4271:                         if ($trole =~ /^cr/) {
 4272:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4273:                                                               $tdom,$spec,$trest,$area);
 4274:                         } else {
 4275:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4276:                                                                 $tdom,$spec,$trest,$area);
 4277:                         }
 4278:                     }
 4279:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4280:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4281:                         if ($1) {
 4282:                             $no_userblock = 1;
 4283:                             last;
 4284:                         }
 4285:                     }
 4286:                 }
 4287:             } else {
 4288:                 # Resource belongs to current user
 4289:                 # Check for 'evb' priv via lonnet::allowed().
 4290:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4291:                     $no_ownblock = 1;
 4292:                     last;
 4293:                 }
 4294:             }
 4295:         }
 4296:         # if they have the evb priv and are currently not playing student
 4297:         next if (($no_ownblock) &&
 4298:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4299:         next if ($no_userblock);
 4300: 
 4301:         # Retrieve blocking times and identity of locker for course
 4302:         # of specified user, unless user has 'evb' privilege.
 4303:         
 4304:         my ($start,$end,$trigger) = 
 4305:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4306:         if (($start != 0) && 
 4307:             (($startblock == 0) || ($startblock > $start))) {
 4308:             $startblock = $start;
 4309:             if ($trigger ne '') {
 4310:                 $triggerblock = $trigger;
 4311:             }
 4312:         }
 4313:         if (($end != 0)  &&
 4314:             (($endblock == 0) || ($endblock < $end))) {
 4315:             $endblock = $end;
 4316:             if ($trigger ne '') {
 4317:                 $triggerblock = $trigger;
 4318:             }
 4319:         }
 4320:     }
 4321:     return ($startblock,$endblock,$triggerblock);
 4322: }
 4323: 
 4324: sub get_blocks {
 4325:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4326:     my $startblock = 0;
 4327:     my $endblock = 0;
 4328:     my $triggerblock = '';
 4329:     my $course = $cdom.'_'.$cnum;
 4330:     $setters->{$course} = {};
 4331:     $setters->{$course}{'staff'} = [];
 4332:     $setters->{$course}{'times'} = [];
 4333:     $setters->{$course}{'triggers'} = [];
 4334:     my (@blockers,%triggered);
 4335:     my $now = time;
 4336:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4337:     if ($activity eq 'docs') {
 4338:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4339:         foreach my $block (@blockers) {
 4340:             if ($block =~ /^firstaccess____(.+)$/) {
 4341:                 my $item = $1;
 4342:                 my $type = 'map';
 4343:                 my $timersymb = $item;
 4344:                 if ($item eq 'course') {
 4345:                     $type = 'course';
 4346:                 } elsif ($item =~ /___\d+___/) {
 4347:                     $type = 'resource';
 4348:                 } else {
 4349:                     $timersymb = &Apache::lonnet::symbread($item);
 4350:                 }
 4351:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4352:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4353:                 $triggered{$block} = {
 4354:                                        start => $start,
 4355:                                        end   => $end,
 4356:                                        type  => $type,
 4357:                                      };
 4358:             }
 4359:         }
 4360:     } else {
 4361:         foreach my $block (keys(%commblocks)) {
 4362:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4363:                 my ($start,$end) = ($1,$2);
 4364:                 if ($start <= time && $end >= time) {
 4365:                     if (ref($commblocks{$block}) eq 'HASH') {
 4366:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4367:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4368:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4369:                                     push(@blockers,$block);
 4370:                                 }
 4371:                             }
 4372:                         }
 4373:                     }
 4374:                 }
 4375:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4376:                 my $item = $1;
 4377:                 my $timersymb = $item; 
 4378:                 my $type = 'map';
 4379:                 if ($item eq 'course') {
 4380:                     $type = 'course';
 4381:                 } elsif ($item =~ /___\d+___/) {
 4382:                     $type = 'resource';
 4383:                 } else {
 4384:                     $timersymb = &Apache::lonnet::symbread($item);
 4385:                 }
 4386:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4387:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4388:                 if ($start && $end) {
 4389:                     if (($start <= time) && ($end >= time)) {
 4390:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4391:                             push(@blockers,$block);
 4392:                             $triggered{$block} = {
 4393:                                                    start => $start,
 4394:                                                    end   => $end,
 4395:                                                    type  => $type,
 4396:                                                  };
 4397:                         }
 4398:                     }
 4399:                 }
 4400:             }
 4401:         }
 4402:     }
 4403:     foreach my $blocker (@blockers) {
 4404:         my ($staff_name,$staff_dom,$title,$blocks) =
 4405:             &parse_block_record($commblocks{$blocker});
 4406:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4407:         my ($start,$end,$triggertype);
 4408:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4409:             ($start,$end) = ($1,$2);
 4410:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4411:             $start = $triggered{$blocker}{'start'};
 4412:             $end = $triggered{$blocker}{'end'};
 4413:             $triggertype = $triggered{$blocker}{'type'};
 4414:         }
 4415:         if ($start) {
 4416:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4417:             if ($triggertype) {
 4418:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4419:             } else {
 4420:                 push(@{$$setters{$course}{'triggers'}},0);
 4421:             }
 4422:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4423:                 $startblock = $start;
 4424:                 if ($triggertype) {
 4425:                     $triggerblock = $blocker;
 4426:                 }
 4427:             }
 4428:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4429:                $endblock = $end;
 4430:                if ($triggertype) {
 4431:                    $triggerblock = $blocker;
 4432:                }
 4433:             }
 4434:         }
 4435:     }
 4436:     return ($startblock,$endblock,$triggerblock);
 4437: }
 4438: 
 4439: sub parse_block_record {
 4440:     my ($record) = @_;
 4441:     my ($setuname,$setudom,$title,$blocks);
 4442:     if (ref($record) eq 'HASH') {
 4443:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4444:         $title = &unescape($record->{'event'});
 4445:         $blocks = $record->{'blocks'};
 4446:     } else {
 4447:         my @data = split(/:/,$record,3);
 4448:         if (scalar(@data) eq 2) {
 4449:             $title = $data[1];
 4450:             ($setuname,$setudom) = split(/@/,$data[0]);
 4451:         } else {
 4452:             ($setuname,$setudom,$title) = @data;
 4453:         }
 4454:         $blocks = { 'com' => 'on' };
 4455:     }
 4456:     return ($setuname,$setudom,$title,$blocks);
 4457: }
 4458: 
 4459: sub blocking_status {
 4460:     my ($activity,$uname,$udom,$url) = @_;
 4461:     my %setters;
 4462: 
 4463: # check for active blocking
 4464:     my ($startblock,$endblock,$triggerblock) = 
 4465:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4466:     my $blocked = 0;
 4467:     if ($startblock && $endblock) {
 4468:         $blocked = 1;
 4469:     }
 4470: 
 4471: # caller just wants to know whether a block is active
 4472:     if (!wantarray) { return $blocked; }
 4473: 
 4474: # build a link to a popup window containing the details
 4475:     my $querystring  = "?activity=$activity";
 4476: # $uname and $udom decide whose portfolio the user is trying to look at
 4477:     if ($activity eq 'port') {
 4478:         $querystring .= "&amp;udom=$udom"      if $udom;
 4479:         $querystring .= "&amp;uname=$uname"    if $uname;
 4480:     } elsif ($activity eq 'docs') {
 4481:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4482:     }
 4483: 
 4484:     my $output .= <<'END_MYBLOCK';
 4485: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4486:     var options = "width=" + w + ",height=" + h + ",";
 4487:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4488:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4489:     var newWin = window.open(url, wdwName, options);
 4490:     newWin.focus();
 4491: }
 4492: END_MYBLOCK
 4493: 
 4494:     $output = Apache::lonhtmlcommon::scripttag($output);
 4495:   
 4496:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4497:     my $text = &mt('Communication Blocked');
 4498:     if ($activity eq 'docs') {
 4499:         $text = &mt('Content Access Blocked');
 4500:     } elsif ($activity eq 'printout') {
 4501:         $text = &mt('Printing Blocked');
 4502:     }
 4503:     $output .= <<"END_BLOCK";
 4504: <div class='LC_comblock'>
 4505:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4506:   title='$text'>
 4507:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4508:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4509:   title='$text'>$text</a>
 4510: </div>
 4511: 
 4512: END_BLOCK
 4513: 
 4514:     return ($blocked, $output);
 4515: }
 4516: 
 4517: ###############################################
 4518: 
 4519: sub check_ip_acc {
 4520:     my ($acc)=@_;
 4521:     &Apache::lonxml::debug("acc is $acc");
 4522:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4523:         return 1;
 4524:     }
 4525:     my $allowed=0;
 4526:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4527: 
 4528:     my $name;
 4529:     foreach my $pattern (split(',',$acc)) {
 4530:         $pattern =~ s/^\s*//;
 4531:         $pattern =~ s/\s*$//;
 4532:         if ($pattern =~ /\*$/) {
 4533:             #35.8.*
 4534:             $pattern=~s/\*//;
 4535:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4536:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4537:             #35.8.3.[34-56]
 4538:             my $low=$2;
 4539:             my $high=$3;
 4540:             $pattern=$1;
 4541:             if ($ip =~ /^\Q$pattern\E/) {
 4542:                 my $last=(split(/\./,$ip))[3];
 4543:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4544:             }
 4545:         } elsif ($pattern =~ /^\*/) {
 4546:             #*.msu.edu
 4547:             $pattern=~s/\*//;
 4548:             if (!defined($name)) {
 4549:                 use Socket;
 4550:                 my $netaddr=inet_aton($ip);
 4551:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4552:             }
 4553:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4554:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4555:             #127.0.0.1
 4556:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4557:         } else {
 4558:             #some.name.com
 4559:             if (!defined($name)) {
 4560:                 use Socket;
 4561:                 my $netaddr=inet_aton($ip);
 4562:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4563:             }
 4564:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4565:         }
 4566:         if ($allowed) { last; }
 4567:     }
 4568:     return $allowed;
 4569: }
 4570: 
 4571: ###############################################
 4572: 
 4573: =pod
 4574: 
 4575: =head1 Domain Template Functions
 4576: 
 4577: =over 4
 4578: 
 4579: =item * &determinedomain()
 4580: 
 4581: Inputs: $domain (usually will be undef)
 4582: 
 4583: Returns: Determines which domain should be used for designs
 4584: 
 4585: =cut
 4586: 
 4587: ###############################################
 4588: sub determinedomain {
 4589:     my $domain=shift;
 4590:     if (! $domain) {
 4591:         # Determine domain if we have not been given one
 4592:         $domain = &Apache::lonnet::default_login_domain();
 4593:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4594:         if ($env{'request.role.domain'}) { 
 4595:             $domain=$env{'request.role.domain'}; 
 4596:         }
 4597:     }
 4598:     return $domain;
 4599: }
 4600: ###############################################
 4601: 
 4602: sub devalidate_domconfig_cache {
 4603:     my ($udom)=@_;
 4604:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4605: }
 4606: 
 4607: # ---------------------- Get domain configuration for a domain
 4608: sub get_domainconf {
 4609:     my ($udom) = @_;
 4610:     my $cachetime=1800;
 4611:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4612:     if (defined($cached)) { return %{$result}; }
 4613: 
 4614:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4615: 					     ['login','rolecolors','autoenroll'],$udom);
 4616:     my (%designhash,%legacy);
 4617:     if (keys(%domconfig) > 0) {
 4618:         if (ref($domconfig{'login'}) eq 'HASH') {
 4619:             if (keys(%{$domconfig{'login'}})) {
 4620:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4621:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4622:                         if ($key eq 'loginvia') {
 4623:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4624:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4625:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4626:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4627:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4628:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4629:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4630: 
 4631:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4632:                                             } else {
 4633:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4634:                                             }
 4635:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4636:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4637:                                             }
 4638:                                         }
 4639:                                     }
 4640:                                 }
 4641:                             }
 4642:                         } else {
 4643:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4644:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4645:                                     $domconfig{'login'}{$key}{$img};
 4646:                             }
 4647:                         }
 4648:                     } else {
 4649:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4650:                     }
 4651:                 }
 4652:             } else {
 4653:                 $legacy{'login'} = 1;
 4654:             }
 4655:         } else {
 4656:             $legacy{'login'} = 1;
 4657:         }
 4658:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4659:             if (keys(%{$domconfig{'rolecolors'}})) {
 4660:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4661:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4662:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4663:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4664:                         }
 4665:                     }
 4666:                 }
 4667:             } else {
 4668:                 $legacy{'rolecolors'} = 1;
 4669:             }
 4670:         } else {
 4671:             $legacy{'rolecolors'} = 1;
 4672:         }
 4673:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4674:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4675:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4676:             }
 4677:         }
 4678:         if (keys(%legacy) > 0) {
 4679:             my %legacyhash = &get_legacy_domconf($udom);
 4680:             foreach my $item (keys(%legacyhash)) {
 4681:                 if ($item =~ /^\Q$udom\E\.login/) {
 4682:                     if ($legacy{'login'}) { 
 4683:                         $designhash{$item} = $legacyhash{$item};
 4684:                     }
 4685:                 } else {
 4686:                     if ($legacy{'rolecolors'}) {
 4687:                         $designhash{$item} = $legacyhash{$item};
 4688:                     }
 4689:                 }
 4690:             }
 4691:         }
 4692:     } else {
 4693:         %designhash = &get_legacy_domconf($udom); 
 4694:     }
 4695:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4696: 				  $cachetime);
 4697:     return %designhash;
 4698: }
 4699: 
 4700: sub get_legacy_domconf {
 4701:     my ($udom) = @_;
 4702:     my %legacyhash;
 4703:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4704:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4705:     if (-e $designfile) {
 4706:         if ( open (my $fh,"<$designfile") ) {
 4707:             while (my $line = <$fh>) {
 4708:                 next if ($line =~ /^\#/);
 4709:                 chomp($line);
 4710:                 my ($key,$val)=(split(/\=/,$line));
 4711:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4712:             }
 4713:             close($fh);
 4714:         }
 4715:     }
 4716:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4717:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4718:     }
 4719:     return %legacyhash;
 4720: }
 4721: 
 4722: =pod
 4723: 
 4724: =item * &domainlogo()
 4725: 
 4726: Inputs: $domain (usually will be undef)
 4727: 
 4728: Returns: A link to a domain logo, if the domain logo exists.
 4729: If the domain logo does not exist, a description of the domain.
 4730: 
 4731: =cut
 4732: 
 4733: ###############################################
 4734: sub domainlogo {
 4735:     my $domain = &determinedomain(shift);
 4736:     my %designhash = &get_domainconf($domain);    
 4737:     # See if there is a logo
 4738:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4739:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4740:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4741: 	    if ($imgsrc =~ m{^/res/}) {
 4742: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4743: 		&Apache::lonnet::repcopy($local_name);
 4744: 	    }
 4745: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4746:         } 
 4747:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4748:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4749:         return &Apache::lonnet::domain($domain,'description');
 4750:     } else {
 4751:         return '';
 4752:     }
 4753: }
 4754: ##############################################
 4755: 
 4756: =pod
 4757: 
 4758: =item * &designparm()
 4759: 
 4760: Inputs: $which parameter; $domain (usually will be undef)
 4761: 
 4762: Returns: value of designparamter $which
 4763: 
 4764: =cut
 4765: 
 4766: 
 4767: ##############################################
 4768: sub designparm {
 4769:     my ($which,$domain)=@_;
 4770:     if (exists($env{'environment.color.'.$which})) {
 4771:         return $env{'environment.color.'.$which};
 4772:     }
 4773:     $domain=&determinedomain($domain);
 4774:     my %domdesign;
 4775:     unless ($domain eq 'public') {
 4776:         %domdesign = &get_domainconf($domain);
 4777:     }
 4778:     my $output;
 4779:     if ($domdesign{$domain.'.'.$which} ne '') {
 4780:         $output = $domdesign{$domain.'.'.$which};
 4781:     } else {
 4782:         $output = $defaultdesign{$which};
 4783:     }
 4784:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4785:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4786:         if ($output =~ m{^/(adm|res)/}) {
 4787:             if ($output =~ m{^/res/}) {
 4788:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4789:                 &Apache::lonnet::repcopy($local_name);
 4790:             }
 4791:             $output = &lonhttpdurl($output);
 4792:         }
 4793:     }
 4794:     return $output;
 4795: }
 4796: 
 4797: ##############################################
 4798: =pod
 4799: 
 4800: =item * &authorspace()
 4801: 
 4802: Inputs: $url (usually will be undef).
 4803: 
 4804: Returns: Path to Construction Space containing the resource or 
 4805:          directory being viewed (or for which action is being taken). 
 4806:          If $url is provided, and begins /priv/<domain>/<uname>
 4807:          the path will be that portion of the $context argument.
 4808:          Otherwise the path will be for the author space of the current
 4809:          user when the current role is author, or for that of the 
 4810:          co-author/assistant co-author space when the current role 
 4811:          is co-author or assistant co-author.
 4812: 
 4813: =cut
 4814: 
 4815: sub authorspace {
 4816:     my ($url) = @_;
 4817:     if ($url ne '') {
 4818:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4819:            return $1;
 4820:         }
 4821:     }
 4822:     my $caname = '';
 4823:     my $cadom = '';
 4824:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4825:         ($cadom,$caname) =
 4826:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4827:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4828:         $caname = $env{'user.name'};
 4829:         $cadom = $env{'user.domain'};
 4830:     }
 4831:     if (($caname ne '') && ($cadom ne '')) {
 4832:         return "/priv/$cadom/$caname/";
 4833:     }
 4834:     return;
 4835: }
 4836: 
 4837: ##############################################
 4838: =pod
 4839: 
 4840: =item * &head_subbox()
 4841: 
 4842: Inputs: $content (contains HTML code with page functions, etc.)
 4843: 
 4844: Returns: HTML div with $content
 4845:          To be included in page header
 4846: 
 4847: =cut
 4848: 
 4849: sub head_subbox {
 4850:     my ($content)=@_;
 4851:     my $output =
 4852:         '<div class="LC_head_subbox">'
 4853:        .$content
 4854:        .'</div>'
 4855: }
 4856: 
 4857: ##############################################
 4858: =pod
 4859: 
 4860: =item * &CSTR_pageheader()
 4861: 
 4862: Input: (optional) filename from which breadcrumb trail is built.
 4863:        In most cases no input as needed, as $env{'request.filename'}
 4864:        is appropriate for use in building the breadcrumb trail.
 4865: 
 4866: Returns: HTML div with CSTR path and recent box
 4867:          To be included on Construction Space pages
 4868: 
 4869: =cut
 4870: 
 4871: sub CSTR_pageheader {
 4872:     my ($trailfile) = @_;
 4873:     if ($trailfile eq '') {
 4874:         $trailfile = $env{'request.filename'};
 4875:     }
 4876: 
 4877: # this is for resources; directories have customtitle, and crumbs
 4878: # and select recent are created in lonpubdir.pm
 4879: 
 4880:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4881:     my ($udom,$uname,$thisdisfn)=
 4882:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
 4883:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4884:     $formaction =~ s{/+}{/}g;
 4885: 
 4886:     my $parentpath = '';
 4887:     my $lastitem = '';
 4888:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4889:         $parentpath = $1;
 4890:         $lastitem = $2;
 4891:     } else {
 4892:         $lastitem = $thisdisfn;
 4893:     }
 4894: 
 4895:     my $output =
 4896:          '<div>'
 4897:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4898:         .'<b>'.&mt('Construction Space:').'</b> '
 4899:         .'<form name="dirs" method="post" action="'.$formaction
 4900:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4901:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4902: 
 4903:     if ($lastitem) {
 4904:         $output .=
 4905:              '<span class="LC_filename">'
 4906:             .$lastitem
 4907:             .'</span>';
 4908:     }
 4909:     $output .=
 4910:          '<br />'
 4911:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4912:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4913:         .'</form>'
 4914:         .&Apache::lonmenu::constspaceform()
 4915:         .'</div>';
 4916: 
 4917:     return $output;
 4918: }
 4919: 
 4920: ###############################################
 4921: ###############################################
 4922: 
 4923: =pod
 4924: 
 4925: =back
 4926: 
 4927: =head1 HTML Helpers
 4928: 
 4929: =over 4
 4930: 
 4931: =item * &bodytag()
 4932: 
 4933: Returns a uniform header for LON-CAPA web pages.
 4934: 
 4935: Inputs: 
 4936: 
 4937: =over 4
 4938: 
 4939: =item * $title, A title to be displayed on the page.
 4940: 
 4941: =item * $function, the current role (can be undef).
 4942: 
 4943: =item * $addentries, extra parameters for the <body> tag.
 4944: 
 4945: =item * $bodyonly, if defined, only return the <body> tag.
 4946: 
 4947: =item * $domain, if defined, force a given domain.
 4948: 
 4949: =item * $forcereg, if page should register as content page (relevant for 
 4950:             text interface only)
 4951: 
 4952: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4953:                      navigational links
 4954: 
 4955: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4956: 
 4957: =item * $no_inline_link, if true and in remote mode, don't show the
 4958:          'Switch To Inline Menu' link
 4959: 
 4960: =item * $args, optional argument valid values are
 4961:             no_auto_mt_title -> prevents &mt()ing the title arg
 4962:             inherit_jsmath -> when creating popup window in a page,
 4963:                               should it have jsmath forced on by the
 4964:                               current page
 4965: 
 4966: =back
 4967: 
 4968: Returns: A uniform header for LON-CAPA web pages.  
 4969: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4970: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4971: other decorations will be returned.
 4972: 
 4973: =cut
 4974: 
 4975: sub bodytag {
 4976:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4977:         $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
 4978: 
 4979:     my $public;
 4980:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4981:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4982:         $public = 1;
 4983:     }
 4984:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4985: 
 4986:     $function = &get_users_function() if (!$function);
 4987:     my $img =    &designparm($function.'.img',$domain);
 4988:     my $font =   &designparm($function.'.font',$domain);
 4989:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4990: 
 4991:     my %design = ( 'style'   => 'margin-top: 0',
 4992: 		   'bgcolor' => $pgbg,
 4993: 		   'text'    => $font,
 4994:                    'alink'   => &designparm($function.'.alink',$domain),
 4995: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4996: 		   'link'    => &designparm($function.'.link',$domain),);
 4997:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4998: 
 4999:  # role and realm
 5000:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5001:     if ($role  eq 'ca') {
 5002:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5003:         $realm = &plainname($rname,$rdom);
 5004:     } 
 5005: # realm
 5006:     if ($env{'request.course.id'}) {
 5007:         if ($env{'request.role'} !~ /^cr/) {
 5008:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5009:         }
 5010:         if ($env{'request.course.sec'}) {
 5011:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5012:         }   
 5013: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5014:     } else {
 5015:         $role = &Apache::lonnet::plaintext($role);
 5016:     }
 5017: 
 5018:     if (!$realm) { $realm='&nbsp;'; }
 5019: # Set messages
 5020:     my $messages=&domainlogo($domain);
 5021: 
 5022:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5023: 
 5024: # construct main body tag
 5025:     my $bodytag = "<body $extra_body_attr>".
 5026: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5027: 
 5028:     if ($bodyonly) {
 5029:         return $bodytag;
 5030:     } 
 5031: 
 5032:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5033:     if ($public) {
 5034: 	undef($role);
 5035:     } else {
 5036: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5037:                                 undef,'LC_menubuttons_link');
 5038:     }
 5039:     
 5040:     my $titleinfo = '<h1>'.$title.'</h1>';
 5041:     #
 5042:     # Extra info if you are the DC
 5043:     my $dc_info = '';
 5044:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5045:                         $env{'course.'.$env{'request.course.id'}.
 5046:                                  '.domain'}.'/'})) {
 5047:         my $cid = $env{'request.course.id'};
 5048:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5049:         $dc_info =~ s/\s+$//;
 5050:     }
 5051: 
 5052:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5053:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5054: 
 5055:     unless ($env{'environment.remote'} eq 'on') {
 5056:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 5057:             return $bodytag; 
 5058:         } 
 5059: 
 5060:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5061: 
 5062:         #    if ($env{'request.state'} eq 'construct') {
 5063:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5064:         #    }
 5065: 
 5066: 
 5067: 
 5068:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5069:             unless ($env{'request.noversionuri'} =~ m{/res/adm/pages/bookmarkmenu/}) {
 5070:                 if ($dc_info) {
 5071:                      $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5072:                 }
 5073:                 $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 5074:                                <em>$realm</em> $dc_info</div>|;
 5075:             }
 5076:             return $bodytag;
 5077:         }
 5078: 
 5079:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5080:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 5081:         }
 5082: 
 5083:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5084:             Apache::lonmenu::utilityfunctions(), 'start');
 5085: 
 5086:         $bodytag .= Apache::lonmenu::primary_menu();
 5087: 
 5088:         if ($dc_info) {
 5089:             $dc_info = &dc_courseid_toggle($dc_info);
 5090:         }
 5091:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5092: 
 5093:         #don't show menus for public users
 5094:         if (!$public){
 5095:             $bodytag .= Apache::lonmenu::secondary_menu();
 5096:             $bodytag .= Apache::lonmenu::serverform();
 5097:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5098:             if ($env{'request.state'} eq 'construct') {
 5099:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5100:                                 $args->{'bread_crumbs'});
 5101:             } elsif ($forcereg) { 
 5102:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 5103:             }
 5104:         }else{
 5105:             # this is to seperate menu from content when there's no secondary
 5106:             # menu. Especially needed for public accessible ressources.
 5107:             $bodytag .= '<hr style="clear:both" />';
 5108:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5109:         }
 5110: 
 5111:         return $bodytag;
 5112:     }
 5113: 
 5114: #
 5115: # Top frame rendering, Remote is up
 5116: #
 5117: 
 5118:     my $imgsrc = $img;
 5119:     if ($img =~ /^\/adm/) {
 5120:         $imgsrc = &lonhttpdurl($img);
 5121:     }
 5122:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5123: 
 5124:     # Explicit link to get inline menu
 5125:     my $menu= ($no_inline_link?''
 5126:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5127: 
 5128:     if ($dc_info) {
 5129:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5130:     }
 5131: 
 5132:     unless ($env{'form.inhibitmenu'}) {
 5133:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5134:                        <ol class="LC_primary_menu LC_right">
 5135:                        <li>$menu</li>
 5136:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5137:     }
 5138:     return(<<ENDBODY);
 5139: $bodytag
 5140: <table id="LC_title_bar" class="LC_with_remote">
 5141: <tr><td>$upperleft</td>
 5142:     <td>$messages&nbsp;</td>
 5143: </tr>
 5144: <tr><td>$titleinfo $dc_info $menu</td>
 5145: </tr>
 5146: </table>
 5147: ENDBODY
 5148: }
 5149: 
 5150: sub dc_courseid_toggle {
 5151:     my ($dc_info) = @_;
 5152:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5153:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5154:            &mt('(More ...)').'</a></span>'.
 5155:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5156: }
 5157: 
 5158: sub make_attr_string {
 5159:     my ($register,$attr_ref) = @_;
 5160: 
 5161:     if ($attr_ref && !ref($attr_ref)) {
 5162: 	die("addentries Must be a hash ref ".
 5163: 	    join(':',caller(1))." ".
 5164: 	    join(':',caller(0))." ");
 5165:     }
 5166: 
 5167:     if ($register) {
 5168: 	my ($on_load,$on_unload);
 5169: 	foreach my $key (keys(%{$attr_ref})) {
 5170: 	    if      (lc($key) eq 'onload') {
 5171: 		$on_load.=$attr_ref->{$key}.';';
 5172: 		delete($attr_ref->{$key});
 5173: 
 5174: 	    } elsif (lc($key) eq 'onunload') {
 5175: 		$on_unload.=$attr_ref->{$key}.';';
 5176: 		delete($attr_ref->{$key});
 5177: 	    }
 5178: 	}
 5179:         if ($env{'environment.remote'} eq 'on') {
 5180:             $attr_ref->{'onload'}  =
 5181:                 &Apache::lonmenu::loadevents().  $on_load;
 5182:             $attr_ref->{'onunload'}=
 5183:                 &Apache::lonmenu::unloadevents().$on_unload;
 5184:         } else {  
 5185: 	    $attr_ref->{'onload'}  = $on_load;
 5186: 	    $attr_ref->{'onunload'}= $on_unload;
 5187:         }
 5188:     }
 5189: 
 5190:     my $attr_string;
 5191:     foreach my $attr (keys(%$attr_ref)) {
 5192: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5193:     }
 5194:     return $attr_string;
 5195: }
 5196: 
 5197: 
 5198: ###############################################
 5199: ###############################################
 5200: 
 5201: =pod
 5202: 
 5203: =item * &endbodytag()
 5204: 
 5205: Returns a uniform footer for LON-CAPA web pages.
 5206: 
 5207: Inputs: 1 - optional reference to an args hash
 5208: If in the hash, key for noredirectlink has a value which evaluates to true,
 5209: a 'Continue' link is not displayed if the page contains an
 5210: internal redirect in the <head></head> section,
 5211: i.e., $env{'internal.head.redirect'} exists   
 5212: 
 5213: =cut
 5214: 
 5215: sub endbodytag {
 5216:     my ($args) = @_;
 5217:     my $endbodytag;
 5218:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5219:         $endbodytag='</body>';
 5220:     }
 5221:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5222:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5223:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5224: 	    $endbodytag=
 5225: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5226: 	        &mt('Continue').'</a>'.
 5227: 	        $endbodytag;
 5228:         }
 5229:     }
 5230:     return $endbodytag;
 5231: }
 5232: 
 5233: =pod
 5234: 
 5235: =item * &standard_css()
 5236: 
 5237: Returns a style sheet
 5238: 
 5239: Inputs: (all optional)
 5240:             domain         -> force to color decorate a page for a specific
 5241:                                domain
 5242:             function       -> force usage of a specific rolish color scheme
 5243:             bgcolor        -> override the default page bgcolor
 5244: 
 5245: =cut
 5246: 
 5247: sub standard_css {
 5248:     my ($function,$domain,$bgcolor) = @_;
 5249:     $function  = &get_users_function() if (!$function);
 5250:     my $img    = &designparm($function.'.img',   $domain);
 5251:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5252:     my $font   = &designparm($function.'.font',  $domain);
 5253:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5254: #second colour for later usage
 5255:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5256:     my $pgbg_or_bgcolor =
 5257: 	         $bgcolor ||
 5258: 	         &designparm($function.'.pgbg',  $domain);
 5259:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5260:     my $alink  = &designparm($function.'.alink', $domain);
 5261:     my $vlink  = &designparm($function.'.vlink', $domain);
 5262:     my $link   = &designparm($function.'.link',  $domain);
 5263: 
 5264:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5265:     my $mono                 = 'monospace';
 5266:     my $data_table_head      = $sidebg;
 5267:     my $data_table_light     = '#FAFAFA';
 5268:     my $data_table_dark      = '#E0E0E0';
 5269:     my $data_table_darker    = '#CCCCCC';
 5270:     my $data_table_highlight = '#FFFF00';
 5271:     my $mail_new             = '#FFBB77';
 5272:     my $mail_new_hover       = '#DD9955';
 5273:     my $mail_read            = '#BBBB77';
 5274:     my $mail_read_hover      = '#999944';
 5275:     my $mail_replied         = '#AAAA88';
 5276:     my $mail_replied_hover   = '#888855';
 5277:     my $mail_other           = '#99BBBB';
 5278:     my $mail_other_hover     = '#669999';
 5279:     my $table_header         = '#DDDDDD';
 5280:     my $feedback_link_bg     = '#BBBBBB';
 5281:     my $lg_border_color      = '#C8C8C8';
 5282:     my $button_hover         = '#BF2317';
 5283: 
 5284:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5285:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5286:                                              : '0 3px 0 4px';
 5287: 
 5288: 
 5289:     return <<END;
 5290: 
 5291: /* needed for iframe to allow 100% height in FF */
 5292: body, html { 
 5293:     margin: 0;
 5294:     padding: 0 0.5%;
 5295:     height: 99%; /* to avoid scrollbars */
 5296: }
 5297: 
 5298: body {
 5299:   font-family: $sans;
 5300:   line-height:130%;
 5301:   font-size:0.83em;
 5302:   color:$font;
 5303: }
 5304: 
 5305: a:focus,
 5306: a:focus img {
 5307:   color: red;
 5308: }
 5309: 
 5310: form, .inline {
 5311:   display: inline;
 5312: }
 5313: 
 5314: .LC_right {
 5315:   text-align:right;
 5316: }
 5317: 
 5318: .LC_middle {
 5319:   vertical-align:middle;
 5320: }
 5321: 
 5322: .LC_400Box {
 5323:   width:400px;
 5324: }
 5325: 
 5326: .LC_iframecontainer {
 5327:     width: 98%;
 5328:     margin: 0;
 5329:     position: fixed;
 5330:     top: 8.5em;
 5331:     bottom: 0;
 5332: }
 5333: 
 5334: .LC_iframecontainer iframe{
 5335:     border: none;
 5336:     width: 100%;
 5337:     height: 100%;
 5338: }
 5339: 
 5340: .LC_filename {
 5341:   font-family: $mono;
 5342:   white-space:pre;
 5343:   font-size: 120%;
 5344: }
 5345: 
 5346: .LC_fileicon {
 5347:   border: none;
 5348:   height: 1.3em;
 5349:   vertical-align: text-bottom;
 5350:   margin-right: 0.3em;
 5351:   text-decoration:none;
 5352: }
 5353: 
 5354: .LC_setting {
 5355:   text-decoration:underline;
 5356: }
 5357: 
 5358: .LC_error {
 5359:   color: red;
 5360:   font-size: larger;
 5361: }
 5362: 
 5363: .LC_warning,
 5364: .LC_diff_removed {
 5365:   color: red;
 5366: }
 5367: 
 5368: .LC_info,
 5369: .LC_success,
 5370: .LC_diff_added {
 5371:   color: green;
 5372: }
 5373: 
 5374: div.LC_confirm_box {
 5375:   background-color: #FAFAFA;
 5376:   border: 1px solid $lg_border_color;
 5377:   margin-right: 0;
 5378:   padding: 5px;
 5379: }
 5380: 
 5381: div.LC_confirm_box .LC_error img,
 5382: div.LC_confirm_box .LC_success img {
 5383:   vertical-align: middle;
 5384: }
 5385: 
 5386: .LC_icon {
 5387:   border: none;
 5388:   vertical-align: middle;
 5389: }
 5390: 
 5391: .LC_docs_spacer {
 5392:   width: 25px;
 5393:   height: 1px;
 5394:   border: none;
 5395: }
 5396: 
 5397: .LC_internal_info {
 5398:   color: #999999;
 5399: }
 5400: 
 5401: .LC_discussion {
 5402:   background: $data_table_dark;
 5403:   border: 1px solid black;
 5404:   margin: 2px;
 5405: }
 5406: 
 5407: .LC_disc_action_left {
 5408:   background: $sidebg;
 5409:   text-align: left;
 5410:   padding: 4px;
 5411:   margin: 2px;
 5412: }
 5413: 
 5414: .LC_disc_action_right {
 5415:   background: $sidebg;
 5416:   text-align: right;
 5417:   padding: 4px;
 5418:   margin: 2px;
 5419: }
 5420: 
 5421: .LC_disc_new_item {
 5422:   background: white;
 5423:   border: 2px solid red;
 5424:   margin: 4px;
 5425:   padding: 4px;
 5426: }
 5427: 
 5428: .LC_disc_old_item {
 5429:   background: white;
 5430:   margin: 4px;
 5431:   padding: 4px;
 5432: }
 5433: 
 5434: table.LC_pastsubmission {
 5435:   border: 1px solid black;
 5436:   margin: 2px;
 5437: }
 5438: 
 5439: table#LC_menubuttons {
 5440:   width: 100%;
 5441:   background: $pgbg;
 5442:   border: 2px;
 5443:   border-collapse: separate;
 5444:   padding: 0;
 5445: }
 5446: 
 5447: table#LC_title_bar a {
 5448:   color: $fontmenu;
 5449: }
 5450: 
 5451: table#LC_title_bar {
 5452:   clear: both;
 5453:   display: none;
 5454: }
 5455: 
 5456: table#LC_title_bar,
 5457: table.LC_breadcrumbs, /* obsolete? */
 5458: table#LC_title_bar.LC_with_remote {
 5459:   width: 100%;
 5460:   border-color: $pgbg;
 5461:   border-style: solid;
 5462:   border-width: $border;
 5463:   background: $pgbg;
 5464:   color: $fontmenu;
 5465:   border-collapse: collapse;
 5466:   padding: 0;
 5467:   margin: 0;
 5468: }
 5469: 
 5470: ul.LC_breadcrumb_tools_outerlist {
 5471:     margin: 0;
 5472:     padding: 0;
 5473:     position: relative;
 5474:     list-style: none;
 5475: }
 5476: ul.LC_breadcrumb_tools_outerlist li {
 5477:     display: inline;
 5478: }
 5479: 
 5480: .LC_breadcrumb_tools_navigation {
 5481:     padding: 0;
 5482:     margin: 0;
 5483:     float: left;
 5484: }
 5485: .LC_breadcrumb_tools_tools {
 5486:     padding: 0;
 5487:     margin: 0;
 5488:     float: right;
 5489: }
 5490: 
 5491: table#LC_title_bar td {
 5492:   background: $tabbg;
 5493: }
 5494: 
 5495: table#LC_menubuttons img {
 5496:   border: none;
 5497: }
 5498: 
 5499: .LC_breadcrumbs_component {
 5500:   float: right;
 5501:   margin: 0 1em;
 5502: }
 5503: .LC_breadcrumbs_component img {
 5504:   vertical-align: middle;
 5505: }
 5506: 
 5507: td.LC_table_cell_checkbox {
 5508:   text-align: center;
 5509: }
 5510: 
 5511: .LC_fontsize_small {
 5512:   font-size: 70%;
 5513: }
 5514: 
 5515: #LC_breadcrumbs {
 5516:   clear:both;
 5517:   background: $sidebg;
 5518:   border-bottom: 1px solid $lg_border_color;
 5519:   line-height: 2.5em;
 5520:   overflow: hidden;
 5521:   margin: 0;
 5522:   padding: 0;
 5523:   text-align: left;
 5524: }
 5525: 
 5526: .LC_head_subbox {
 5527:   clear:both;
 5528:   background: #F8F8F8; /* $sidebg; */
 5529:   border: 1px solid $sidebg;
 5530:   margin: 0 0 10px 0;      
 5531:   padding: 3px;
 5532:   text-align: left;
 5533: }
 5534: 
 5535: .LC_fontsize_medium {
 5536:   font-size: 85%;
 5537: }
 5538: 
 5539: .LC_fontsize_large {
 5540:   font-size: 120%;
 5541: }
 5542: 
 5543: .LC_menubuttons_inline_text {
 5544:   color: $font;
 5545:   font-size: 90%;
 5546:   padding-left:3px;
 5547: }
 5548: 
 5549: .LC_menubuttons_inline_text img{
 5550:   vertical-align: middle;
 5551: }
 5552: 
 5553: li.LC_menubuttons_inline_text img {
 5554:   cursor:pointer;
 5555:   text-decoration: none;
 5556: }
 5557: 
 5558: .LC_menubuttons_link {
 5559:   text-decoration: none;
 5560: }
 5561: 
 5562: .LC_menubuttons_category {
 5563:   color: $font;
 5564:   background: $pgbg;
 5565:   font-size: larger;
 5566:   font-weight: bold;
 5567: }
 5568: 
 5569: td.LC_menubuttons_text {
 5570:   color: $font;
 5571: }
 5572: 
 5573: .LC_current_location {
 5574:   background: $tabbg;
 5575: }
 5576: 
 5577: table.LC_data_table {
 5578:   border: 1px solid #000000;
 5579:   border-collapse: separate;
 5580:   border-spacing: 1px;
 5581:   background: $pgbg;
 5582: }
 5583: 
 5584: .LC_data_table_dense {
 5585:   font-size: small;
 5586: }
 5587: 
 5588: table.LC_nested_outer {
 5589:   border: 1px solid #000000;
 5590:   border-collapse: collapse;
 5591:   border-spacing: 0;
 5592:   width: 100%;
 5593: }
 5594: 
 5595: table.LC_innerpickbox,
 5596: table.LC_nested {
 5597:   border: none;
 5598:   border-collapse: collapse;
 5599:   border-spacing: 0;
 5600:   width: 100%;
 5601: }
 5602: 
 5603: table.LC_data_table tr th,
 5604: table.LC_calendar tr th,
 5605: table.LC_prior_tries tr th,
 5606: table.LC_innerpickbox tr th {
 5607:   font-weight: bold;
 5608:   background-color: $data_table_head;
 5609:   color:$fontmenu;
 5610:   font-size:90%;
 5611: }
 5612: 
 5613: table.LC_innerpickbox tr th,
 5614: table.LC_innerpickbox tr td {
 5615:   vertical-align: top;
 5616: }
 5617: 
 5618: table.LC_data_table tr.LC_info_row > td {
 5619:   background-color: #CCCCCC;
 5620:   font-weight: bold;
 5621:   text-align: left;
 5622: }
 5623: 
 5624: table.LC_data_table tr.LC_odd_row > td {
 5625:   background-color: $data_table_light;
 5626:   padding: 2px;
 5627:   vertical-align: top;
 5628: }
 5629: 
 5630: table.LC_pick_box tr > td.LC_odd_row {
 5631:   background-color: $data_table_light;
 5632:   vertical-align: top;
 5633: }
 5634: 
 5635: table.LC_data_table tr.LC_even_row > td {
 5636:   background-color: $data_table_dark;
 5637:   padding: 2px;
 5638:   vertical-align: top;
 5639: }
 5640: 
 5641: table.LC_pick_box tr > td.LC_even_row {
 5642:   background-color: $data_table_dark;
 5643:   vertical-align: top;
 5644: }
 5645: 
 5646: table.LC_data_table tr.LC_data_table_highlight td {
 5647:   background-color: $data_table_darker;
 5648: }
 5649: 
 5650: table.LC_data_table tr td.LC_leftcol_header {
 5651:   background-color: $data_table_head;
 5652:   font-weight: bold;
 5653: }
 5654: 
 5655: table.LC_data_table tr.LC_empty_row td,
 5656: table.LC_nested tr.LC_empty_row td {
 5657:   font-weight: bold;
 5658:   font-style: italic;
 5659:   text-align: center;
 5660:   padding: 8px;
 5661: }
 5662: 
 5663: table.LC_data_table tr.LC_empty_row td {
 5664:   background-color: $sidebg;
 5665: }
 5666: 
 5667: table.LC_nested tr.LC_empty_row td {
 5668:   background-color: #FFFFFF;
 5669: }
 5670: 
 5671: table.LC_caption {
 5672: }
 5673: 
 5674: table.LC_nested tr.LC_empty_row td {
 5675:   padding: 4ex
 5676: }
 5677: 
 5678: table.LC_nested_outer tr th {
 5679:   font-weight: bold;
 5680:   color:$fontmenu;
 5681:   background-color: $data_table_head;
 5682:   font-size: small;
 5683:   border-bottom: 1px solid #000000;
 5684: }
 5685: 
 5686: table.LC_nested_outer tr td.LC_subheader {
 5687:   background-color: $data_table_head;
 5688:   font-weight: bold;
 5689:   font-size: small;
 5690:   border-bottom: 1px solid #000000;
 5691:   text-align: right;
 5692: }
 5693: 
 5694: table.LC_nested tr.LC_info_row td {
 5695:   background-color: #CCCCCC;
 5696:   font-weight: bold;
 5697:   font-size: small;
 5698:   text-align: center;
 5699: }
 5700: 
 5701: table.LC_nested tr.LC_info_row td.LC_left_item,
 5702: table.LC_nested_outer tr th.LC_left_item {
 5703:   text-align: left;
 5704: }
 5705: 
 5706: table.LC_nested td {
 5707:   background-color: #FFFFFF;
 5708:   font-size: small;
 5709: }
 5710: 
 5711: table.LC_nested_outer tr th.LC_right_item,
 5712: table.LC_nested tr.LC_info_row td.LC_right_item,
 5713: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5714: table.LC_nested tr td.LC_right_item {
 5715:   text-align: right;
 5716: }
 5717: 
 5718: table.LC_nested tr.LC_odd_row td {
 5719:   background-color: #EEEEEE;
 5720: }
 5721: 
 5722: table.LC_createuser {
 5723: }
 5724: 
 5725: table.LC_createuser tr.LC_section_row td {
 5726:   font-size: small;
 5727: }
 5728: 
 5729: table.LC_createuser tr.LC_info_row td  {
 5730:   background-color: #CCCCCC;
 5731:   font-weight: bold;
 5732:   text-align: center;
 5733: }
 5734: 
 5735: table.LC_calendar {
 5736:   border: 1px solid #000000;
 5737:   border-collapse: collapse;
 5738:   width: 98%;
 5739: }
 5740: 
 5741: table.LC_calendar_pickdate {
 5742:   font-size: xx-small;
 5743: }
 5744: 
 5745: table.LC_calendar tr td {
 5746:   border: 1px solid #000000;
 5747:   vertical-align: top;
 5748:   width: 14%;
 5749: }
 5750: 
 5751: table.LC_calendar tr td.LC_calendar_day_empty {
 5752:   background-color: $data_table_dark;
 5753: }
 5754: 
 5755: table.LC_calendar tr td.LC_calendar_day_current {
 5756:   background-color: $data_table_highlight;
 5757: }
 5758: 
 5759: table.LC_data_table tr td.LC_mail_new {
 5760:   background-color: $mail_new;
 5761: }
 5762: 
 5763: table.LC_data_table tr.LC_mail_new:hover {
 5764:   background-color: $mail_new_hover;
 5765: }
 5766: 
 5767: table.LC_data_table tr td.LC_mail_read {
 5768:   background-color: $mail_read;
 5769: }
 5770: 
 5771: /*
 5772: table.LC_data_table tr.LC_mail_read:hover {
 5773:   background-color: $mail_read_hover;
 5774: }
 5775: */
 5776: 
 5777: table.LC_data_table tr td.LC_mail_replied {
 5778:   background-color: $mail_replied;
 5779: }
 5780: 
 5781: /*
 5782: table.LC_data_table tr.LC_mail_replied:hover {
 5783:   background-color: $mail_replied_hover;
 5784: }
 5785: */
 5786: 
 5787: table.LC_data_table tr td.LC_mail_other {
 5788:   background-color: $mail_other;
 5789: }
 5790: 
 5791: /*
 5792: table.LC_data_table tr.LC_mail_other:hover {
 5793:   background-color: $mail_other_hover;
 5794: }
 5795: */
 5796: 
 5797: table.LC_data_table tr > td.LC_browser_file,
 5798: table.LC_data_table tr > td.LC_browser_file_published {
 5799:   background: #AAEE77;
 5800: }
 5801: 
 5802: table.LC_data_table tr > td.LC_browser_file_locked,
 5803: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5804:   background: #FFAA99;
 5805: }
 5806: 
 5807: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5808:   background: #888888;
 5809: }
 5810: 
 5811: table.LC_data_table tr > td.LC_browser_file_modified,
 5812: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5813:   background: #F8F866;
 5814: }
 5815: 
 5816: table.LC_data_table tr.LC_browser_folder > td {
 5817:   background: #E0E8FF;
 5818: }
 5819: 
 5820: table.LC_data_table tr > td.LC_roles_is {
 5821:   /* background: #77FF77; */
 5822: }
 5823: 
 5824: table.LC_data_table tr > td.LC_roles_future {
 5825:   border-right: 8px solid #FFFF77;
 5826: }
 5827: 
 5828: table.LC_data_table tr > td.LC_roles_will {
 5829:   border-right: 8px solid #FFAA77;
 5830: }
 5831: 
 5832: table.LC_data_table tr > td.LC_roles_expired {
 5833:   border-right: 8px solid #FF7777;
 5834: }
 5835: 
 5836: table.LC_data_table tr > td.LC_roles_will_not {
 5837:   border-right: 8px solid #AAFF77;
 5838: }
 5839: 
 5840: table.LC_data_table tr > td.LC_roles_selected {
 5841:   border-right: 8px solid #11CC55;
 5842: }
 5843: 
 5844: span.LC_current_location {
 5845:   font-size:larger;
 5846:   background: $pgbg;
 5847: }
 5848: 
 5849: span.LC_current_nav_location {
 5850:   font-weight:bold;
 5851:   background: $sidebg;
 5852: }
 5853: 
 5854: span.LC_parm_menu_item {
 5855:   font-size: larger;
 5856: }
 5857: 
 5858: span.LC_parm_scope_all {
 5859:   color: red;
 5860: }
 5861: 
 5862: span.LC_parm_scope_folder {
 5863:   color: green;
 5864: }
 5865: 
 5866: span.LC_parm_scope_resource {
 5867:   color: orange;
 5868: }
 5869: 
 5870: span.LC_parm_part {
 5871:   color: blue;
 5872: }
 5873: 
 5874: span.LC_parm_folder,
 5875: span.LC_parm_symb {
 5876:   font-size: x-small;
 5877:   font-family: $mono;
 5878:   color: #AAAAAA;
 5879: }
 5880: 
 5881: ul.LC_parm_parmlist li {
 5882:   display: inline-block;
 5883:   padding: 0.3em 0.8em;
 5884:   vertical-align: top;
 5885:   width: 150px;
 5886:   border-top:1px solid $lg_border_color;
 5887: }
 5888: 
 5889: td.LC_parm_overview_level_menu,
 5890: td.LC_parm_overview_map_menu,
 5891: td.LC_parm_overview_parm_selectors,
 5892: td.LC_parm_overview_restrictions  {
 5893:   border: 1px solid black;
 5894:   border-collapse: collapse;
 5895: }
 5896: 
 5897: table.LC_parm_overview_restrictions td {
 5898:   border-width: 1px 4px 1px 4px;
 5899:   border-style: solid;
 5900:   border-color: $pgbg;
 5901:   text-align: center;
 5902: }
 5903: 
 5904: table.LC_parm_overview_restrictions th {
 5905:   background: $tabbg;
 5906:   border-width: 1px 4px 1px 4px;
 5907:   border-style: solid;
 5908:   border-color: $pgbg;
 5909: }
 5910: 
 5911: table#LC_helpmenu {
 5912:   border: none;
 5913:   height: 55px;
 5914:   border-spacing: 0;
 5915: }
 5916: 
 5917: table#LC_helpmenu fieldset legend {
 5918:   font-size: larger;
 5919: }
 5920: 
 5921: table#LC_helpmenu_links {
 5922:   width: 100%;
 5923:   border: 1px solid black;
 5924:   background: $pgbg;
 5925:   padding: 0;
 5926:   border-spacing: 1px;
 5927: }
 5928: 
 5929: table#LC_helpmenu_links tr td {
 5930:   padding: 1px;
 5931:   background: $tabbg;
 5932:   text-align: center;
 5933:   font-weight: bold;
 5934: }
 5935: 
 5936: table#LC_helpmenu_links a:link,
 5937: table#LC_helpmenu_links a:visited,
 5938: table#LC_helpmenu_links a:active {
 5939:   text-decoration: none;
 5940:   color: $font;
 5941: }
 5942: 
 5943: table#LC_helpmenu_links a:hover {
 5944:   text-decoration: underline;
 5945:   color: $vlink;
 5946: }
 5947: 
 5948: .LC_chrt_popup_exists {
 5949:   border: 1px solid #339933;
 5950:   margin: -1px;
 5951: }
 5952: 
 5953: .LC_chrt_popup_up {
 5954:   border: 1px solid yellow;
 5955:   margin: -1px;
 5956: }
 5957: 
 5958: .LC_chrt_popup {
 5959:   border: 1px solid #8888FF;
 5960:   background: #CCCCFF;
 5961: }
 5962: 
 5963: table.LC_pick_box {
 5964:   border-collapse: separate;
 5965:   background: white;
 5966:   border: 1px solid black;
 5967:   border-spacing: 1px;
 5968: }
 5969: 
 5970: table.LC_pick_box td.LC_pick_box_title {
 5971:   background: $sidebg;
 5972:   font-weight: bold;
 5973:   text-align: left;
 5974:   vertical-align: top;
 5975:   width: 184px;
 5976:   padding: 8px;
 5977: }
 5978: 
 5979: table.LC_pick_box td.LC_pick_box_value {
 5980:   text-align: left;
 5981:   padding: 8px;
 5982: }
 5983: 
 5984: table.LC_pick_box td.LC_pick_box_select {
 5985:   text-align: left;
 5986:   padding: 8px;
 5987: }
 5988: 
 5989: table.LC_pick_box td.LC_pick_box_separator {
 5990:   padding: 0;
 5991:   height: 1px;
 5992:   background: black;
 5993: }
 5994: 
 5995: table.LC_pick_box td.LC_pick_box_submit {
 5996:   text-align: right;
 5997: }
 5998: 
 5999: table.LC_pick_box td.LC_evenrow_value {
 6000:   text-align: left;
 6001:   padding: 8px;
 6002:   background-color: $data_table_light;
 6003: }
 6004: 
 6005: table.LC_pick_box td.LC_oddrow_value {
 6006:   text-align: left;
 6007:   padding: 8px;
 6008:   background-color: $data_table_light;
 6009: }
 6010: 
 6011: span.LC_helpform_receipt_cat {
 6012:   font-weight: bold;
 6013: }
 6014: 
 6015: table.LC_group_priv_box {
 6016:   background: white;
 6017:   border: 1px solid black;
 6018:   border-spacing: 1px;
 6019: }
 6020: 
 6021: table.LC_group_priv_box td.LC_pick_box_title {
 6022:   background: $tabbg;
 6023:   font-weight: bold;
 6024:   text-align: right;
 6025:   width: 184px;
 6026: }
 6027: 
 6028: table.LC_group_priv_box td.LC_groups_fixed {
 6029:   background: $data_table_light;
 6030:   text-align: center;
 6031: }
 6032: 
 6033: table.LC_group_priv_box td.LC_groups_optional {
 6034:   background: $data_table_dark;
 6035:   text-align: center;
 6036: }
 6037: 
 6038: table.LC_group_priv_box td.LC_groups_functionality {
 6039:   background: $data_table_darker;
 6040:   text-align: center;
 6041:   font-weight: bold;
 6042: }
 6043: 
 6044: table.LC_group_priv td {
 6045:   text-align: left;
 6046:   padding: 0;
 6047: }
 6048: 
 6049: .LC_navbuttons {
 6050:   margin: 2ex 0ex 2ex 0ex;
 6051: }
 6052: 
 6053: .LC_topic_bar {
 6054:   font-weight: bold;
 6055:   background: $tabbg;
 6056:   margin: 1em 0em 1em 2em;
 6057:   padding: 3px;
 6058:   font-size: 1.2em;
 6059: }
 6060: 
 6061: .LC_topic_bar span {
 6062:   left: 0.5em;
 6063:   position: absolute;
 6064:   vertical-align: middle;
 6065:   font-size: 1.2em;
 6066: }
 6067: 
 6068: table.LC_course_group_status {
 6069:   margin: 20px;
 6070: }
 6071: 
 6072: table.LC_status_selector td {
 6073:   vertical-align: top;
 6074:   text-align: center;
 6075:   padding: 4px;
 6076: }
 6077: 
 6078: div.LC_feedback_link {
 6079:   clear: both;
 6080:   background: $sidebg;
 6081:   width: 100%;
 6082:   padding-bottom: 10px;
 6083:   border: 1px $tabbg solid;
 6084:   height: 22px;
 6085:   line-height: 22px;
 6086:   padding-top: 5px;
 6087: }
 6088: 
 6089: div.LC_feedback_link img {
 6090:   height: 22px;
 6091:   vertical-align:middle;
 6092: }
 6093: 
 6094: div.LC_feedback_link a {
 6095:   text-decoration: none;
 6096: }
 6097: 
 6098: div.LC_comblock {
 6099:   display:inline;
 6100:   color:$font;
 6101:   font-size:90%;
 6102: }
 6103: 
 6104: div.LC_feedback_link div.LC_comblock {
 6105:   padding-left:5px;
 6106: }
 6107: 
 6108: div.LC_feedback_link div.LC_comblock a {
 6109:   color:$font;
 6110: }
 6111: 
 6112: span.LC_feedback_link {
 6113:   /* background: $feedback_link_bg; */
 6114:   font-size: larger;
 6115: }
 6116: 
 6117: span.LC_message_link {
 6118:   /* background: $feedback_link_bg; */
 6119:   font-size: larger;
 6120:   position: absolute;
 6121:   right: 1em;
 6122: }
 6123: 
 6124: table.LC_prior_tries {
 6125:   border: 1px solid #000000;
 6126:   border-collapse: separate;
 6127:   border-spacing: 1px;
 6128: }
 6129: 
 6130: table.LC_prior_tries td {
 6131:   padding: 2px;
 6132: }
 6133: 
 6134: .LC_answer_correct {
 6135:   background: lightgreen;
 6136:   color: darkgreen;
 6137:   padding: 6px;
 6138: }
 6139: 
 6140: .LC_answer_charged_try {
 6141:   background: #FFAAAA;
 6142:   color: darkred;
 6143:   padding: 6px;
 6144: }
 6145: 
 6146: .LC_answer_not_charged_try,
 6147: .LC_answer_no_grade,
 6148: .LC_answer_late {
 6149:   background: lightyellow;
 6150:   color: black;
 6151:   padding: 6px;
 6152: }
 6153: 
 6154: .LC_answer_previous {
 6155:   background: lightblue;
 6156:   color: darkblue;
 6157:   padding: 6px;
 6158: }
 6159: 
 6160: .LC_answer_no_message {
 6161:   background: #FFFFFF;
 6162:   color: black;
 6163:   padding: 6px;
 6164: }
 6165: 
 6166: .LC_answer_unknown {
 6167:   background: orange;
 6168:   color: black;
 6169:   padding: 6px;
 6170: }
 6171: 
 6172: span.LC_prior_numerical,
 6173: span.LC_prior_string,
 6174: span.LC_prior_custom,
 6175: span.LC_prior_reaction,
 6176: span.LC_prior_math {
 6177:   font-family: $mono;
 6178:   white-space: pre;
 6179: }
 6180: 
 6181: span.LC_prior_string {
 6182:   font-family: $mono;
 6183:   white-space: pre;
 6184: }
 6185: 
 6186: table.LC_prior_option {
 6187:   width: 100%;
 6188:   border-collapse: collapse;
 6189: }
 6190: 
 6191: table.LC_prior_rank,
 6192: table.LC_prior_match {
 6193:   border-collapse: collapse;
 6194: }
 6195: 
 6196: table.LC_prior_option tr td,
 6197: table.LC_prior_rank tr td,
 6198: table.LC_prior_match tr td {
 6199:   border: 1px solid #000000;
 6200: }
 6201: 
 6202: .LC_nobreak {
 6203:   white-space: nowrap;
 6204: }
 6205: 
 6206: span.LC_cusr_emph {
 6207:   font-style: italic;
 6208: }
 6209: 
 6210: span.LC_cusr_subheading {
 6211:   font-weight: normal;
 6212:   font-size: 85%;
 6213: }
 6214: 
 6215: div.LC_docs_entry_move {
 6216:   border: 1px solid #BBBBBB;
 6217:   background: #DDDDDD;
 6218:   width: 22px;
 6219:   padding: 1px;
 6220:   margin: 0;
 6221: }
 6222: 
 6223: table.LC_data_table tr > td.LC_docs_entry_commands,
 6224: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6225:   background: #DDDDDD;
 6226:   font-size: x-small;
 6227: }
 6228: 
 6229: .LC_docs_entry_parameter {
 6230:   white-space: nowrap;
 6231: }
 6232: 
 6233: .LC_docs_copy {
 6234:   color: #000099;
 6235: }
 6236: 
 6237: .LC_docs_cut {
 6238:   color: #550044;
 6239: }
 6240: 
 6241: .LC_docs_rename {
 6242:   color: #009900;
 6243: }
 6244: 
 6245: .LC_docs_remove {
 6246:   color: #990000;
 6247: }
 6248: 
 6249: .LC_docs_reinit_warn,
 6250: .LC_docs_ext_edit {
 6251:   font-size: x-small;
 6252: }
 6253: 
 6254: table.LC_docs_adddocs td,
 6255: table.LC_docs_adddocs th {
 6256:   border: 1px solid #BBBBBB;
 6257:   padding: 4px;
 6258:   background: #DDDDDD;
 6259: }
 6260: 
 6261: table.LC_sty_begin {
 6262:   background: #BBFFBB;
 6263: }
 6264: 
 6265: table.LC_sty_end {
 6266:   background: #FFBBBB;
 6267: }
 6268: 
 6269: table.LC_double_column {
 6270:   border-width: 0;
 6271:   border-collapse: collapse;
 6272:   width: 100%;
 6273:   padding: 2px;
 6274: }
 6275: 
 6276: table.LC_double_column tr td.LC_left_col {
 6277:   top: 2px;
 6278:   left: 2px;
 6279:   width: 47%;
 6280:   vertical-align: top;
 6281: }
 6282: 
 6283: table.LC_double_column tr td.LC_right_col {
 6284:   top: 2px;
 6285:   right: 2px;
 6286:   width: 47%;
 6287:   vertical-align: top;
 6288: }
 6289: 
 6290: div.LC_left_float {
 6291:   float: left;
 6292:   padding-right: 5%;
 6293:   padding-bottom: 4px;
 6294: }
 6295: 
 6296: div.LC_clear_float_header {
 6297:   padding-bottom: 2px;
 6298: }
 6299: 
 6300: div.LC_clear_float_footer {
 6301:   padding-top: 10px;
 6302:   clear: both;
 6303: }
 6304: 
 6305: div.LC_grade_show_user {
 6306: /*  border-left: 5px solid $sidebg; */
 6307:   border-top: 5px solid #000000;
 6308:   margin: 50px 0 0 0;
 6309:   padding: 15px 0 5px 10px;
 6310: }
 6311: 
 6312: div.LC_grade_show_user_odd_row {
 6313: /*  border-left: 5px solid #000000; */
 6314: }
 6315: 
 6316: div.LC_grade_show_user div.LC_Box {
 6317:   margin-right: 50px;
 6318: }
 6319: 
 6320: div.LC_grade_submissions,
 6321: div.LC_grade_message_center,
 6322: div.LC_grade_info_links {
 6323:   margin: 5px;
 6324:   width: 99%;
 6325:   background: #FFFFFF;
 6326: }
 6327: 
 6328: div.LC_grade_submissions_header,
 6329: div.LC_grade_message_center_header {
 6330:   font-weight: bold;
 6331:   font-size: large;
 6332: }
 6333: 
 6334: div.LC_grade_submissions_body,
 6335: div.LC_grade_message_center_body {
 6336:   border: 1px solid black;
 6337:   width: 99%;
 6338:   background: #FFFFFF;
 6339: }
 6340: 
 6341: table.LC_scantron_action {
 6342:   width: 100%;
 6343: }
 6344: 
 6345: table.LC_scantron_action tr th {
 6346:   font-weight:bold;
 6347:   font-style:normal;
 6348: }
 6349: 
 6350: .LC_edit_problem_header,
 6351: div.LC_edit_problem_footer {
 6352:   font-weight: normal;
 6353:   font-size:  medium;
 6354:   margin: 2px;
 6355:   background-color: $sidebg;
 6356: }
 6357: 
 6358: div.LC_edit_problem_header,
 6359: div.LC_edit_problem_header div,
 6360: div.LC_edit_problem_footer,
 6361: div.LC_edit_problem_footer div,
 6362: div.LC_edit_problem_editxml_header,
 6363: div.LC_edit_problem_editxml_header div {
 6364:   margin-top: 5px;
 6365: }
 6366: 
 6367: div.LC_edit_problem_header_title {
 6368:   font-weight: bold;
 6369:   font-size: larger;
 6370:   background: $tabbg;
 6371:   padding: 3px;
 6372:   margin: 0 0 5px 0;
 6373: }
 6374: 
 6375: table.LC_edit_problem_header_title {
 6376:   width: 100%;
 6377:   background: $tabbg;
 6378: }
 6379: 
 6380: div.LC_edit_problem_discards {
 6381:   float: left;
 6382:   padding-bottom: 5px;
 6383: }
 6384: 
 6385: div.LC_edit_problem_saves {
 6386:   float: right;
 6387:   padding-bottom: 5px;
 6388: }
 6389: 
 6390: img.stift {
 6391:   border-width: 0;
 6392:   vertical-align: middle;
 6393: }
 6394: 
 6395: table td.LC_mainmenu_col_fieldset {
 6396:   vertical-align: top;
 6397: }
 6398: 
 6399: div.LC_createcourse {
 6400:   margin: 10px 10px 10px 10px;
 6401: }
 6402: 
 6403: .LC_dccid {
 6404:   margin: 0.2em 0 0 0;
 6405:   padding: 0;
 6406:   font-size: 90%;
 6407:   display:none;
 6408: }
 6409: 
 6410: ol.LC_primary_menu a:hover,
 6411: ol#LC_MenuBreadcrumbs a:hover,
 6412: ol#LC_PathBreadcrumbs a:hover,
 6413: ul#LC_secondary_menu a:hover,
 6414: .LC_FormSectionClearButton input:hover
 6415: ul.LC_TabContent   li:hover a {
 6416:   color:$button_hover;
 6417:   text-decoration:none;
 6418: }
 6419: 
 6420: h1 {
 6421:   padding: 0;
 6422:   line-height:130%;
 6423: }
 6424: 
 6425: h2,
 6426: h3,
 6427: h4,
 6428: h5,
 6429: h6 {
 6430:   margin: 5px 0 5px 0;
 6431:   padding: 0;
 6432:   line-height:130%;
 6433: }
 6434: 
 6435: .LC_hcell {
 6436:   padding:3px 15px 3px 15px;
 6437:   margin: 0;
 6438:   background-color:$tabbg;
 6439:   color:$fontmenu;
 6440:   border-bottom:solid 1px $lg_border_color;
 6441: }
 6442: 
 6443: .LC_Box > .LC_hcell {
 6444:   margin: 0 -10px 10px -10px;
 6445: }
 6446: 
 6447: .LC_noBorder {
 6448:   border: 0;
 6449: }
 6450: 
 6451: .LC_FormSectionClearButton input {
 6452:   background-color:transparent;
 6453:   border: none;
 6454:   cursor:pointer;
 6455:   text-decoration:underline;
 6456: }
 6457: 
 6458: .LC_help_open_topic {
 6459:   color: #FFFFFF;
 6460:   background-color: #EEEEFF;
 6461:   margin: 1px;
 6462:   padding: 4px;
 6463:   border: 1px solid #000033;
 6464:   white-space: nowrap;
 6465:   /* vertical-align: middle; */
 6466: }
 6467: 
 6468: dl,
 6469: ul,
 6470: div,
 6471: fieldset {
 6472:   margin: 10px 10px 10px 0;
 6473:   /* overflow: hidden; */
 6474: }
 6475: 
 6476: fieldset > legend {
 6477:   font-weight: bold;
 6478:   padding: 0 5px 0 5px;
 6479: }
 6480: 
 6481: #LC_nav_bar {
 6482:   float: left;
 6483:   background-color: $pgbg_or_bgcolor;
 6484:   margin: 0 0 2px 0;
 6485: }
 6486: 
 6487: #LC_realm {
 6488:   margin: 0.2em 0 0 0;
 6489:   padding: 0;
 6490:   font-weight: bold;
 6491:   text-align: center;
 6492:   background-color: $pgbg_or_bgcolor;
 6493: }
 6494: 
 6495: #LC_nav_bar em {
 6496:   font-weight: bold;
 6497:   font-style: normal;
 6498: }
 6499: 
 6500: ol.LC_primary_menu {
 6501:   float: right;
 6502:   margin: 0;
 6503:   padding: 0;
 6504:   background-color: $pgbg_or_bgcolor;
 6505: }
 6506: 
 6507: ol#LC_PathBreadcrumbs {
 6508:   margin: 0;
 6509: }
 6510: 
 6511: ol.LC_primary_menu li {
 6512:   color: RGB(80, 80, 80);
 6513:   vertical-align: middle;
 6514:   text-align: left;
 6515:   list-style: none;
 6516:   float: left;
 6517: }
 6518: 
 6519: ol.LC_primary_menu li a {
 6520:   display: block;
 6521:   margin: 0;
 6522:   padding: 0 5px 0 10px;
 6523:   text-decoration: none;
 6524: }
 6525: 
 6526: ol.LC_primary_menu li ul {
 6527:   display: none;
 6528:   width: 10em;
 6529:   background-color: $data_table_light;
 6530: }
 6531: 
 6532: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6533:   display: block;
 6534:   position: absolute;
 6535:   margin: 0;
 6536:   padding: 0;
 6537:   z-index: 2;
 6538: }
 6539: 
 6540: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6541:   font-size: 90%;
 6542:   vertical-align: top;
 6543:   float: none;
 6544:   border-left: 1px solid black;
 6545:   border-right: 1px solid black;
 6546: }
 6547: 
 6548: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6549:   background-color:$data_table_light;
 6550: }
 6551: 
 6552: ol.LC_primary_menu li li a:hover {
 6553:    color:$button_hover;
 6554:    background-color:$data_table_dark;
 6555: }
 6556: 
 6557: ol.LC_primary_menu li img {
 6558:   vertical-align: bottom;
 6559:   height: 1.1em;
 6560:   margin: 0.2em 0 0 0;
 6561: }
 6562: 
 6563: ol.LC_primary_menu a {
 6564:   color: RGB(80, 80, 80);
 6565:   text-decoration: none;
 6566: }
 6567: 
 6568: ol.LC_primary_menu a.LC_new_message {
 6569:   font-weight:bold;
 6570:   color: darkred;
 6571: }
 6572: 
 6573: ol.LC_docs_parameters {
 6574:   margin-left: 0;
 6575:   padding: 0;
 6576:   list-style: none;
 6577: }
 6578: 
 6579: ol.LC_docs_parameters li {
 6580:   margin: 0;
 6581:   padding-right: 20px;
 6582:   display: inline;
 6583: }
 6584: 
 6585: ol.LC_docs_parameters li:before {
 6586:   content: "\\002022 \\0020";
 6587: }
 6588: 
 6589: li.LC_docs_parameters_title {
 6590:   font-weight: bold;
 6591: }
 6592: 
 6593: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6594:   content: "";
 6595: }
 6596: 
 6597: ul#LC_secondary_menu {
 6598:   clear: both;
 6599:   color: $fontmenu;
 6600:   background: $tabbg;
 6601:   list-style: none;
 6602:   padding: 0;
 6603:   margin: 0;
 6604:   width: 100%;
 6605:   text-align: left;
 6606:   float: left;
 6607: }
 6608: 
 6609: ul#LC_secondary_menu li {
 6610:   font-weight: bold;
 6611:   line-height: 1.8em;
 6612:   border-right: 1px solid black;
 6613:   vertical-align: middle;
 6614:   float: left;
 6615: }
 6616: 
 6617: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6618:   background-color: $data_table_light;
 6619: }
 6620: 
 6621: ul#LC_secondary_menu li a {
 6622:   padding: 0 0.8em;
 6623: }
 6624: 
 6625: ul#LC_secondary_menu li ul {
 6626:   display: none;
 6627: }
 6628: 
 6629: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6630:   display: block;
 6631:   position: absolute;
 6632:   margin: 0;
 6633:   padding: 0;
 6634:   list-style:none;
 6635:   float: none;
 6636:   background-color: $data_table_light;
 6637:   z-index: 2;
 6638:   margin-left: -1px;
 6639: }
 6640: 
 6641: ul#LC_secondary_menu li ul li {
 6642:   font-size: 90%;
 6643:   vertical-align: top;
 6644:   border-left: 1px solid black;
 6645:   border-right: 1px solid black;
 6646:   background-color: $data_table_light
 6647:   list-style:none;
 6648:   float: none;
 6649: }
 6650: 
 6651: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6652:   background-color: $data_table_dark;
 6653: }
 6654: 
 6655: ul.LC_TabContent {
 6656:   display:block;
 6657:   background: $sidebg;
 6658:   border-bottom: solid 1px $lg_border_color;
 6659:   list-style:none;
 6660:   margin: -1px -10px 0 -10px;
 6661:   padding: 0;
 6662: }
 6663: 
 6664: ul.LC_TabContent li,
 6665: ul.LC_TabContentBigger li {
 6666:   float:left;
 6667: }
 6668: 
 6669: ul#LC_secondary_menu li a {
 6670:   color: $fontmenu;
 6671:   text-decoration: none;
 6672: }
 6673: 
 6674: ul.LC_TabContent {
 6675:   min-height:20px;
 6676: }
 6677: 
 6678: ul.LC_TabContent li {
 6679:   vertical-align:middle;
 6680:   padding: 0 16px 0 10px;
 6681:   background-color:$tabbg;
 6682:   border-bottom:solid 1px $lg_border_color;
 6683:   border-left: solid 1px $font;
 6684: }
 6685: 
 6686: ul.LC_TabContent .right {
 6687:   float:right;
 6688: }
 6689: 
 6690: ul.LC_TabContent li a,
 6691: ul.LC_TabContent li {
 6692:   color:rgb(47,47,47);
 6693:   text-decoration:none;
 6694:   font-size:95%;
 6695:   font-weight:bold;
 6696:   min-height:20px;
 6697: }
 6698: 
 6699: ul.LC_TabContent li a:hover,
 6700: ul.LC_TabContent li a:focus {
 6701:   color: $button_hover;
 6702:   background:none;
 6703:   outline:none;
 6704: }
 6705: 
 6706: ul.LC_TabContent li:hover {
 6707:   color: $button_hover;
 6708:   cursor:pointer;
 6709: }
 6710: 
 6711: ul.LC_TabContent li.active {
 6712:   color: $font;
 6713:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6714:   border-bottom:solid 1px #FFFFFF;
 6715:   cursor: default;
 6716: }
 6717: 
 6718: ul.LC_TabContent li.active a {
 6719:   color:$font;
 6720:   background:#FFFFFF;
 6721:   outline: none;
 6722: }
 6723: 
 6724: ul.LC_TabContent li.goback {
 6725:   float: left;
 6726:   border-left: none;
 6727: }
 6728: 
 6729: #maincoursedoc {
 6730:   clear:both;
 6731: }
 6732: 
 6733: ul.LC_TabContentBigger {
 6734:   display:block;
 6735:   list-style:none;
 6736:   padding: 0;
 6737: }
 6738: 
 6739: ul.LC_TabContentBigger li {
 6740:   vertical-align:bottom;
 6741:   height: 30px;
 6742:   font-size:110%;
 6743:   font-weight:bold;
 6744:   color: #737373;
 6745: }
 6746: 
 6747: ul.LC_TabContentBigger li.active {
 6748:   position: relative;
 6749:   top: 1px;
 6750: }
 6751: 
 6752: ul.LC_TabContentBigger li a {
 6753:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6754:   height: 30px;
 6755:   line-height: 30px;
 6756:   text-align: center;
 6757:   display: block;
 6758:   text-decoration: none;
 6759:   outline: none;  
 6760: }
 6761: 
 6762: ul.LC_TabContentBigger li.active a {
 6763:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6764:   color:$font;
 6765: }
 6766: 
 6767: ul.LC_TabContentBigger li b {
 6768:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6769:   display: block;
 6770:   float: left;
 6771:   padding: 0 30px;
 6772:   border-bottom: 1px solid $lg_border_color;
 6773: }
 6774: 
 6775: ul.LC_TabContentBigger li:hover b {
 6776:   color:$button_hover;
 6777: }
 6778: 
 6779: ul.LC_TabContentBigger li.active b {
 6780:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6781:   color:$font;
 6782:   border: 0;
 6783: }
 6784: 
 6785: 
 6786: ul.LC_CourseBreadcrumbs {
 6787:   background: $sidebg;
 6788:   height: 2em;
 6789:   padding-left: 10px;
 6790:   margin: 0;
 6791:   list-style-position: inside;
 6792: }
 6793: 
 6794: ol#LC_MenuBreadcrumbs,
 6795: ol#LC_PathBreadcrumbs {
 6796:   padding-left: 10px;
 6797:   margin: 0;
 6798:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6799: }
 6800: 
 6801: ol#LC_MenuBreadcrumbs li,
 6802: ol#LC_PathBreadcrumbs li,
 6803: ul.LC_CourseBreadcrumbs li {
 6804:   display: inline;
 6805:   white-space: normal;  
 6806: }
 6807: 
 6808: ol#LC_MenuBreadcrumbs li a,
 6809: ul.LC_CourseBreadcrumbs li a {
 6810:   text-decoration: none;
 6811:   font-size:90%;
 6812: }
 6813: 
 6814: ol#LC_MenuBreadcrumbs h1 {
 6815:   display: inline;
 6816:   font-size: 90%;
 6817:   line-height: 2.5em;
 6818:   margin: 0;
 6819:   padding: 0;
 6820: }
 6821: 
 6822: ol#LC_PathBreadcrumbs li a {
 6823:   text-decoration:none;
 6824:   font-size:100%;
 6825:   font-weight:bold;
 6826: }
 6827: 
 6828: .LC_Box {
 6829:   border: solid 1px $lg_border_color;
 6830:   padding: 0 10px 10px 10px;
 6831: }
 6832: 
 6833: .LC_DocsBox {
 6834:   border: solid 1px $lg_border_color;
 6835:   padding: 0 0 10px 10px;
 6836: }
 6837: 
 6838: .LC_AboutMe_Image {
 6839:   float:left;
 6840:   margin-right:10px;
 6841: }
 6842: 
 6843: .LC_Clear_AboutMe_Image {
 6844:   clear:left;
 6845: }
 6846: 
 6847: dl.LC_ListStyleClean dt {
 6848:   padding-right: 5px;
 6849:   display: table-header-group;
 6850: }
 6851: 
 6852: dl.LC_ListStyleClean dd {
 6853:   display: table-row;
 6854: }
 6855: 
 6856: .LC_ListStyleClean,
 6857: .LC_ListStyleSimple,
 6858: .LC_ListStyleNormal,
 6859: .LC_ListStyleSpecial {
 6860:   /* display:block; */
 6861:   list-style-position: inside;
 6862:   list-style-type: none;
 6863:   overflow: hidden;
 6864:   padding: 0;
 6865: }
 6866: 
 6867: .LC_ListStyleSimple li,
 6868: .LC_ListStyleSimple dd,
 6869: .LC_ListStyleNormal li,
 6870: .LC_ListStyleNormal dd,
 6871: .LC_ListStyleSpecial li,
 6872: .LC_ListStyleSpecial dd {
 6873:   margin: 0;
 6874:   padding: 5px 5px 5px 10px;
 6875:   clear: both;
 6876: }
 6877: 
 6878: .LC_ListStyleClean li,
 6879: .LC_ListStyleClean dd {
 6880:   padding-top: 0;
 6881:   padding-bottom: 0;
 6882: }
 6883: 
 6884: .LC_ListStyleSimple dd,
 6885: .LC_ListStyleSimple li {
 6886:   border-bottom: solid 1px $lg_border_color;
 6887: }
 6888: 
 6889: .LC_ListStyleSpecial li,
 6890: .LC_ListStyleSpecial dd {
 6891:   list-style-type: none;
 6892:   background-color: RGB(220, 220, 220);
 6893:   margin-bottom: 4px;
 6894: }
 6895: 
 6896: table.LC_SimpleTable {
 6897:   margin:5px;
 6898:   border:solid 1px $lg_border_color;
 6899: }
 6900: 
 6901: table.LC_SimpleTable tr {
 6902:   padding: 0;
 6903:   border:solid 1px $lg_border_color;
 6904: }
 6905: 
 6906: table.LC_SimpleTable thead {
 6907:   background:rgb(220,220,220);
 6908: }
 6909: 
 6910: div.LC_columnSection {
 6911:   display: block;
 6912:   clear: both;
 6913:   overflow: hidden;
 6914:   margin: 0;
 6915: }
 6916: 
 6917: div.LC_columnSection>* {
 6918:   float: left;
 6919:   margin: 10px 20px 10px 0;
 6920:   overflow:hidden;
 6921: }
 6922: 
 6923: table em {
 6924:   font-weight: bold;
 6925:   font-style: normal;
 6926: }
 6927: 
 6928: table.LC_tableBrowseRes,
 6929: table.LC_tableOfContent {
 6930:   border:none;
 6931:   border-spacing: 1px;
 6932:   padding: 3px;
 6933:   background-color: #FFFFFF;
 6934:   font-size: 90%;
 6935: }
 6936: 
 6937: table.LC_tableOfContent {
 6938:   border-collapse: collapse;
 6939: }
 6940: 
 6941: table.LC_tableBrowseRes a,
 6942: table.LC_tableOfContent a {
 6943:   background-color: transparent;
 6944:   text-decoration: none;
 6945: }
 6946: 
 6947: table.LC_tableOfContent img {
 6948:   border: none;
 6949:   height: 1.3em;
 6950:   vertical-align: text-bottom;
 6951:   margin-right: 0.3em;
 6952: }
 6953: 
 6954: a#LC_content_toolbar_firsthomework {
 6955:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6956: }
 6957: 
 6958: a#LC_content_toolbar_everything {
 6959:   background-image:url(/res/adm/pages/show-all.gif);
 6960: }
 6961: 
 6962: a#LC_content_toolbar_uncompleted {
 6963:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6964: }
 6965: 
 6966: #LC_content_toolbar_clearbubbles {
 6967:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6968: }
 6969: 
 6970: a#LC_content_toolbar_changefolder {
 6971:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6972: }
 6973: 
 6974: a#LC_content_toolbar_changefolder_toggled {
 6975:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6976: }
 6977: 
 6978: a#LC_content_toolbar_edittoplevel {
 6979:   background-image:url(/res/adm/pages/edittoplevel.gif);
 6980: }
 6981: 
 6982: ul#LC_toolbar li a:hover {
 6983:   background-position: bottom center;
 6984: }
 6985: 
 6986: ul#LC_toolbar {
 6987:   padding: 0;
 6988:   margin: 2px;
 6989:   list-style:none;
 6990:   position:relative;
 6991:   background-color:white;
 6992:   overflow: auto;
 6993: }
 6994: 
 6995: ul#LC_toolbar li {
 6996:   border:1px solid white;
 6997:   padding: 0;
 6998:   margin: 0;
 6999:   float: left;
 7000:   display:inline;
 7001:   vertical-align:middle;
 7002:   white-space: nowrap;
 7003: }
 7004: 
 7005: 
 7006: a.LC_toolbarItem {
 7007:   display:block;
 7008:   padding: 0;
 7009:   margin: 0;
 7010:   height: 32px;
 7011:   width: 32px;
 7012:   color:white;
 7013:   border: none;
 7014:   background-repeat:no-repeat;
 7015:   background-color:transparent;
 7016: }
 7017: 
 7018: ul.LC_funclist {
 7019:     margin: 0;
 7020:     padding: 0.5em 1em 0.5em 0;
 7021: }
 7022: 
 7023: ul.LC_funclist > li:first-child {
 7024:     font-weight:bold; 
 7025:     margin-left:0.8em;
 7026: }
 7027: 
 7028: ul.LC_funclist + ul.LC_funclist {
 7029:     /* 
 7030:        left border as a seperator if we have more than
 7031:        one list 
 7032:     */
 7033:     border-left: 1px solid $sidebg;
 7034:     /* 
 7035:        this hides the left border behind the border of the 
 7036:        outer box if element is wrapped to the next 'line' 
 7037:     */
 7038:     margin-left: -1px;
 7039: }
 7040: 
 7041: ul.LC_funclist li {
 7042:   display: inline;
 7043:   white-space: nowrap;
 7044:   margin: 0 0 0 25px;
 7045:   line-height: 150%;
 7046: }
 7047: 
 7048: .LC_hidden {
 7049:   display: none;
 7050: }
 7051: 
 7052: .LCmodal-overlay {
 7053: 		position:fixed;
 7054: 		top:0;
 7055: 		right:0;
 7056: 		bottom:0;
 7057: 		left:0;
 7058: 		height:100%;
 7059: 		width:100%;
 7060: 		margin:0;
 7061: 		padding:0;
 7062: 		background:#999;
 7063: 		opacity:.75;
 7064: 		filter: alpha(opacity=75);
 7065: 		-moz-opacity: 0.75;
 7066: 		z-index:101;
 7067: }
 7068: 
 7069: * html .LCmodal-overlay {   
 7070: 		position: absolute;
 7071: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7072: }
 7073: 
 7074: .LCmodal-window {
 7075: 		position:fixed;
 7076: 		top:50%;
 7077: 		left:50%;
 7078: 		margin:0;
 7079: 		padding:0;
 7080: 		z-index:102;
 7081: 	}
 7082: 
 7083: * html .LCmodal-window {
 7084: 		position:absolute;
 7085: }
 7086: 
 7087: .LCclose-window {
 7088: 		position:absolute;
 7089: 		width:32px;
 7090: 		height:32px;
 7091: 		right:8px;
 7092: 		top:8px;
 7093: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7094: 		text-indent:-99999px;
 7095: 		overflow:hidden;
 7096: 		cursor:pointer;
 7097: }
 7098: 
 7099: END
 7100: }
 7101: 
 7102: =pod
 7103: 
 7104: =item * &headtag()
 7105: 
 7106: Returns a uniform footer for LON-CAPA web pages.
 7107: 
 7108: Inputs: $title - optional title for the head
 7109:         $head_extra - optional extra HTML to put inside the <head>
 7110:         $args - optional arguments
 7111:             force_register - if is true call registerurl so the remote is 
 7112:                              informed
 7113:             redirect       -> array ref of
 7114:                                    1- seconds before redirect occurs
 7115:                                    2- url to redirect to
 7116:                                    3- whether the side effect should occur
 7117:                            (side effect of setting 
 7118:                                $env{'internal.head.redirect'} to the url 
 7119:                                redirected too)
 7120:             domain         -> force to color decorate a page for a specific
 7121:                                domain
 7122:             function       -> force usage of a specific rolish color scheme
 7123:             bgcolor        -> override the default page bgcolor
 7124:             no_auto_mt_title
 7125:                            -> prevent &mt()ing the title arg
 7126: 
 7127: =cut
 7128: 
 7129: sub headtag {
 7130:     my ($title,$head_extra,$args) = @_;
 7131:     
 7132:     my $function = $args->{'function'} || &get_users_function();
 7133:     my $domain   = $args->{'domain'}   || &determinedomain();
 7134:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7135:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7136: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7137: 		   #time(),
 7138: 		   $env{'environment.color.timestamp'},
 7139: 		   $function,$domain,$bgcolor);
 7140: 
 7141:     $url = '/adm/css/'.&escape($url).'.css';
 7142: 
 7143:     my $result =
 7144: 	'<head>'.
 7145: 	&font_settings();
 7146: 
 7147:     my $inhibitprint = &print_suppression();
 7148: 
 7149:     if (!$args->{'frameset'}) {
 7150: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7151:     }
 7152:     if ($args->{'force_register'}) {
 7153:         $result .= &Apache::lonmenu::registerurl(1);
 7154:     }
 7155:     if (!$args->{'no_nav_bar'} 
 7156: 	&& !$args->{'only_body'}
 7157: 	&& !$args->{'frameset'}) {
 7158: 	$result .= &help_menu_js();
 7159:         $result.=&modal_window();
 7160:         $result.=&togglebox_script();
 7161:         $result.=&wishlist_window();
 7162:         $result.=&LCprogressbarUpdate_script();
 7163:     } else {
 7164:         if ($args->{'add_modal'}) {
 7165:            $result.=&modal_window();
 7166:         }
 7167:         if ($args->{'add_wishlist'}) {
 7168:            $result.=&wishlist_window();
 7169:         }
 7170:         if ($args->{'add_togglebox'}) {
 7171:            $result.=&togglebox_script();
 7172:         }
 7173:         if ($args->{'add_progressbar'}) {
 7174:            $result.=&LCprogressbarUpdate_script();
 7175:         }
 7176:     }
 7177:     if (ref($args->{'redirect'})) {
 7178: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7179: 	$url = &Apache::lonenc::check_encrypt($url);
 7180: 	if (!$inhibit_continue) {
 7181: 	    $env{'internal.head.redirect'} = $url;
 7182: 	}
 7183: 	$result.=<<ADDMETA
 7184: <meta http-equiv="pragma" content="no-cache" />
 7185: <meta http-equiv="Refresh" content="$time; url=$url" />
 7186: ADDMETA
 7187:     }
 7188:     if (!defined($title)) {
 7189: 	$title = 'The LearningOnline Network with CAPA';
 7190:     }
 7191:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7192:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7193: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7194:         .$inhibitprint
 7195: 	.$head_extra;
 7196:     return $result.'</head>';
 7197: }
 7198: 
 7199: =pod
 7200: 
 7201: =item * &font_settings()
 7202: 
 7203: Returns neccessary <meta> to set the proper encoding
 7204: 
 7205: Inputs: none
 7206: 
 7207: =cut
 7208: 
 7209: sub font_settings {
 7210:     my $headerstring='';
 7211:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 7212: 	$headerstring.=
 7213: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 7214:     }
 7215:     return $headerstring;
 7216: }
 7217: 
 7218: =pod
 7219: 
 7220: =item * &print_suppression()
 7221: 
 7222: In course context returns css which causes the body to be blank when media="print",
 7223: if printout generation is unavailable for the current resource.
 7224: 
 7225: This could be because:
 7226: 
 7227: (a) printstartdate is in the future
 7228: 
 7229: (b) printenddate is in the past
 7230: 
 7231: (c) there is an active exam block with "printout"
 7232: functionality blocked
 7233: 
 7234: Users with pav, pfo or evb privileges are exempt.
 7235: 
 7236: Inputs: none
 7237: 
 7238: =cut
 7239: 
 7240: 
 7241: sub print_suppression {
 7242:     my $noprint;
 7243:     if ($env{'request.course.id'}) {
 7244:         my $scope = $env{'request.course.id'};
 7245:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7246:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7247:             return;
 7248:         }
 7249:         if ($env{'request.course.sec'} ne '') {
 7250:             $scope .= "/$env{'request.course.sec'}";
 7251:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7252:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7253:                 return;
 7254:             }
 7255:         }
 7256:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7257:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7258:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7259:         if ($blocked) {
 7260:             my $checkrole = "cm./$cdom/$cnum";
 7261:             if ($env{'request.course.sec'} ne '') {
 7262:                 $checkrole .= "/$env{'request.course.sec'}";
 7263:             }
 7264:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7265:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7266:                 $noprint = 1;
 7267:             }
 7268:         }
 7269:         unless ($noprint) {
 7270:             my $symb = &Apache::lonnet::symbread();
 7271:             if ($symb ne '') {
 7272:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7273:                 if (ref($navmap)) {
 7274:                     my $res = $navmap->getBySymb($symb);
 7275:                     if (ref($res)) {
 7276:                         if (!$res->resprintable()) {
 7277:                             $noprint = 1;
 7278:                         }
 7279:                     }
 7280:                 }
 7281:             }
 7282:         }
 7283:         if ($noprint) {
 7284:             return <<"ENDSTYLE";
 7285: <style type="text/css" media="print">
 7286:     body { display:none }
 7287: </style>
 7288: ENDSTYLE
 7289:         }
 7290:     }
 7291:     return;
 7292: }
 7293: 
 7294: =pod
 7295: 
 7296: =item * &xml_begin()
 7297: 
 7298: Returns the needed doctype and <html>
 7299: 
 7300: Inputs: none
 7301: 
 7302: =cut
 7303: 
 7304: sub xml_begin {
 7305:     my $output='';
 7306: 
 7307:     if ($env{'browser.mathml'}) {
 7308: 	$output='<?xml version="1.0"?>'
 7309:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7310: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7311:             
 7312: #	    .'<!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">] >'
 7313: 	    .'<!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">'
 7314:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7315: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7316:     } else {
 7317: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7318:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7319:     }
 7320:     return $output;
 7321: }
 7322: 
 7323: =pod
 7324: 
 7325: =item * &start_page()
 7326: 
 7327: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7328: 
 7329: Inputs:
 7330: 
 7331: =over 4
 7332: 
 7333: $title - optional title for the page
 7334: 
 7335: $head_extra - optional extra HTML to incude inside the <head>
 7336: 
 7337: $args - additional optional args supported are:
 7338: 
 7339: =over 8
 7340: 
 7341:              only_body      -> is true will set &bodytag() onlybodytag
 7342:                                     arg on
 7343:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7344:              add_entries    -> additional attributes to add to the  <body>
 7345:              domain         -> force to color decorate a page for a 
 7346:                                     specific domain
 7347:              function       -> force usage of a specific rolish color
 7348:                                     scheme
 7349:              redirect       -> see &headtag()
 7350:              bgcolor        -> override the default page bg color
 7351:              js_ready       -> return a string ready for being used in 
 7352:                                     a javascript writeln
 7353:              html_encode    -> return a string ready for being used in 
 7354:                                     a html attribute
 7355:              force_register -> if is true will turn on the &bodytag()
 7356:                                     $forcereg arg
 7357:              frameset       -> if true will start with a <frameset>
 7358:                                     rather than <body>
 7359:              skip_phases    -> hash ref of 
 7360:                                     head -> skip the <html><head> generation
 7361:                                     body -> skip all <body> generation
 7362:              no_inline_link -> if true and in remote mode, don't show the
 7363:                                     'Switch To Inline Menu' link
 7364:              no_auto_mt_title -> prevent &mt()ing the title arg
 7365:              inherit_jsmath -> when creating popup window in a page,
 7366:                                     should it have jsmath forced on by the
 7367:                                     current page
 7368:              bread_crumbs ->             Array containing breadcrumbs
 7369:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7370: 
 7371: =back
 7372: 
 7373: =back
 7374: 
 7375: =cut
 7376: 
 7377: sub start_page {
 7378:     my ($title,$head_extra,$args) = @_;
 7379:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7380: 
 7381:     $env{'internal.start_page'}++;
 7382:     my $result;
 7383: 
 7384:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7385:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7386:     }
 7387:     
 7388:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7389: 	if ($args->{'frameset'}) {
 7390: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7391: 						$args->{'add_entries'});
 7392: 	    $result .= "\n<frameset $attr_string>\n";
 7393:         } else {
 7394:             $result .=
 7395:                 &bodytag($title, 
 7396:                          $args->{'function'},       $args->{'add_entries'},
 7397:                          $args->{'only_body'},      $args->{'domain'},
 7398:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7399:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7400:                          $args);
 7401:         }
 7402:     }
 7403: 
 7404:     if ($args->{'js_ready'}) {
 7405: 		$result = &js_ready($result);
 7406:     }
 7407:     if ($args->{'html_encode'}) {
 7408: 		$result = &html_encode($result);
 7409:     }
 7410: 
 7411:     # Preparation for new and consistent functionlist at top of screen
 7412:     # if ($args->{'functionlist'}) {
 7413:     #            $result .= &build_functionlist();
 7414:     #}
 7415: 
 7416:     # Don't add anything more if only_body wanted or in const space
 7417:     return $result if    $args->{'only_body'} 
 7418:                       || $env{'request.state'} eq 'construct';
 7419: 
 7420:     #Breadcrumbs
 7421:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7422: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7423: 		#if any br links exists, add them to the breadcrumbs
 7424: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7425: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7426: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7427: 			}
 7428: 		}
 7429: 
 7430: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7431: 		if(exists($args->{'bread_crumbs_component'})){
 7432: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7433: 		}else{
 7434: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7435: 		}
 7436:     }
 7437:     return $result;
 7438: }
 7439: 
 7440: sub end_page {
 7441:     my ($args) = @_;
 7442:     $env{'internal.end_page'}++;
 7443:     my $result;
 7444:     if ($args->{'discussion'}) {
 7445: 	my ($target,$parser);
 7446: 	if (ref($args->{'discussion'})) {
 7447: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7448: 				$args->{'discussion'}{'parser'});
 7449: 	}
 7450: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7451:     }
 7452:     if ($args->{'frameset'}) {
 7453: 	$result .= '</frameset>';
 7454:     } else {
 7455: 	$result .= &endbodytag($args);
 7456:     }
 7457:     unless ($args->{'notbody'}) {
 7458:         $result .= "\n</html>";
 7459:     }
 7460: 
 7461:     if ($args->{'js_ready'}) {
 7462: 	$result = &js_ready($result);
 7463:     }
 7464: 
 7465:     if ($args->{'html_encode'}) {
 7466: 	$result = &html_encode($result);
 7467:     }
 7468: 
 7469:     return $result;
 7470: }
 7471: 
 7472: sub wishlist_window {
 7473:     return(<<'ENDWISHLIST');
 7474: <script type="text/javascript">
 7475: // <![CDATA[
 7476: // <!-- BEGIN LON-CAPA Internal
 7477: function set_wishlistlink(title, path) {
 7478:     if (!title) {
 7479:         title = document.title;
 7480:         title = title.replace(/^LON-CAPA /,'');
 7481:     }
 7482:     if (!path) {
 7483:         path = location.pathname;
 7484:     }
 7485:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7486:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7487: }
 7488: // END LON-CAPA Internal -->
 7489: // ]]>
 7490: </script>
 7491: ENDWISHLIST
 7492: }
 7493: 
 7494: sub modal_window {
 7495:     return(<<'ENDMODAL');
 7496: <script type="text/javascript">
 7497: // <![CDATA[
 7498: // <!-- BEGIN LON-CAPA Internal
 7499: var modalWindow = {
 7500: 	parent:"body",
 7501: 	windowId:null,
 7502: 	content:null,
 7503: 	width:null,
 7504: 	height:null,
 7505: 	close:function()
 7506: 	{
 7507: 	        $(".LCmodal-window").remove();
 7508: 	        $(".LCmodal-overlay").remove();
 7509: 	},
 7510: 	open:function()
 7511: 	{
 7512: 		var modal = "";
 7513: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7514: 		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;\">";
 7515: 		modal += this.content;
 7516: 		modal += "</div>";	
 7517: 
 7518: 		$(this.parent).append(modal);
 7519: 
 7520: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7521: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7522: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7523: 	}
 7524: };
 7525: 	var openMyModal = function(source,width,height,scrolling)
 7526: 	{
 7527: 		modalWindow.windowId = "myModal";
 7528: 		modalWindow.width = width;
 7529: 		modalWindow.height = height;
 7530: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
 7531: 		modalWindow.open();
 7532: 	};	
 7533: // END LON-CAPA Internal -->
 7534: // ]]>
 7535: </script>
 7536: ENDMODAL
 7537: }
 7538: 
 7539: sub modal_link {
 7540:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
 7541:     unless ($width) { $width=480; }
 7542:     unless ($height) { $height=400; }
 7543:     unless ($scrolling) { $scrolling='yes'; }
 7544:     my $target_attr;
 7545:     if (defined($target)) {
 7546:         $target_attr = 'target="'.$target.'"';
 7547:     }
 7548:     return <<"ENDLINK";
 7549: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
 7550:            $linktext</a>
 7551: ENDLINK
 7552: }
 7553: 
 7554: sub modal_adhoc_script {
 7555:     my ($funcname,$width,$height,$content)=@_;
 7556:     return (<<ENDADHOC);
 7557: <script type="text/javascript">
 7558: // <![CDATA[
 7559:         var $funcname = function()
 7560:         {
 7561:                 modalWindow.windowId = "myModal";
 7562:                 modalWindow.width = $width;
 7563:                 modalWindow.height = $height;
 7564:                 modalWindow.content = '$content';
 7565:                 modalWindow.open();
 7566:         };  
 7567: // ]]>
 7568: </script>
 7569: ENDADHOC
 7570: }
 7571: 
 7572: sub modal_adhoc_inner {
 7573:     my ($funcname,$width,$height,$content)=@_;
 7574:     my $innerwidth=$width-20;
 7575:     $content=&js_ready(
 7576:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7577:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
 7578:                     $content.
 7579:                  &end_scrollbox().
 7580:                &end_page()
 7581:              );
 7582:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7583: }
 7584: 
 7585: sub modal_adhoc_window {
 7586:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7587:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7588:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7589: }
 7590: 
 7591: sub modal_adhoc_launch {
 7592:     my ($funcname,$width,$height,$content)=@_;
 7593:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7594: <script type="text/javascript">
 7595: // <![CDATA[
 7596: $funcname();
 7597: // ]]>
 7598: </script>
 7599: ENDLAUNCH
 7600: }
 7601: 
 7602: sub modal_adhoc_close {
 7603:     return (<<ENDCLOSE);
 7604: <script type="text/javascript">
 7605: // <![CDATA[
 7606: modalWindow.close();
 7607: // ]]>
 7608: </script>
 7609: ENDCLOSE
 7610: }
 7611: 
 7612: sub togglebox_script {
 7613:    return(<<ENDTOGGLE);
 7614: <script type="text/javascript"> 
 7615: // <![CDATA[
 7616: function LCtoggleDisplay(id,hidetext,showtext) {
 7617:    link = document.getElementById(id + "link").childNodes[0];
 7618:    with (document.getElementById(id).style) {
 7619:       if (display == "none" ) {
 7620:           display = "inline";
 7621:           link.nodeValue = hidetext;
 7622:         } else {
 7623:           display = "none";
 7624:           link.nodeValue = showtext;
 7625:        }
 7626:    }
 7627: }
 7628: // ]]>
 7629: </script>
 7630: ENDTOGGLE
 7631: }
 7632: 
 7633: sub start_togglebox {
 7634:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7635:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7636:     unless ($showtext) { $showtext=&mt('show'); }
 7637:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7638:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7639:     return &start_data_table().
 7640:            &start_data_table_header_row().
 7641:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7642:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7643:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7644:            &end_data_table_header_row().
 7645:            '<tr id="'.$id.'" style="display:none""><td>';
 7646: }
 7647: 
 7648: sub end_togglebox {
 7649:     return '</td></tr>'.&end_data_table();
 7650: }
 7651: 
 7652: sub LCprogressbar_script {
 7653:    my ($id)=@_;
 7654:    return(<<ENDPROGRESS);
 7655: <script type="text/javascript">
 7656: // <![CDATA[
 7657: \$('#progressbar$id').progressbar({
 7658:   value: 0,
 7659:   change: function(event, ui) {
 7660:     var newVal = \$(this).progressbar('option', 'value');
 7661:     \$('.pblabel', this).text(LCprogressTxt);
 7662:   }
 7663: });
 7664: // ]]>
 7665: </script>
 7666: ENDPROGRESS
 7667: }
 7668: 
 7669: sub LCprogressbarUpdate_script {
 7670:    return(<<ENDPROGRESSUPDATE);
 7671: <style type="text/css">
 7672: .ui-progressbar { position:relative; }
 7673: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7674: </style>
 7675: <script type="text/javascript">
 7676: // <![CDATA[
 7677: var LCprogressTxt='---';
 7678: 
 7679: function LCupdateProgress(percent,progresstext,id) {
 7680:    LCprogressTxt=progresstext;
 7681:    \$('#progressbar'+id).progressbar('value',percent);
 7682: }
 7683: // ]]>
 7684: </script>
 7685: ENDPROGRESSUPDATE
 7686: }
 7687: 
 7688: my $LClastpercent;
 7689: my $LCidcnt;
 7690: my $LCcurrentid;
 7691: 
 7692: sub LCprogressbar {
 7693:     my ($r)=(@_);
 7694:     $LClastpercent=0;
 7695:     $LCidcnt++;
 7696:     $LCcurrentid=$$.'_'.$LCidcnt;
 7697:     my $starting=&mt('Starting');
 7698:     my $content=(<<ENDPROGBAR);
 7699: <p>
 7700:   <div id="progressbar$LCcurrentid">
 7701:     <span class="pblabel">$starting</span>
 7702:   </div>
 7703: </p>
 7704: ENDPROGBAR
 7705:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7706: }
 7707: 
 7708: sub LCprogressbarUpdate {
 7709:     my ($r,$val,$text)=@_;
 7710:     unless ($val) { 
 7711:        if ($LClastpercent) {
 7712:            $val=$LClastpercent;
 7713:        } else {
 7714:            $val=0;
 7715:        }
 7716:     }
 7717:     if ($val<0) { $val=0; }
 7718:     if ($val>100) { $val=0; }
 7719:     $LClastpercent=$val;
 7720:     unless ($text) { $text=$val.'%'; }
 7721:     $text=&js_ready($text);
 7722:     &r_print($r,<<ENDUPDATE);
 7723: <script type="text/javascript">
 7724: // <![CDATA[
 7725: LCupdateProgress($val,'$text','$LCcurrentid');
 7726: // ]]>
 7727: </script>
 7728: ENDUPDATE
 7729: }
 7730: 
 7731: sub LCprogressbarClose {
 7732:     my ($r)=@_;
 7733:     $LClastpercent=0;
 7734:     &r_print($r,<<ENDCLOSE);
 7735: <script type="text/javascript">
 7736: // <![CDATA[
 7737: \$("#progressbar$LCcurrentid").hide('slow'); 
 7738: // ]]>
 7739: </script>
 7740: ENDCLOSE
 7741: }
 7742: 
 7743: sub r_print {
 7744:     my ($r,$to_print)=@_;
 7745:     if ($r) {
 7746:       $r->print($to_print);
 7747:       $r->rflush();
 7748:     } else {
 7749:       print($to_print);
 7750:     }
 7751: }
 7752: 
 7753: sub html_encode {
 7754:     my ($result) = @_;
 7755: 
 7756:     $result = &HTML::Entities::encode($result,'<>&"');
 7757:     
 7758:     return $result;
 7759: }
 7760: 
 7761: sub js_ready {
 7762:     my ($result) = @_;
 7763: 
 7764:     $result =~ s/[\n\r]/ /xmsg;
 7765:     $result =~ s/\\/\\\\/xmsg;
 7766:     $result =~ s/'/\\'/xmsg;
 7767:     $result =~ s{</}{<\\/}xmsg;
 7768:     
 7769:     return $result;
 7770: }
 7771: 
 7772: sub validate_page {
 7773:     if (  exists($env{'internal.start_page'})
 7774: 	  &&     $env{'internal.start_page'} > 1) {
 7775: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7776: 				 $env{'internal.start_page'}.' '.
 7777: 				 $ENV{'request.filename'});
 7778:     }
 7779:     if (  exists($env{'internal.end_page'})
 7780: 	  &&     $env{'internal.end_page'} > 1) {
 7781: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7782: 				 $env{'internal.end_page'}.' '.
 7783: 				 $env{'request.filename'});
 7784:     }
 7785:     if (     exists($env{'internal.start_page'})
 7786: 	&& ! exists($env{'internal.end_page'})) {
 7787: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7788: 				 $env{'request.filename'});
 7789:     }
 7790:     if (   ! exists($env{'internal.start_page'})
 7791: 	&&   exists($env{'internal.end_page'})) {
 7792: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7793: 				 $env{'request.filename'});
 7794:     }
 7795: }
 7796: 
 7797: 
 7798: sub start_scrollbox {
 7799:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
 7800:     unless ($outerwidth) { $outerwidth='520px'; }
 7801:     unless ($width) { $width='500px'; }
 7802:     unless ($height) { $height='200px'; }
 7803:     my ($table_id,$div_id,$tdcol);
 7804:     if ($id ne '') {
 7805:         $table_id = " id='table_$id'";
 7806:         $div_id = " id='div_$id'";
 7807:     }
 7808:     if ($bgcolor ne '') {
 7809:         $tdcol = "background-color: $bgcolor;";
 7810:     }
 7811:     return <<"END";
 7812: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
 7813: END
 7814: }
 7815: 
 7816: sub end_scrollbox {
 7817:     return '</div></td></tr></table>';
 7818: }
 7819: 
 7820: sub simple_error_page {
 7821:     my ($r,$title,$msg) = @_;
 7822:     my $page =
 7823: 	&Apache::loncommon::start_page($title).
 7824: 	&mt($msg).
 7825: 	&Apache::loncommon::end_page();
 7826:     if (ref($r)) {
 7827: 	$r->print($page);
 7828: 	return;
 7829:     }
 7830:     return $page;
 7831: }
 7832: 
 7833: {
 7834:     my @row_count;
 7835: 
 7836:     sub start_data_table_count {
 7837:         unshift(@row_count, 0);
 7838:         return;
 7839:     }
 7840: 
 7841:     sub end_data_table_count {
 7842:         shift(@row_count);
 7843:         return;
 7844:     }
 7845: 
 7846:     sub start_data_table {
 7847: 	my ($add_class,$id) = @_;
 7848: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7849:         my $table_id;
 7850:         if (defined($id)) {
 7851:             $table_id = ' id="'.$id.'"';
 7852:         }
 7853: 	&start_data_table_count();
 7854: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 7855:     }
 7856: 
 7857:     sub end_data_table {
 7858: 	&end_data_table_count();
 7859: 	return '</table>'."\n";;
 7860:     }
 7861: 
 7862:     sub start_data_table_row {
 7863: 	my ($add_class, $id) = @_;
 7864: 	$row_count[0]++;
 7865: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7866: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7867:         $id = (' id="'.$id.'"') unless ($id eq '');
 7868:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7869:     }
 7870:     
 7871:     sub continue_data_table_row {
 7872: 	my ($add_class, $id) = @_;
 7873: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7874: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7875:         $id = (' id="'.$id.'"') unless ($id eq '');
 7876:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7877:     }
 7878: 
 7879:     sub end_data_table_row {
 7880: 	return '</tr>'."\n";;
 7881:     }
 7882: 
 7883:     sub start_data_table_empty_row {
 7884: #	$row_count[0]++;
 7885: 	return  '<tr class="LC_empty_row" >'."\n";;
 7886:     }
 7887: 
 7888:     sub end_data_table_empty_row {
 7889: 	return '</tr>'."\n";;
 7890:     }
 7891: 
 7892:     sub start_data_table_header_row {
 7893: 	return  '<tr class="LC_header_row">'."\n";;
 7894:     }
 7895: 
 7896:     sub end_data_table_header_row {
 7897: 	return '</tr>'."\n";;
 7898:     }
 7899: 
 7900:     sub data_table_caption {
 7901:         my $caption = shift;
 7902:         return "<caption class=\"LC_caption\">$caption</caption>";
 7903:     }
 7904: }
 7905: 
 7906: =pod
 7907: 
 7908: =item * &inhibit_menu_check($arg)
 7909: 
 7910: Checks for a inhibitmenu state and generates output to preserve it
 7911: 
 7912: Inputs:         $arg - can be any of
 7913:                      - undef - in which case the return value is a string 
 7914:                                to add  into arguments list of a uri
 7915:                      - 'input' - in which case the return value is a HTML
 7916:                                  <form> <input> field of type hidden to
 7917:                                  preserve the value
 7918:                      - a url - in which case the return value is the url with
 7919:                                the neccesary cgi args added to preserve the
 7920:                                inhibitmenu state
 7921:                      - a ref to a url - no return value, but the string is
 7922:                                         updated to include the neccessary cgi
 7923:                                         args to preserve the inhibitmenu state
 7924: 
 7925: =cut
 7926: 
 7927: sub inhibit_menu_check {
 7928:     my ($arg) = @_;
 7929:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7930:     if ($arg eq 'input') {
 7931: 	if ($env{'form.inhibitmenu'}) {
 7932: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7933: 	} else {
 7934: 	    return
 7935: 	}
 7936:     }
 7937:     if ($env{'form.inhibitmenu'}) {
 7938: 	if (ref($arg)) {
 7939: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7940: 	} elsif ($arg eq '') {
 7941: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7942: 	} else {
 7943: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7944: 	}
 7945:     }
 7946:     if (!ref($arg)) {
 7947: 	return $arg;
 7948:     }
 7949: }
 7950: 
 7951: ###############################################
 7952: 
 7953: =pod
 7954: 
 7955: =back
 7956: 
 7957: =head1 User Information Routines
 7958: 
 7959: =over 4
 7960: 
 7961: =item * &get_users_function()
 7962: 
 7963: Used by &bodytag to determine the current users primary role.
 7964: Returns either 'student','coordinator','admin', or 'author'.
 7965: 
 7966: =cut
 7967: 
 7968: ###############################################
 7969: sub get_users_function {
 7970:     my $function = 'norole';
 7971:     if ($env{'request.role'}=~/^(st)/) {
 7972:         $function='student';
 7973:     }
 7974:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7975:         $function='coordinator';
 7976:     }
 7977:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7978:         $function='admin';
 7979:     }
 7980:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7981:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 7982:         $function='author';
 7983:     }
 7984:     return $function;
 7985: }
 7986: 
 7987: ###############################################
 7988: 
 7989: =pod
 7990: 
 7991: =item * &show_course()
 7992: 
 7993: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7994: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7995: 
 7996: Inputs:
 7997: None
 7998: 
 7999: Outputs:
 8000: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8001: 
 8002: =cut
 8003: 
 8004: ###############################################
 8005: sub show_course {
 8006:     my $course = !$env{'user.adv'};
 8007:     if (!$env{'user.adv'}) {
 8008:         foreach my $env (keys(%env)) {
 8009:             next if ($env !~ m/^user\.priv\./);
 8010:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8011:                 $course = 0;
 8012:                 last;
 8013:             }
 8014:         }
 8015:     }
 8016:     return $course;
 8017: }
 8018: 
 8019: ###############################################
 8020: 
 8021: =pod
 8022: 
 8023: =item * &check_user_status()
 8024: 
 8025: Determines current status of supplied role for a
 8026: specific user. Roles can be active, previous or future.
 8027: 
 8028: Inputs: 
 8029: user's domain, user's username, course's domain,
 8030: course's number, optional section ID.
 8031: 
 8032: Outputs:
 8033: role status: active, previous or future. 
 8034: 
 8035: =cut
 8036: 
 8037: sub check_user_status {
 8038:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8039:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8040:     my @uroles = keys %userinfo;
 8041:     my $srchstr;
 8042:     my $active_chk = 'none';
 8043:     my $now = time;
 8044:     if (@uroles > 0) {
 8045:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8046:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8047:         } else {
 8048:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8049:         }
 8050:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8051:             my $role_end = 0;
 8052:             my $role_start = 0;
 8053:             $active_chk = 'active';
 8054:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8055:                 $role_end = $1;
 8056:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8057:                     $role_start = $1;
 8058:                 }
 8059:             }
 8060:             if ($role_start > 0) {
 8061:                 if ($now < $role_start) {
 8062:                     $active_chk = 'future';
 8063:                 }
 8064:             }
 8065:             if ($role_end > 0) {
 8066:                 if ($now > $role_end) {
 8067:                     $active_chk = 'previous';
 8068:                 }
 8069:             }
 8070:         }
 8071:     }
 8072:     return $active_chk;
 8073: }
 8074: 
 8075: ###############################################
 8076: 
 8077: =pod
 8078: 
 8079: =item * &get_sections()
 8080: 
 8081: Determines all the sections for a course including
 8082: sections with students and sections containing other roles.
 8083: Incoming parameters: 
 8084: 
 8085: 1. domain
 8086: 2. course number 
 8087: 3. reference to array containing roles for which sections should 
 8088: be gathered (optional).
 8089: 4. reference to array containing status types for which sections 
 8090: should be gathered (optional).
 8091: 
 8092: If the third argument is undefined, sections are gathered for any role. 
 8093: If the fourth argument is undefined, sections are gathered for any status.
 8094: Permissible values are 'active' or 'future' or 'previous'.
 8095:  
 8096: Returns section hash (keys are section IDs, values are
 8097: number of users in each section), subject to the
 8098: optional roles filter, optional status filter 
 8099: 
 8100: =cut
 8101: 
 8102: ###############################################
 8103: sub get_sections {
 8104:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8105:     if (!defined($cdom) || !defined($cnum)) {
 8106:         my $cid =  $env{'request.course.id'};
 8107: 
 8108: 	return if (!defined($cid));
 8109: 
 8110:         $cdom = $env{'course.'.$cid.'.domain'};
 8111:         $cnum = $env{'course.'.$cid.'.num'};
 8112:     }
 8113: 
 8114:     my %sectioncount;
 8115:     my $now = time;
 8116: 
 8117:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 8118: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8119: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8120: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8121:         my $start_index = &Apache::loncoursedata::CL_START();
 8122:         my $end_index = &Apache::loncoursedata::CL_END();
 8123:         my $status;
 8124: 	while (my ($student,$data) = each(%$classlist)) {
 8125: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8126: 				                     $data->[$status_index],
 8127:                                                      $data->[$start_index],
 8128:                                                      $data->[$end_index]);
 8129:             if ($stu_status eq 'Active') {
 8130:                 $status = 'active';
 8131:             } elsif ($end < $now) {
 8132:                 $status = 'previous';
 8133:             } elsif ($start > $now) {
 8134:                 $status = 'future';
 8135:             } 
 8136: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8137:                 if ((!defined($possible_status)) || (($status ne '') && 
 8138:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8139: 		    $sectioncount{$section}++;
 8140:                 }
 8141: 	    }
 8142: 	}
 8143:     }
 8144:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8145:     foreach my $user (sort(keys(%courseroles))) {
 8146: 	if ($user !~ /^(\w{2})/) { next; }
 8147: 	my ($role) = ($user =~ /^(\w{2})/);
 8148: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8149: 	my ($section,$status);
 8150: 	if ($role eq 'cr' &&
 8151: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8152: 	    $section=$1;
 8153: 	}
 8154: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8155: 	if (!defined($section) || $section eq '-1') { next; }
 8156:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8157:         if ($end == -1 && $start == -1) {
 8158:             next; #deleted role
 8159:         }
 8160:         if (!defined($possible_status)) { 
 8161:             $sectioncount{$section}++;
 8162:         } else {
 8163:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8164:                 $status = 'active';
 8165:             } elsif ($end < $now) {
 8166:                 $status = 'future';
 8167:             } elsif ($start > $now) {
 8168:                 $status = 'previous';
 8169:             }
 8170:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8171:                 $sectioncount{$section}++;
 8172:             }
 8173:         }
 8174:     }
 8175:     return %sectioncount;
 8176: }
 8177: 
 8178: ###############################################
 8179: 
 8180: =pod
 8181: 
 8182: =item * &get_course_users()
 8183: 
 8184: Retrieves usernames:domains for users in the specified course
 8185: with specific role(s), and access status. 
 8186: 
 8187: Incoming parameters:
 8188: 1. course domain
 8189: 2. course number
 8190: 3. access status: users must have - either active, 
 8191: previous, future, or all.
 8192: 4. reference to array of permissible roles
 8193: 5. reference to array of section restrictions (optional)
 8194: 6. reference to results object (hash of hashes).
 8195: 7. reference to optional userdata hash
 8196: 8. reference to optional statushash
 8197: 9. flag if privileged users (except those set to unhide in
 8198:    course settings) should be excluded    
 8199: Keys of top level results hash are roles.
 8200: Keys of inner hashes are username:domain, with 
 8201: values set to access type.
 8202: Optional userdata hash returns an array with arguments in the 
 8203: same order as loncoursedata::get_classlist() for student data.
 8204: 
 8205: Optional statushash returns
 8206: 
 8207: Entries for end, start, section and status are blank because
 8208: of the possibility of multiple values for non-student roles.
 8209: 
 8210: =cut
 8211: 
 8212: ###############################################
 8213: 
 8214: sub get_course_users {
 8215:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8216:     my %idx = ();
 8217:     my %seclists;
 8218: 
 8219:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8220:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8221:     $idx{end} = &Apache::loncoursedata::CL_END();
 8222:     $idx{start} = &Apache::loncoursedata::CL_START();
 8223:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8224:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8225:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8226:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8227: 
 8228:     if (grep(/^st$/,@{$roles})) {
 8229:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8230:         my $now = time;
 8231:         foreach my $student (keys(%{$classlist})) {
 8232:             my $match = 0;
 8233:             my $secmatch = 0;
 8234:             my $section = $$classlist{$student}[$idx{section}];
 8235:             my $status = $$classlist{$student}[$idx{status}];
 8236:             if ($section eq '') {
 8237:                 $section = 'none';
 8238:             }
 8239:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8240:                 if (grep(/^all$/,@{$sections})) {
 8241:                     $secmatch = 1;
 8242:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8243:                     if (grep(/^none$/,@{$sections})) {
 8244:                         $secmatch = 1;
 8245:                     }
 8246:                 } else {  
 8247: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8248: 		        $secmatch = 1;
 8249:                     }
 8250: 		}
 8251:                 if (!$secmatch) {
 8252:                     next;
 8253:                 }
 8254:             }
 8255:             if (defined($$types{'active'})) {
 8256:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8257:                     push(@{$$users{st}{$student}},'active');
 8258:                     $match = 1;
 8259:                 }
 8260:             }
 8261:             if (defined($$types{'previous'})) {
 8262:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8263:                     push(@{$$users{st}{$student}},'previous');
 8264:                     $match = 1;
 8265:                 }
 8266:             }
 8267:             if (defined($$types{'future'})) {
 8268:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8269:                     push(@{$$users{st}{$student}},'future');
 8270:                     $match = 1;
 8271:                 }
 8272:             }
 8273:             if ($match) {
 8274:                 push(@{$seclists{$student}},$section);
 8275:                 if (ref($userdata) eq 'HASH') {
 8276:                     $$userdata{$student} = $$classlist{$student};
 8277:                 }
 8278:                 if (ref($statushash) eq 'HASH') {
 8279:                     $statushash->{$student}{'st'}{$section} = $status;
 8280:                 }
 8281:             }
 8282:         }
 8283:     }
 8284:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8285:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8286:         my $now = time;
 8287:         my %displaystatus = ( previous => 'Expired',
 8288:                               active   => 'Active',
 8289:                               future   => 'Future',
 8290:                             );
 8291:         my %nothide;
 8292:         if ($hidepriv) {
 8293:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8294:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8295:                 if ($user !~ /:/) {
 8296:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8297:                 } else {
 8298:                     $nothide{$user} = 1;
 8299:                 }
 8300:             }
 8301:         }
 8302:         foreach my $person (sort(keys(%coursepersonnel))) {
 8303:             my $match = 0;
 8304:             my $secmatch = 0;
 8305:             my $status;
 8306:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8307:             $user =~ s/:$//;
 8308:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8309:             if ($end == -1 || $start == -1) {
 8310:                 next;
 8311:             }
 8312:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8313:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8314:                 my ($uname,$udom) = split(/:/,$user);
 8315:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8316:                     if (grep(/^all$/,@{$sections})) {
 8317:                         $secmatch = 1;
 8318:                     } elsif ($usec eq '') {
 8319:                         if (grep(/^none$/,@{$sections})) {
 8320:                             $secmatch = 1;
 8321:                         }
 8322:                     } else {
 8323:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8324:                             $secmatch = 1;
 8325:                         }
 8326:                     }
 8327:                     if (!$secmatch) {
 8328:                         next;
 8329:                     }
 8330:                 }
 8331:                 if ($usec eq '') {
 8332:                     $usec = 'none';
 8333:                 }
 8334:                 if ($uname ne '' && $udom ne '') {
 8335:                     if ($hidepriv) {
 8336:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 8337:                             (!$nothide{$uname.':'.$udom})) {
 8338:                             next;
 8339:                         }
 8340:                     }
 8341:                     if ($end > 0 && $end < $now) {
 8342:                         $status = 'previous';
 8343:                     } elsif ($start > $now) {
 8344:                         $status = 'future';
 8345:                     } else {
 8346:                         $status = 'active';
 8347:                     }
 8348:                     foreach my $type (keys(%{$types})) { 
 8349:                         if ($status eq $type) {
 8350:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8351:                                 push(@{$$users{$role}{$user}},$type);
 8352:                             }
 8353:                             $match = 1;
 8354:                         }
 8355:                     }
 8356:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8357:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8358: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8359:                         }
 8360:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8361:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8362:                         }
 8363:                         if (ref($statushash) eq 'HASH') {
 8364:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8365:                         }
 8366:                     }
 8367:                 }
 8368:             }
 8369:         }
 8370:         if (grep(/^ow$/,@{$roles})) {
 8371:             if ((defined($cdom)) && (defined($cnum))) {
 8372:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8373:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8374:                     my $owner = $csettings{'internal.courseowner'};
 8375:                     next if ($owner eq '');
 8376:                     my ($ownername,$ownerdom);
 8377:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8378:                         $ownername = $1;
 8379:                         $ownerdom = $2;
 8380:                     } else {
 8381:                         $ownername = $owner;
 8382:                         $ownerdom = $cdom;
 8383:                         $owner = $ownername.':'.$ownerdom;
 8384:                     }
 8385:                     @{$$users{'ow'}{$owner}} = 'any';
 8386:                     if (defined($userdata) && 
 8387: 			!exists($$userdata{$owner})) {
 8388: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8389:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8390:                             push(@{$seclists{$owner}},'none');
 8391:                         }
 8392:                         if (ref($statushash) eq 'HASH') {
 8393:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8394:                         }
 8395: 		    }
 8396:                 }
 8397:             }
 8398:         }
 8399:         foreach my $user (keys(%seclists)) {
 8400:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8401:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8402:         }
 8403:     }
 8404:     return;
 8405: }
 8406: 
 8407: sub get_user_info {
 8408:     my ($udom,$uname,$idx,$userdata) = @_;
 8409:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8410: 	&plainname($uname,$udom,'lastname');
 8411:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8412:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8413:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8414:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8415:     return;
 8416: }
 8417: 
 8418: ###############################################
 8419: 
 8420: =pod
 8421: 
 8422: =item * &get_user_quota()
 8423: 
 8424: Retrieves quota assigned for storage of portfolio files for a user  
 8425: 
 8426: Incoming parameters:
 8427: 1. user's username
 8428: 2. user's domain
 8429: 
 8430: Returns:
 8431: 1. Disk quota (in Mb) assigned to student.
 8432: 2. (Optional) Type of setting: custom or default
 8433:    (individually assigned or default for user's 
 8434:    institutional status).
 8435: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8436:    or student - types as defined in localenroll::inst_usertypes 
 8437:    for user's domain, which determines default quota for user.
 8438: 4. (Optional) - Default quota which would apply to the user.
 8439: 
 8440: If a value has been stored in the user's environment, 
 8441: it will return that, otherwise it returns the maximal default
 8442: defined for the user's instituional status(es) in the domain.
 8443: 
 8444: =cut
 8445: 
 8446: ###############################################
 8447: 
 8448: 
 8449: sub get_user_quota {
 8450:     my ($uname,$udom) = @_;
 8451:     my ($quota,$quotatype,$settingstatus,$defquota);
 8452:     if (!defined($udom)) {
 8453:         $udom = $env{'user.domain'};
 8454:     }
 8455:     if (!defined($uname)) {
 8456:         $uname = $env{'user.name'};
 8457:     }
 8458:     if (($udom eq '' || $uname eq '') ||
 8459:         ($udom eq 'public') && ($uname eq 'public')) {
 8460:         $quota = 0;
 8461:         $quotatype = 'default';
 8462:         $defquota = 0; 
 8463:     } else {
 8464:         my $inststatus;
 8465:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8466:             $quota = $env{'environment.portfolioquota'};
 8467:             $inststatus = $env{'environment.inststatus'};
 8468:         } else {
 8469:             my %userenv = 
 8470:                 &Apache::lonnet::get('environment',['portfolioquota',
 8471:                                      'inststatus'],$udom,$uname);
 8472:             my ($tmp) = keys(%userenv);
 8473:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8474:                 $quota = $userenv{'portfolioquota'};
 8475:                 $inststatus = $userenv{'inststatus'};
 8476:             } else {
 8477:                 undef(%userenv);
 8478:             }
 8479:         }
 8480:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 8481:         if ($quota eq '') {
 8482:             $quota = $defquota;
 8483:             $quotatype = 'default';
 8484:         } else {
 8485:             $quotatype = 'custom';
 8486:         }
 8487:     }
 8488:     if (wantarray) {
 8489:         return ($quota,$quotatype,$settingstatus,$defquota);
 8490:     } else {
 8491:         return $quota;
 8492:     }
 8493: }
 8494: 
 8495: ###############################################
 8496: 
 8497: =pod
 8498: 
 8499: =item * &default_quota()
 8500: 
 8501: Retrieves default quota assigned for storage of user portfolio files,
 8502: given an (optional) user's institutional status.
 8503: 
 8504: Incoming parameters:
 8505: 1. domain
 8506: 2. (Optional) institutional status(es).  This is a : separated list of 
 8507:    status types (e.g., faculty, staff, student etc.)
 8508:    which apply to the user for whom the default is being retrieved.
 8509:    If the institutional status string in undefined, the domain
 8510:    default quota will be returned. 
 8511: 
 8512: Returns:
 8513: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8514: 2. (Optional) institutional type which determined the value of the
 8515:    default quota.
 8516: 
 8517: If a value has been stored in the domain's configuration db,
 8518: it will return that, otherwise it returns 20 (for backwards 
 8519: compatibility with domains which have not set up a configuration
 8520: db file; the original statically defined portfolio quota was 20 Mb). 
 8521: 
 8522: If the user's status includes multiple types (e.g., staff and student),
 8523: the largest default quota which applies to the user determines the
 8524: default quota returned.
 8525: 
 8526: =back
 8527: 
 8528: =cut
 8529: 
 8530: ###############################################
 8531: 
 8532: 
 8533: sub default_quota {
 8534:     my ($udom,$inststatus) = @_;
 8535:     my ($defquota,$settingstatus);
 8536:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8537:                                             ['quotas'],$udom);
 8538:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8539:         if ($inststatus ne '') {
 8540:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8541:             foreach my $item (@statuses) {
 8542:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8543:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 8544:                         if ($defquota eq '') {
 8545:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8546:                             $settingstatus = $item;
 8547:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 8548:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8549:                             $settingstatus = $item;
 8550:                         }
 8551:                     }
 8552:                 } else {
 8553:                     if ($quotahash{'quotas'}{$item} ne '') {
 8554:                         if ($defquota eq '') {
 8555:                             $defquota = $quotahash{'quotas'}{$item};
 8556:                             $settingstatus = $item;
 8557:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8558:                             $defquota = $quotahash{'quotas'}{$item};
 8559:                             $settingstatus = $item;
 8560:                         }
 8561:                     }
 8562:                 }
 8563:             }
 8564:         }
 8565:         if ($defquota eq '') {
 8566:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8567:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 8568:             } else {
 8569:                 $defquota = $quotahash{'quotas'}{'default'};
 8570:             }
 8571:             $settingstatus = 'default';
 8572:         }
 8573:     } else {
 8574:         $settingstatus = 'default';
 8575:         $defquota = 20;
 8576:     }
 8577:     if (wantarray) {
 8578:         return ($defquota,$settingstatus);
 8579:     } else {
 8580:         return $defquota;
 8581:     }
 8582: }
 8583: 
 8584: sub get_secgrprole_info {
 8585:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8586:     my %sections_count = &get_sections($cdom,$cnum);
 8587:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8588:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8589:     my @groups = sort(keys(%curr_groups));
 8590:     my $allroles = [];
 8591:     my $rolehash;
 8592:     my $accesshash = {
 8593:                      active => 'Currently has access',
 8594:                      future => 'Will have future access',
 8595:                      previous => 'Previously had access',
 8596:                   };
 8597:     if ($needroles) {
 8598:         $rolehash = {'all' => 'all'};
 8599:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8600: 	if (&Apache::lonnet::error(%user_roles)) {
 8601: 	    undef(%user_roles);
 8602: 	}
 8603:         foreach my $item (keys(%user_roles)) {
 8604:             my ($role)=split(/\:/,$item,2);
 8605:             if ($role eq 'cr') { next; }
 8606:             if ($role =~ /^cr/) {
 8607:                 $$rolehash{$role} = (split('/',$role))[3];
 8608:             } else {
 8609:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8610:             }
 8611:         }
 8612:         foreach my $key (sort(keys(%{$rolehash}))) {
 8613:             push(@{$allroles},$key);
 8614:         }
 8615:         push (@{$allroles},'st');
 8616:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8617:     }
 8618:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8619: }
 8620: 
 8621: sub user_picker {
 8622:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8623:     my $currdom = $dom;
 8624:     my %curr_selected = (
 8625:                         srchin => 'dom',
 8626:                         srchby => 'lastname',
 8627:                       );
 8628:     my $srchterm;
 8629:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8630:         if ($srch->{'srchby'} ne '') {
 8631:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8632:         }
 8633:         if ($srch->{'srchin'} ne '') {
 8634:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8635:         }
 8636:         if ($srch->{'srchtype'} ne '') {
 8637:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8638:         }
 8639:         if ($srch->{'srchdomain'} ne '') {
 8640:             $currdom = $srch->{'srchdomain'};
 8641:         }
 8642:         $srchterm = $srch->{'srchterm'};
 8643:     }
 8644:     my %lt=&Apache::lonlocal::texthash(
 8645:                     'usr'       => 'Search criteria',
 8646:                     'doma'      => 'Domain/institution to search',
 8647:                     'uname'     => 'username',
 8648:                     'lastname'  => 'last name',
 8649:                     'lastfirst' => 'last name, first name',
 8650:                     'crs'       => 'in this course',
 8651:                     'dom'       => 'in selected LON-CAPA domain', 
 8652:                     'alc'       => 'all LON-CAPA',
 8653:                     'instd'     => 'in institutional directory for selected domain',
 8654:                     'exact'     => 'is',
 8655:                     'contains'  => 'contains',
 8656:                     'begins'    => 'begins with',
 8657:                     'youm'      => "You must include some text to search for.",
 8658:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 8659:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 8660:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 8661:                     'ymcd'      => "You must choose a domain when using a domain search.",
 8662:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 8663:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 8664:                      'thfo'     => "The following need to be corrected before the search can be run:",
 8665:                                        );
 8666:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 8667:     my $srchinsel = ' <select name="srchin">';
 8668: 
 8669:     my @srchins = ('crs','dom','alc','instd');
 8670: 
 8671:     foreach my $option (@srchins) {
 8672:         # FIXME 'alc' option unavailable until 
 8673:         #       loncreateuser::print_user_query_page()
 8674:         #       has been completed.
 8675:         next if ($option eq 'alc');
 8676:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 8677:         next if ($option eq 'crs' && !$env{'request.course.id'});
 8678:         if ($curr_selected{'srchin'} eq $option) {
 8679:             $srchinsel .= ' 
 8680:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8681:         } else {
 8682:             $srchinsel .= '
 8683:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8684:         }
 8685:     }
 8686:     $srchinsel .= "\n  </select>\n";
 8687: 
 8688:     my $srchbysel =  ' <select name="srchby">';
 8689:     foreach my $option ('lastname','lastfirst','uname') {
 8690:         if ($curr_selected{'srchby'} eq $option) {
 8691:             $srchbysel .= '
 8692:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8693:         } else {
 8694:             $srchbysel .= '
 8695:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8696:          }
 8697:     }
 8698:     $srchbysel .= "\n  </select>\n";
 8699: 
 8700:     my $srchtypesel = ' <select name="srchtype">';
 8701:     foreach my $option ('begins','contains','exact') {
 8702:         if ($curr_selected{'srchtype'} eq $option) {
 8703:             $srchtypesel .= '
 8704:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8705:         } else {
 8706:             $srchtypesel .= '
 8707:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8708:         }
 8709:     }
 8710:     $srchtypesel .= "\n  </select>\n";
 8711: 
 8712:     my ($newuserscript,$new_user_create);
 8713:     my $context_dom = $env{'request.role.domain'};
 8714:     if ($context eq 'requestcrs') {
 8715:         if ($env{'form.coursedom'} ne '') { 
 8716:             $context_dom = $env{'form.coursedom'};
 8717:         }
 8718:     }
 8719:     if ($forcenewuser) {
 8720:         if (ref($srch) eq 'HASH') {
 8721:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 8722:                 if ($cancreate) {
 8723:                     $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>';
 8724:                 } else {
 8725:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 8726:                     my %usertypetext = (
 8727:                         official   => 'institutional',
 8728:                         unofficial => 'non-institutional',
 8729:                     );
 8730:                     $new_user_create = '<p class="LC_warning">'
 8731:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8732:                                       .' '
 8733:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8734:                                           ,'<a href="'.$helplink.'">','</a>')
 8735:                                       .'</p><br />';
 8736:                 }
 8737:             }
 8738:         }
 8739: 
 8740:         $newuserscript = <<"ENDSCRIPT";
 8741: 
 8742: function setSearch(createnew,callingForm) {
 8743:     if (createnew == 1) {
 8744:         for (var i=0; i<callingForm.srchby.length; i++) {
 8745:             if (callingForm.srchby.options[i].value == 'uname') {
 8746:                 callingForm.srchby.selectedIndex = i;
 8747:             }
 8748:         }
 8749:         for (var i=0; i<callingForm.srchin.length; i++) {
 8750:             if ( callingForm.srchin.options[i].value == 'dom') {
 8751: 		callingForm.srchin.selectedIndex = i;
 8752:             }
 8753:         }
 8754:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8755:             if (callingForm.srchtype.options[i].value == 'exact') {
 8756:                 callingForm.srchtype.selectedIndex = i;
 8757:             }
 8758:         }
 8759:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8760:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8761:                 callingForm.srchdomain.selectedIndex = i;
 8762:             }
 8763:         }
 8764:     }
 8765: }
 8766: ENDSCRIPT
 8767: 
 8768:     }
 8769: 
 8770:     my $output = <<"END_BLOCK";
 8771: <script type="text/javascript">
 8772: // <![CDATA[
 8773: function validateEntry(callingForm) {
 8774: 
 8775:     var checkok = 1;
 8776:     var srchin;
 8777:     for (var i=0; i<callingForm.srchin.length; i++) {
 8778: 	if ( callingForm.srchin[i].checked ) {
 8779: 	    srchin = callingForm.srchin[i].value;
 8780: 	}
 8781:     }
 8782: 
 8783:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8784:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8785:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8786:     var srchterm =  callingForm.srchterm.value;
 8787:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8788:     var msg = "";
 8789: 
 8790:     if (srchterm == "") {
 8791:         checkok = 0;
 8792:         msg += "$lt{'youm'}\\n";
 8793:     }
 8794: 
 8795:     if (srchtype== 'begins') {
 8796:         if (srchterm.length < 2) {
 8797:             checkok = 0;
 8798:             msg += "$lt{'thte'}\\n";
 8799:         }
 8800:     }
 8801: 
 8802:     if (srchtype== 'contains') {
 8803:         if (srchterm.length < 3) {
 8804:             checkok = 0;
 8805:             msg += "$lt{'thet'}\\n";
 8806:         }
 8807:     }
 8808:     if (srchin == 'instd') {
 8809:         if (srchdomain == '') {
 8810:             checkok = 0;
 8811:             msg += "$lt{'yomc'}\\n";
 8812:         }
 8813:     }
 8814:     if (srchin == 'dom') {
 8815:         if (srchdomain == '') {
 8816:             checkok = 0;
 8817:             msg += "$lt{'ymcd'}\\n";
 8818:         }
 8819:     }
 8820:     if (srchby == 'lastfirst') {
 8821:         if (srchterm.indexOf(",") == -1) {
 8822:             checkok = 0;
 8823:             msg += "$lt{'whus'}\\n";
 8824:         }
 8825:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8826:             checkok = 0;
 8827:             msg += "$lt{'whse'}\\n";
 8828:         }
 8829:     }
 8830:     if (checkok == 0) {
 8831:         alert("$lt{'thfo'}\\n"+msg);
 8832:         return;
 8833:     }
 8834:     if (checkok == 1) {
 8835:         callingForm.submit();
 8836:     }
 8837: }
 8838: 
 8839: $newuserscript
 8840: 
 8841: // ]]>
 8842: </script>
 8843: 
 8844: $new_user_create
 8845: 
 8846: END_BLOCK
 8847: 
 8848:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8849:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8850:                $domform.
 8851:                &Apache::lonhtmlcommon::row_closure().
 8852:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8853:                $srchbysel.
 8854:                $srchtypesel. 
 8855:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8856:                $srchinsel.
 8857:                &Apache::lonhtmlcommon::row_closure(1). 
 8858:                &Apache::lonhtmlcommon::end_pick_box().
 8859:                '<br />';
 8860:     return $output;
 8861: }
 8862: 
 8863: sub user_rule_check {
 8864:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8865:     my $response;
 8866:     if (ref($usershash) eq 'HASH') {
 8867:         foreach my $user (keys(%{$usershash})) {
 8868:             my ($uname,$udom) = split(/:/,$user);
 8869:             next if ($udom eq '' || $uname eq '');
 8870:             my ($id,$newuser);
 8871:             if (ref($usershash->{$user}) eq 'HASH') {
 8872:                 $newuser = $usershash->{$user}->{'newuser'};
 8873:                 $id = $usershash->{$user}->{'id'};
 8874:             }
 8875:             my $inst_response;
 8876:             if (ref($checks) eq 'HASH') {
 8877:                 if (defined($checks->{'username'})) {
 8878:                     ($inst_response,%{$inst_results->{$user}}) = 
 8879:                         &Apache::lonnet::get_instuser($udom,$uname);
 8880:                 } elsif (defined($checks->{'id'})) {
 8881:                     ($inst_response,%{$inst_results->{$user}}) =
 8882:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8883:                 }
 8884:             } else {
 8885:                 ($inst_response,%{$inst_results->{$user}}) =
 8886:                     &Apache::lonnet::get_instuser($udom,$uname);
 8887:                 return;
 8888:             }
 8889:             if (!$got_rules->{$udom}) {
 8890:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8891:                                                   ['usercreation'],$udom);
 8892:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8893:                     foreach my $item ('username','id') {
 8894:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8895:                             $$curr_rules{$udom}{$item} = 
 8896:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8897:                         }
 8898:                     }
 8899:                 }
 8900:                 $got_rules->{$udom} = 1;  
 8901:             }
 8902:             foreach my $item (keys(%{$checks})) {
 8903:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8904:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8905:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8906:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8907:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8908:                                 if ($rule_check{$rule}) {
 8909:                                     $$rulematch{$user}{$item} = $rule;
 8910:                                     if ($inst_response eq 'ok') {
 8911:                                         if (ref($inst_results) eq 'HASH') {
 8912:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8913:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8914:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8915:                                                 }
 8916:                                             }
 8917:                                         }
 8918:                                     }
 8919:                                     last;
 8920:                                 }
 8921:                             }
 8922:                         }
 8923:                     }
 8924:                 }
 8925:             }
 8926:         }
 8927:     }
 8928:     return;
 8929: }
 8930: 
 8931: sub user_rule_formats {
 8932:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8933:     my %text = ( 
 8934:                  'username' => 'Usernames',
 8935:                  'id'       => 'IDs',
 8936:                );
 8937:     my $output;
 8938:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8939:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8940:         if (@{$ruleorder} > 0) {
 8941:             $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>';
 8942:             foreach my $rule (@{$ruleorder}) {
 8943:                 if (ref($curr_rules) eq 'ARRAY') {
 8944:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8945:                         if (ref($rules->{$rule}) eq 'HASH') {
 8946:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8947:                                         $rules->{$rule}{'desc'}.'</li>';
 8948:                         }
 8949:                     }
 8950:                 }
 8951:             }
 8952:             $output .= '</ul>';
 8953:         }
 8954:     }
 8955:     return $output;
 8956: }
 8957: 
 8958: sub instrule_disallow_msg {
 8959:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8960:     my $response;
 8961:     my %text = (
 8962:                   item   => 'username',
 8963:                   items  => 'usernames',
 8964:                   match  => 'matches',
 8965:                   do     => 'does',
 8966:                   action => 'a username',
 8967:                   one    => 'one',
 8968:                );
 8969:     if ($count > 1) {
 8970:         $text{'item'} = 'usernames';
 8971:         $text{'match'} ='match';
 8972:         $text{'do'} = 'do';
 8973:         $text{'action'} = 'usernames',
 8974:         $text{'one'} = 'ones';
 8975:     }
 8976:     if ($checkitem eq 'id') {
 8977:         $text{'items'} = 'IDs';
 8978:         $text{'item'} = 'ID';
 8979:         $text{'action'} = 'an ID';
 8980:         if ($count > 1) {
 8981:             $text{'item'} = 'IDs';
 8982:             $text{'action'} = 'IDs';
 8983:         }
 8984:     }
 8985:     $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 />';
 8986:     if ($mode eq 'upload') {
 8987:         if ($checkitem eq 'username') {
 8988:             $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'}.");
 8989:         } elsif ($checkitem eq 'id') {
 8990:             $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.");
 8991:         }
 8992:     } elsif ($mode eq 'selfcreate') {
 8993:         if ($checkitem eq 'id') {
 8994:             $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.");
 8995:         }
 8996:     } else {
 8997:         if ($checkitem eq 'username') {
 8998:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8999:         } elsif ($checkitem eq 'id') {
 9000:             $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.");
 9001:         }
 9002:     }
 9003:     return $response;
 9004: }
 9005: 
 9006: sub personal_data_fieldtitles {
 9007:     my %fieldtitles = &Apache::lonlocal::texthash (
 9008:                         id => 'Student/Employee ID',
 9009:                         permanentemail => 'E-mail address',
 9010:                         lastname => 'Last Name',
 9011:                         firstname => 'First Name',
 9012:                         middlename => 'Middle Name',
 9013:                         generation => 'Generation',
 9014:                         gen => 'Generation',
 9015:                         inststatus => 'Affiliation',
 9016:                    );
 9017:     return %fieldtitles;
 9018: }
 9019: 
 9020: sub sorted_inst_types {
 9021:     my ($dom) = @_;
 9022:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9023:     my $othertitle = &mt('All users');
 9024:     if ($env{'request.course.id'}) {
 9025:         $othertitle  = &mt('Any users');
 9026:     }
 9027:     my @types;
 9028:     if (ref($order) eq 'ARRAY') {
 9029:         @types = @{$order};
 9030:     }
 9031:     if (@types == 0) {
 9032:         if (ref($usertypes) eq 'HASH') {
 9033:             @types = sort(keys(%{$usertypes}));
 9034:         }
 9035:     }
 9036:     if (keys(%{$usertypes}) > 0) {
 9037:         $othertitle = &mt('Other users');
 9038:     }
 9039:     return ($othertitle,$usertypes,\@types);
 9040: }
 9041: 
 9042: sub get_institutional_codes {
 9043:     my ($settings,$allcourses,$LC_code) = @_;
 9044: # Get complete list of course sections to update
 9045:     my @currsections = ();
 9046:     my @currxlists = ();
 9047:     my $coursecode = $$settings{'internal.coursecode'};
 9048: 
 9049:     if ($$settings{'internal.sectionnums'} ne '') {
 9050:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9051:     }
 9052: 
 9053:     if ($$settings{'internal.crosslistings'} ne '') {
 9054:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9055:     }
 9056: 
 9057:     if (@currxlists > 0) {
 9058:         foreach (@currxlists) {
 9059:             if (m/^([^:]+):(\w*)$/) {
 9060:                 unless (grep/^$1$/,@{$allcourses}) {
 9061:                     push @{$allcourses},$1;
 9062:                     $$LC_code{$1} = $2;
 9063:                 }
 9064:             }
 9065:         }
 9066:     }
 9067:  
 9068:     if (@currsections > 0) {
 9069:         foreach (@currsections) {
 9070:             if (m/^(\w+):(\w*)$/) {
 9071:                 my $sec = $coursecode.$1;
 9072:                 my $lc_sec = $2;
 9073:                 unless (grep/^$sec$/,@{$allcourses}) {
 9074:                     push @{$allcourses},$sec;
 9075:                     $$LC_code{$sec} = $lc_sec;
 9076:                 }
 9077:             }
 9078:         }
 9079:     }
 9080:     return;
 9081: }
 9082: 
 9083: sub get_standard_codeitems {
 9084:     return ('Year','Semester','Department','Number','Section');
 9085: }
 9086: 
 9087: =pod
 9088: 
 9089: =head1 Slot Helpers
 9090: 
 9091: =over 4
 9092: 
 9093: =item * sorted_slots()
 9094: 
 9095: Sorts an array of slot names in order of an optional sort key,
 9096: default sort is by slot start time (earliest first). 
 9097: 
 9098: Inputs:
 9099: 
 9100: =over 4
 9101: 
 9102: slotsarr  - Reference to array of unsorted slot names.
 9103: 
 9104: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9105: 
 9106: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9107: 
 9108: =back
 9109: 
 9110: Returns:
 9111: 
 9112: =over 4
 9113: 
 9114: sorted   - An array of slot names sorted by a specified sort key 
 9115:            (default sort key is start time of the slot).
 9116: 
 9117: =back
 9118: 
 9119: =cut
 9120: 
 9121: 
 9122: sub sorted_slots {
 9123:     my ($slotsarr,$slots,$sortkey) = @_;
 9124:     if ($sortkey eq '') {
 9125:         $sortkey = 'starttime';
 9126:     }
 9127:     my @sorted;
 9128:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9129:         @sorted =
 9130:             sort {
 9131:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9132:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9133:                      }
 9134:                      if (ref($slots->{$a})) { return -1;}
 9135:                      if (ref($slots->{$b})) { return 1;}
 9136:                      return 0;
 9137:                  } @{$slotsarr};
 9138:     }
 9139:     return @sorted;
 9140: }
 9141: 
 9142: =pod
 9143: 
 9144: =item * get_future_slots()
 9145: 
 9146: Inputs:
 9147: 
 9148: =over 4
 9149: 
 9150: cnum - course number
 9151: 
 9152: cdom - course domain
 9153: 
 9154: now - current UNIX time
 9155: 
 9156: symb - optional symb
 9157: 
 9158: =back
 9159: 
 9160: Returns:
 9161: 
 9162: =over 4
 9163: 
 9164: sorted_reservable - ref to array of student_schedulable slots currently 
 9165:                     reservable, ordered by end date of reservation period.
 9166: 
 9167: reservable_now - ref to hash of student_schedulable slots currently
 9168:                  reservable.
 9169: 
 9170:     Keys in inner hash are:
 9171:     (a) symb: either blank or symb to which slot use is restricted.
 9172:     (b) endreserve: end date of reservation period. 
 9173: 
 9174: sorted_future - ref to array of student_schedulable slots reservable in
 9175:                 the future, ordered by start date of reservation period.
 9176: 
 9177: future_reservable - ref to hash of student_schedulable slots reservable
 9178:                     in the future.
 9179: 
 9180:     Keys in inner hash are:
 9181:     (a) symb: either blank or symb to which slot use is restricted.
 9182:     (b) startreserve:  start date of reservation period.
 9183: 
 9184: =back
 9185: 
 9186: =cut
 9187: 
 9188: sub get_future_slots {
 9189:     my ($cnum,$cdom,$now,$symb) = @_;
 9190:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9191:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9192:     foreach my $slot (keys(%slots)) {
 9193:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9194:         if ($symb) {
 9195:             next if (($slots{$slot}->{'symb'} ne '') && 
 9196:                      ($slots{$slot}->{'symb'} ne $symb));
 9197:         }
 9198:         if (($slots{$slot}->{'starttime'} > $now) &&
 9199:             ($slots{$slot}->{'endtime'} > $now)) {
 9200:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9201:                 my $userallowed = 0;
 9202:                 if ($slots{$slot}->{'allowedsections'}) {
 9203:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9204:                     if (!defined($env{'request.role.sec'})
 9205:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9206:                         $userallowed=1;
 9207:                     } else {
 9208:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9209:                             $userallowed=1;
 9210:                         }
 9211:                     }
 9212:                     unless ($userallowed) {
 9213:                         if (defined($env{'request.course.groups'})) {
 9214:                             my @groups = split(/:/,$env{'request.course.groups'});
 9215:                             foreach my $group (@groups) {
 9216:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9217:                                     $userallowed=1;
 9218:                                     last;
 9219:                                 }
 9220:                             }
 9221:                         }
 9222:                     }
 9223:                 }
 9224:                 if ($slots{$slot}->{'allowedusers'}) {
 9225:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9226:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9227:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9228:                         $userallowed = 1;
 9229:                     }
 9230:                 }
 9231:                 next unless($userallowed);
 9232:             }
 9233:             my $startreserve = $slots{$slot}->{'startreserve'};
 9234:             my $endreserve = $slots{$slot}->{'endreserve'};
 9235:             my $symb = $slots{$slot}->{'symb'};
 9236:             if (($startreserve < $now) &&
 9237:                 (!$endreserve || $endreserve > $now)) {
 9238:                 my $lastres = $endreserve;
 9239:                 if (!$lastres) {
 9240:                     $lastres = $slots{$slot}->{'starttime'};
 9241:                 }
 9242:                 $reservable_now{$slot} = {
 9243:                                            symb       => $symb,
 9244:                                            endreserve => $lastres
 9245:                                          };
 9246:             } elsif (($startreserve > $now) &&
 9247:                      (!$endreserve || $endreserve > $startreserve)) {
 9248:                 $future_reservable{$slot} = {
 9249:                                               symb         => $symb,
 9250:                                               startreserve => $startreserve
 9251:                                             };
 9252:             }
 9253:         }
 9254:     }
 9255:     my @unsorted_reservable = keys(%reservable_now);
 9256:     if (@unsorted_reservable > 0) {
 9257:         @sorted_reservable = 
 9258:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9259:     }
 9260:     my @unsorted_future = keys(%future_reservable);
 9261:     if (@unsorted_future > 0) {
 9262:         @sorted_future =
 9263:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9264:     }
 9265:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9266: }
 9267: 
 9268: =pod
 9269: 
 9270: =back
 9271: 
 9272: =head1 HTTP Helpers
 9273: 
 9274: =over 4
 9275: 
 9276: =item * &get_unprocessed_cgi($query,$possible_names)
 9277: 
 9278: Modify the %env hash to contain unprocessed CGI form parameters held in
 9279: $query.  The parameters listed in $possible_names (an array reference),
 9280: will be set in $env{'form.name'} if they do not already exist.
 9281: 
 9282: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9283: $possible_names is an ref to an array of form element names.  As an example:
 9284: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9285: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9286: 
 9287: =cut
 9288: 
 9289: sub get_unprocessed_cgi {
 9290:   my ($query,$possible_names)= @_;
 9291:   # $Apache::lonxml::debug=1;
 9292:   foreach my $pair (split(/&/,$query)) {
 9293:     my ($name, $value) = split(/=/,$pair);
 9294:     $name = &unescape($name);
 9295:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9296:       $value =~ tr/+/ /;
 9297:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9298:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9299:     }
 9300:   }
 9301: }
 9302: 
 9303: =pod
 9304: 
 9305: =item * &cacheheader() 
 9306: 
 9307: returns cache-controlling header code
 9308: 
 9309: =cut
 9310: 
 9311: sub cacheheader {
 9312:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9313:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9314:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9315:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9316:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9317:     return $output;
 9318: }
 9319: 
 9320: =pod
 9321: 
 9322: =item * &no_cache($r) 
 9323: 
 9324: specifies header code to not have cache
 9325: 
 9326: =cut
 9327: 
 9328: sub no_cache {
 9329:     my ($r) = @_;
 9330:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9331: 	$env{'request.method'} ne 'GET') { return ''; }
 9332:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9333:     $r->no_cache(1);
 9334:     $r->header_out("Expires" => $date);
 9335:     $r->header_out("Pragma" => "no-cache");
 9336: }
 9337: 
 9338: sub content_type {
 9339:     my ($r,$type,$charset) = @_;
 9340:     if ($r) {
 9341: 	#  Note that printout.pl calls this with undef for $r.
 9342: 	&no_cache($r);
 9343:     }
 9344:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9345:     unless ($charset) {
 9346: 	$charset=&Apache::lonlocal::current_encoding;
 9347:     }
 9348:     if ($charset) { $type.='; charset='.$charset; }
 9349:     if ($r) {
 9350: 	$r->content_type($type);
 9351:     } else {
 9352: 	print("Content-type: $type\n\n");
 9353:     }
 9354: }
 9355: 
 9356: =pod
 9357: 
 9358: =item * &add_to_env($name,$value) 
 9359: 
 9360: adds $name to the %env hash with value
 9361: $value, if $name already exists, the entry is converted to an array
 9362: reference and $value is added to the array.
 9363: 
 9364: =cut
 9365: 
 9366: sub add_to_env {
 9367:   my ($name,$value)=@_;
 9368:   if (defined($env{$name})) {
 9369:     if (ref($env{$name})) {
 9370:       #already have multiple values
 9371:       push(@{ $env{$name} },$value);
 9372:     } else {
 9373:       #first time seeing multiple values, convert hash entry to an arrayref
 9374:       my $first=$env{$name};
 9375:       undef($env{$name});
 9376:       push(@{ $env{$name} },$first,$value);
 9377:     }
 9378:   } else {
 9379:     $env{$name}=$value;
 9380:   }
 9381: }
 9382: 
 9383: =pod
 9384: 
 9385: =item * &get_env_multiple($name) 
 9386: 
 9387: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9388: values may be defined and end up as an array ref.
 9389: 
 9390: returns an array of values
 9391: 
 9392: =cut
 9393: 
 9394: sub get_env_multiple {
 9395:     my ($name) = @_;
 9396:     my @values;
 9397:     if (defined($env{$name})) {
 9398:         # exists is it an array
 9399:         if (ref($env{$name})) {
 9400:             @values=@{ $env{$name} };
 9401:         } else {
 9402:             $values[0]=$env{$name};
 9403:         }
 9404:     }
 9405:     return(@values);
 9406: }
 9407: 
 9408: sub ask_for_embedded_content {
 9409:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9410:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9411:         %currsubfile,%unused,$rem);
 9412:     my $counter = 0;
 9413:     my $numnew = 0;
 9414:     my $numremref = 0;
 9415:     my $numinvalid = 0;
 9416:     my $numpathchg = 0;
 9417:     my $numexisting = 0;
 9418:     my $numunused = 0;
 9419:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9420:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9421:     my $heading = &mt('Upload embedded files');
 9422:     my $buttontext = &mt('Upload');
 9423: 
 9424:     my $navmap;
 9425:     if ($env{'request.course.id'}) {
 9426:         $navmap = Apache::lonnavmaps::navmap->new();
 9427:     }
 9428:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9429:         my $current_path='/';
 9430:         if ($env{'form.currentpath'}) {
 9431:             $current_path = $env{'form.currentpath'};
 9432:         }
 9433:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9434:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9435:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 9436:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9437:         } else {
 9438:             $udom = $env{'user.domain'};
 9439:             $uname = $env{'user.name'};
 9440:             $url = '/userfiles/portfolio';
 9441:         }
 9442:         $toplevel = $url.'/';
 9443:         $url .= $current_path;
 9444:         $getpropath = 1;
 9445:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9446:              ($actionurl eq '/adm/imsimport')) { 
 9447:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9448:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9449:         $toplevel = $url;
 9450:         if ($rest ne '') {
 9451:             $url .= $rest;
 9452:         }
 9453:     } elsif ($actionurl eq '/adm/coursedocs') {
 9454:         if (ref($args) eq 'HASH') {
 9455:             $url = $args->{'docs_url'};
 9456:             $toplevel = $url;
 9457:             if ($args->{'context'} eq 'paste') {
 9458:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9459:                 ($path) =
 9460:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9461:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9462:                 $fileloc =~ s{^/}{};
 9463:             }
 9464:         }
 9465:     } elsif ($actionurl eq '/adm/dependencies') {
 9466:         if ($env{'request.course.id'} ne '') {
 9467:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9468:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
 9469:             if (ref($args) eq 'HASH') {
 9470:                 $url = $args->{'docs_url'};
 9471:                 $title = $args->{'docs_title'};
 9472:                 $toplevel = "/$url";
 9473:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9474:                 ($path) =  
 9475:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9476:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9477:                 $fileloc =~ s{^/}{};
 9478:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9479:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9480:             }
 9481:         }
 9482:     }
 9483:     my $now = time();
 9484:     foreach my $embed_file (keys(%{$allfiles})) {
 9485:         my $absolutepath;
 9486:         if ($embed_file =~ m{^\w+://}) {
 9487:             $newfiles{$embed_file} = 1;
 9488:             $mapping{$embed_file} = $embed_file;
 9489:         } else {
 9490:             if ($embed_file =~ m{^/}) {
 9491:                 $absolutepath = $embed_file;
 9492:                 $embed_file =~ s{^(/+)}{};
 9493:             }
 9494:             if ($embed_file =~ m{/}) {
 9495:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 9496:                 $path = &check_for_traversal($path,$url,$toplevel);
 9497:                 my $item = $fname;
 9498:                 if ($path ne '') {
 9499:                     $item = $path.'/'.$fname;
 9500:                     $subdependencies{$path}{$fname} = 1;
 9501:                 } else {
 9502:                     $dependencies{$item} = 1;
 9503:                 }
 9504:                 if ($absolutepath) {
 9505:                     $mapping{$item} = $absolutepath;
 9506:                 } else {
 9507:                     $mapping{$item} = $embed_file;
 9508:                 }
 9509:             } else {
 9510:                 $dependencies{$embed_file} = 1;
 9511:                 if ($absolutepath) {
 9512:                     $mapping{$embed_file} = $absolutepath;
 9513:                 } else {
 9514:                     $mapping{$embed_file} = $embed_file;
 9515:                 }
 9516:             }
 9517:         }
 9518:     }
 9519:     my $dirptr = 16384;
 9520:     foreach my $path (keys(%subdependencies)) {
 9521:         $currsubfile{$path} = {};
 9522:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9523:             my ($sublistref,$listerror) =
 9524:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9525:             if (ref($sublistref) eq 'ARRAY') {
 9526:                 foreach my $line (@{$sublistref}) {
 9527:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9528:                     $currsubfile{$path}{$file_name} = 1;
 9529:                 }
 9530:             }
 9531:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9532:             if (opendir(my $dir,$url.'/'.$path)) {
 9533:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9534:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9535:             }
 9536:         } elsif (($actionurl eq '/adm/dependencies') ||
 9537:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9538:                   ($args->{'context'} eq 'paste'))) {
 9539:             if ($env{'request.course.id'} ne '') {
 9540:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9541:                 if ($dir ne '') {
 9542:                     my ($sublistref,$listerror) =
 9543:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9544:                     if (ref($sublistref) eq 'ARRAY') {
 9545:                         foreach my $line (@{$sublistref}) {
 9546:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9547:                                 undef,$mtime)=split(/\&/,$line,12);
 9548:                             unless (($testdir&$dirptr) ||
 9549:                                     ($file_name =~ /^\.\.?$/)) {
 9550:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9551:                             }
 9552:                         }
 9553:                     }
 9554:                 }
 9555:             }
 9556:         }
 9557:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9558:             if (exists($currsubfile{$path}{$file})) {
 9559:                 my $item = $path.'/'.$file;
 9560:                 unless ($mapping{$item} eq $item) {
 9561:                     $pathchanges{$item} = 1;
 9562:                 }
 9563:                 $existing{$item} = 1;
 9564:                 $numexisting ++;
 9565:             } else {
 9566:                 $newfiles{$path.'/'.$file} = 1;
 9567:             }
 9568:         }
 9569:         if ($actionurl eq '/adm/dependencies') {
 9570:             foreach my $path (keys(%currsubfile)) {
 9571:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9572:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9573:                          unless ($subdependencies{$path}{$file}) {
 9574:                              next if (($rem ne '') &&
 9575:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9576:                                        (ref($navmap) &&
 9577:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9578:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9579:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9580:                              $unused{$path.'/'.$file} = 1; 
 9581:                          }
 9582:                     }
 9583:                 }
 9584:             }
 9585:         }
 9586:     }
 9587:     my %currfile;
 9588:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9589:         my ($dirlistref,$listerror) =
 9590:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9591:         if (ref($dirlistref) eq 'ARRAY') {
 9592:             foreach my $line (@{$dirlistref}) {
 9593:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9594:                 $currfile{$file_name} = 1;
 9595:             }
 9596:         }
 9597:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9598:         if (opendir(my $dir,$url)) {
 9599:             my @dir_list = grep(!/^\./,readdir($dir));
 9600:             map {$currfile{$_} = 1;} @dir_list;
 9601:         }
 9602:     } elsif (($actionurl eq '/adm/dependencies') ||
 9603:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9604:               ($args->{'context'} eq 'paste'))) {
 9605:         if ($env{'request.course.id'} ne '') {
 9606:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9607:             if ($dir ne '') {
 9608:                 my ($dirlistref,$listerror) =
 9609:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9610:                 if (ref($dirlistref) eq 'ARRAY') {
 9611:                     foreach my $line (@{$dirlistref}) {
 9612:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9613:                             $size,undef,$mtime)=split(/\&/,$line,12);
 9614:                         unless (($testdir&$dirptr) ||
 9615:                                 ($file_name =~ /^\.\.?$/)) {
 9616:                             $currfile{$file_name} = [$size,$mtime];
 9617:                         }
 9618:                     }
 9619:                 }
 9620:             }
 9621:         }
 9622:     }
 9623:     foreach my $file (keys(%dependencies)) {
 9624:         if (exists($currfile{$file})) {
 9625:             unless ($mapping{$file} eq $file) {
 9626:                 $pathchanges{$file} = 1;
 9627:             }
 9628:             $existing{$file} = 1;
 9629:             $numexisting ++;
 9630:         } else {
 9631:             $newfiles{$file} = 1;
 9632:         }
 9633:     }
 9634:     foreach my $file (keys(%currfile)) {
 9635:         unless (($file eq $filename) ||
 9636:                 ($file eq $filename.'.bak') ||
 9637:                 ($dependencies{$file})) {
 9638:             if ($actionurl eq '/adm/dependencies') {
 9639:                 next if (($rem ne '') &&
 9640:                          (($env{"httpref.$rem".$file} ne '') ||
 9641:                           (ref($navmap) &&
 9642:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
 9643:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9644:                             ($navmap->getResourceByUrl($rem.$1)))))));
 9645:             }
 9646:             $unused{$file} = 1;
 9647:         }
 9648:     }
 9649:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9650:         ($args->{'context'} eq 'paste')) {
 9651:         $counter = scalar(keys(%existing));
 9652:         $numpathchg = scalar(keys(%pathchanges));
 9653:         return ($output,$counter,$numpathchg,\%existing);
 9654:     }
 9655:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 9656:         if ($actionurl eq '/adm/dependencies') {
 9657:             next if ($embed_file =~ m{^\w+://});
 9658:         }
 9659:         $upload_output .= &start_data_table_row().
 9660:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
 9661:                           '<span class="LC_filename">'.$embed_file.'</span>';
 9662:         unless ($mapping{$embed_file} eq $embed_file) {
 9663:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 9664:         }
 9665:         $upload_output .= '</td><td>';
 9666:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
 9667:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 9668:             $numremref++;
 9669:         } elsif ($args->{'error_on_invalid_names'}
 9670:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 9671:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 9672:             $numinvalid++;
 9673:         } else {
 9674:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
 9675:                                                      $embed_file,\%mapping,
 9676:                                                      $allfiles,$codebase,'upload');
 9677:             $counter ++;
 9678:             $numnew ++;
 9679:         }
 9680:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 9681:     }
 9682:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 9683:         if ($actionurl eq '/adm/dependencies') {
 9684:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
 9685:             $modify_output .= &start_data_table_row().
 9686:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
 9687:                               '<img src="'.&icon($embed_file).'" border="0" />'.
 9688:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
 9689:                               '<td>'.$size.'</td>'.
 9690:                               '<td>'.$mtime.'</td>'.
 9691:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
 9692:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
 9693:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
 9694:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
 9695:                               &embedded_file_element('upload_embedded',$counter,
 9696:                                                      $embed_file,\%mapping,
 9697:                                                      $allfiles,$codebase,'modify').
 9698:                               '</div></td>'.
 9699:                               &end_data_table_row()."\n";
 9700:             $counter ++;
 9701:         } else {
 9702:             $upload_output .= &start_data_table_row().
 9703:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
 9704:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 9705:                               &Apache::loncommon::end_data_table_row()."\n";
 9706:         }
 9707:     }
 9708:     my $delidx = $counter;
 9709:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
 9710:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
 9711:         $delete_output .= &start_data_table_row().
 9712:                           '<td><img src="'.&icon($oldfile).'" />'.
 9713:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
 9714:                           '<td>'.$size.'</td>'.
 9715:                           '<td>'.$mtime.'</td>'.
 9716:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
 9717:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
 9718:                           &embedded_file_element('upload_embedded',$delidx,
 9719:                                                  $oldfile,\%mapping,$allfiles,
 9720:                                                  $codebase,'delete').'</td>'.
 9721:                           &end_data_table_row()."\n"; 
 9722:         $numunused ++;
 9723:         $delidx ++;
 9724:     }
 9725:     if ($upload_output) {
 9726:         $upload_output = &start_data_table().
 9727:                          $upload_output.
 9728:                          &end_data_table()."\n";
 9729:     }
 9730:     if ($modify_output) {
 9731:         $modify_output = &start_data_table().
 9732:                          &start_data_table_header_row().
 9733:                          '<th>'.&mt('File').'</th>'.
 9734:                          '<th>'.&mt('Size (KB)').'</th>'.
 9735:                          '<th>'.&mt('Modified').'</th>'.
 9736:                          '<th>'.&mt('Upload replacement?').'</th>'.
 9737:                          &end_data_table_header_row().
 9738:                          $modify_output.
 9739:                          &end_data_table()."\n";
 9740:     }
 9741:     if ($delete_output) {
 9742:         $delete_output = &start_data_table().
 9743:                          &start_data_table_header_row().
 9744:                          '<th>'.&mt('File').'</th>'.
 9745:                          '<th>'.&mt('Size (KB)').'</th>'.
 9746:                          '<th>'.&mt('Modified').'</th>'.
 9747:                          '<th>'.&mt('Delete?').'</th>'.
 9748:                          &end_data_table_header_row().
 9749:                          $delete_output.
 9750:                          &end_data_table()."\n";
 9751:     }
 9752:     my $applies = 0;
 9753:     if ($numremref) {
 9754:         $applies ++;
 9755:     }
 9756:     if ($numinvalid) {
 9757:         $applies ++;
 9758:     }
 9759:     if ($numexisting) {
 9760:         $applies ++;
 9761:     }
 9762:     if ($counter || $numunused) {
 9763:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 9764:                   ' method="post" enctype="multipart/form-data">'."\n".
 9765:                   $state.'<h3>'.$heading.'</h3>'; 
 9766:         if ($actionurl eq '/adm/dependencies') {
 9767:             if ($numnew) {
 9768:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
 9769:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
 9770:                            $upload_output.'<br />'."\n";
 9771:             }
 9772:             if ($numexisting) {
 9773:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
 9774:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
 9775:                            $modify_output.'<br />'."\n";
 9776:                            $buttontext = &mt('Save changes');
 9777:             }
 9778:             if ($numunused) {
 9779:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
 9780:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
 9781:                            $delete_output.'<br />'."\n";
 9782:                            $buttontext = &mt('Save changes');
 9783:             }
 9784:         } else {
 9785:             $output .= $upload_output.'<br />'."\n";
 9786:         }
 9787:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
 9788:                    $counter.'" />'."\n";
 9789:         if ($actionurl eq '/adm/dependencies') { 
 9790:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
 9791:                        $numnew.'" />'."\n";
 9792:         } elsif ($actionurl eq '') {
 9793:             $output .=  '<input type="hidden" name="phase" value="three" />';
 9794:         }
 9795:     } elsif ($applies) {
 9796:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 9797:         if ($applies > 1) {
 9798:             $output .=  
 9799:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 9800:             if ($numremref) {
 9801:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 9802:             }
 9803:             if ($numinvalid) {
 9804:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 9805:             }
 9806:             if ($numexisting) {
 9807:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 9808:             }
 9809:             $output .= '</ul><br />';
 9810:         } elsif ($numremref) {
 9811:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 9812:         } elsif ($numinvalid) {
 9813:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 9814:         } elsif ($numexisting) {
 9815:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 9816:         }
 9817:         $output .= $upload_output.'<br />';
 9818:     }
 9819:     my ($pathchange_output,$chgcount);
 9820:     $chgcount = $counter;
 9821:     if (keys(%pathchanges) > 0) {
 9822:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 9823:             if ($counter) {
 9824:                 $output .= &embedded_file_element('pathchange',$chgcount,
 9825:                                                   $embed_file,\%mapping,
 9826:                                                   $allfiles,$codebase,'change');
 9827:             } else {
 9828:                 $pathchange_output .= 
 9829:                     &start_data_table_row().
 9830:                     '<td><input type ="checkbox" name="namechange" value="'.
 9831:                     $chgcount.'" checked="checked" /></td>'.
 9832:                     '<td>'.$mapping{$embed_file}.'</td>'.
 9833:                     '<td>'.$embed_file.
 9834:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 9835:                                            \%mapping,$allfiles,$codebase,'change').
 9836:                     '</td>'.&end_data_table_row();
 9837:             }
 9838:             $numpathchg ++;
 9839:             $chgcount ++;
 9840:         }
 9841:     }
 9842:     if ($counter) {
 9843:         if ($numpathchg) {
 9844:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 9845:                        $numpathchg.'" />'."\n";
 9846:         }
 9847:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 9848:             ($actionurl eq '/adm/imsimport')) {
 9849:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 9850:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 9851:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 9852:         } elsif ($actionurl eq '/adm/dependencies') {
 9853:             $output .= '<input type="hidden" name="action" value="process_changes" />';
 9854:         }
 9855:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
 9856:     } elsif ($numpathchg) {
 9857:         my %pathchange = ();
 9858:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 9859:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9860:             $output .= '<p>'.&mt('or').'</p>'; 
 9861:         } 
 9862:     }
 9863:     return ($output,$counter,$numpathchg);
 9864: }
 9865: 
 9866: sub embedded_file_element {
 9867:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
 9868:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 9869:                    (ref($codebase) eq 'HASH'));
 9870:     my $output;
 9871:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
 9872:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 9873:     }
 9874:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 9875:                &escape($embed_file).'" />';
 9876:     unless (($context eq 'upload_embedded') && 
 9877:             ($mapping->{$embed_file} eq $embed_file)) {
 9878:         $output .='
 9879:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 9880:     }
 9881:     my $attrib;
 9882:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 9883:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 9884:     }
 9885:     $output .=
 9886:         "\n\t\t".
 9887:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 9888:         $attrib.'" />';
 9889:     if (exists($codebase->{$mapping->{$embed_file}})) {
 9890:         $output .=
 9891:             "\n\t\t".
 9892:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 9893:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 9894:     }
 9895:     return $output;
 9896: }
 9897: 
 9898: sub get_dependency_details {
 9899:     my ($currfile,$currsubfile,$embed_file) = @_;
 9900:     my ($size,$mtime,$showsize,$showmtime);
 9901:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
 9902:         if ($embed_file =~ m{/}) {
 9903:             my ($path,$fname) = split(/\//,$embed_file);
 9904:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
 9905:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
 9906:             }
 9907:         } else {
 9908:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
 9909:                 ($size,$mtime) = @{$currfile->{$embed_file}};
 9910:             }
 9911:         }
 9912:         $showsize = $size/1024.0;
 9913:         $showsize = sprintf("%.1f",$showsize);
 9914:         if ($mtime > 0) {
 9915:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
 9916:         }
 9917:     }
 9918:     return ($showsize,$showmtime);
 9919: }
 9920: 
 9921: sub ask_embedded_js {
 9922:     return <<"END";
 9923: <script type="text/javascript"">
 9924: // <![CDATA[
 9925: function toggleBrowse(counter) {
 9926:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
 9927:     var fileid = document.getElementById('embedded_item_'+counter);
 9928:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
 9929:     if (chkboxid.checked == true) {
 9930:         uploaddivid.style.display='block';
 9931:     } else {
 9932:         uploaddivid.style.display='none';
 9933:         fileid.value = '';
 9934:     }
 9935: }
 9936: // ]]>
 9937: </script>
 9938: 
 9939: END
 9940: }
 9941: 
 9942: sub upload_embedded {
 9943:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 9944:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 9945:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 9946:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 9947:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 9948:         my $orig_uploaded_filename =
 9949:             $env{'form.embedded_item_'.$i.'.filename'};
 9950:         foreach my $type ('orig','ref','attrib','codebase') {
 9951:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 9952:                 $env{'form.embedded_'.$type.'_'.$i} =
 9953:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 9954:             }
 9955:         }
 9956:         my ($path,$fname) =
 9957:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 9958:         # no path, whole string is fname
 9959:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 9960:         $fname = &Apache::lonnet::clean_filename($fname);
 9961:         # See if there is anything left
 9962:         next if ($fname eq '');
 9963: 
 9964:         # Check if file already exists as a file or directory.
 9965:         my ($state,$msg);
 9966:         if ($context eq 'portfolio') {
 9967:             my $port_path = $dirpath;
 9968:             if ($group ne '') {
 9969:                 $port_path = "groups/$group/$port_path";
 9970:             }
 9971:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 9972:                                               $fname,$group,'embedded_item_'.$i,
 9973:                                               $dir_root,$port_path,$disk_quota,
 9974:                                               $current_disk_usage,$uname,$udom);
 9975:             if ($state eq 'will_exceed_quota'
 9976:                 || $state eq 'file_locked') {
 9977:                 $output .= $msg;
 9978:                 next;
 9979:             }
 9980:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 9981:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 9982:             if ($state eq 'exists') {
 9983:                 $output .= $msg;
 9984:                 next;
 9985:             }
 9986:         }
 9987:         # Check if extension is valid
 9988:         if (($fname =~ /\.(\w+)$/) &&
 9989:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 9990:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 9991:             next;
 9992:         } elsif (($fname =~ /\.(\w+)$/) &&
 9993:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 9994:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
 9995:             next;
 9996:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 9997:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
 9998:             next;
 9999:         }
10000:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10001:         if ($context eq 'portfolio') {
10002:             my $result;
10003:             if ($state eq 'existingfile') {
10004:                 $result=
10005:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10006:                                                     $dirpath.$env{'form.currentpath'}.$path);
10007:             } else {
10008:                 $result=
10009:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10010:                                                     $dirpath.
10011:                                                     $env{'form.currentpath'}.$path);
10012:                 if ($result !~ m|^/uploaded/|) {
10013:                     $output .= '<span class="LC_error">'
10014:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10015:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10016:                                .'</span><br />';
10017:                     next;
10018:                 } else {
10019:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10020:                                $path.$fname.'</span>').'<br />';     
10021:                 }
10022:             }
10023:         } elsif ($context eq 'coursedoc') {
10024:             my $result =
10025:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
10026:                                                 $dirpath.'/'.$path);
10027:             if ($result !~ m|^/uploaded/|) {
10028:                 $output .= '<span class="LC_error">'
10029:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10030:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10031:                            .'</span><br />';
10032:                     next;
10033:             } else {
10034:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10035:                            $path.$fname.'</span>').'<br />';
10036:             }
10037:         } else {
10038: # Save the file
10039:             my $target = $env{'form.embedded_item_'.$i};
10040:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10041:             my $dest = $fullpath.$fname;
10042:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10043:             my @parts=split(/\//,"$dirpath/$path");
10044:             my $count;
10045:             my $filepath = $dir_root;
10046:             foreach my $subdir (@parts) {
10047:                 $filepath .= "/$subdir";
10048:                 if (!-e $filepath) {
10049:                     mkdir($filepath,0770);
10050:                 }
10051:             }
10052:             my $fh;
10053:             if (!open($fh,'>'.$dest)) {
10054:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10055:                 $output .= '<span class="LC_error">'.
10056:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10057:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10058:                            '</span><br />';
10059:             } else {
10060:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10061:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10062:                     $output .= '<span class="LC_error">'.
10063:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10064:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10065:                               '</span><br />';
10066:                 } else {
10067:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10068:                                $url.'</span>').'<br />';
10069:                     unless ($context eq 'testbank') {
10070:                         $footer .= &mt('View embedded file: [_1]',
10071:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10072:                     }
10073:                 }
10074:                 close($fh);
10075:             }
10076:         }
10077:         if ($env{'form.embedded_ref_'.$i}) {
10078:             $pathchange{$i} = 1;
10079:         }
10080:     }
10081:     if ($output) {
10082:         $output = '<p>'.$output.'</p>';
10083:     }
10084:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10085:     $returnflag = 'ok';
10086:     my $numpathchgs = scalar(keys(%pathchange));
10087:     if ($numpathchgs > 0) {
10088:         if ($context eq 'portfolio') {
10089:             $output .= '<p>'.&mt('or').'</p>';
10090:         } elsif ($context eq 'testbank') {
10091:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10092:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10093:             $returnflag = 'modify_orightml';
10094:         }
10095:     }
10096:     return ($output.$footer,$returnflag,$numpathchgs);
10097: }
10098: 
10099: sub modify_html_form {
10100:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10101:     my $end = 0;
10102:     my $modifyform;
10103:     if ($context eq 'upload_embedded') {
10104:         return unless (ref($pathchange) eq 'HASH');
10105:         if ($env{'form.number_embedded_items'}) {
10106:             $end += $env{'form.number_embedded_items'};
10107:         }
10108:         if ($env{'form.number_pathchange_items'}) {
10109:             $end += $env{'form.number_pathchange_items'};
10110:         }
10111:         if ($end) {
10112:             for (my $i=0; $i<$end; $i++) {
10113:                 if ($i < $env{'form.number_embedded_items'}) {
10114:                     next unless($pathchange->{$i});
10115:                 }
10116:                 $modifyform .=
10117:                     &start_data_table_row().
10118:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10119:                     'checked="checked" /></td>'.
10120:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10121:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10122:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10123:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10124:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10125:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10126:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10127:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10128:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10129:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10130:                     &end_data_table_row();
10131:             }
10132:         }
10133:     } else {
10134:         $modifyform = $pathchgtable;
10135:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10136:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10137:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10138:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10139:         }
10140:     }
10141:     if ($modifyform) {
10142:         if ($actionurl eq '/adm/dependencies') {
10143:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10144:         }
10145:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10146:                '<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".
10147:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10148:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10149:                '</ol></p>'."\n".'<p>'.
10150:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10151:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10152:                &start_data_table()."\n".
10153:                &start_data_table_header_row().
10154:                '<th>'.&mt('Change?').'</th>'.
10155:                '<th>'.&mt('Current reference').'</th>'.
10156:                '<th>'.&mt('Required reference').'</th>'.
10157:                &end_data_table_header_row()."\n".
10158:                $modifyform.
10159:                &end_data_table().'<br />'."\n".$hiddenstate.
10160:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10161:                '</form>'."\n";
10162:     }
10163:     return;
10164: }
10165: 
10166: sub modify_html_refs {
10167:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
10168:     my $container;
10169:     if ($context eq 'portfolio') {
10170:         $container = $env{'form.container'};
10171:     } elsif ($context eq 'coursedoc') {
10172:         $container = $env{'form.primaryurl'};
10173:     } elsif ($context eq 'manage_dependencies') {
10174:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10175:         $container = "/$container";
10176:     } else {
10177:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10178:     }
10179:     my (%allfiles,%codebase,$output,$content);
10180:     my @changes = &get_env_multiple('form.namechange');
10181:     unless (@changes > 0) {
10182:         if (wantarray) {
10183:             return ('',0,0); 
10184:         } else {
10185:             return;
10186:         }
10187:     }
10188:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10189:         ($context eq 'manage_dependencies')) {
10190:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10191:             if (wantarray) {
10192:                 return ('',0,0);
10193:             } else {
10194:                 return;
10195:             }
10196:         } 
10197:         $content = &Apache::lonnet::getfile($container);
10198:         if ($content eq '-1') {
10199:             if (wantarray) {
10200:                 return ('',0,0);
10201:             } else {
10202:                 return;
10203:             }
10204:         }
10205:     } else {
10206:         unless ($container =~ /^\Q$dir_root\E/) {
10207:             if (wantarray) {
10208:                 return ('',0,0);
10209:             } else {
10210:                 return;
10211:             }
10212:         } 
10213:         if (open(my $fh,"<$container")) {
10214:             $content = join('', <$fh>);
10215:             close($fh);
10216:         } else {
10217:             if (wantarray) {
10218:                 return ('',0,0);
10219:             } else {
10220:                 return;
10221:             }
10222:         }
10223:     }
10224:     my ($count,$codebasecount) = (0,0);
10225:     my $mm = new File::MMagic;
10226:     my $mime_type = $mm->checktype_contents($content);
10227:     if ($mime_type eq 'text/html') {
10228:         my $parse_result = 
10229:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10230:                                                     \%codebase,\$content);
10231:         if ($parse_result eq 'ok') {
10232:             foreach my $i (@changes) {
10233:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10234:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10235:                 if ($allfiles{$ref}) {
10236:                     my $newname =  $orig;
10237:                     my ($attrib_regexp,$codebase);
10238:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10239:                     if ($attrib_regexp =~ /:/) {
10240:                         $attrib_regexp =~ s/\:/|/g;
10241:                     }
10242:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10243:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10244:                         $count += $numchg;
10245:                     }
10246:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10247:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10248:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10249:                         $codebasecount ++;
10250:                     }
10251:                 }
10252:             }
10253:             if ($count || $codebasecount) {
10254:                 my $saveresult;
10255:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10256:                     ($context eq 'manage_dependencies')) {
10257:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10258:                     if ($url eq $container) {
10259:                         my ($fname) = ($container =~ m{/([^/]+)$});
10260:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10261:                                             $count,'<span class="LC_filename">'.
10262:                                             $fname.'</span>').'</p>';
10263:                     } else {
10264:                          $output = '<p class="LC_error">'.
10265:                                    &mt('Error: update failed for: [_1].',
10266:                                    '<span class="LC_filename">'.
10267:                                    $container.'</span>').'</p>';
10268:                     }
10269:                 } else {
10270:                     if (open(my $fh,">$container")) {
10271:                         print $fh $content;
10272:                         close($fh);
10273:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10274:                                   $count,'<span class="LC_filename">'.
10275:                                   $container.'</span>').'</p>';
10276:                     } else {
10277:                          $output = '<p class="LC_error">'.
10278:                                    &mt('Error: could not update [_1].',
10279:                                    '<span class="LC_filename">'.
10280:                                    $container.'</span>').'</p>';
10281:                     }
10282:                 }
10283:             }
10284:         } else {
10285:             &logthis('Failed to parse '.$container.
10286:                      ' to modify references: '.$parse_result);
10287:         }
10288:     }
10289:     if (wantarray) {
10290:         return ($output,$count,$codebasecount);
10291:     } else {
10292:         return $output;
10293:     }
10294: }
10295: 
10296: sub check_for_existing {
10297:     my ($path,$fname,$element) = @_;
10298:     my ($state,$msg);
10299:     if (-d $path.'/'.$fname) {
10300:         $state = 'exists';
10301:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10302:     } elsif (-e $path.'/'.$fname) {
10303:         $state = 'exists';
10304:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10305:     }
10306:     if ($state eq 'exists') {
10307:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10308:     }
10309:     return ($state,$msg);
10310: }
10311: 
10312: sub check_for_upload {
10313:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10314:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10315:     my $filesize = length($env{'form.'.$element});
10316:     if (!$filesize) {
10317:         my $msg = '<span class="LC_error">'.
10318:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10319:                       '<span class="LC_filename">'.$fname.'</span>',
10320:                       $filesize).'<br />'.
10321:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10322:                   '</span>';
10323:         return ('zero_bytes',$msg);
10324:     }
10325:     $filesize =  $filesize/1000; #express in k (1024?)
10326:     my $getpropath = 1;
10327:     my ($dirlistref,$listerror) =
10328:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10329:     my $found_file = 0;
10330:     my $locked_file = 0;
10331:     my @lockers;
10332:     my $navmap;
10333:     if ($env{'request.course.id'}) {
10334:         $navmap = Apache::lonnavmaps::navmap->new();
10335:     }
10336:     if (ref($dirlistref) eq 'ARRAY') {
10337:         foreach my $line (@{$dirlistref}) {
10338:             my ($file_name,$rest)=split(/\&/,$line,2);
10339:             if ($file_name eq $fname){
10340:                 $file_name = $path.$file_name;
10341:                 if ($group ne '') {
10342:                     $file_name = $group.$file_name;
10343:                 }
10344:                 $found_file = 1;
10345:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10346:                     foreach my $lock (@lockers) {
10347:                         if (ref($lock) eq 'ARRAY') {
10348:                             my ($symb,$crsid) = @{$lock};
10349:                             if ($crsid eq $env{'request.course.id'}) {
10350:                                 if (ref($navmap)) {
10351:                                     my $res = $navmap->getBySymb($symb);
10352:                                     foreach my $part (@{$res->parts()}) { 
10353:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10354:                                         unless (($slot_status == $res->RESERVED) ||
10355:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10356:                                             $locked_file = 1;
10357:                                         }
10358:                                     }
10359:                                 } else {
10360:                                     $locked_file = 1;
10361:                                 }
10362:                             } else {
10363:                                 $locked_file = 1;
10364:                             }
10365:                         }
10366:                    }
10367:                 } else {
10368:                     my @info = split(/\&/,$rest);
10369:                     my $currsize = $info[6]/1000;
10370:                     if ($currsize < $filesize) {
10371:                         my $extra = $filesize - $currsize;
10372:                         if (($current_disk_usage + $extra) > $disk_quota) {
10373:                             my $msg = '<span class="LC_error">'.
10374:                                       &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.',
10375:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10376:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10377:                                                    $disk_quota,$current_disk_usage);
10378:                             return ('will_exceed_quota',$msg);
10379:                         }
10380:                     }
10381:                 }
10382:             }
10383:         }
10384:     }
10385:     if (($current_disk_usage + $filesize) > $disk_quota){
10386:         my $msg = '<span class="LC_error">'.
10387:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10388:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10389:         return ('will_exceed_quota',$msg);
10390:     } elsif ($found_file) {
10391:         if ($locked_file) {
10392:             my $msg = '<span class="LC_error">';
10393:             $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>');
10394:             $msg .= '</span><br />';
10395:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10396:             return ('file_locked',$msg);
10397:         } else {
10398:             my $msg = '<span class="LC_error">';
10399:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10400:             $msg .= '</span>';
10401:             return ('existingfile',$msg);
10402:         }
10403:     }
10404: }
10405: 
10406: sub check_for_traversal {
10407:     my ($path,$url,$toplevel) = @_;
10408:     my @parts=split(/\//,$path);
10409:     my $cleanpath;
10410:     my $fullpath = $url;
10411:     for (my $i=0;$i<@parts;$i++) {
10412:         next if ($parts[$i] eq '.');
10413:         if ($parts[$i] eq '..') {
10414:             $fullpath =~ s{([^/]+/)$}{};
10415:         } else {
10416:             $fullpath .= $parts[$i].'/';
10417:         }
10418:     }
10419:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10420:         $cleanpath = $1;
10421:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10422:         my $curr_toprel = $1;
10423:         my @parts = split(/\//,$curr_toprel);
10424:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10425:         my @urlparts = split(/\//,$url_toprel);
10426:         my $doubledots;
10427:         my $startdiff = -1;
10428:         for (my $i=0; $i<@urlparts; $i++) {
10429:             if ($startdiff == -1) {
10430:                 unless ($urlparts[$i] eq $parts[$i]) {
10431:                     $startdiff = $i;
10432:                     $doubledots .= '../';
10433:                 }
10434:             } else {
10435:                 $doubledots .= '../';
10436:             }
10437:         }
10438:         if ($startdiff > -1) {
10439:             $cleanpath = $doubledots;
10440:             for (my $i=$startdiff; $i<@parts; $i++) {
10441:                 $cleanpath .= $parts[$i].'/';
10442:             }
10443:         }
10444:     }
10445:     $cleanpath =~ s{(/)$}{};
10446:     return $cleanpath;
10447: }
10448: 
10449: sub is_archive_file {
10450:     my ($mimetype) = @_;
10451:     if (($mimetype eq 'application/octet-stream') ||
10452:         ($mimetype eq 'application/x-stuffit') ||
10453:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10454:         return 1;
10455:     }
10456:     return;
10457: }
10458: 
10459: sub decompress_form {
10460:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10461:     my %lt = &Apache::lonlocal::texthash (
10462:         this => 'This file is an archive file.',
10463:         camt => 'This file is a Camtasia archive file.',
10464:         itsc => 'Its contents are as follows:',
10465:         youm => 'You may wish to extract its contents.',
10466:         extr => 'Extract contents',
10467:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10468:         proa => 'Process automatically?',
10469:         yes  => 'Yes',
10470:         no   => 'No',
10471:         fold => 'Title for folder containing movie',
10472:         movi => 'Title for page containing embedded movie', 
10473:     );
10474:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10475:     my ($is_camtasia,$topdir,%toplevel,@paths);
10476:     my $info = &list_archive_contents($fileloc,\@paths);
10477:     if (@paths) {
10478:         foreach my $path (@paths) {
10479:             $path =~ s{^/}{};
10480:             if ($path =~ m{^([^/]+)/$}) {
10481:                 $topdir = $1;
10482:             }
10483:             if ($path =~ m{^([^/]+)/}) {
10484:                 $toplevel{$1} = $path;
10485:             } else {
10486:                 $toplevel{$path} = $path;
10487:             }
10488:         }
10489:     }
10490:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10491:         my @camtasia = ("$topdir/","$topdir/index.html",
10492:                         "$topdir/media/",
10493:                         "$topdir/media/$topdir.mp4",
10494:                         "$topdir/media/FirstFrame.png",
10495:                         "$topdir/media/player.swf",
10496:                         "$topdir/media/swfobject.js",
10497:                         "$topdir/media/expressInstall.swf");
10498:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10499:         if (@diffs == 0) {
10500:             $is_camtasia = 1;
10501:         }
10502:     }
10503:     my $output;
10504:     if ($is_camtasia) {
10505:         $output = <<"ENDCAM";
10506: <script type="text/javascript" language="Javascript">
10507: // <![CDATA[
10508: 
10509: function camtasiaToggle() {
10510:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10511:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10512:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10513: 
10514:                 document.getElementById('camtasia_titles').style.display='block';
10515:             } else {
10516:                 document.getElementById('camtasia_titles').style.display='none';
10517:             }
10518:         }
10519:     }
10520:     return;
10521: }
10522: 
10523: // ]]>
10524: </script>
10525: <p>$lt{'camt'}</p>
10526: ENDCAM
10527:     } else {
10528:         $output = '<p>'.$lt{'this'};
10529:         if ($info eq '') {
10530:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
10531:         } else {
10532:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10533:                        '<div><pre>'.$info.'</pre></div>';
10534:         }
10535:     }
10536:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10537:     my $duplicates;
10538:     my $num = 0;
10539:     if (ref($dirlist) eq 'ARRAY') {
10540:         foreach my $item (@{$dirlist}) {
10541:             if (ref($item) eq 'ARRAY') {
10542:                 if (exists($toplevel{$item->[0]})) {
10543:                     $duplicates .= 
10544:                         &start_data_table_row().
10545:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10546:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
10547:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
10548:                         'value="1" />'.&mt('Yes').'</label>'.
10549:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10550:                         '<td>'.$item->[0].'</td>';
10551:                     if ($item->[2]) {
10552:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
10553:                     } else {
10554:                         $duplicates .= '<td>'.&mt('File').'</td>';
10555:                     }
10556:                     $duplicates .= '<td>'.$item->[3].'</td>'.
10557:                                    '<td>'.
10558:                                    &Apache::lonlocal::locallocaltime($item->[4]).
10559:                                    '</td>'.
10560:                                    &end_data_table_row();
10561:                     $num ++;
10562:                 }
10563:             }
10564:         }
10565:     }
10566:     my $itemcount;
10567:     if (@paths > 0) {
10568:         $itemcount = scalar(@paths);
10569:     } else {
10570:         $itemcount = 1;
10571:     }
10572:     if ($is_camtasia) {
10573:         $output .= $lt{'auto'}.'<br />'.
10574:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10575:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10576:                    $lt{'yes'}.'</label>&nbsp;<label>'.
10577:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10578:                    $lt{'no'}.'</label></span><br />'.
10579:                    '<div id="camtasia_titles" style="display:block">'.
10580:                    &Apache::lonhtmlcommon::start_pick_box().
10581:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10582:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10583:                    &Apache::lonhtmlcommon::row_closure().
10584:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10585:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10586:                    &Apache::lonhtmlcommon::row_closure(1).
10587:                    &Apache::lonhtmlcommon::end_pick_box().
10588:                    '</div>';
10589:     }
10590:     $output .= 
10591:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10592:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10593:         "\n";
10594:     if ($duplicates ne '') {
10595:         $output .= '<p><span class="LC_warning">'.
10596:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
10597:                    &start_data_table().
10598:                    &start_data_table_header_row().
10599:                    '<th>'.&mt('Overwrite?').'</th>'.
10600:                    '<th>'.&mt('Name').'</th>'.
10601:                    '<th>'.&mt('Type').'</th>'.
10602:                    '<th>'.&mt('Size').'</th>'.
10603:                    '<th>'.&mt('Last modified').'</th>'.
10604:                    &end_data_table_header_row().
10605:                    $duplicates.
10606:                    &end_data_table().
10607:                    '</p>';
10608:     }
10609:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10610:     if (ref($hiddenelements) eq 'HASH') {
10611:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10612:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10613:         }
10614:     }
10615:     $output .= <<"END";
10616: <br />
10617: <input type="submit" name="decompress" value="$lt{'extr'}" />
10618: </form>
10619: $noextract
10620: END
10621:     return $output;
10622: }
10623: 
10624: sub decompression_utility {
10625:     my ($program) = @_;
10626:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
10627:     my $location;
10628:     if (grep(/^\Q$program\E$/,@utilities)) { 
10629:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10630:                          '/usr/sbin/') {
10631:             if (-x $dir.$program) {
10632:                 $location = $dir.$program;
10633:                 last;
10634:             }
10635:         }
10636:     }
10637:     return $location;
10638: }
10639: 
10640: sub list_archive_contents {
10641:     my ($file,$pathsref) = @_;
10642:     my (@cmd,$output);
10643:     my $needsregexp;
10644:     if ($file =~ /\.zip$/) {
10645:         @cmd = (&decompression_utility('unzip'),"-l");
10646:         $needsregexp = 1;
10647:     } elsif (($file =~ m/\.tar\.gz$/) ||
10648:              ($file =~ /\.tgz$/)) {
10649:         @cmd = (&decompression_utility('tar'),"-ztf");
10650:     } elsif ($file =~ /\.tar\.bz2$/) {
10651:         @cmd = (&decompression_utility('tar'),"-jtf");
10652:     } elsif ($file =~ m|\.tar$|) {
10653:         @cmd = (&decompression_utility('tar'),"-tf");
10654:     }
10655:     if (@cmd) {
10656:         undef($!);
10657:         undef($@);
10658:         if (open(my $fh,"-|", @cmd, $file)) {
10659:             while (my $line = <$fh>) {
10660:                 $output .= $line;
10661:                 chomp($line);
10662:                 my $item;
10663:                 if ($needsregexp) {
10664:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
10665:                 } else {
10666:                     $item = $line;
10667:                 }
10668:                 if ($item ne '') {
10669:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10670:                         push(@{$pathsref},$item);
10671:                     } 
10672:                 }
10673:             }
10674:             close($fh);
10675:         }
10676:     }
10677:     return $output;
10678: }
10679: 
10680: sub decompress_uploaded_file {
10681:     my ($file,$dir) = @_;
10682:     &Apache::lonnet::appenv({'cgi.file' => $file});
10683:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
10684:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10685:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10686:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10687:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10688:     my $decompressed = $env{'cgi.decompressed'};
10689:     &Apache::lonnet::delenv('cgi.file');
10690:     &Apache::lonnet::delenv('cgi.dir');
10691:     &Apache::lonnet::delenv('cgi.decompressed');
10692:     return ($decompressed,$result);
10693: }
10694: 
10695: sub process_decompression {
10696:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10697:     my ($dir,$error,$warning,$output);
10698:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10699:         $error = &mt('File name not a supported archive file type.').
10700:                  '<br />'.&mt('File name should end with one of: [_1].',
10701:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10702:     } else {
10703:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10704:         if ($docuhome eq 'no_host') {
10705:             $error = &mt('Could not determine home server for course.');
10706:         } else {
10707:             my @ids=&Apache::lonnet::current_machine_ids();
10708:             my $currdir = "$dir_root/$destination";
10709:             if (grep(/^\Q$docuhome\E$/,@ids)) {
10710:                 $dir = &LONCAPA::propath($docudom,$docuname).
10711:                        "$dir_root/$destination";
10712:             } else {
10713:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10714:                        "$dir_root/$docudom/$docuname/$destination";
10715:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10716:                     $error = &mt('Archive file not found.');
10717:                 }
10718:             }
10719:             my (@to_overwrite,@to_skip);
10720:             if ($env{'form.archive_overwrite_total'} > 0) {
10721:                 my $total = $env{'form.archive_overwrite_total'};
10722:                 for (my $i=0; $i<$total; $i++) {
10723:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
10724:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10725:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10726:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10727:                     }
10728:                 }
10729:             }
10730:             my $numskip = scalar(@to_skip);
10731:             if (($numskip > 0) && 
10732:                 ($numskip == $env{'form.archive_itemcount'})) {
10733:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
10734:             } elsif ($dir eq '') {
10735:                 $error = &mt('Directory containing archive file unavailable.');
10736:             } elsif (!$error) {
10737:                 my ($decompressed,$display);
10738:                 if ($numskip > 0) {
10739:                     my $tempdir = time.'_'.$$.int(rand(10000));
10740:                     mkdir("$dir/$tempdir",0755);
10741:                     system("mv $dir/$file $dir/$tempdir/$file");
10742:                     ($decompressed,$display) = 
10743:                         &decompress_uploaded_file($file,"$dir/$tempdir");
10744:                     foreach my $item (@to_skip) {
10745:                         if (($item ne '') && ($item !~ /\.\./)) {
10746:                             if (-f "$dir/$tempdir/$item") { 
10747:                                 unlink("$dir/$tempdir/$item");
10748:                             } elsif (-d "$dir/$tempdir/$item") {
10749:                                 system("rm -rf $dir/$tempdir/$item");
10750:                             }
10751:                         }
10752:                     }
10753:                     system("mv $dir/$tempdir/* $dir");
10754:                     rmdir("$dir/$tempdir");   
10755:                 } else {
10756:                     ($decompressed,$display) = 
10757:                         &decompress_uploaded_file($file,$dir);
10758:                 }
10759:                 if ($decompressed eq 'ok') {
10760:                     $output = '<p class="LC_info">'.
10761:                               &mt('Files extracted successfully from archive.').
10762:                               '</p>'."\n";
10763:                     my ($warning,$result,@contents);
10764:                     my ($newdirlistref,$newlisterror) =
10765:                         &Apache::lonnet::dirlist($currdir,$docudom,
10766:                                                  $docuname,1);
10767:                     my (%is_dir,%changes,@newitems);
10768:                     my $dirptr = 16384;
10769:                     if (ref($newdirlistref) eq 'ARRAY') {
10770:                         foreach my $dir_line (@{$newdirlistref}) {
10771:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10772:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
10773:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10774:                                 push(@newitems,$item);
10775:                                 if ($dirptr&$testdir) {
10776:                                     $is_dir{$item} = 1;
10777:                                 }
10778:                                 $changes{$item} = 1;
10779:                             }
10780:                         }
10781:                     }
10782:                     if (keys(%changes) > 0) {
10783:                         foreach my $item (sort(@newitems)) {
10784:                             if ($changes{$item}) {
10785:                                 push(@contents,$item);
10786:                             }
10787:                         }
10788:                     }
10789:                     if (@contents > 0) {
10790:                         my $wantform;
10791:                         unless ($env{'form.autoextract_camtasia'}) {
10792:                             $wantform = 1;
10793:                         }
10794:                         my (%children,%parent,%dirorder,%titles);
10795:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
10796:                                                                 $currdir,\%is_dir,
10797:                                                                 \%children,\%parent,
10798:                                                                 \@contents,\%dirorder,
10799:                                                                 \%titles,$wantform);
10800:                         if ($datatable ne '') {
10801:                             $output .= &archive_options_form('decompressed',$datatable,
10802:                                                              $count,$hiddenelem);
10803:                             my $startcount = 6;
10804:                             $output .= &archive_javascript($startcount,$count,
10805:                                                            \%titles,\%children);
10806:                         }
10807:                         if ($env{'form.autoextract_camtasia'}) {
10808:                             my %displayed;
10809:                             my $total = 1;
10810:                             $env{'form.archive_directory'} = [];
10811:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
10812:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
10813:                                 $path =~ s{/$}{};
10814:                                 my $item;
10815:                                 if ($path ne '') {
10816:                                     $item = "$path/$titles{$i}";
10817:                                 } else {
10818:                                     $item = $titles{$i};
10819:                                 }
10820:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
10821:                                 if ($item eq $contents[0]) {
10822:                                     push(@{$env{'form.archive_directory'}},$i);
10823:                                     $env{'form.archive_'.$i} = 'display';
10824:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
10825:                                     $displayed{'folder'} = $i;
10826:                                 } elsif ($item eq "$contents[0]/index.html") {
10827:                                     $env{'form.archive_'.$i} = 'display';
10828:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
10829:                                     $displayed{'web'} = $i;
10830:                                 } else {
10831:                                     if ($item eq "$contents[0]/media") {
10832:                                         push(@{$env{'form.archive_directory'}},$i);
10833:                                     }
10834:                                     $env{'form.archive_'.$i} = 'dependency';
10835:                                 }
10836:                                 $total ++;
10837:                             }
10838:                             for (my $i=1; $i<$total; $i++) {
10839:                                 next if ($i == $displayed{'web'});
10840:                                 next if ($i == $displayed{'folder'});
10841:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
10842:                             }
10843:                             $env{'form.phase'} = 'decompress_cleanup';
10844:                             $env{'form.archivedelete'} = 1;
10845:                             $env{'form.archive_count'} = $total-1;
10846:                             $output .=
10847:                                 &process_extracted_files('coursedocs',$docudom,
10848:                                                          $docuname,$destination,
10849:                                                          $dir_root,$hiddenelem);
10850:                         }
10851:                     } else {
10852:                         $warning = &mt('No new items extracted from archive file.');
10853:                     }
10854:                 } else {
10855:                     $output = $display;
10856:                     $error = &mt('An error occurred during extraction from the archive file.');
10857:                 }
10858:             }
10859:         }
10860:     }
10861:     if ($error) {
10862:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10863:                    $error.'</p>'."\n";
10864:     }
10865:     if ($warning) {
10866:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10867:     }
10868:     return $output;
10869: }
10870: 
10871: sub get_extracted {
10872:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10873:         $titles,$wantform) = @_;
10874:     my $count = 0;
10875:     my $depth = 0;
10876:     my $datatable;
10877:     my @hierarchy;
10878:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10879:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10880:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10881:     foreach my $item (@{$contents}) {
10882:         $count ++;
10883:         @{$dirorder->{$count}} = @hierarchy;
10884:         $titles->{$count} = $item;
10885:         &archive_hierarchy($depth,$count,$parent,$children);
10886:         if ($wantform) {
10887:             $datatable .= &archive_row($is_dir->{$item},$item,
10888:                                        $currdir,$depth,$count);
10889:         }
10890:         if ($is_dir->{$item}) {
10891:             $depth ++;
10892:             push(@hierarchy,$count);
10893:             $parent->{$depth} = $count;
10894:             $datatable .=
10895:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10896:                                            \$depth,\$count,\@hierarchy,$dirorder,
10897:                                            $children,$parent,$titles,$wantform);
10898:             $depth --;
10899:             pop(@hierarchy);
10900:         }
10901:     }
10902:     return ($count,$datatable);
10903: }
10904: 
10905: sub recurse_extracted_archive {
10906:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
10907:         $children,$parent,$titles,$wantform) = @_;
10908:     my $result='';
10909:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
10910:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
10911:             (ref($dirorder) eq 'HASH')) {
10912:         return $result;
10913:     }
10914:     my $dirptr = 16384;
10915:     my ($newdirlistref,$newlisterror) =
10916:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
10917:     if (ref($newdirlistref) eq 'ARRAY') {
10918:         foreach my $dir_line (@{$newdirlistref}) {
10919:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10920:             unless ($item =~ /^\.+$/) {
10921:                 $$count ++;
10922:                 @{$dirorder->{$$count}} = @{$hierarchy};
10923:                 $titles->{$$count} = $item;
10924:                 &archive_hierarchy($$depth,$$count,$parent,$children);
10925: 
10926:                 my $is_dir;
10927:                 if ($dirptr&$testdir) {
10928:                     $is_dir = 1;
10929:                 }
10930:                 if ($wantform) {
10931:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
10932:                 }
10933:                 if ($is_dir) {
10934:                     $$depth ++;
10935:                     push(@{$hierarchy},$$count);
10936:                     $parent->{$$depth} = $$count;
10937:                     $result .=
10938:                         &recurse_extracted_archive("$currdir/$item",$docudom,
10939:                                                    $docuname,$depth,$count,
10940:                                                    $hierarchy,$dirorder,$children,
10941:                                                    $parent,$titles,$wantform);
10942:                     $$depth --;
10943:                     pop(@{$hierarchy});
10944:                 }
10945:             }
10946:         }
10947:     }
10948:     return $result;
10949: }
10950: 
10951: sub archive_hierarchy {
10952:     my ($depth,$count,$parent,$children) =@_;
10953:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
10954:         if (exists($parent->{$depth})) {
10955:              $children->{$parent->{$depth}} .= $count.':';
10956:         }
10957:     }
10958:     return;
10959: }
10960: 
10961: sub archive_row {
10962:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
10963:     my ($name) = ($item =~ m{([^/]+)$});
10964:     my %choices = &Apache::lonlocal::texthash (
10965:                                        'display'    => 'Add as file',
10966:                                        'dependency' => 'Include as dependency',
10967:                                        'discard'    => 'Discard',
10968:                                       );
10969:     if ($is_dir) {
10970:         $choices{'display'} = &mt('Add as folder'); 
10971:     }
10972:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
10973:     my $offset = 0;
10974:     foreach my $action ('display','dependency','discard') {
10975:         $offset ++;
10976:         if ($action ne 'display') {
10977:             $offset ++;
10978:         }  
10979:         $output .= '<td><span class="LC_nobreak">'.
10980:                    '<label><input type="radio" name="archive_'.$count.
10981:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
10982:         my $text = $choices{$action};
10983:         if ($is_dir) {
10984:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
10985:             if ($action eq 'display') {
10986:                 $text = &mt('Add as folder');
10987:             }
10988:         } else {
10989:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
10990: 
10991:         }
10992:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
10993:         if ($action eq 'dependency') {
10994:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
10995:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
10996:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
10997:                        '<option value=""></option>'."\n".
10998:                        '</select>'."\n".
10999:                        '</div>';
11000:         } elsif ($action eq 'display') {
11001:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11002:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11003:                        '</div>';
11004:         }
11005:         $output .= '</td>';
11006:     }
11007:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11008:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11009:     for (my $i=0; $i<$depth; $i++) {
11010:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11011:     }
11012:     if ($is_dir) {
11013:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11014:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11015:     } else {
11016:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11017:     }
11018:     $output .= '&nbsp;'.$name.'</td>'."\n".
11019:                &end_data_table_row();
11020:     return $output;
11021: }
11022: 
11023: sub archive_options_form {
11024:     my ($form,$display,$count,$hiddenelem) = @_;
11025:     my %lt = &Apache::lonlocal::texthash(
11026:                perm => 'Permanently remove archive file?',
11027:                hows => 'How should each extracted item be incorporated in the course?',
11028:                cont => 'Content actions for all',
11029:                addf => 'Add as folder/file',
11030:                incd => 'Include as dependency for a displayed file',
11031:                disc => 'Discard',
11032:                no   => 'No',
11033:                yes  => 'Yes',
11034:                save => 'Save',
11035:     );
11036:     my $output = <<"END";
11037: <form name="$form" method="post" action="">
11038: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11039: <label>
11040:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11041: </label>
11042: &nbsp;
11043: <label>
11044:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11045: </span>
11046: </p>
11047: <input type="hidden" name="phase" value="decompress_cleanup" />
11048: <br />$lt{'hows'}
11049: <div class="LC_columnSection">
11050:   <fieldset>
11051:     <legend>$lt{'cont'}</legend>
11052:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11053:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11054:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11055:   </fieldset>
11056: </div>
11057: END
11058:     return $output.
11059:            &start_data_table()."\n".
11060:            $display."\n".
11061:            &end_data_table()."\n".
11062:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11063:            $hiddenelem.
11064:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11065:            '</form>';
11066: }
11067: 
11068: sub archive_javascript {
11069:     my ($startcount,$numitems,$titles,$children) = @_;
11070:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11071:     my $maintitle = $env{'form.comment'};
11072:     my $scripttag = <<START;
11073: <script type="text/javascript">
11074: // <![CDATA[
11075: 
11076: function checkAll(form,prefix) {
11077:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11078:     for (var i=0; i < form.elements.length; i++) {
11079:         var id = form.elements[i].id;
11080:         if ((id != '') && (id != undefined)) {
11081:             if (idstr.test(id)) {
11082:                 if (form.elements[i].type == 'radio') {
11083:                     form.elements[i].checked = true;
11084:                     var nostart = i-$startcount;
11085:                     var offset = nostart%7;
11086:                     var count = (nostart-offset)/7;    
11087:                     dependencyCheck(form,count,offset);
11088:                 }
11089:             }
11090:         }
11091:     }
11092: }
11093: 
11094: function propagateCheck(form,count) {
11095:     if (count > 0) {
11096:         var startelement = $startcount + ((count-1) * 7);
11097:         for (var j=1; j<6; j++) {
11098:             if ((j != 2) && (j != 4)) {
11099:                 var item = startelement + j; 
11100:                 if (form.elements[item].type == 'radio') {
11101:                     if (form.elements[item].checked) {
11102:                         containerCheck(form,count,j);
11103:                         break;
11104:                     }
11105:                 }
11106:             }
11107:         }
11108:     }
11109: }
11110: 
11111: numitems = $numitems
11112: var titles = new Array(numitems);
11113: var parents = new Array(numitems);
11114: for (var i=0; i<numitems; i++) {
11115:     parents[i] = new Array;
11116: }
11117: var maintitle = '$maintitle';
11118: 
11119: START
11120: 
11121:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11122:         my @contents = split(/:/,$children->{$container});
11123:         for (my $i=0; $i<@contents; $i ++) {
11124:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11125:         }
11126:     }
11127: 
11128:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11129:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11130:     }
11131: 
11132:     $scripttag .= <<END;
11133: 
11134: function containerCheck(form,count,offset) {
11135:     if (count > 0) {
11136:         dependencyCheck(form,count,offset);
11137:         var item = (offset+$startcount)+7*(count-1);
11138:         form.elements[item].checked = true;
11139:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11140:             if (parents[count].length > 0) {
11141:                 for (var j=0; j<parents[count].length; j++) {
11142:                     containerCheck(form,parents[count][j],offset);
11143:                 }
11144:             }
11145:         }
11146:     }
11147: }
11148: 
11149: function dependencyCheck(form,count,offset) {
11150:     if (count > 0) {
11151:         var chosen = (offset+$startcount)+7*(count-1);
11152:         var depitem = $startcount + ((count-1) * 7) + 4;
11153:         var currtype = form.elements[depitem].type;
11154:         if (form.elements[chosen].value == 'dependency') {
11155:             document.getElementById('arc_depon_'+count).style.display='block'; 
11156:             form.elements[depitem].options.length = 0;
11157:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11158:             for (var i=1; i<=numitems; i++) {
11159:                 if (i == count) {
11160:                     continue;
11161:                 }
11162:                 var startelement = $startcount + (i-1) * 7;
11163:                 for (var j=1; j<6; j++) {
11164:                     if ((j != 2) && (j!= 4)) {
11165:                         var item = startelement + j;
11166:                         if (form.elements[item].type == 'radio') {
11167:                             if (form.elements[item].checked) {
11168:                                 if (form.elements[item].value == 'display') {
11169:                                     var n = form.elements[depitem].options.length;
11170:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11171:                                 }
11172:                             }
11173:                         }
11174:                     }
11175:                 }
11176:             }
11177:         } else {
11178:             document.getElementById('arc_depon_'+count).style.display='none';
11179:             form.elements[depitem].options.length = 0;
11180:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11181:         }
11182:         titleCheck(form,count,offset);
11183:     }
11184: }
11185: 
11186: function propagateSelect(form,count,offset) {
11187:     if (count > 0) {
11188:         var item = (1+offset+$startcount)+7*(count-1);
11189:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11190:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11191:             if (parents[count].length > 0) {
11192:                 for (var j=0; j<parents[count].length; j++) {
11193:                     containerSelect(form,parents[count][j],offset,picked);
11194:                 }
11195:             }
11196:         }
11197:     }
11198: }
11199: 
11200: function containerSelect(form,count,offset,picked) {
11201:     if (count > 0) {
11202:         var item = (offset+$startcount)+7*(count-1);
11203:         if (form.elements[item].type == 'radio') {
11204:             if (form.elements[item].value == 'dependency') {
11205:                 if (form.elements[item+1].type == 'select-one') {
11206:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11207:                         if (form.elements[item+1].options[i].value == picked) {
11208:                             form.elements[item+1].selectedIndex = i;
11209:                             break;
11210:                         }
11211:                     }
11212:                 }
11213:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11214:                     if (parents[count].length > 0) {
11215:                         for (var j=0; j<parents[count].length; j++) {
11216:                             containerSelect(form,parents[count][j],offset,picked);
11217:                         }
11218:                     }
11219:                 }
11220:             }
11221:         }
11222:     }
11223: }
11224: 
11225: function titleCheck(form,count,offset) {
11226:     if (count > 0) {
11227:         var chosen = (offset+$startcount)+7*(count-1);
11228:         var depitem = $startcount + ((count-1) * 7) + 2;
11229:         var currtype = form.elements[depitem].type;
11230:         if (form.elements[chosen].value == 'display') {
11231:             document.getElementById('arc_title_'+count).style.display='block';
11232:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11233:                 document.getElementById('archive_title_'+count).value=maintitle;
11234:             }
11235:         } else {
11236:             document.getElementById('arc_title_'+count).style.display='none';
11237:             if (currtype == 'text') { 
11238:                 document.getElementById('archive_title_'+count).value='';
11239:             }
11240:         }
11241:     }
11242:     return;
11243: }
11244: 
11245: // ]]>
11246: </script>
11247: END
11248:     return $scripttag;
11249: }
11250: 
11251: sub process_extracted_files {
11252:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11253:     my $numitems = $env{'form.archive_count'};
11254:     return unless ($numitems);
11255:     my @ids=&Apache::lonnet::current_machine_ids();
11256:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11257:         %folders,%containers,%mapinner,%prompttofetch);
11258:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11259:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11260:         $prefix = &LONCAPA::propath($docudom,$docuname);
11261:         $pathtocheck = "$dir_root/$destination";
11262:         $dir = $dir_root;
11263:         $ishome = 1;
11264:     } else {
11265:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11266:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11267:         $dir = "$dir_root/$docudom/$docuname";    
11268:     }
11269:     my $currdir = "$dir_root/$destination";
11270:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11271:     if ($env{'form.folderpath'}) {
11272:         my @items = split('&',$env{'form.folderpath'});
11273:         $folders{'0'} = $items[-2];
11274:         $containers{'0'}='sequence';
11275:     } elsif ($env{'form.pagepath'}) {
11276:         my @items = split('&',$env{'form.pagepath'});
11277:         $folders{'0'} = $items[-2];
11278:         $containers{'0'}='page';
11279:     }
11280:     my @archdirs = &get_env_multiple('form.archive_directory');
11281:     if ($numitems) {
11282:         for (my $i=1; $i<=$numitems; $i++) {
11283:             my $path = $env{'form.archive_content_'.$i};
11284:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11285:                 my $item = $1;
11286:                 $toplevelitems{$item} = $i;
11287:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11288:                     $is_dir{$item} = 1;
11289:                 }
11290:             }
11291:         }
11292:     }
11293:     my ($output,%children,%parent,%titles,%dirorder,$result);
11294:     if (keys(%toplevelitems) > 0) {
11295:         my @contents = sort(keys(%toplevelitems));
11296:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11297:                                            \%parent,\@contents,\%dirorder,\%titles);
11298:     }
11299:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11300:     if ($numitems) {
11301:         for (my $i=1; $i<=$numitems; $i++) {
11302:             next if ($env{'form.archive_'.$i} eq 'dependency');
11303:             my $path = $env{'form.archive_content_'.$i};
11304:             if ($path =~ /^\Q$pathtocheck\E/) {
11305:                 if ($env{'form.archive_'.$i} eq 'discard') {
11306:                     if ($prefix ne '' && $path ne '') {
11307:                         if (-e $prefix.$path) {
11308:                             if ((@archdirs > 0) && 
11309:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11310:                                 $todeletedir{$prefix.$path} = 1;
11311:                             } else {
11312:                                 $todelete{$prefix.$path} = 1;
11313:                             }
11314:                         }
11315:                     }
11316:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11317:                     my ($docstitle,$title,$url,$outer);
11318:                     ($title) = ($path =~ m{/([^/]+)$});
11319:                     $docstitle = $env{'form.archive_title_'.$i};
11320:                     if ($docstitle eq '') {
11321:                         $docstitle = $title;
11322:                     }
11323:                     $outer = 0;
11324:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11325:                         if (@{$dirorder{$i}} > 0) {
11326:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11327:                                 if ($env{'form.archive_'.$item} eq 'display') {
11328:                                     $outer = $item;
11329:                                     last;
11330:                                 }
11331:                             }
11332:                         }
11333:                     }
11334:                     my ($errtext,$fatal) = 
11335:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11336:                                                '/'.$folders{$outer}.'.'.
11337:                                                $containers{$outer});
11338:                     next if ($fatal);
11339:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11340:                         if ($context eq 'coursedocs') {
11341:                             $mapinner{$i} = time;
11342:                             $folders{$i} = 'default_'.$mapinner{$i};
11343:                             $containers{$i} = 'sequence';
11344:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11345:                                       $folders{$i}.'.'.$containers{$i};
11346:                             my $newidx = &LONCAPA::map::getresidx();
11347:                             $LONCAPA::map::resources[$newidx]=
11348:                                 $docstitle.':'.$url.':false:normal:res';
11349:                             push(@LONCAPA::map::order,$newidx);
11350:                             my ($outtext,$errtext) =
11351:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11352:                                                         $docuname.'/'.$folders{$outer}.
11353:                                                         '.'.$containers{$outer},1,1);
11354:                             $newseqid{$i} = $newidx;
11355:                             unless ($errtext) {
11356:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11357:                             }
11358:                         }
11359:                     } else {
11360:                         if ($context eq 'coursedocs') {
11361:                             my $newidx=&LONCAPA::map::getresidx();
11362:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11363:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11364:                                       $title;
11365:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11366:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11367:                             }
11368:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11369:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11370:                             }
11371:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11372:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11373:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11374:                                 unless ($ishome) {
11375:                                     my $fetch = "$newdest{$i}/$title";
11376:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11377:                                     $prompttofetch{$fetch} = 1;
11378:                                 }
11379:                             }
11380:                             $LONCAPA::map::resources[$newidx]=
11381:                                 $docstitle.':'.$url.':false:normal:res';
11382:                             push(@LONCAPA::map::order, $newidx);
11383:                             my ($outtext,$errtext)=
11384:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11385:                                                         $docuname.'/'.$folders{$outer}.
11386:                                                         '.'.$containers{$outer},1,1);
11387:                             unless ($errtext) {
11388:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11389:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11390:                                 }
11391:                             }
11392:                         }
11393:                     }
11394:                 }
11395:             } else {
11396:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11397:             }
11398:         }
11399:         for (my $i=1; $i<=$numitems; $i++) {
11400:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11401:             my $path = $env{'form.archive_content_'.$i};
11402:             if ($path =~ /^\Q$pathtocheck\E/) {
11403:                 my ($title) = ($path =~ m{/([^/]+)$});
11404:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11405:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11406:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11407:                         my ($itemidx,$fullpath,$relpath);
11408:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11409:                             my $container = $dirorder{$referrer{$i}}->[-1];
11410:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11411:                                 if ($dirorder{$i}->[$j] eq $container) {
11412:                                     $itemidx = $j;
11413:                                 }
11414:                             }
11415:                         }
11416:                         if ($itemidx eq '') {
11417:                             $itemidx =  0;
11418:                         }
11419:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11420:                             if ($mapinner{$referrer{$i}}) {
11421:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11422:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11423:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11424:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11425:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11426:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11427:                                             if (!-e $fullpath) {
11428:                                                 mkdir($fullpath,0755);
11429:                                             }
11430:                                         }
11431:                                     } else {
11432:                                         last;
11433:                                     }
11434:                                 }
11435:                             }
11436:                         } elsif ($newdest{$referrer{$i}}) {
11437:                             $fullpath = $newdest{$referrer{$i}};
11438:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11439:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11440:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11441:                                     last;
11442:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11443:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11444:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11445:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11446:                                         if (!-e $fullpath) {
11447:                                             mkdir($fullpath,0755);
11448:                                         }
11449:                                     }
11450:                                 } else {
11451:                                     last;
11452:                                 }
11453:                             }
11454:                         }
11455:                         if ($fullpath ne '') {
11456:                             if (-e "$prefix$path") {
11457:                                 system("mv $prefix$path $fullpath/$title");
11458:                             }
11459:                             if (-e "$fullpath/$title") {
11460:                                 my $showpath;
11461:                                 if ($relpath ne '') {
11462:                                     $showpath = "$relpath/$title";
11463:                                 } else {
11464:                                     $showpath = "/$title";
11465:                                 }
11466:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11467:                             }
11468:                             unless ($ishome) {
11469:                                 my $fetch = "$fullpath/$title";
11470:                                 $fetch =~ s/^\Q$prefix$dir\E//;
11471:                                 $prompttofetch{$fetch} = 1;
11472:                             }
11473:                         }
11474:                     }
11475:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11476:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11477:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11478:                 }
11479:             } else {
11480:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11481:             }
11482:         }
11483:         if (keys(%todelete)) {
11484:             foreach my $key (keys(%todelete)) {
11485:                 unlink($key);
11486:             }
11487:         }
11488:         if (keys(%todeletedir)) {
11489:             foreach my $key (keys(%todeletedir)) {
11490:                 rmdir($key);
11491:             }
11492:         }
11493:         foreach my $dir (sort(keys(%is_dir))) {
11494:             if (($pathtocheck ne '') && ($dir ne ''))  {
11495:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11496:             }
11497:         }
11498:         if ($result ne '') {
11499:             $output .= '<ul>'."\n".
11500:                        $result."\n".
11501:                        '</ul>';
11502:         }
11503:         unless ($ishome) {
11504:             my $replicationfail;
11505:             foreach my $item (keys(%prompttofetch)) {
11506:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11507:                 unless ($fetchresult eq 'ok') {
11508:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
11509:                 }
11510:             }
11511:             if ($replicationfail) {
11512:                 $output .= '<p class="LC_error">'.
11513:                            &mt('Course home server failed to retrieve:').'<ul>'.
11514:                            $replicationfail.
11515:                            '</ul></p>';
11516:             }
11517:         }
11518:     } else {
11519:         $warning = &mt('No items found in archive.');
11520:     }
11521:     if ($error) {
11522:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11523:                    $error.'</p>'."\n";
11524:     }
11525:     if ($warning) {
11526:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11527:     }
11528:     return $output;
11529: }
11530: 
11531: sub cleanup_empty_dirs {
11532:     my ($path) = @_;
11533:     if (($path ne '') && (-d $path)) {
11534:         if (opendir(my $dirh,$path)) {
11535:             my @dircontents = grep(!/^\./,readdir($dirh));
11536:             my $numitems = 0;
11537:             foreach my $item (@dircontents) {
11538:                 if (-d "$path/$item") {
11539:                     &recurse_dirs("$path/$item");
11540:                     if (-e "$path/$item") {
11541:                         $numitems ++;
11542:                     }
11543:                 } else {
11544:                     $numitems ++;
11545:                 }
11546:             }
11547:             if ($numitems == 0) {
11548:                 rmdir($path);
11549:             }
11550:             closedir($dirh);
11551:         }
11552:     }
11553:     return;
11554: }
11555: 
11556: =pod
11557: 
11558: =item &get_folder_hierarchy()
11559: 
11560: Provides hierarchy of names of folders/sub-folders containing the current
11561: item,
11562: 
11563: Inputs: 3
11564:      - $navmap - navmaps object
11565: 
11566:      - $map - url for map (either the trigger itself, or map containing
11567:                            the resource, which is the trigger).
11568: 
11569:      - $showitem - 1 => show title for map itself; 0 => do not show.
11570: 
11571: Outputs: 1 @pathitems - array of folder/subfolder names.
11572: 
11573: =cut
11574: 
11575: sub get_folder_hierarchy {
11576:     my ($navmap,$map,$showitem) = @_;
11577:     my @pathitems;
11578:     if (ref($navmap)) {
11579:         my $mapres = $navmap->getResourceByUrl($map);
11580:         if (ref($mapres)) {
11581:             my $pcslist = $mapres->map_hierarchy();
11582:             if ($pcslist ne '') {
11583:                 my @pcs = split(/,/,$pcslist);
11584:                 foreach my $pc (@pcs) {
11585:                     if ($pc == 1) {
11586:                         push(@pathitems,&mt('Main Course Documents'));
11587:                     } else {
11588:                         my $res = $navmap->getByMapPc($pc);
11589:                         if (ref($res)) {
11590:                             my $title = $res->compTitle();
11591:                             $title =~ s/\W+/_/g;
11592:                             if ($title ne '') {
11593:                                 push(@pathitems,$title);
11594:                             }
11595:                         }
11596:                     }
11597:                 }
11598:             }
11599:             if ($showitem) {
11600:                 if ($mapres->{ID} eq '0.0') {
11601:                     push(@pathitems,&mt('Main Course Documents'));
11602:                 } else {
11603:                     my $maptitle = $mapres->compTitle();
11604:                     $maptitle =~ s/\W+/_/g;
11605:                     if ($maptitle ne '') {
11606:                         push(@pathitems,$maptitle);
11607:                     }
11608:                 }
11609:             }
11610:         }
11611:     }
11612:     return @pathitems;
11613: }
11614: 
11615: =pod
11616: 
11617: =item * &get_turnedin_filepath()
11618: 
11619: Determines path in a user's portfolio file for storage of files uploaded
11620: to a specific essayresponse or dropbox item.
11621: 
11622: Inputs: 3 required + 1 optional.
11623: $symb is symb for resource, $uname and $udom are for current user (required).
11624: $caller is optional (can be "submission", if routine is called when storing
11625: an upoaded file when "Submit Answer" button was pressed).
11626: 
11627: Returns array containing $path and $multiresp. 
11628: $path is path in portfolio.  $multiresp is 1 if this resource contains more
11629: than one file upload item.  Callers of routine should append partid as a 
11630: subdirectory to $path in cases where $multiresp is 1.
11631: 
11632: Called by: homework/essayresponse.pm and homework/structuretags.pm
11633: 
11634: =cut
11635: 
11636: sub get_turnedin_filepath {
11637:     my ($symb,$uname,$udom,$caller) = @_;
11638:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11639:     my $turnindir;
11640:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11641:     $turnindir = $userhash{'turnindir'};
11642:     my ($path,$multiresp);
11643:     if ($turnindir eq '') {
11644:         if ($caller eq 'submission') {
11645:             $turnindir = &mt('turned in');
11646:             $turnindir =~ s/\W+/_/g;
11647:             my %newhash = (
11648:                             'turnindir' => $turnindir,
11649:                           );
11650:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11651:         }
11652:     }
11653:     if ($turnindir ne '') {
11654:         $path = '/'.$turnindir.'/';
11655:         my ($multipart,$turnin,@pathitems);
11656:         my $navmap = Apache::lonnavmaps::navmap->new();
11657:         if (defined($navmap)) {
11658:             my $mapres = $navmap->getResourceByUrl($map);
11659:             if (ref($mapres)) {
11660:                 my $pcslist = $mapres->map_hierarchy();
11661:                 if ($pcslist ne '') {
11662:                     foreach my $pc (split(/,/,$pcslist)) {
11663:                         my $res = $navmap->getByMapPc($pc);
11664:                         if (ref($res)) {
11665:                             my $title = $res->compTitle();
11666:                             $title =~ s/\W+/_/g;
11667:                             if ($title ne '') {
11668:                                 push(@pathitems,$title);
11669:                             }
11670:                         }
11671:                     }
11672:                 }
11673:                 my $maptitle = $mapres->compTitle();
11674:                 $maptitle =~ s/\W+/_/g;
11675:                 if ($maptitle ne '') {
11676:                     push(@pathitems,$maptitle);
11677:                 }
11678:                 unless ($env{'request.state'} eq 'construct') {
11679:                     my $res = $navmap->getBySymb($symb);
11680:                     if (ref($res)) {
11681:                         my $partlist = $res->parts();
11682:                         my $totaluploads = 0;
11683:                         if (ref($partlist) eq 'ARRAY') {
11684:                             foreach my $part (@{$partlist}) {
11685:                                 my @types = $res->responseType($part);
11686:                                 my @ids = $res->responseIds($part);
11687:                                 for (my $i=0; $i < scalar(@ids); $i++) {
11688:                                     if ($types[$i] eq 'essay') {
11689:                                         my $partid = $part.'_'.$ids[$i];
11690:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11691:                                             $totaluploads ++;
11692:                                         }
11693:                                     }
11694:                                 }
11695:                             }
11696:                             if ($totaluploads > 1) {
11697:                                 $multiresp = 1;
11698:                             }
11699:                         }
11700:                     }
11701:                 }
11702:             } else {
11703:                 return;
11704:             }
11705:         } else {
11706:             return;
11707:         }
11708:         my $restitle=&Apache::lonnet::gettitle($symb);
11709:         $restitle =~ s/\W+/_/g;
11710:         if ($restitle eq '') {
11711:             $restitle = ($resurl =~ m{/[^/]+$});
11712:             if ($restitle eq '') {
11713:                 $restitle = time;
11714:             }
11715:         }
11716:         push(@pathitems,$restitle);
11717:         $path .= join('/',@pathitems);
11718:     }
11719:     return ($path,$multiresp);
11720: }
11721: 
11722: =pod
11723: 
11724: =back
11725: 
11726: =head1 CSV Upload/Handling functions
11727: 
11728: =over 4
11729: 
11730: =item * &upfile_store($r)
11731: 
11732: Store uploaded file, $r should be the HTTP Request object,
11733: needs $env{'form.upfile'}
11734: returns $datatoken to be put into hidden field
11735: 
11736: =cut
11737: 
11738: sub upfile_store {
11739:     my $r=shift;
11740:     $env{'form.upfile'}=~s/\r/\n/gs;
11741:     $env{'form.upfile'}=~s/\f/\n/gs;
11742:     $env{'form.upfile'}=~s/\n+/\n/gs;
11743:     $env{'form.upfile'}=~s/\n+$//gs;
11744: 
11745:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11746: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11747:     {
11748:         my $datafile = $r->dir_config('lonDaemons').
11749:                            '/tmp/'.$datatoken.'.tmp';
11750:         if ( open(my $fh,">$datafile") ) {
11751:             print $fh $env{'form.upfile'};
11752:             close($fh);
11753:         }
11754:     }
11755:     return $datatoken;
11756: }
11757: 
11758: =pod
11759: 
11760: =item * &load_tmp_file($r)
11761: 
11762: Load uploaded file from tmp, $r should be the HTTP Request object,
11763: needs $env{'form.datatoken'},
11764: sets $env{'form.upfile'} to the contents of the file
11765: 
11766: =cut
11767: 
11768: sub load_tmp_file {
11769:     my $r=shift;
11770:     my @studentdata=();
11771:     {
11772:         my $studentfile = $r->dir_config('lonDaemons').
11773:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
11774:         if ( open(my $fh,"<$studentfile") ) {
11775:             @studentdata=<$fh>;
11776:             close($fh);
11777:         }
11778:     }
11779:     $env{'form.upfile'}=join('',@studentdata);
11780: }
11781: 
11782: =pod
11783: 
11784: =item * &upfile_record_sep()
11785: 
11786: Separate uploaded file into records
11787: returns array of records,
11788: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11789: 
11790: =cut
11791: 
11792: sub upfile_record_sep {
11793:     if ($env{'form.upfiletype'} eq 'xml') {
11794:     } else {
11795: 	my @records;
11796: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
11797: 	    if ($line=~/^\s*$/) { next; }
11798: 	    push(@records,$line);
11799: 	}
11800: 	return @records;
11801:     }
11802: }
11803: 
11804: =pod
11805: 
11806: =item * &record_sep($record)
11807: 
11808: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11809: 
11810: =cut
11811: 
11812: sub takeleft {
11813:     my $index=shift;
11814:     return substr('0000'.$index,-4,4);
11815: }
11816: 
11817: sub record_sep {
11818:     my $record=shift;
11819:     my %components=();
11820:     if ($env{'form.upfiletype'} eq 'xml') {
11821:     } elsif ($env{'form.upfiletype'} eq 'space') {
11822:         my $i=0;
11823:         foreach my $field (split(/\s+/,$record)) {
11824:             $field=~s/^(\"|\')//;
11825:             $field=~s/(\"|\')$//;
11826:             $components{&takeleft($i)}=$field;
11827:             $i++;
11828:         }
11829:     } elsif ($env{'form.upfiletype'} eq 'tab') {
11830:         my $i=0;
11831:         foreach my $field (split(/\t/,$record)) {
11832:             $field=~s/^(\"|\')//;
11833:             $field=~s/(\"|\')$//;
11834:             $components{&takeleft($i)}=$field;
11835:             $i++;
11836:         }
11837:     } else {
11838:         my $separator=',';
11839:         if ($env{'form.upfiletype'} eq 'semisv') {
11840:             $separator=';';
11841:         }
11842:         my $i=0;
11843: # the character we are looking for to indicate the end of a quote or a record 
11844:         my $looking_for=$separator;
11845: # do not add the characters to the fields
11846:         my $ignore=0;
11847: # we just encountered a separator (or the beginning of the record)
11848:         my $just_found_separator=1;
11849: # store the field we are working on here
11850:         my $field='';
11851: # work our way through all characters in record
11852:         foreach my $character ($record=~/(.)/g) {
11853:             if ($character eq $looking_for) {
11854:                if ($character ne $separator) {
11855: # Found the end of a quote, again looking for separator
11856:                   $looking_for=$separator;
11857:                   $ignore=1;
11858:                } else {
11859: # Found a separator, store away what we got
11860:                   $components{&takeleft($i)}=$field;
11861: 	          $i++;
11862:                   $just_found_separator=1;
11863:                   $ignore=0;
11864:                   $field='';
11865:                }
11866:                next;
11867:             }
11868: # single or double quotation marks after a separator indicate beginning of a quote
11869: # we are now looking for the end of the quote and need to ignore separators
11870:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
11871:                $looking_for=$character;
11872:                next;
11873:             }
11874: # ignore would be true after we reached the end of a quote
11875:             if ($ignore) { next; }
11876:             if (($just_found_separator) && ($character=~/\s/)) { next; }
11877:             $field.=$character;
11878:             $just_found_separator=0; 
11879:         }
11880: # catch the very last entry, since we never encountered the separator
11881:         $components{&takeleft($i)}=$field;
11882:     }
11883:     return %components;
11884: }
11885: 
11886: ######################################################
11887: ######################################################
11888: 
11889: =pod
11890: 
11891: =item * &upfile_select_html()
11892: 
11893: Return HTML code to select a file from the users machine and specify 
11894: the file type.
11895: 
11896: =cut
11897: 
11898: ######################################################
11899: ######################################################
11900: sub upfile_select_html {
11901:     my %Types = (
11902:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
11903:                  semisv => &mt('Semicolon separated values'),
11904:                  space => &mt('Space separated'),
11905:                  tab   => &mt('Tabulator separated'),
11906: #                 xml   => &mt('HTML/XML'),
11907:                  );
11908:     my $Str = '<input type="file" name="upfile" size="50" />'.
11909:         '<br />'.&mt('Type').': <select name="upfiletype">';
11910:     foreach my $type (sort(keys(%Types))) {
11911:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
11912:     }
11913:     $Str .= "</select>\n";
11914:     return $Str;
11915: }
11916: 
11917: sub get_samples {
11918:     my ($records,$toget) = @_;
11919:     my @samples=({});
11920:     my $got=0;
11921:     foreach my $rec (@$records) {
11922: 	my %temp = &record_sep($rec);
11923: 	if (! grep(/\S/, values(%temp))) { next; }
11924: 	if (%temp) {
11925: 	    $samples[$got]=\%temp;
11926: 	    $got++;
11927: 	    if ($got == $toget) { last; }
11928: 	}
11929:     }
11930:     return \@samples;
11931: }
11932: 
11933: ######################################################
11934: ######################################################
11935: 
11936: =pod
11937: 
11938: =item * &csv_print_samples($r,$records)
11939: 
11940: Prints a table of sample values from each column uploaded $r is an
11941: Apache Request ref, $records is an arrayref from
11942: &Apache::loncommon::upfile_record_sep
11943: 
11944: =cut
11945: 
11946: ######################################################
11947: ######################################################
11948: sub csv_print_samples {
11949:     my ($r,$records) = @_;
11950:     my $samples = &get_samples($records,5);
11951: 
11952:     $r->print(&mt('Samples').'<br />'.&start_data_table().
11953:               &start_data_table_header_row());
11954:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
11955:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
11956:     $r->print(&end_data_table_header_row());
11957:     foreach my $hash (@$samples) {
11958: 	$r->print(&start_data_table_row());
11959: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
11960: 	    $r->print('<td>');
11961: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
11962: 	    $r->print('</td>');
11963: 	}
11964: 	$r->print(&end_data_table_row());
11965:     }
11966:     $r->print(&end_data_table().'<br />'."\n");
11967: }
11968: 
11969: ######################################################
11970: ######################################################
11971: 
11972: =pod
11973: 
11974: =item * &csv_print_select_table($r,$records,$d)
11975: 
11976: Prints a table to create associations between values and table columns.
11977: 
11978: $r is an Apache Request ref,
11979: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
11980: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
11981: 
11982: =cut
11983: 
11984: ######################################################
11985: ######################################################
11986: sub csv_print_select_table {
11987:     my ($r,$records,$d) = @_;
11988:     my $i=0;
11989:     my $samples = &get_samples($records,1);
11990:     $r->print(&mt('Associate columns with student attributes.')."\n".
11991: 	      &start_data_table().&start_data_table_header_row().
11992:               '<th>'.&mt('Attribute').'</th>'.
11993:               '<th>'.&mt('Column').'</th>'.
11994:               &end_data_table_header_row()."\n");
11995:     foreach my $array_ref (@$d) {
11996: 	my ($value,$display,$defaultcol)=@{ $array_ref };
11997: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
11998: 
11999: 	$r->print('<td><select name="f'.$i.'"'.
12000: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12001: 	$r->print('<option value="none"></option>');
12002: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12003: 	    $r->print('<option value="'.$sample.'"'.
12004:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12005:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12006: 	}
12007: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12008: 	$i++;
12009:     }
12010:     $r->print(&end_data_table());
12011:     $i--;
12012:     return $i;
12013: }
12014: 
12015: ######################################################
12016: ######################################################
12017: 
12018: =pod
12019: 
12020: =item * &csv_samples_select_table($r,$records,$d)
12021: 
12022: Prints a table of sample values from the upload and can make associate samples to internal names.
12023: 
12024: $r is an Apache Request ref,
12025: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12026: $d is an array of 2 element arrays (internal name, displayed name)
12027: 
12028: =cut
12029: 
12030: ######################################################
12031: ######################################################
12032: sub csv_samples_select_table {
12033:     my ($r,$records,$d) = @_;
12034:     my $i=0;
12035:     #
12036:     my $max_samples = 5;
12037:     my $samples = &get_samples($records,$max_samples);
12038:     $r->print(&start_data_table().
12039:               &start_data_table_header_row().'<th>'.
12040:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12041:               &end_data_table_header_row());
12042: 
12043:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12044: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12045: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12046: 	foreach my $option (@$d) {
12047: 	    my ($value,$display,$defaultcol)=@{ $option };
12048: 	    $r->print('<option value="'.$value.'"'.
12049:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12050:                       $display.'</option>');
12051: 	}
12052: 	$r->print('</select></td><td>');
12053: 	foreach my $line (0..($max_samples-1)) {
12054: 	    if (defined($samples->[$line]{$key})) { 
12055: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12056: 	    }
12057: 	}
12058: 	$r->print('</td>'.&end_data_table_row());
12059: 	$i++;
12060:     }
12061:     $r->print(&end_data_table());
12062:     $i--;
12063:     return($i);
12064: }
12065: 
12066: ######################################################
12067: ######################################################
12068: 
12069: =pod
12070: 
12071: =item * &clean_excel_name($name)
12072: 
12073: Returns a replacement for $name which does not contain any illegal characters.
12074: 
12075: =cut
12076: 
12077: ######################################################
12078: ######################################################
12079: sub clean_excel_name {
12080:     my ($name) = @_;
12081:     $name =~ s/[:\*\?\/\\]//g;
12082:     if (length($name) > 31) {
12083:         $name = substr($name,0,31);
12084:     }
12085:     return $name;
12086: }
12087: 
12088: =pod
12089: 
12090: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12091: 
12092: Returns either 1 or undef
12093: 
12094: 1 if the part is to be hidden, undef if it is to be shown
12095: 
12096: Arguments are:
12097: 
12098: $id the id of the part to be checked
12099: $symb, optional the symb of the resource to check
12100: $udom, optional the domain of the user to check for
12101: $uname, optional the username of the user to check for
12102: 
12103: =cut
12104: 
12105: sub check_if_partid_hidden {
12106:     my ($id,$symb,$udom,$uname) = @_;
12107:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12108: 					 $symb,$udom,$uname);
12109:     my $truth=1;
12110:     #if the string starts with !, then the list is the list to show not hide
12111:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12112:     my @hiddenlist=split(/,/,$hiddenparts);
12113:     foreach my $checkid (@hiddenlist) {
12114: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12115:     }
12116:     return !$truth;
12117: }
12118: 
12119: 
12120: ############################################################
12121: ############################################################
12122: 
12123: =pod
12124: 
12125: =back 
12126: 
12127: =head1 cgi-bin script and graphing routines
12128: 
12129: =over 4
12130: 
12131: =item * &get_cgi_id()
12132: 
12133: Inputs: none
12134: 
12135: Returns an id which can be used to pass environment variables
12136: to various cgi-bin scripts.  These environment variables will
12137: be removed from the users environment after a given time by
12138: the routine &Apache::lonnet::transfer_profile_to_env.
12139: 
12140: =cut
12141: 
12142: ############################################################
12143: ############################################################
12144: my $uniq=0;
12145: sub get_cgi_id {
12146:     $uniq=($uniq+1)%100000;
12147:     return (time.'_'.$$.'_'.$uniq);
12148: }
12149: 
12150: ############################################################
12151: ############################################################
12152: 
12153: =pod
12154: 
12155: =item * &DrawBarGraph()
12156: 
12157: Facilitates the plotting of data in a (stacked) bar graph.
12158: Puts plot definition data into the users environment in order for 
12159: graph.png to plot it.  Returns an <img> tag for the plot.
12160: The bars on the plot are labeled '1','2',...,'n'.
12161: 
12162: Inputs:
12163: 
12164: =over 4
12165: 
12166: =item $Title: string, the title of the plot
12167: 
12168: =item $xlabel: string, text describing the X-axis of the plot
12169: 
12170: =item $ylabel: string, text describing the Y-axis of the plot
12171: 
12172: =item $Max: scalar, the maximum Y value to use in the plot
12173: If $Max is < any data point, the graph will not be rendered.
12174: 
12175: =item $colors: array ref holding the colors to be used for the data sets when
12176: they are plotted.  If undefined, default values will be used.
12177: 
12178: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12179: 
12180: =item @Values: An array of array references.  Each array reference holds data
12181: to be plotted in a stacked bar chart.
12182: 
12183: =item If the final element of @Values is a hash reference the key/value
12184: pairs will be added to the graph definition.
12185: 
12186: =back
12187: 
12188: Returns:
12189: 
12190: An <img> tag which references graph.png and the appropriate identifying
12191: information for the plot.
12192: 
12193: =cut
12194: 
12195: ############################################################
12196: ############################################################
12197: sub DrawBarGraph {
12198:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12199:     #
12200:     if (! defined($colors)) {
12201:         $colors = ['#33ff00', 
12202:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12203:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12204:                   ]; 
12205:     }
12206:     my $extra_settings = {};
12207:     if (ref($Values[-1]) eq 'HASH') {
12208:         $extra_settings = pop(@Values);
12209:     }
12210:     #
12211:     my $identifier = &get_cgi_id();
12212:     my $id = 'cgi.'.$identifier;        
12213:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12214:         return '';
12215:     }
12216:     #
12217:     my @Labels;
12218:     if (defined($labels)) {
12219:         @Labels = @$labels;
12220:     } else {
12221:         for (my $i=0;$i<@{$Values[0]};$i++) {
12222:             push (@Labels,$i+1);
12223:         }
12224:     }
12225:     #
12226:     my $NumBars = scalar(@{$Values[0]});
12227:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12228:     my %ValuesHash;
12229:     my $NumSets=1;
12230:     foreach my $array (@Values) {
12231:         next if (! ref($array));
12232:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12233:             join(',',@$array);
12234:     }
12235:     #
12236:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12237:     if ($NumBars < 3) {
12238:         $width = 120+$NumBars*32;
12239:         $xskip = 1;
12240:         $bar_width = 30;
12241:     } elsif ($NumBars < 5) {
12242:         $width = 120+$NumBars*20;
12243:         $xskip = 1;
12244:         $bar_width = 20;
12245:     } elsif ($NumBars < 10) {
12246:         $width = 120+$NumBars*15;
12247:         $xskip = 1;
12248:         $bar_width = 15;
12249:     } elsif ($NumBars <= 25) {
12250:         $width = 120+$NumBars*11;
12251:         $xskip = 5;
12252:         $bar_width = 8;
12253:     } elsif ($NumBars <= 50) {
12254:         $width = 120+$NumBars*8;
12255:         $xskip = 5;
12256:         $bar_width = 4;
12257:     } else {
12258:         $width = 120+$NumBars*8;
12259:         $xskip = 5;
12260:         $bar_width = 4;
12261:     }
12262:     #
12263:     $Max = 1 if ($Max < 1);
12264:     if ( int($Max) < $Max ) {
12265:         $Max++;
12266:         $Max = int($Max);
12267:     }
12268:     $Title  = '' if (! defined($Title));
12269:     $xlabel = '' if (! defined($xlabel));
12270:     $ylabel = '' if (! defined($ylabel));
12271:     $ValuesHash{$id.'.title'}    = &escape($Title);
12272:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12273:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12274:     $ValuesHash{$id.'.y_max_value'} = $Max;
12275:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12276:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12277:     $ValuesHash{$id.'.PlotType'} = 'bar';
12278:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12279:     $ValuesHash{$id.'.height'}   = $height;
12280:     $ValuesHash{$id.'.width'}    = $width;
12281:     $ValuesHash{$id.'.xskip'}    = $xskip;
12282:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12283:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12284:     #
12285:     # Deal with other parameters
12286:     while (my ($key,$value) = each(%$extra_settings)) {
12287:         $ValuesHash{$id.'.'.$key} = $value;
12288:     }
12289:     #
12290:     &Apache::lonnet::appenv(\%ValuesHash);
12291:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12292: }
12293: 
12294: ############################################################
12295: ############################################################
12296: 
12297: =pod
12298: 
12299: =item * &DrawXYGraph()
12300: 
12301: Facilitates the plotting of data in an XY graph.
12302: Puts plot definition data into the users environment in order for 
12303: graph.png to plot it.  Returns an <img> tag for the plot.
12304: 
12305: Inputs:
12306: 
12307: =over 4
12308: 
12309: =item $Title: string, the title of the plot
12310: 
12311: =item $xlabel: string, text describing the X-axis of the plot
12312: 
12313: =item $ylabel: string, text describing the Y-axis of the plot
12314: 
12315: =item $Max: scalar, the maximum Y value to use in the plot
12316: If $Max is < any data point, the graph will not be rendered.
12317: 
12318: =item $colors: Array ref containing the hex color codes for the data to be 
12319: plotted in.  If undefined, default values will be used.
12320: 
12321: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12322: 
12323: =item $Ydata: Array ref containing Array refs.  
12324: Each of the contained arrays will be plotted as a separate curve.
12325: 
12326: =item %Values: hash indicating or overriding any default values which are 
12327: passed to graph.png.  
12328: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12329: 
12330: =back
12331: 
12332: Returns:
12333: 
12334: An <img> tag which references graph.png and the appropriate identifying
12335: information for the plot.
12336: 
12337: =cut
12338: 
12339: ############################################################
12340: ############################################################
12341: sub DrawXYGraph {
12342:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12343:     #
12344:     # Create the identifier for the graph
12345:     my $identifier = &get_cgi_id();
12346:     my $id = 'cgi.'.$identifier;
12347:     #
12348:     $Title  = '' if (! defined($Title));
12349:     $xlabel = '' if (! defined($xlabel));
12350:     $ylabel = '' if (! defined($ylabel));
12351:     my %ValuesHash = 
12352:         (
12353:          $id.'.title'  => &escape($Title),
12354:          $id.'.xlabel' => &escape($xlabel),
12355:          $id.'.ylabel' => &escape($ylabel),
12356:          $id.'.y_max_value'=> $Max,
12357:          $id.'.labels'     => join(',',@$Xlabels),
12358:          $id.'.PlotType'   => 'XY',
12359:          );
12360:     #
12361:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12362:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12363:     }
12364:     #
12365:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12366:         return '';
12367:     }
12368:     my $NumSets=1;
12369:     foreach my $array (@{$Ydata}){
12370:         next if (! ref($array));
12371:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12372:     }
12373:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12374:     #
12375:     # Deal with other parameters
12376:     while (my ($key,$value) = each(%Values)) {
12377:         $ValuesHash{$id.'.'.$key} = $value;
12378:     }
12379:     #
12380:     &Apache::lonnet::appenv(\%ValuesHash);
12381:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12382: }
12383: 
12384: ############################################################
12385: ############################################################
12386: 
12387: =pod
12388: 
12389: =item * &DrawXYYGraph()
12390: 
12391: Facilitates the plotting of data in an XY graph with two Y axes.
12392: Puts plot definition data into the users environment in order for 
12393: graph.png to plot it.  Returns an <img> tag for the plot.
12394: 
12395: Inputs:
12396: 
12397: =over 4
12398: 
12399: =item $Title: string, the title of the plot
12400: 
12401: =item $xlabel: string, text describing the X-axis of the plot
12402: 
12403: =item $ylabel: string, text describing the Y-axis of the plot
12404: 
12405: =item $colors: Array ref containing the hex color codes for the data to be 
12406: plotted in.  If undefined, default values will be used.
12407: 
12408: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12409: 
12410: =item $Ydata1: The first data set
12411: 
12412: =item $Min1: The minimum value of the left Y-axis
12413: 
12414: =item $Max1: The maximum value of the left Y-axis
12415: 
12416: =item $Ydata2: The second data set
12417: 
12418: =item $Min2: The minimum value of the right Y-axis
12419: 
12420: =item $Max2: The maximum value of the left Y-axis
12421: 
12422: =item %Values: hash indicating or overriding any default values which are 
12423: passed to graph.png.  
12424: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12425: 
12426: =back
12427: 
12428: Returns:
12429: 
12430: An <img> tag which references graph.png and the appropriate identifying
12431: information for the plot.
12432: 
12433: =cut
12434: 
12435: ############################################################
12436: ############################################################
12437: sub DrawXYYGraph {
12438:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12439:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12440:     #
12441:     # Create the identifier for the graph
12442:     my $identifier = &get_cgi_id();
12443:     my $id = 'cgi.'.$identifier;
12444:     #
12445:     $Title  = '' if (! defined($Title));
12446:     $xlabel = '' if (! defined($xlabel));
12447:     $ylabel = '' if (! defined($ylabel));
12448:     my %ValuesHash = 
12449:         (
12450:          $id.'.title'  => &escape($Title),
12451:          $id.'.xlabel' => &escape($xlabel),
12452:          $id.'.ylabel' => &escape($ylabel),
12453:          $id.'.labels' => join(',',@$Xlabels),
12454:          $id.'.PlotType' => 'XY',
12455:          $id.'.NumSets' => 2,
12456:          $id.'.two_axes' => 1,
12457:          $id.'.y1_max_value' => $Max1,
12458:          $id.'.y1_min_value' => $Min1,
12459:          $id.'.y2_max_value' => $Max2,
12460:          $id.'.y2_min_value' => $Min2,
12461:          );
12462:     #
12463:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12464:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12465:     }
12466:     #
12467:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12468:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12469:         return '';
12470:     }
12471:     my $NumSets=1;
12472:     foreach my $array ($Ydata1,$Ydata2){
12473:         next if (! ref($array));
12474:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12475:     }
12476:     #
12477:     # Deal with other parameters
12478:     while (my ($key,$value) = each(%Values)) {
12479:         $ValuesHash{$id.'.'.$key} = $value;
12480:     }
12481:     #
12482:     &Apache::lonnet::appenv(\%ValuesHash);
12483:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12484: }
12485: 
12486: ############################################################
12487: ############################################################
12488: 
12489: =pod
12490: 
12491: =back 
12492: 
12493: =head1 Statistics helper routines?  
12494: 
12495: Bad place for them but what the hell.
12496: 
12497: =over 4
12498: 
12499: =item * &chartlink()
12500: 
12501: Returns a link to the chart for a specific student.  
12502: 
12503: Inputs:
12504: 
12505: =over 4
12506: 
12507: =item $linktext: The text of the link
12508: 
12509: =item $sname: The students username
12510: 
12511: =item $sdomain: The students domain
12512: 
12513: =back
12514: 
12515: =back
12516: 
12517: =cut
12518: 
12519: ############################################################
12520: ############################################################
12521: sub chartlink {
12522:     my ($linktext, $sname, $sdomain) = @_;
12523:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12524:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
12525:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
12526:        '">'.$linktext.'</a>';
12527: }
12528: 
12529: #######################################################
12530: #######################################################
12531: 
12532: =pod
12533: 
12534: =head1 Course Environment Routines
12535: 
12536: =over 4
12537: 
12538: =item * &restore_course_settings()
12539: 
12540: =item * &store_course_settings()
12541: 
12542: Restores/Store indicated form parameters from the course environment.
12543: Will not overwrite existing values of the form parameters.
12544: 
12545: Inputs: 
12546: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12547: 
12548: a hash ref describing the data to be stored.  For example:
12549:    
12550: %Save_Parameters = ('Status' => 'scalar',
12551:     'chartoutputmode' => 'scalar',
12552:     'chartoutputdata' => 'scalar',
12553:     'Section' => 'array',
12554:     'Group' => 'array',
12555:     'StudentData' => 'array',
12556:     'Maps' => 'array');
12557: 
12558: Returns: both routines return nothing
12559: 
12560: =back
12561: 
12562: =cut
12563: 
12564: #######################################################
12565: #######################################################
12566: sub store_course_settings {
12567:     return &store_settings($env{'request.course.id'},@_);
12568: }
12569: 
12570: sub store_settings {
12571:     # save to the environment
12572:     # appenv the same items, just to be safe
12573:     my $udom  = $env{'user.domain'};
12574:     my $uname = $env{'user.name'};
12575:     my ($context,$prefix,$Settings) = @_;
12576:     my %SaveHash;
12577:     my %AppHash;
12578:     while (my ($setting,$type) = each(%$Settings)) {
12579:         my $basename = join('.','internal',$context,$prefix,$setting);
12580:         my $envname = 'environment.'.$basename;
12581:         if (exists($env{'form.'.$setting})) {
12582:             # Save this value away
12583:             if ($type eq 'scalar' &&
12584:                 (! exists($env{$envname}) || 
12585:                  $env{$envname} ne $env{'form.'.$setting})) {
12586:                 $SaveHash{$basename} = $env{'form.'.$setting};
12587:                 $AppHash{$envname}   = $env{'form.'.$setting};
12588:             } elsif ($type eq 'array') {
12589:                 my $stored_form;
12590:                 if (ref($env{'form.'.$setting})) {
12591:                     $stored_form = join(',',
12592:                                         map {
12593:                                             &escape($_);
12594:                                         } sort(@{$env{'form.'.$setting}}));
12595:                 } else {
12596:                     $stored_form = 
12597:                         &escape($env{'form.'.$setting});
12598:                 }
12599:                 # Determine if the array contents are the same.
12600:                 if ($stored_form ne $env{$envname}) {
12601:                     $SaveHash{$basename} = $stored_form;
12602:                     $AppHash{$envname}   = $stored_form;
12603:                 }
12604:             }
12605:         }
12606:     }
12607:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12608:                                           $udom,$uname);
12609:     if ($put_result !~ /^(ok|delayed)/) {
12610:         &Apache::lonnet::logthis('unable to save form parameters, '.
12611:                                  'got error:'.$put_result);
12612:     }
12613:     # Make sure these settings stick around in this session, too
12614:     &Apache::lonnet::appenv(\%AppHash);
12615:     return;
12616: }
12617: 
12618: sub restore_course_settings {
12619:     return &restore_settings($env{'request.course.id'},@_);
12620: }
12621: 
12622: sub restore_settings {
12623:     my ($context,$prefix,$Settings) = @_;
12624:     while (my ($setting,$type) = each(%$Settings)) {
12625:         next if (exists($env{'form.'.$setting}));
12626:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
12627:             '.'.$setting;
12628:         if (exists($env{$envname})) {
12629:             if ($type eq 'scalar') {
12630:                 $env{'form.'.$setting} = $env{$envname};
12631:             } elsif ($type eq 'array') {
12632:                 $env{'form.'.$setting} = [ 
12633:                                            map { 
12634:                                                &unescape($_); 
12635:                                            } split(',',$env{$envname})
12636:                                            ];
12637:             }
12638:         }
12639:     }
12640: }
12641: 
12642: #######################################################
12643: #######################################################
12644: 
12645: =pod
12646: 
12647: =head1 Domain E-mail Routines  
12648: 
12649: =over 4
12650: 
12651: =item * &build_recipient_list()
12652: 
12653: Build recipient lists for five types of e-mail:
12654: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12655: (d) Help requests, (e) Course requests needing approval,  generated by
12656: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12657: loncoursequeueadmin.pm respectively.
12658: 
12659: Inputs:
12660: defmail (scalar - email address of default recipient), 
12661: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
12662: defdom (domain for which to retrieve configuration settings),
12663: origmail (scalar - email address of recipient from loncapa.conf, 
12664: i.e., predates configuration by DC via domainprefs.pm 
12665: 
12666: Returns: comma separated list of addresses to which to send e-mail.
12667: 
12668: =back
12669: 
12670: =cut
12671: 
12672: ############################################################
12673: ############################################################
12674: sub build_recipient_list {
12675:     my ($defmail,$mailing,$defdom,$origmail) = @_;
12676:     my @recipients;
12677:     my $otheremails;
12678:     my %domconfig =
12679:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12680:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12681:         if (exists($domconfig{'contacts'}{$mailing})) {
12682:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12683:                 my @contacts = ('adminemail','supportemail');
12684:                 foreach my $item (@contacts) {
12685:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
12686:                         my $addr = $domconfig{'contacts'}{$item}; 
12687:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
12688:                             push(@recipients,$addr);
12689:                         }
12690:                     }
12691:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12692:                 }
12693:             }
12694:         } elsif ($origmail ne '') {
12695:             push(@recipients,$origmail);
12696:         }
12697:     } elsif ($origmail ne '') {
12698:         push(@recipients,$origmail);
12699:     }
12700:     if (defined($defmail)) {
12701:         if ($defmail ne '') {
12702:             push(@recipients,$defmail);
12703:         }
12704:     }
12705:     if ($otheremails) {
12706:         my @others;
12707:         if ($otheremails =~ /,/) {
12708:             @others = split(/,/,$otheremails);
12709:         } else {
12710:             push(@others,$otheremails);
12711:         }
12712:         foreach my $addr (@others) {
12713:             if (!grep(/^\Q$addr\E$/,@recipients)) {
12714:                 push(@recipients,$addr);
12715:             }
12716:         }
12717:     }
12718:     my $recipientlist = join(',',@recipients); 
12719:     return $recipientlist;
12720: }
12721: 
12722: ############################################################
12723: ############################################################
12724: 
12725: =pod
12726: 
12727: =head1 Course Catalog Routines
12728: 
12729: =over 4
12730: 
12731: =item * &gather_categories()
12732: 
12733: Converts category definitions - keys of categories hash stored in  
12734: coursecategories in configuration.db on the primary library server in a 
12735: domain - to an array.  Also generates javascript and idx hash used to 
12736: generate Domain Coordinator interface for editing Course Categories.
12737: 
12738: Inputs:
12739: 
12740: categories (reference to hash of category definitions).
12741: 
12742: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12743:       categories and subcategories).
12744: 
12745: idx (reference to hash of counters used in Domain Coordinator interface for 
12746:       editing Course Categories).
12747: 
12748: jsarray (reference to array of categories used to create Javascript arrays for
12749:          Domain Coordinator interface for editing Course Categories).
12750: 
12751: Returns: nothing
12752: 
12753: Side effects: populates cats, idx and jsarray. 
12754: 
12755: =cut
12756: 
12757: sub gather_categories {
12758:     my ($categories,$cats,$idx,$jsarray) = @_;
12759:     my %counters;
12760:     my $num = 0;
12761:     foreach my $item (keys(%{$categories})) {
12762:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12763:         if ($container eq '' && $depth == 0) {
12764:             $cats->[$depth][$categories->{$item}] = $cat;
12765:         } else {
12766:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12767:         }
12768:         my ($escitem,$tail) = split(/:/,$item,2);
12769:         if ($counters{$tail} eq '') {
12770:             $counters{$tail} = $num;
12771:             $num ++;
12772:         }
12773:         if (ref($idx) eq 'HASH') {
12774:             $idx->{$item} = $counters{$tail};
12775:         }
12776:         if (ref($jsarray) eq 'ARRAY') {
12777:             push(@{$jsarray->[$counters{$tail}]},$item);
12778:         }
12779:     }
12780:     return;
12781: }
12782: 
12783: =pod
12784: 
12785: =item * &extract_categories()
12786: 
12787: Used to generate breadcrumb trails for course categories.
12788: 
12789: Inputs:
12790: 
12791: categories (reference to hash of category definitions).
12792: 
12793: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12794:       categories and subcategories).
12795: 
12796: trails (reference to array of breacrumb trails for each category).
12797: 
12798: allitems (reference to hash - key is category key 
12799:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12800: 
12801: idx (reference to hash of counters used in Domain Coordinator interface for
12802:       editing Course Categories).
12803: 
12804: jsarray (reference to array of categories used to create Javascript arrays for
12805:          Domain Coordinator interface for editing Course Categories).
12806: 
12807: subcats (reference to hash of arrays containing all subcategories within each 
12808:          category, -recursive)
12809: 
12810: Returns: nothing
12811: 
12812: Side effects: populates trails and allitems hash references.
12813: 
12814: =cut
12815: 
12816: sub extract_categories {
12817:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12818:     if (ref($categories) eq 'HASH') {
12819:         &gather_categories($categories,$cats,$idx,$jsarray);
12820:         if (ref($cats->[0]) eq 'ARRAY') {
12821:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
12822:                 my $name = $cats->[0][$i];
12823:                 my $item = &escape($name).'::0';
12824:                 my $trailstr;
12825:                 if ($name eq 'instcode') {
12826:                     $trailstr = &mt('Official courses (with institutional codes)');
12827:                 } elsif ($name eq 'communities') {
12828:                     $trailstr = &mt('Communities');
12829:                 } else {
12830:                     $trailstr = $name;
12831:                 }
12832:                 if ($allitems->{$item} eq '') {
12833:                     push(@{$trails},$trailstr);
12834:                     $allitems->{$item} = scalar(@{$trails})-1;
12835:                 }
12836:                 my @parents = ($name);
12837:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
12838:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12839:                         my $category = $cats->[1]{$name}[$j];
12840:                         if (ref($subcats) eq 'HASH') {
12841:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12842:                         }
12843:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12844:                     }
12845:                 } else {
12846:                     if (ref($subcats) eq 'HASH') {
12847:                         $subcats->{$item} = [];
12848:                     }
12849:                 }
12850:             }
12851:         }
12852:     }
12853:     return;
12854: }
12855: 
12856: =pod
12857: 
12858: =item *&recurse_categories()
12859: 
12860: Recursively used to generate breadcrumb trails for course categories.
12861: 
12862: Inputs:
12863: 
12864: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12865:       categories and subcategories).
12866: 
12867: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12868: 
12869: category (current course category, for which breadcrumb trail is being generated).
12870: 
12871: trails (reference to array of breadcrumb trails for each category).
12872: 
12873: allitems (reference to hash - key is category key
12874:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12875: 
12876: parents (array containing containers directories for current category, 
12877:          back to top level). 
12878: 
12879: Returns: nothing
12880: 
12881: Side effects: populates trails and allitems hash references
12882: 
12883: =cut
12884: 
12885: sub recurse_categories {
12886:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12887:     my $shallower = $depth - 1;
12888:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12889:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12890:             my $name = $cats->[$depth]{$category}[$k];
12891:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12892:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
12893:             if ($allitems->{$item} eq '') {
12894:                 push(@{$trails},$trailstr);
12895:                 $allitems->{$item} = scalar(@{$trails})-1;
12896:             }
12897:             my $deeper = $depth+1;
12898:             push(@{$parents},$category);
12899:             if (ref($subcats) eq 'HASH') {
12900:                 my $subcat = &escape($name).':'.$category.':'.$depth;
12901:                 for (my $j=@{$parents}; $j>=0; $j--) {
12902:                     my $higher;
12903:                     if ($j > 0) {
12904:                         $higher = &escape($parents->[$j]).':'.
12905:                                   &escape($parents->[$j-1]).':'.$j;
12906:                     } else {
12907:                         $higher = &escape($parents->[$j]).'::'.$j;
12908:                     }
12909:                     push(@{$subcats->{$higher}},$subcat);
12910:                 }
12911:             }
12912:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
12913:                                 $subcats);
12914:             pop(@{$parents});
12915:         }
12916:     } else {
12917:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12918:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
12919:         if ($allitems->{$item} eq '') {
12920:             push(@{$trails},$trailstr);
12921:             $allitems->{$item} = scalar(@{$trails})-1;
12922:         }
12923:     }
12924:     return;
12925: }
12926: 
12927: =pod
12928: 
12929: =item *&assign_categories_table()
12930: 
12931: Create a datatable for display of hierarchical categories in a domain,
12932: with checkboxes to allow a course to be categorized. 
12933: 
12934: Inputs:
12935: 
12936: cathash - reference to hash of categories defined for the domain (from
12937:           configuration.db)
12938: 
12939: currcat - scalar with an & separated list of categories assigned to a course. 
12940: 
12941: type    - scalar contains course type (Course or Community).
12942: 
12943: Returns: $output (markup to be displayed) 
12944: 
12945: =cut
12946: 
12947: sub assign_categories_table {
12948:     my ($cathash,$currcat,$type) = @_;
12949:     my $output;
12950:     if (ref($cathash) eq 'HASH') {
12951:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
12952:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
12953:         $maxdepth = scalar(@cats);
12954:         if (@cats > 0) {
12955:             my $itemcount = 0;
12956:             if (ref($cats[0]) eq 'ARRAY') {
12957:                 my @currcategories;
12958:                 if ($currcat ne '') {
12959:                     @currcategories = split('&',$currcat);
12960:                 }
12961:                 my $table;
12962:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
12963:                     my $parent = $cats[0][$i];
12964:                     next if ($parent eq 'instcode');
12965:                     if ($type eq 'Community') {
12966:                         next unless ($parent eq 'communities');
12967:                     } else {
12968:                         next if ($parent eq 'communities');
12969:                     }
12970:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
12971:                     my $item = &escape($parent).'::0';
12972:                     my $checked = '';
12973:                     if (@currcategories > 0) {
12974:                         if (grep(/^\Q$item\E$/,@currcategories)) {
12975:                             $checked = ' checked="checked"';
12976:                         }
12977:                     }
12978:                     my $parent_title = $parent;
12979:                     if ($parent eq 'communities') {
12980:                         $parent_title = &mt('Communities');
12981:                     }
12982:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
12983:                               '<input type="checkbox" name="usecategory" value="'.
12984:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
12985:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
12986:                     my $depth = 1;
12987:                     push(@path,$parent);
12988:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
12989:                     pop(@path);
12990:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
12991:                     $itemcount ++;
12992:                 }
12993:                 if ($itemcount) {
12994:                     $output = &Apache::loncommon::start_data_table().
12995:                               $table.
12996:                               &Apache::loncommon::end_data_table();
12997:                 }
12998:             }
12999:         }
13000:     }
13001:     return $output;
13002: }
13003: 
13004: =pod
13005: 
13006: =item *&assign_category_rows()
13007: 
13008: Create a datatable row for display of nested categories in a domain,
13009: with checkboxes to allow a course to be categorized,called recursively.
13010: 
13011: Inputs:
13012: 
13013: itemcount - track row number for alternating colors
13014: 
13015: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13016:       categories and subcategories.
13017: 
13018: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13019: 
13020: parent - parent of current category item
13021: 
13022: path - Array containing all categories back up through the hierarchy from the
13023:        current category to the top level.
13024: 
13025: currcategories - reference to array of current categories assigned to the course
13026: 
13027: Returns: $output (markup to be displayed).
13028: 
13029: =cut
13030: 
13031: sub assign_category_rows {
13032:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13033:     my ($text,$name,$item,$chgstr);
13034:     if (ref($cats) eq 'ARRAY') {
13035:         my $maxdepth = scalar(@{$cats});
13036:         if (ref($cats->[$depth]) eq 'HASH') {
13037:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13038:                 my $numchildren = @{$cats->[$depth]{$parent}};
13039:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13040:                 $text .= '<td><table class="LC_datatable">';
13041:                 for (my $j=0; $j<$numchildren; $j++) {
13042:                     $name = $cats->[$depth]{$parent}[$j];
13043:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13044:                     my $deeper = $depth+1;
13045:                     my $checked = '';
13046:                     if (ref($currcategories) eq 'ARRAY') {
13047:                         if (@{$currcategories} > 0) {
13048:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13049:                                 $checked = ' checked="checked"';
13050:                             }
13051:                         }
13052:                     }
13053:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13054:                              '<input type="checkbox" name="usecategory" value="'.
13055:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13056:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13057:                              '</td><td>';
13058:                     if (ref($path) eq 'ARRAY') {
13059:                         push(@{$path},$name);
13060:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13061:                         pop(@{$path});
13062:                     }
13063:                     $text .= '</td></tr>';
13064:                 }
13065:                 $text .= '</table></td>';
13066:             }
13067:         }
13068:     }
13069:     return $text;
13070: }
13071: 
13072: ############################################################
13073: ############################################################
13074: 
13075: 
13076: sub commit_customrole {
13077:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13078:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13079:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13080:                          ($end?', ending '.localtime($end):'').': <b>'.
13081:               &Apache::lonnet::assigncustomrole(
13082:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13083:                  '</b><br />';
13084:     return $output;
13085: }
13086: 
13087: sub commit_standardrole {
13088:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13089:     my ($output,$logmsg,$linefeed);
13090:     if ($context eq 'auto') {
13091:         $linefeed = "\n";
13092:     } else {
13093:         $linefeed = "<br />\n";
13094:     }  
13095:     if ($three eq 'st') {
13096:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13097:                                          $one,$two,$sec,$context);
13098:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13099:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13100:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13101:         } else {
13102:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13103:                ($start?', '.&mt('starting').' '.localtime($start):'').
13104:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13105:             if ($context eq 'auto') {
13106:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13107:             } else {
13108:                $output .= '<b>'.$result.'</b>'.$linefeed.
13109:                &mt('Add to classlist').': <b>ok</b>';
13110:             }
13111:             $output .= $linefeed;
13112:         }
13113:     } else {
13114:         $output = &mt('Assigning').' '.$three.' in '.$url.
13115:                ($start?', '.&mt('starting').' '.localtime($start):'').
13116:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13117:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13118:         if ($context eq 'auto') {
13119:             $output .= $result.$linefeed;
13120:         } else {
13121:             $output .= '<b>'.$result.'</b>'.$linefeed;
13122:         }
13123:     }
13124:     return $output;
13125: }
13126: 
13127: sub commit_studentrole {
13128:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13129:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13130:     if ($context eq 'auto') {
13131:         $linefeed = "\n";
13132:     } else {
13133:         $linefeed = '<br />'."\n";
13134:     }
13135:     if (defined($one) && defined($two)) {
13136:         my $cid=$one.'_'.$two;
13137:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13138:         my $secchange = 0;
13139:         my $expire_role_result;
13140:         my $modify_section_result;
13141:         if ($oldsec ne '-1') { 
13142:             if ($oldsec ne $sec) {
13143:                 $secchange = 1;
13144:                 my $now = time;
13145:                 my $uurl='/'.$cid;
13146:                 $uurl=~s/\_/\//g;
13147:                 if ($oldsec) {
13148:                     $uurl.='/'.$oldsec;
13149:                 }
13150:                 $oldsecurl = $uurl;
13151:                 $expire_role_result = 
13152:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13153:                 if ($env{'request.course.sec'} ne '') { 
13154:                     if ($expire_role_result eq 'refused') {
13155:                         my @roles = ('st');
13156:                         my @statuses = ('previous');
13157:                         my @roledoms = ($one);
13158:                         my $withsec = 1;
13159:                         my %roleshash = 
13160:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13161:                                               \@statuses,\@roles,\@roledoms,$withsec);
13162:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13163:                             my ($oldstart,$oldend) = 
13164:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13165:                             if ($oldend > 0 && $oldend <= $now) {
13166:                                 $expire_role_result = 'ok';
13167:                             }
13168:                         }
13169:                     }
13170:                 }
13171:                 $result = $expire_role_result;
13172:             }
13173:         }
13174:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13175:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
13176:             if ($modify_section_result =~ /^ok/) {
13177:                 if ($secchange == 1) {
13178:                     if ($sec eq '') {
13179:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13180:                     } else {
13181:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13182:                     }
13183:                 } elsif ($oldsec eq '-1') {
13184:                     if ($sec eq '') {
13185:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13186:                     } else {
13187:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13188:                     }
13189:                 } else {
13190:                     if ($sec eq '') {
13191:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13192:                     } else {
13193:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13194:                     }
13195:                 }
13196:             } else {
13197:                 if ($secchange) {       
13198:                     $$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;
13199:                 } else {
13200:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13201:                 }
13202:             }
13203:             $result = $modify_section_result;
13204:         } elsif ($secchange == 1) {
13205:             if ($oldsec eq '') {
13206:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13207:             } else {
13208:                 $$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;
13209:             }
13210:             if ($expire_role_result eq 'refused') {
13211:                 my $newsecurl = '/'.$cid;
13212:                 $newsecurl =~ s/\_/\//g;
13213:                 if ($sec ne '') {
13214:                     $newsecurl.='/'.$sec;
13215:                 }
13216:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13217:                     if ($sec eq '') {
13218:                         $$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;
13219:                     } else {
13220:                         $$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;
13221:                     }
13222:                 }
13223:             }
13224:         }
13225:     } else {
13226:         $$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;
13227:         $result = "error: incomplete course id\n";
13228:     }
13229:     return $result;
13230: }
13231: 
13232: ############################################################
13233: ############################################################
13234: 
13235: sub check_clone {
13236:     my ($args,$linefeed) = @_;
13237:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13238:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13239:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13240:     my $clonemsg;
13241:     my $can_clone = 0;
13242:     my $lctype = lc($args->{'crstype'});
13243:     if ($lctype ne 'community') {
13244:         $lctype = 'course';
13245:     }
13246:     if ($clonehome eq 'no_host') {
13247:         if ($args->{'crstype'} eq 'Community') {
13248:             $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'});
13249:         } else {
13250:             $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'});
13251:         }     
13252:     } else {
13253: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13254:         if ($args->{'crstype'} eq 'Community') {
13255:             if ($clonedesc{'type'} ne 'Community') {
13256:                  $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'});
13257:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13258:             }
13259:         }
13260: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13261:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13262: 	    $can_clone = 1;
13263: 	} else {
13264: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13265: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13266: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13267:             if (grep(/^\*$/,@cloners)) {
13268:                 $can_clone = 1;
13269:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13270:                 $can_clone = 1;
13271:             } else {
13272:                 my $ccrole = 'cc';
13273:                 if ($args->{'crstype'} eq 'Community') {
13274:                     $ccrole = 'co';
13275:                 }
13276: 	        my %roleshash =
13277: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13278: 					 $args->{'ccdomain'},
13279:                                          'userroles',['active'],[$ccrole],
13280: 					 [$args->{'clonedomain'}]);
13281: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13282:                     $can_clone = 1;
13283:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13284:                     $can_clone = 1;
13285:                 } else {
13286:                     if ($args->{'crstype'} eq 'Community') {
13287:                         $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'});
13288:                     } else {
13289:                         $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'});
13290:                     }
13291: 	        }
13292: 	    }
13293:         }
13294:     }
13295:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13296: }
13297: 
13298: sub construct_course {
13299:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13300:     my $outcome;
13301:     my $linefeed =  '<br />'."\n";
13302:     if ($context eq 'auto') {
13303:         $linefeed = "\n";
13304:     }
13305: 
13306: #
13307: # Are we cloning?
13308: #
13309:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13310:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13311: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13312: 	if ($context ne 'auto') {
13313:             if ($clonemsg ne '') {
13314: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13315:             }
13316: 	}
13317: 	$outcome .= $clonemsg.$linefeed;
13318: 
13319:         if (!$can_clone) {
13320: 	    return (0,$outcome);
13321: 	}
13322:     }
13323: 
13324: #
13325: # Open course
13326: #
13327:     my $crstype = lc($args->{'crstype'});
13328:     my %cenv=();
13329:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13330:                                              $args->{'cdescr'},
13331:                                              $args->{'curl'},
13332:                                              $args->{'course_home'},
13333:                                              $args->{'nonstandard'},
13334:                                              $args->{'crscode'},
13335:                                              $args->{'ccuname'}.':'.
13336:                                              $args->{'ccdomain'},
13337:                                              $args->{'crstype'},
13338:                                              $cnum,$context,$category);
13339: 
13340:     # Note: The testing routines depend on this being output; see 
13341:     # Utils::Course. This needs to at least be output as a comment
13342:     # if anyone ever decides to not show this, and Utils::Course::new
13343:     # will need to be suitably modified.
13344:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13345:     if ($$courseid =~ /^error:/) {
13346:         return (0,$outcome);
13347:     }
13348: 
13349: #
13350: # Check if created correctly
13351: #
13352:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13353:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13354:     if ($crsuhome eq 'no_host') {
13355:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13356:         return (0,$outcome);
13357:     }
13358:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13359: 
13360: #
13361: # Do the cloning
13362: #   
13363:     if ($can_clone && $cloneid) {
13364: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13365: 	if ($context ne 'auto') {
13366: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13367: 	}
13368: 	$outcome .= $clonemsg.$linefeed;
13369: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13370: # Copy all files
13371: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13372: # Restore URL
13373: 	$cenv{'url'}=$oldcenv{'url'};
13374: # Restore title
13375: 	$cenv{'description'}=$oldcenv{'description'};
13376: # Restore creation date, creator and creation context.
13377:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13378:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13379:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13380: # Mark as cloned
13381: 	$cenv{'clonedfrom'}=$cloneid;
13382: # Need to clone grading mode
13383:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13384:         $cenv{'grading'}=$newenv{'grading'};
13385: # Do not clone these environment entries
13386:         &Apache::lonnet::del('environment',
13387:                   ['default_enrollment_start_date',
13388:                    'default_enrollment_end_date',
13389:                    'question.email',
13390:                    'policy.email',
13391:                    'comment.email',
13392:                    'pch.users.denied',
13393:                    'plc.users.denied',
13394:                    'hidefromcat',
13395:                    'categories'],
13396:                    $$crsudom,$$crsunum);
13397:     }
13398: 
13399: #
13400: # Set environment (will override cloned, if existing)
13401: #
13402:     my @sections = ();
13403:     my @xlists = ();
13404:     if ($args->{'crstype'}) {
13405:         $cenv{'type'}=$args->{'crstype'};
13406:     }
13407:     if ($args->{'crsid'}) {
13408:         $cenv{'courseid'}=$args->{'crsid'};
13409:     }
13410:     if ($args->{'crscode'}) {
13411:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13412:     }
13413:     if ($args->{'crsquota'} ne '') {
13414:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13415:     } else {
13416:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13417:     }
13418:     if ($args->{'ccuname'}) {
13419:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13420:                                         ':'.$args->{'ccdomain'};
13421:     } else {
13422:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13423:     }
13424:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13425:     if ($args->{'crssections'}) {
13426:         $cenv{'internal.sectionnums'} = '';
13427:         if ($args->{'crssections'} =~ m/,/) {
13428:             @sections = split/,/,$args->{'crssections'};
13429:         } else {
13430:             $sections[0] = $args->{'crssections'};
13431:         }
13432:         if (@sections > 0) {
13433:             foreach my $item (@sections) {
13434:                 my ($sec,$gp) = split/:/,$item;
13435:                 my $class = $args->{'crscode'}.$sec;
13436:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13437:                 $cenv{'internal.sectionnums'} .= $item.',';
13438:                 unless ($addcheck eq 'ok') {
13439:                     push @badclasses, $class;
13440:                 }
13441:             }
13442:             $cenv{'internal.sectionnums'} =~ s/,$//;
13443:         }
13444:     }
13445: # do not hide course coordinator from staff listing, 
13446: # even if privileged
13447:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13448: # add crosslistings
13449:     if ($args->{'crsxlist'}) {
13450:         $cenv{'internal.crosslistings'}='';
13451:         if ($args->{'crsxlist'} =~ m/,/) {
13452:             @xlists = split/,/,$args->{'crsxlist'};
13453:         } else {
13454:             $xlists[0] = $args->{'crsxlist'};
13455:         }
13456:         if (@xlists > 0) {
13457:             foreach my $item (@xlists) {
13458:                 my ($xl,$gp) = split/:/,$item;
13459:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13460:                 $cenv{'internal.crosslistings'} .= $item.',';
13461:                 unless ($addcheck eq 'ok') {
13462:                     push @badclasses, $xl;
13463:                 }
13464:             }
13465:             $cenv{'internal.crosslistings'} =~ s/,$//;
13466:         }
13467:     }
13468:     if ($args->{'autoadds'}) {
13469:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
13470:     }
13471:     if ($args->{'autodrops'}) {
13472:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
13473:     }
13474: # check for notification of enrollment changes
13475:     my @notified = ();
13476:     if ($args->{'notify_owner'}) {
13477:         if ($args->{'ccuname'} ne '') {
13478:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13479:         }
13480:     }
13481:     if ($args->{'notify_dc'}) {
13482:         if ($uname ne '') { 
13483:             push(@notified,$uname.':'.$udom);
13484:         }
13485:     }
13486:     if (@notified > 0) {
13487:         my $notifylist;
13488:         if (@notified > 1) {
13489:             $notifylist = join(',',@notified);
13490:         } else {
13491:             $notifylist = $notified[0];
13492:         }
13493:         $cenv{'internal.notifylist'} = $notifylist;
13494:     }
13495:     if (@badclasses > 0) {
13496:         my %lt=&Apache::lonlocal::texthash(
13497:                 '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',
13498:                 'dnhr' => 'does not have rights to access enrollment in these classes',
13499:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
13500:         );
13501:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13502:                            ' ('.$lt{'adby'}.')';
13503:         if ($context eq 'auto') {
13504:             $outcome .= $badclass_msg.$linefeed;
13505:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13506:             foreach my $item (@badclasses) {
13507:                 if ($context eq 'auto') {
13508:                     $outcome .= " - $item\n";
13509:                 } else {
13510:                     $outcome .= "<li>$item</li>\n";
13511:                 }
13512:             }
13513:             if ($context eq 'auto') {
13514:                 $outcome .= $linefeed;
13515:             } else {
13516:                 $outcome .= "</ul><br /><br /></div>\n";
13517:             }
13518:         } 
13519:     }
13520:     if ($args->{'no_end_date'}) {
13521:         $args->{'endaccess'} = 0;
13522:     }
13523:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
13524:     $cenv{'internal.autoend'}=$args->{'enrollend'};
13525:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13526:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13527:     if ($args->{'showphotos'}) {
13528:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
13529:     }
13530:     $cenv{'internal.authtype'} = $args->{'authtype'};
13531:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
13532:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13533:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
13534:             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'); 
13535:             if ($context eq 'auto') {
13536:                 $outcome .= $krb_msg;
13537:             } else {
13538:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13539:             }
13540:             $outcome .= $linefeed;
13541:         }
13542:     }
13543:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13544:        if ($args->{'setpolicy'}) {
13545:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13546:        }
13547:        if ($args->{'setcontent'}) {
13548:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13549:        }
13550:     }
13551:     if ($args->{'reshome'}) {
13552: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
13553: 	$cenv{'reshome'}=~s/\/+$/\//;
13554:     }
13555: #
13556: # course has keyed access
13557: #
13558:     if ($args->{'setkeys'}) {
13559:        $cenv{'keyaccess'}='yes';
13560:     }
13561: # if specified, key authority is not course, but user
13562: # only active if keyaccess is yes
13563:     if ($args->{'keyauth'}) {
13564: 	my ($user,$domain) = split(':',$args->{'keyauth'});
13565: 	$user = &LONCAPA::clean_username($user);
13566: 	$domain = &LONCAPA::clean_username($domain);
13567: 	if ($user ne '' && $domain ne '') {
13568: 	    $cenv{'keyauth'}=$user.':'.$domain;
13569: 	}
13570:     }
13571: 
13572:     if ($args->{'disresdis'}) {
13573:         $cenv{'pch.roles.denied'}='st';
13574:     }
13575:     if ($args->{'disablechat'}) {
13576:         $cenv{'plc.roles.denied'}='st';
13577:     }
13578: 
13579:     # Record we've not yet viewed the Course Initialization Helper for this 
13580:     # course
13581:     $cenv{'course.helper.not.run'} = 1;
13582:     #
13583:     # Use new Randomseed
13584:     #
13585:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13586:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13587:     #
13588:     # The encryption code and receipt prefix for this course
13589:     #
13590:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13591:     $cenv{'internal.encpref'}=100+int(9*rand(99));
13592:     #
13593:     # By default, use standard grading
13594:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13595: 
13596:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
13597:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13598: #
13599: # Open all assignments
13600: #
13601:     if ($args->{'openall'}) {
13602:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13603:        my %storecontent = ($storeunder         => time,
13604:                            $storeunder.'.type' => 'date_start');
13605:        
13606:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13607:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13608:    }
13609: #
13610: # Set first page
13611: #
13612:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13613: 	    || ($cloneid)) {
13614: 	use LONCAPA::map;
13615: 	$outcome .= &mt('Setting first resource').': ';
13616: 
13617: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13618:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13619: 
13620:         $outcome .= ($fatal?$errtext:'read ok').' - ';
13621:         my $title; my $url;
13622:         if ($args->{'firstres'} eq 'syl') {
13623: 	    $title=&mt('Syllabus');
13624:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13625:         } else {
13626:             $title=&mt('Table of Contents');
13627:             $url='/adm/navmaps';
13628:         }
13629: 
13630:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13631: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13632: 
13633: 	if ($errtext) { $fatal=2; }
13634:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13635:     }
13636: 
13637:     return (1,$outcome);
13638: }
13639: 
13640: ############################################################
13641: ############################################################
13642: 
13643: #SD
13644: # only Community and Course, or anything else?
13645: sub course_type {
13646:     my ($cid) = @_;
13647:     if (!defined($cid)) {
13648:         $cid = $env{'request.course.id'};
13649:     }
13650:     if (defined($env{'course.'.$cid.'.type'})) {
13651:         return $env{'course.'.$cid.'.type'};
13652:     } else {
13653:         return 'Course';
13654:     }
13655: }
13656: 
13657: sub group_term {
13658:     my $crstype = &course_type();
13659:     my %names = (
13660:                   'Course' => 'group',
13661:                   'Community' => 'group',
13662:                 );
13663:     return $names{$crstype};
13664: }
13665: 
13666: sub course_types {
13667:     my @types = ('official','unofficial','community');
13668:     my %typename = (
13669:                          official   => 'Official course',
13670:                          unofficial => 'Unofficial course',
13671:                          community  => 'Community',
13672:                    );
13673:     return (\@types,\%typename);
13674: }
13675: 
13676: sub icon {
13677:     my ($file)=@_;
13678:     my $curfext = lc((split(/\./,$file))[-1]);
13679:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13680:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13681:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13682: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13683: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13684: 	            $curfext.".gif") {
13685: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13686: 		$curfext.".gif";
13687: 	}
13688:     }
13689:     return &lonhttpdurl($iconname);
13690: } 
13691: 
13692: sub lonhttpdurl {
13693: #
13694: # Had been used for "small fry" static images on separate port 8080.
13695: # Modify here if lightweight http functionality desired again.
13696: # Currently eliminated due to increasing firewall issues.
13697: #
13698:     my ($url)=@_;
13699:     return $url;
13700: }
13701: 
13702: sub connection_aborted {
13703:     my ($r)=@_;
13704:     $r->print(" ");$r->rflush();
13705:     my $c = $r->connection;
13706:     return $c->aborted();
13707: }
13708: 
13709: #    Escapes strings that may have embedded 's that will be put into
13710: #    strings as 'strings'.
13711: sub escape_single {
13712:     my ($input) = @_;
13713:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
13714:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
13715:     return $input;
13716: }
13717: 
13718: #  Same as escape_single, but escape's "'s  This 
13719: #  can be used for  "strings"
13720: sub escape_double {
13721:     my ($input) = @_;
13722:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
13723:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
13724:     return $input;
13725: }
13726:  
13727: #   Escapes the last element of a full URL.
13728: sub escape_url {
13729:     my ($url)   = @_;
13730:     my @urlslices = split(/\//, $url,-1);
13731:     my $lastitem = &escape(pop(@urlslices));
13732:     return join('/',@urlslices).'/'.$lastitem;
13733: }
13734: 
13735: sub compare_arrays {
13736:     my ($arrayref1,$arrayref2) = @_;
13737:     my (@difference,%count);
13738:     @difference = ();
13739:     %count = ();
13740:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
13741:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
13742:         foreach my $element (keys(%count)) {
13743:             if ($count{$element} == 1) {
13744:                 push(@difference,$element);
13745:             }
13746:         }
13747:     }
13748:     return @difference;
13749: }
13750: 
13751: # -------------------------------------------------------- Initialize user login
13752: sub init_user_environment {
13753:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
13754:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13755: 
13756:     my $public=($username eq 'public' && $domain eq 'public');
13757: 
13758: # See if old ID present, if so, remove
13759: 
13760:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13761:     my $now=time;
13762: 
13763:     if ($public) {
13764: 	my $max_public=100;
13765: 	my $oldest;
13766: 	my $oldest_time=0;
13767: 	for(my $next=1;$next<=$max_public;$next++) {
13768: 	    if (-e $lonids."/publicuser_$next.id") {
13769: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13770: 		if ($mtime<$oldest_time || !$oldest_time) {
13771: 		    $oldest_time=$mtime;
13772: 		    $oldest=$next;
13773: 		}
13774: 	    } else {
13775: 		$cookie="publicuser_$next";
13776: 		last;
13777: 	    }
13778: 	}
13779: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
13780:     } else {
13781: 	# if this isn't a robot, kill any existing non-robot sessions
13782: 	if (!$args->{'robot'}) {
13783: 	    opendir(DIR,$lonids);
13784: 	    while ($filename=readdir(DIR)) {
13785: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13786: 		    unlink($lonids.'/'.$filename);
13787: 		}
13788: 	    }
13789: 	    closedir(DIR);
13790: 	}
13791: # Give them a new cookie
13792: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13793: 		                   : $now.$$.int(rand(10000)));
13794: 	$cookie="$username\_$id\_$domain\_$authhost";
13795:     
13796: # Initialize roles
13797: 
13798: 	($userroles,$firstaccenv,$timerintenv) = 
13799:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
13800:     }
13801: # ------------------------------------ Check browser type and MathML capability
13802: 
13803:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13804:         $clientunicode,$clientos) = &decode_user_agent($r);
13805: 
13806: # ------------------------------------------------------------- Get environment
13807: 
13808:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13809:     my ($tmp) = keys(%userenv);
13810:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13811:     } else {
13812: 	undef(%userenv);
13813:     }
13814:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
13815: 	$form->{'interface'}=$userenv{'interface'};
13816:     }
13817:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13818: 
13819: # --------------- Do not trust query string to be put directly into environment
13820:     foreach my $option ('interface','localpath','localres') {
13821:         $form->{$option}=~s/[\n\r\=]//gs;
13822:     }
13823: # --------------------------------------------------------- Write first profile
13824: 
13825:     {
13826: 	my %initial_env = 
13827: 	    ("user.name"          => $username,
13828: 	     "user.domain"        => $domain,
13829: 	     "user.home"          => $authhost,
13830: 	     "browser.type"       => $clientbrowser,
13831: 	     "browser.version"    => $clientversion,
13832: 	     "browser.mathml"     => $clientmathml,
13833: 	     "browser.unicode"    => $clientunicode,
13834: 	     "browser.os"         => $clientos,
13835: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
13836: 	     "request.course.fn"  => '',
13837: 	     "request.course.uri" => '',
13838: 	     "request.course.sec" => '',
13839: 	     "request.role"       => 'cm',
13840: 	     "request.role.adv"   => $env{'user.adv'},
13841: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
13842: 
13843:         if ($form->{'localpath'}) {
13844: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
13845: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
13846:         }
13847: 	
13848: 	if ($form->{'interface'}) {
13849: 	    $form->{'interface'}=~s/\W//gs;
13850: 	    $initial_env{"browser.interface"} = $form->{'interface'};
13851: 	    $env{'browser.interface'}=$form->{'interface'};
13852: 	}
13853: 
13854:         my %is_adv = ( is_adv => $env{'user.adv'} );
13855:         my %domdef;
13856:         unless ($domain eq 'public') {
13857:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
13858:         }
13859: 
13860:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
13861:             $userenv{'availabletools.'.$tool} = 
13862:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13863:                                                   undef,\%userenv,\%domdef,\%is_adv);
13864:         }
13865: 
13866:         foreach my $crstype ('official','unofficial','community') {
13867:             $userenv{'canrequest.'.$crstype} =
13868:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
13869:                                                   'reload','requestcourses',
13870:                                                   \%userenv,\%domdef,\%is_adv);
13871:         }
13872: 
13873: 	$env{'user.environment'} = "$lonids/$cookie.id";
13874: 
13875: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
13876: 		 &GDBM_WRCREAT(),0640)) {
13877: 	    &_add_to_env(\%disk_env,\%initial_env);
13878: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
13879: 	    &_add_to_env(\%disk_env,$userroles);
13880:             if (ref($firstaccenv) eq 'HASH') {
13881:                 &_add_to_env(\%disk_env,$firstaccenv);
13882:             }
13883:             if (ref($timerintenv) eq 'HASH') {
13884:                 &_add_to_env(\%disk_env,$timerintenv);
13885:             }
13886: 	    if (ref($args->{'extra_env'})) {
13887: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
13888: 	    }
13889: 	    untie(%disk_env);
13890: 	} else {
13891: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
13892: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
13893: 	    return 'error: '.$!;
13894: 	}
13895:     }
13896:     $env{'request.role'}='cm';
13897:     $env{'request.role.adv'}=$env{'user.adv'};
13898:     $env{'browser.type'}=$clientbrowser;
13899: 
13900:     return $cookie;
13901: 
13902: }
13903: 
13904: sub _add_to_env {
13905:     my ($idf,$env_data,$prefix) = @_;
13906:     if (ref($env_data) eq 'HASH') {
13907:         while (my ($key,$value) = each(%$env_data)) {
13908: 	    $idf->{$prefix.$key} = $value;
13909: 	    $env{$prefix.$key}   = $value;
13910:         }
13911:     }
13912: }
13913: 
13914: # --- Get the symbolic name of a problem and the url
13915: sub get_symb {
13916:     my ($request,$silent) = @_;
13917:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
13918:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
13919:     if ($symb eq '') {
13920:         if (!$silent) {
13921:             if (ref($request)) { 
13922:                 $request->print("Unable to handle ambiguous references:$url:.");
13923:             }
13924:             return ();
13925:         }
13926:     }
13927:     &Apache::lonenc::check_decrypt(\$symb);
13928:     return ($symb);
13929: }
13930: 
13931: # --------------------------------------------------------------Get annotation
13932: 
13933: sub get_annotation {
13934:     my ($symb,$enc) = @_;
13935: 
13936:     my $key = $symb;
13937:     if (!$enc) {
13938:         $key =
13939:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
13940:     }
13941:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
13942:     return $annotation{$key};
13943: }
13944: 
13945: sub clean_symb {
13946:     my ($symb,$delete_enc) = @_;
13947: 
13948:     &Apache::lonenc::check_decrypt(\$symb);
13949:     my $enc = $env{'request.enc'};
13950:     if ($delete_enc) {
13951:         delete($env{'request.enc'});
13952:     }
13953: 
13954:     return ($symb,$enc);
13955: }
13956: 
13957: sub build_release_hashes {
13958:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
13959:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
13960:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
13961:                   (ref($randomizetry) eq 'HASH'));
13962:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
13963:         my ($item,$name,$value) = split(/:/,$key);
13964:         if ($item eq 'parameter') {
13965:             if (ref($checkparms->{$name}) eq 'ARRAY') {
13966:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
13967:                     push(@{$checkparms->{$name}},$value);
13968:                 }
13969:             } else {
13970:                 push(@{$checkparms->{$name}},$value);
13971:             }
13972:         } elsif ($item eq 'resourcetag') {
13973:             if ($name eq 'responsetype') {
13974:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
13975:             }
13976:         } elsif ($item eq 'course') {
13977:             if ($name eq 'crstype') {
13978:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
13979:             }
13980:         }
13981:     }
13982:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
13983:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
13984:     return;
13985: }
13986: 
13987: sub update_content_constraints {
13988:     my ($cdom,$cnum,$chome,$cid) = @_;
13989:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
13990:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
13991:     my %checkresponsetypes;
13992:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
13993:         my ($item,$name,$value) = split(/:/,$key);
13994:         if ($item eq 'resourcetag') {
13995:             if ($name eq 'responsetype') {
13996:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
13997:             }
13998:         }
13999:     }
14000:     my $navmap = Apache::lonnavmaps::navmap->new();
14001:     if (defined($navmap)) {
14002:         my %allresponses;
14003:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14004:             my %responses = $res->responseTypes();
14005:             foreach my $key (keys(%responses)) {
14006:                 next unless(exists($checkresponsetypes{$key}));
14007:                 $allresponses{$key} += $responses{$key};
14008:             }
14009:         }
14010:         foreach my $key (keys(%allresponses)) {
14011:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14012:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14013:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14014:             }
14015:         }
14016:         undef($navmap);
14017:     }
14018:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14019:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14020:     }
14021:     return;
14022: }
14023: 
14024: sub parse_supplemental_title {
14025:     my ($title) = @_;
14026: 
14027:     my ($foldertitle,$renametitle);
14028:     if ($title =~ /&amp;&amp;&amp;/) {
14029:         $title = &HTML::Entites::decode($title);
14030:     }
14031:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14032:         $renametitle=$4;
14033:         my ($time,$uname,$udom) = ($1,$2,$3);
14034:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14035:         my $name =  &plainname($uname,$udom);
14036:         $name = &HTML::Entities::encode($name,'"<>&\'');
14037:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14038:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14039:             $name.': <br />'.$foldertitle;
14040:     }
14041:     if (wantarray) {
14042:         return ($title,$foldertitle,$renametitle);
14043:     }
14044:     return $title;
14045: }
14046: 
14047: =pod
14048: 
14049: =back
14050: 
14051: =cut
14052: 
14053: 1;
14054: __END__;
14055: 

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