File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.32: download - view: text, annotated - select for diffs
Tue Mar 19 00:49:27 2013 UTC (11 years, 2 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.1117

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.32 2013/03/19 00:49:27 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 Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use LONCAPA qw(:DEFAULT :match);
   73: use DateTime::TimeZone;
   74: use DateTime::Locale::Catalog;
   75: use Authen::Captcha;
   76: use Captcha::reCAPTCHA;
   77: 
   78: # ---------------------------------------------- Designs
   79: use vars qw(%defaultdesign);
   80: 
   81: my $readit;
   82: 
   83: 
   84: ##
   85: ## Global Variables
   86: ##
   87: 
   88: 
   89: # ----------------------------------------------- SSI with retries:
   90: #
   91: 
   92: =pod
   93: 
   94: =head1 Server Side include with retries:
   95: 
   96: =over 4
   97: 
   98: =item * &ssi_with_retries(resource,retries form)
   99: 
  100: Performs an ssi with some number of retries.  Retries continue either
  101: until the result is ok or until the retry count supplied by the
  102: caller is exhausted.  
  103: 
  104: Inputs:
  105: 
  106: =over 4
  107: 
  108: resource   - Identifies the resource to insert.
  109: 
  110: retries    - Count of the number of retries allowed.
  111: 
  112: form       - Hash that identifies the rendering options.
  113: 
  114: =back
  115: 
  116: Returns:
  117: 
  118: =over 4
  119: 
  120: content    - The content of the response.  If retries were exhausted this is empty.
  121: 
  122: response   - The response from the last attempt (which may or may not have been successful.
  123: 
  124: =back
  125: 
  126: =back
  127: 
  128: =cut
  129: 
  130: sub ssi_with_retries {
  131:     my ($resource, $retries, %form) = @_;
  132: 
  133: 
  134:     my $ok = 0;			# True if we got a good response.
  135:     my $content;
  136:     my $response;
  137: 
  138:     # Try to get the ssi done. within the retries count:
  139: 
  140:     do {
  141: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  142: 	$ok      = $response->is_success;
  143:         if (!$ok) {
  144:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  145:         }
  146: 	$retries--;
  147:     } while (!$ok && ($retries > 0));
  148: 
  149:     if (!$ok) {
  150: 	$content = '';		# On error return an empty content.
  151:     }
  152:     return ($content, $response);
  153: 
  154: }
  155: 
  156: 
  157: 
  158: # ----------------------------------------------- Filetypes/Languages/Copyright
  159: my %language;
  160: my %supported_language;
  161: my %latex_language;		# For choosing hyphenation in <transl..>
  162: my %latex_language_bykey;	# for choosing hyphenation from metadata
  163: my %cprtag;
  164: my %scprtag;
  165: my %fe; my %fd; my %fm;
  166: my %category_extensions;
  167: 
  168: # ---------------------------------------------- Thesaurus variables
  169: #
  170: # %Keywords:
  171: #      A hash used by &keyword to determine if a word is considered a keyword.
  172: # $thesaurus_db_file 
  173: #      Scalar containing the full path to the thesaurus database.
  174: 
  175: my %Keywords;
  176: my $thesaurus_db_file;
  177: 
  178: #
  179: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  180: # thesaurus.tab, and filecategories.tab.
  181: #
  182: BEGIN {
  183:     # Variable initialization
  184:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  185:     #
  186:     unless ($readit) {
  187: # ------------------------------------------------------------------- languages
  188:     {
  189:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  190:                                    '/language.tab';
  191:         if ( open(my $fh,"<$langtabfile") ) {
  192:             while (my $line = <$fh>) {
  193:                 next if ($line=~/^\#/);
  194:                 chomp($line);
  195:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  196:                 $language{$key}=$val.' - '.$enc;
  197:                 if ($sup) {
  198:                     $supported_language{$key}=$sup;
  199:                 }
  200: 		if ($latex) {
  201: 		    $latex_language_bykey{$key} = $latex;
  202: 		    $latex_language{$two} = $latex;
  203: 		}
  204:             }
  205:             close($fh);
  206:         }
  207:     }
  208: # ------------------------------------------------------------------ copyrights
  209:     {
  210:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  211:                                   '/copyright.tab';
  212:         if ( open (my $fh,"<$copyrightfile") ) {
  213:             while (my $line = <$fh>) {
  214:                 next if ($line=~/^\#/);
  215:                 chomp($line);
  216:                 my ($key,$val)=(split(/\s+/,$line,2));
  217:                 $cprtag{$key}=$val;
  218:             }
  219:             close($fh);
  220:         }
  221:     }
  222: # ----------------------------------------------------------- source copyrights
  223:     {
  224:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  225:                                   '/source_copyright.tab';
  226:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  227:             while (my $line = <$fh>) {
  228:                 next if ($line =~ /^\#/);
  229:                 chomp($line);
  230:                 my ($key,$val)=(split(/\s+/,$line,2));
  231:                 $scprtag{$key}=$val;
  232:             }
  233:             close($fh);
  234:         }
  235:     }
  236: 
  237: # -------------------------------------------------------------- default domain designs
  238:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  239:     my $designfile = $designdir.'/default.tab';
  240:     if ( open (my $fh,"<$designfile") ) {
  241:         while (my $line = <$fh>) {
  242:             next if ($line =~ /^\#/);
  243:             chomp($line);
  244:             my ($key,$val)=(split(/\=/,$line));
  245:             if ($val) { $defaultdesign{$key}=$val; }
  246:         }
  247:         close($fh);
  248:     }
  249: 
  250: # ------------------------------------------------------------- file categories
  251:     {
  252:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  253:                                   '/filecategories.tab';
  254:         if ( open (my $fh,"<$categoryfile") ) {
  255: 	    while (my $line = <$fh>) {
  256: 		next if ($line =~ /^\#/);
  257: 		chomp($line);
  258:                 my ($extension,$category)=(split(/\s+/,$line,2));
  259:                 push @{$category_extensions{lc($category)}},$extension;
  260:             }
  261:             close($fh);
  262:         }
  263: 
  264:     }
  265: # ------------------------------------------------------------------ file types
  266:     {
  267:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  268:                '/filetypes.tab';
  269:         if ( open (my $fh,"<$typesfile") ) {
  270:             while (my $line = <$fh>) {
  271: 		next if ($line =~ /^\#/);
  272: 		chomp($line);
  273:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  274:                 if ($descr ne '') {
  275:                     $fe{$ending}=lc($emb);
  276:                     $fd{$ending}=$descr;
  277:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  278:                 }
  279:             }
  280:             close($fh);
  281:         }
  282:     }
  283:     &Apache::lonnet::logthis(
  284:              "<span style='color:yellow;'>INFO: Read file types</span>");
  285:     $readit=1;
  286:     }  # end of unless($readit) 
  287:     
  288: }
  289: 
  290: ###############################################################
  291: ##           HTML and Javascript Helper Functions            ##
  292: ###############################################################
  293: 
  294: =pod 
  295: 
  296: =head1 HTML and Javascript Functions
  297: 
  298: =over 4
  299: 
  300: =item * &browser_and_searcher_javascript()
  301: 
  302: X<browsing, javascript>X<searching, javascript>Returns a string
  303: containing javascript with two functions, C<openbrowser> and
  304: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  305: tags.
  306: 
  307: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  308: 
  309: inputs: formname, elementname, only, omit
  310: 
  311: formname and elementname indicate the name of the html form and name of
  312: the element that the results of the browsing selection are to be placed in. 
  313: 
  314: Specifying 'only' will restrict the browser to displaying only files
  315: with the given extension.  Can be a comma separated list.
  316: 
  317: Specifying 'omit' will restrict the browser to NOT displaying files
  318: with the given extension.  Can be a comma separated list.
  319: 
  320: =item * &opensearcher(formname,elementname) [javascript]
  321: 
  322: Inputs: formname, elementname
  323: 
  324: formname and elementname specify the name of the html form and the name
  325: of the element the selection from the search results will be placed in.
  326: 
  327: =cut
  328: 
  329: sub browser_and_searcher_javascript {
  330:     my ($mode)=@_;
  331:     if (!defined($mode)) { $mode='edit'; }
  332:     my $resurl=&escape_single(&lastresurl());
  333:     return <<END;
  334: // <!-- BEGIN LON-CAPA Internal
  335:     var editbrowser = null;
  336:     function openbrowser(formname,elementname,only,omit,titleelement) {
  337:         var url = '$resurl/?';
  338:         if (editbrowser == null) {
  339:             url += 'launch=1&';
  340:         }
  341:         url += 'catalogmode=interactive&';
  342:         url += 'mode=$mode&';
  343:         url += 'inhibitmenu=yes&';
  344:         url += 'form=' + formname + '&';
  345:         if (only != null) {
  346:             url += 'only=' + only + '&';
  347:         } else {
  348:             url += 'only=&';
  349: 	}
  350:         if (omit != null) {
  351:             url += 'omit=' + omit + '&';
  352:         } else {
  353:             url += 'omit=&';
  354: 	}
  355:         if (titleelement != null) {
  356:             url += 'titleelement=' + titleelement + '&';
  357:         } else {
  358: 	    url += 'titleelement=&';
  359: 	}
  360:         url += 'element=' + elementname + '';
  361:         var title = 'Browser';
  362:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  363:         options += ',width=700,height=600';
  364:         editbrowser = open(url,title,options,'1');
  365:         editbrowser.focus();
  366:     }
  367:     var editsearcher;
  368:     function opensearcher(formname,elementname,titleelement) {
  369:         var url = '/adm/searchcat?';
  370:         if (editsearcher == null) {
  371:             url += 'launch=1&';
  372:         }
  373:         url += 'catalogmode=interactive&';
  374:         url += 'mode=$mode&';
  375:         url += 'form=' + formname + '&';
  376:         if (titleelement != null) {
  377:             url += 'titleelement=' + titleelement + '&';
  378:         } else {
  379: 	    url += 'titleelement=&';
  380: 	}
  381:         url += 'element=' + elementname + '';
  382:         var title = 'Search';
  383:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  384:         options += ',width=700,height=600';
  385:         editsearcher = open(url,title,options,'1');
  386:         editsearcher.focus();
  387:     }
  388: // END LON-CAPA Internal -->
  389: END
  390: }
  391: 
  392: sub lastresurl {
  393:     if ($env{'environment.lastresurl'}) {
  394: 	return $env{'environment.lastresurl'}
  395:     } else {
  396: 	return '/res';
  397:     }
  398: }
  399: 
  400: sub storeresurl {
  401:     my $resurl=&Apache::lonnet::clutter(shift);
  402:     unless ($resurl=~/^\/res/) { return 0; }
  403:     $resurl=~s/\/$//;
  404:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  405:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  406:     return 1;
  407: }
  408: 
  409: sub studentbrowser_javascript {
  410:    unless (
  411:             (($env{'request.course.id'}) && 
  412:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  413: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  414: 					  '/'.$env{'request.course.sec'})
  415: 	      ))
  416:          || ($env{'request.role'}=~/^(au|dc|su)/)
  417:           ) { return ''; }  
  418:    return (<<'ENDSTDBRW');
  419: <script type="text/javascript" language="Javascript">
  420: // <![CDATA[
  421:     var stdeditbrowser;
  422:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  423:         var url = '/adm/pickstudent?';
  424:         var filter;
  425: 	if (!ignorefilter) {
  426: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  427: 	}
  428:         if (filter != null) {
  429:            if (filter != '') {
  430:                url += 'filter='+filter+'&';
  431: 	   }
  432:         }
  433:         url += 'form=' + formname + '&unameelement='+uname+
  434:                                     '&udomelement='+udom+
  435:                                     '&clicker='+clicker;
  436: 	if (roleflag) { url+="&roles=1"; }
  437:         if (courseadvonly) { url+="&courseadvonly=1"; }
  438:         var title = 'Student_Browser';
  439:         var options = 'scrollbars=1,resizable=1,menubar=0';
  440:         options += ',width=700,height=600';
  441:         stdeditbrowser = open(url,title,options,'1');
  442:         stdeditbrowser.focus();
  443:     }
  444: // ]]>
  445: </script>
  446: ENDSTDBRW
  447: }
  448: 
  449: sub resourcebrowser_javascript {
  450:    unless ($env{'request.course.id'}) { return ''; }
  451:    return (<<'ENDRESBRW');
  452: <script type="text/javascript" language="Javascript">
  453: // <![CDATA[
  454:     var reseditbrowser;
  455:     function openresbrowser(formname,reslink) {
  456:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  457:         var title = 'Resource_Browser';
  458:         var options = 'scrollbars=1,resizable=1,menubar=0';
  459:         options += ',width=700,height=500';
  460:         reseditbrowser = open(url,title,options,'1');
  461:         reseditbrowser.focus();
  462:     }
  463: // ]]>
  464: </script>
  465: ENDRESBRW
  466: }
  467: 
  468: sub selectstudent_link {
  469:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  470:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  471:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  472:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  473:    if ($env{'request.course.id'}) {  
  474:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  475: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  476: 					'/'.$env{'request.course.sec'})) {
  477: 	   return '';
  478:        }
  479:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  480:        if ($courseadvonly)  {
  481:            $callargs .= ",'',1,1";
  482:        }
  483:        return '<span class="LC_nobreak">'.
  484:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  485:               &mt('Select User').'</a></span>';
  486:    }
  487:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  488:        $callargs .= ",'',1"; 
  489:        return '<span class="LC_nobreak">'.
  490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  491:               &mt('Select User').'</a></span>';
  492:    }
  493:    return '';
  494: }
  495: 
  496: sub selectresource_link {
  497:    my ($form,$reslink,$arg)=@_;
  498:    
  499:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  500:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  501:    unless ($env{'request.course.id'}) { return $arg; }
  502:    return '<span class="LC_nobreak">'.
  503:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  504:               $arg.'</a></span>';
  505: }
  506: 
  507: 
  508: 
  509: sub authorbrowser_javascript {
  510:     return <<"ENDAUTHORBRW";
  511: <script type="text/javascript" language="JavaScript">
  512: // <![CDATA[
  513: var stdeditbrowser;
  514: 
  515: function openauthorbrowser(formname,udom) {
  516:     var url = '/adm/pickauthor?';
  517:     url += 'form='+formname+'&roledom='+udom;
  518:     var title = 'Author_Browser';
  519:     var options = 'scrollbars=1,resizable=1,menubar=0';
  520:     options += ',width=700,height=600';
  521:     stdeditbrowser = open(url,title,options,'1');
  522:     stdeditbrowser.focus();
  523: }
  524: 
  525: // ]]>
  526: </script>
  527: ENDAUTHORBRW
  528: }
  529: 
  530: sub coursebrowser_javascript {
  531:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  532:         $credits_element) = @_;
  533:     my $wintitle = 'Course_Browser';
  534:     if ($crstype eq 'Community') {
  535:         $wintitle = 'Community_Browser';
  536:     }
  537:     my $id_functions = &javascript_index_functions();
  538:     my $output = '
  539: <script type="text/javascript" language="JavaScript">
  540: // <![CDATA[
  541:     var stdeditbrowser;'."\n";
  542: 
  543:     $output .= <<"ENDSTDBRW";
  544:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  545:         var url = '/adm/pickcourse?';
  546:         var formid = getFormIdByName(formname);
  547:         var domainfilter = getDomainFromSelectbox(formname,udom);
  548:         if (domainfilter != null) {
  549:            if (domainfilter != '') {
  550:                url += 'domainfilter='+domainfilter+'&';
  551: 	   }
  552:         }
  553:         url += 'form=' + formname + '&cnumelement='+uname+
  554: 	                            '&cdomelement='+udom+
  555:                                     '&cnameelement='+desc;
  556:         if (extra_element !=null && extra_element != '') {
  557:             if (formname == 'rolechoice' || formname == 'studentform') {
  558:                 url += '&roleelement='+extra_element;
  559:                 if (domainfilter == null || domainfilter == '') {
  560:                     url += '&domainfilter='+extra_element;
  561:                 }
  562:             }
  563:             else {
  564:                 if (formname == 'portform') {
  565:                     url += '&setroles='+extra_element;
  566:                 } else {
  567:                     if (formname == 'rules') {
  568:                         url += '&fixeddom='+extra_element; 
  569:                     }
  570:                 }
  571:             }     
  572:         }
  573:         if (type != null && type != '') {
  574:             url += '&type='+type;
  575:         }
  576:         if (type_elem != null && type_elem != '') {
  577:             url += '&typeelement='+type_elem;
  578:         }
  579:         if (formname == 'ccrs') {
  580:             var ownername = document.forms[formid].ccuname.value;
  581:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  582:             url += '&cloner='+ownername+':'+ownerdom;
  583:         }
  584:         if (multflag !=null && multflag != '') {
  585:             url += '&multiple='+multflag;
  586:         }
  587:         var title = '$wintitle';
  588:         var options = 'scrollbars=1,resizable=1,menubar=0';
  589:         options += ',width=700,height=600';
  590:         stdeditbrowser = open(url,title,options,'1');
  591:         stdeditbrowser.focus();
  592:     }
  593: $id_functions
  594: ENDSTDBRW
  595:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  596:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  597:                                       $credits_element);
  598:     }
  599:     $output .= '
  600: // ]]>
  601: </script>';
  602:     return $output;
  603: }
  604: 
  605: sub javascript_index_functions {
  606:     return <<"ENDJS";
  607: 
  608: function getFormIdByName(formname) {
  609:     for (var i=0;i<document.forms.length;i++) {
  610:         if (document.forms[i].name == formname) {
  611:             return i;
  612:         }
  613:     }
  614:     return -1;
  615: }
  616: 
  617: function getIndexByName(formid,item) {
  618:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  619:         if (document.forms[formid].elements[i].name == item) {
  620:             return i;
  621:         }
  622:     }
  623:     return -1;
  624: }
  625: 
  626: function getDomainFromSelectbox(formname,udom) {
  627:     var userdom;
  628:     var formid = getFormIdByName(formname);
  629:     if (formid > -1) {
  630:         var domid = getIndexByName(formid,udom);
  631:         if (domid > -1) {
  632:             if (document.forms[formid].elements[domid].type == 'select-one') {
  633:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  634:             }
  635:             if (document.forms[formid].elements[domid].type == 'hidden') {
  636:                 userdom=document.forms[formid].elements[domid].value;
  637:             }
  638:         }
  639:     }
  640:     return userdom;
  641: }
  642: 
  643: ENDJS
  644: 
  645: }
  646: 
  647: sub javascript_array_indexof {
  648:     return <<ENDJS;
  649: <script type="text/javascript" language="JavaScript">
  650: // <![CDATA[
  651: 
  652: if (!Array.prototype.indexOf) {
  653:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  654:         "use strict";
  655:         if (this === void 0 || this === null) {
  656:             throw new TypeError();
  657:         }
  658:         var t = Object(this);
  659:         var len = t.length >>> 0;
  660:         if (len === 0) {
  661:             return -1;
  662:         }
  663:         var n = 0;
  664:         if (arguments.length > 0) {
  665:             n = Number(arguments[1]);
  666:             if (n !== n) { // shortcut for verifying if it's NaN
  667:                 n = 0;
  668:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  669:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  670:             }
  671:         }
  672:         if (n >= len) {
  673:             return -1;
  674:         }
  675:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  676:         for (; k < len; k++) {
  677:             if (k in t && t[k] === searchElement) {
  678:                 return k;
  679:             }
  680:         }
  681:         return -1;
  682:     }
  683: }
  684: 
  685: // ]]>
  686: </script>
  687: 
  688: ENDJS
  689: 
  690: }
  691: 
  692: sub userbrowser_javascript {
  693:     my $id_functions = &javascript_index_functions();
  694:     return <<"ENDUSERBRW";
  695: 
  696: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  697:     var url = '/adm/pickuser?';
  698:     var userdom = getDomainFromSelectbox(formname,udom);
  699:     if (userdom != null) {
  700:        if (userdom != '') {
  701:            url += 'srchdom='+userdom+'&';
  702:        }
  703:     }
  704:     url += 'form=' + formname + '&unameelement='+uname+
  705:                                 '&udomelement='+udom+
  706:                                 '&ulastelement='+ulast+
  707:                                 '&ufirstelement='+ufirst+
  708:                                 '&uemailelement='+uemail+
  709:                                 '&hideudomelement='+hideudom+
  710:                                 '&coursedom='+crsdom;
  711:     if ((caller != null) && (caller != undefined)) {
  712:         url += '&caller='+caller;
  713:     }
  714:     var title = 'User_Browser';
  715:     var options = 'scrollbars=1,resizable=1,menubar=0';
  716:     options += ',width=700,height=600';
  717:     var stdeditbrowser = open(url,title,options,'1');
  718:     stdeditbrowser.focus();
  719: }
  720: 
  721: function fix_domain (formname,udom,origdom,uname) {
  722:     var formid = getFormIdByName(formname);
  723:     if (formid > -1) {
  724:         var unameid = getIndexByName(formid,uname);
  725:         var domid = getIndexByName(formid,udom);
  726:         var hidedomid = getIndexByName(formid,origdom);
  727:         if (hidedomid > -1) {
  728:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  729:             var unameval = document.forms[formid].elements[unameid].value;
  730:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  731:                 if (domid > -1) {
  732:                     var slct = document.forms[formid].elements[domid];
  733:                     if (slct.type == 'select-one') {
  734:                         var i;
  735:                         for (i=0;i<slct.length;i++) {
  736:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  737:                         }
  738:                     }
  739:                     if (slct.type == 'hidden') {
  740:                         slct.value = fixeddom;
  741:                     }
  742:                 }
  743:             }
  744:         }
  745:     }
  746:     return;
  747: }
  748: 
  749: $id_functions
  750: ENDUSERBRW
  751: }
  752: 
  753: sub setsec_javascript {
  754:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  755:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  756:         $communityrolestr);
  757:     if ($role_element ne '') {
  758:         my @allroles = ('st','ta','ep','in','ad');
  759:         foreach my $crstype ('Course','Community') {
  760:             if ($crstype eq 'Community') {
  761:                 foreach my $role (@allroles) {
  762:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  763:                 }
  764:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  765:             } else {
  766:                 foreach my $role (@allroles) {
  767:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  768:                 }
  769:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  770:             }
  771:         }
  772:         $rolestr = '"'.join('","',@allroles).'"';
  773:         $courserolestr = '"'.join('","',@courserolenames).'"';
  774:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  775:     }
  776:     my $setsections = qq|
  777: function setSect(sectionlist) {
  778:     var sectionsArray = new Array();
  779:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  780:         sectionsArray = sectionlist.split(",");
  781:     }
  782:     var numSections = sectionsArray.length;
  783:     document.$formname.$sec_element.length = 0;
  784:     if (numSections == 0) {
  785:         document.$formname.$sec_element.multiple=false;
  786:         document.$formname.$sec_element.size=1;
  787:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  788:     } else {
  789:         if (numSections == 1) {
  790:             document.$formname.$sec_element.multiple=false;
  791:             document.$formname.$sec_element.size=1;
  792:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  793:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  794:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  795:         } else {
  796:             for (var i=0; i<numSections; i++) {
  797:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  798:             }
  799:             document.$formname.$sec_element.multiple=true
  800:             if (numSections < 3) {
  801:                 document.$formname.$sec_element.size=numSections;
  802:             } else {
  803:                 document.$formname.$sec_element.size=3;
  804:             }
  805:             document.$formname.$sec_element.options[0].selected = false
  806:         }
  807:     }
  808: }
  809: 
  810: function setRole(crstype) {
  811: |;
  812:     if ($role_element eq '') {
  813:         $setsections .= '    return;
  814: }
  815: ';
  816:     } else {
  817:         $setsections .= qq|
  818:     var elementLength = document.$formname.$role_element.length;
  819:     var allroles = Array($rolestr);
  820:     var courserolenames = Array($courserolestr);
  821:     var communityrolenames = Array($communityrolestr);
  822:     if (elementLength != undefined) {
  823:         if (document.$formname.$role_element.options[5].value == 'cc') {
  824:             if (crstype == 'Course') {
  825:                 return;
  826:             } else {
  827:                 allroles[5] = 'co';
  828:                 for (var i=0; i<6; i++) {
  829:                     document.$formname.$role_element.options[i].value = allroles[i];
  830:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  831:                 }
  832:             }
  833:         } else {
  834:             if (crstype == 'Community') {
  835:                 return;
  836:             } else {
  837:                 allroles[5] = 'cc';
  838:                 for (var i=0; i<6; i++) {
  839:                     document.$formname.$role_element.options[i].value = allroles[i];
  840:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  841:                 }
  842:             }
  843:         }
  844:     }
  845:     return;
  846: }
  847: |;
  848:     }
  849:     if ($credits_element) {
  850:         $setsections .= qq|
  851: function setCredits(defaultcredits) {
  852:     document.$formname.$credits_element.value = defaultcredits;
  853:     return;
  854: }
  855: |;
  856:     }
  857:     return $setsections;
  858: }
  859: 
  860: sub selectcourse_link {
  861:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  862:        $typeelement) = @_;
  863:    my $type = $selecttype;
  864:    my $linktext = &mt('Select Course');
  865:    if ($selecttype eq 'Community') {
  866:        $linktext = &mt('Select Community');
  867:    } elsif ($selecttype eq 'Course/Community') {
  868:        $linktext = &mt('Select Course/Community');
  869:        $type = '';
  870:    } elsif ($selecttype eq 'Select') {
  871:        $linktext = &mt('Select');
  872:        $type = '';
  873:    }
  874:    return '<span class="LC_nobreak">'
  875:          ."<a href='"
  876:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  877:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  878:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  879:          ."'>".$linktext.'</a>'
  880:          .'</span>';
  881: }
  882: 
  883: sub selectauthor_link {
  884:    my ($form,$udom)=@_;
  885:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  886:           &mt('Select Author').'</a>';
  887: }
  888: 
  889: sub selectuser_link {
  890:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  891:         $coursedom,$linktext,$caller) = @_;
  892:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  893:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  894:            ');">'.$linktext.'</a>';
  895: }
  896: 
  897: sub check_uncheck_jscript {
  898:     my $jscript = <<"ENDSCRT";
  899: function checkAll(field) {
  900:     if (field.length > 0) {
  901:         for (i = 0; i < field.length; i++) {
  902:             if (!field[i].disabled) {
  903:                 field[i].checked = true;
  904:             }
  905:         }
  906:     } else {
  907:         if (!field.disabled) {
  908:             field.checked = true;
  909:         }
  910:     }
  911: }
  912:  
  913: function uncheckAll(field) {
  914:     if (field.length > 0) {
  915:         for (i = 0; i < field.length; i++) {
  916:             field[i].checked = false ;
  917:         }
  918:     } else {
  919:         field.checked = false ;
  920:     }
  921: }
  922: ENDSCRT
  923:     return $jscript;
  924: }
  925: 
  926: sub select_timezone {
  927:    my ($name,$selected,$onchange,$includeempty)=@_;
  928:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  929:    if ($includeempty) {
  930:        $output .= '<option value=""';
  931:        if (($selected eq '') || ($selected eq 'local')) {
  932:            $output .= ' selected="selected" ';
  933:        }
  934:        $output .= '> </option>';
  935:    }
  936:    my @timezones = DateTime::TimeZone->all_names;
  937:    foreach my $tzone (@timezones) {
  938:        $output.= '<option value="'.$tzone.'"';
  939:        if ($tzone eq $selected) {
  940:            $output.=' selected="selected"';
  941:        }
  942:        $output.=">$tzone</option>\n";
  943:    }
  944:    $output.="</select>";
  945:    return $output;
  946: }
  947: 
  948: sub select_datelocale {
  949:     my ($name,$selected,$onchange,$includeempty)=@_;
  950:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  951:     if ($includeempty) {
  952:         $output .= '<option value=""';
  953:         if ($selected eq '') {
  954:             $output .= ' selected="selected" ';
  955:         }
  956:         $output .= '> </option>';
  957:     }
  958:     my (@possibles,%locale_names);
  959:     my @locales = DateTime::Locale::Catalog::Locales;
  960:     foreach my $locale (@locales) {
  961:         if (ref($locale) eq 'HASH') {
  962:             my $id = $locale->{'id'};
  963:             if ($id ne '') {
  964:                 my $en_terr = $locale->{'en_territory'};
  965:                 my $native_terr = $locale->{'native_territory'};
  966:                 my @languages = &Apache::lonlocal::preferred_languages();
  967:                 if (grep(/^en$/,@languages) || !@languages) {
  968:                     if ($en_terr ne '') {
  969:                         $locale_names{$id} = '('.$en_terr.')';
  970:                     } elsif ($native_terr ne '') {
  971:                         $locale_names{$id} = $native_terr;
  972:                     }
  973:                 } else {
  974:                     if ($native_terr ne '') {
  975:                         $locale_names{$id} = $native_terr.' ';
  976:                     } elsif ($en_terr ne '') {
  977:                         $locale_names{$id} = '('.$en_terr.')';
  978:                     }
  979:                 }
  980:                 push (@possibles,$id);
  981:             }
  982:         }
  983:     }
  984:     foreach my $item (sort(@possibles)) {
  985:         $output.= '<option value="'.$item.'"';
  986:         if ($item eq $selected) {
  987:             $output.=' selected="selected"';
  988:         }
  989:         $output.=">$item";
  990:         if ($locale_names{$item} ne '') {
  991:             $output.="  $locale_names{$item}</option>\n";
  992:         }
  993:         $output.="</option>\n";
  994:     }
  995:     $output.="</select>";
  996:     return $output;
  997: }
  998: 
  999: sub select_language {
 1000:     my ($name,$selected,$includeempty) = @_;
 1001:     my %langchoices;
 1002:     if ($includeempty) {
 1003:         %langchoices = ('' => 'No language preference');
 1004:     }
 1005:     foreach my $id (&languageids()) {
 1006:         my $code = &supportedlanguagecode($id);
 1007:         if ($code) {
 1008:             $langchoices{$code} = &plainlanguagedescription($id);
 1009:         }
 1010:     }
 1011:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1012:     return &select_form($selected,$name,\%langchoices);
 1013: }
 1014: 
 1015: =pod
 1016: 
 1017: =item * &linked_select_forms(...)
 1018: 
 1019: linked_select_forms returns a string containing a <script></script> block
 1020: and html for two <select> menus.  The select menus will be linked in that
 1021: changing the value of the first menu will result in new values being placed
 1022: in the second menu.  The values in the select menu will appear in alphabetical
 1023: order unless a defined order is provided.
 1024: 
 1025: linked_select_forms takes the following ordered inputs:
 1026: 
 1027: =over 4
 1028: 
 1029: =item * $formname, the name of the <form> tag
 1030: 
 1031: =item * $middletext, the text which appears between the <select> tags
 1032: 
 1033: =item * $firstdefault, the default value for the first menu
 1034: 
 1035: =item * $firstselectname, the name of the first <select> tag
 1036: 
 1037: =item * $secondselectname, the name of the second <select> tag
 1038: 
 1039: =item * $hashref, a reference to a hash containing the data for the menus.
 1040: 
 1041: =item * $menuorder, the order of values in the first menu
 1042: 
 1043: =item * $onchangefirst, additional javascript call to execute for an onchange
 1044:         event for the first <select> tag
 1045: 
 1046: =item * $onchangesecond, additional javascript call to execute for an onchange
 1047:         event for the second <select> tag
 1048: 
 1049: =back 
 1050: 
 1051: Below is an example of such a hash.  Only the 'text', 'default', and 
 1052: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1053: values for the first select menu.  The text that coincides with the 
 1054: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1055: and text for the second menu are given in the hash pointed to by 
 1056: $menu{$choice1}->{'select2'}.  
 1057: 
 1058:  my %menu = ( A1 => { text =>"Choice A1" ,
 1059:                        default => "B3",
 1060:                        select2 => { 
 1061:                            B1 => "Choice B1",
 1062:                            B2 => "Choice B2",
 1063:                            B3 => "Choice B3",
 1064:                            B4 => "Choice B4"
 1065:                            },
 1066:                        order => ['B4','B3','B1','B2'],
 1067:                    },
 1068:                A2 => { text =>"Choice A2" ,
 1069:                        default => "C2",
 1070:                        select2 => { 
 1071:                            C1 => "Choice C1",
 1072:                            C2 => "Choice C2",
 1073:                            C3 => "Choice C3"
 1074:                            },
 1075:                        order => ['C2','C1','C3'],
 1076:                    },
 1077:                A3 => { text =>"Choice A3" ,
 1078:                        default => "D6",
 1079:                        select2 => { 
 1080:                            D1 => "Choice D1",
 1081:                            D2 => "Choice D2",
 1082:                            D3 => "Choice D3",
 1083:                            D4 => "Choice D4",
 1084:                            D5 => "Choice D5",
 1085:                            D6 => "Choice D6",
 1086:                            D7 => "Choice D7"
 1087:                            },
 1088:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1089:                    }
 1090:                );
 1091: 
 1092: =cut
 1093: 
 1094: sub linked_select_forms {
 1095:     my ($formname,
 1096:         $middletext,
 1097:         $firstdefault,
 1098:         $firstselectname,
 1099:         $secondselectname, 
 1100:         $hashref,
 1101:         $menuorder,
 1102:         $onchangefirst,
 1103:         $onchangesecond
 1104:         ) = @_;
 1105:     my $second = "document.$formname.$secondselectname";
 1106:     my $first = "document.$formname.$firstselectname";
 1107:     # output the javascript to do the changing
 1108:     my $result = '';
 1109:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1110:     $result.="// <![CDATA[\n";
 1111:     $result.="var select2data = new Object();\n";
 1112:     $" = '","';
 1113:     my $debug = '';
 1114:     foreach my $s1 (sort(keys(%$hashref))) {
 1115:         $result.="select2data.d_$s1 = new Object();\n";        
 1116:         $result.="select2data.d_$s1.def = new String('".
 1117:             $hashref->{$s1}->{'default'}."');\n";
 1118:         $result.="select2data.d_$s1.values = new Array(";
 1119:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1120:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1121:             @s2values = @{$hashref->{$s1}->{'order'}};
 1122:         }
 1123:         $result.="\"@s2values\");\n";
 1124:         $result.="select2data.d_$s1.texts = new Array(";        
 1125:         my @s2texts;
 1126:         foreach my $value (@s2values) {
 1127:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1128:         }
 1129:         $result.="\"@s2texts\");\n";
 1130:     }
 1131:     $"=' ';
 1132:     $result.= <<"END";
 1133: 
 1134: function select1_changed() {
 1135:     // Determine new choice
 1136:     var newvalue = "d_" + $first.value;
 1137:     // update select2
 1138:     var values     = select2data[newvalue].values;
 1139:     var texts      = select2data[newvalue].texts;
 1140:     var select2def = select2data[newvalue].def;
 1141:     var i;
 1142:     // out with the old
 1143:     for (i = 0; i < $second.options.length; i++) {
 1144:         $second.options[i] = null;
 1145:     }
 1146:     // in with the nuclear
 1147:     for (i=0;i<values.length; i++) {
 1148:         $second.options[i] = new Option(values[i]);
 1149:         $second.options[i].value = values[i];
 1150:         $second.options[i].text = texts[i];
 1151:         if (values[i] == select2def) {
 1152:             $second.options[i].selected = true;
 1153:         }
 1154:     }
 1155: }
 1156: // ]]>
 1157: </script>
 1158: END
 1159:     # output the initial values for the selection lists
 1160:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1161:     my @order = sort(keys(%{$hashref}));
 1162:     if (ref($menuorder) eq 'ARRAY') {
 1163:         @order = @{$menuorder};
 1164:     }
 1165:     foreach my $value (@order) {
 1166:         $result.="    <option value=\"$value\" ";
 1167:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1168:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1169:     }
 1170:     $result .= "</select>\n";
 1171:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1172:     $result .= $middletext;
 1173:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1174:     if ($onchangesecond) {
 1175:         $result .= ' onchange="'.$onchangesecond.'"';
 1176:     }
 1177:     $result .= ">\n";
 1178:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1179:     
 1180:     my @secondorder = sort(keys(%select2));
 1181:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1182:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1183:     }
 1184:     foreach my $value (@secondorder) {
 1185:         $result.="    <option value=\"$value\" ";        
 1186:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1187:         $result.=">".&mt($select2{$value})."</option>\n";
 1188:     }
 1189:     $result .= "</select>\n";
 1190:     #    return $debug;
 1191:     return $result;
 1192: }   #  end of sub linked_select_forms {
 1193: 
 1194: =pod
 1195: 
 1196: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1197: 
 1198: Returns a string corresponding to an HTML link to the given help
 1199: $topic, where $topic corresponds to the name of a .tex file in
 1200: /home/httpd/html/adm/help/tex, with underscores replaced by
 1201: spaces. 
 1202: 
 1203: $text will optionally be linked to the same topic, allowing you to
 1204: link text in addition to the graphic. If you do not want to link
 1205: text, but wish to specify one of the later parameters, pass an
 1206: empty string. 
 1207: 
 1208: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1209: the link will not open a new window. If false, the link will open
 1210: a new window using Javascript. (Default is false.) 
 1211: 
 1212: $width and $height are optional numerical parameters that will
 1213: override the width and height of the popped up window, which may
 1214: be useful for certain help topics with big pictures included.
 1215: 
 1216: $imgid is the id of the img tag used for the help icon. This may be
 1217: used in a javascript call to switch the image src.  See 
 1218: lonhtmlcommon::htmlareaselectactive() for an example.
 1219: 
 1220: =cut
 1221: 
 1222: sub help_open_topic {
 1223:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1224:     $text = "" if (not defined $text);
 1225:     $stayOnPage = 0 if (not defined $stayOnPage);
 1226:     $width = 500 if (not defined $width);
 1227:     $height = 400 if (not defined $height);
 1228:     my $filename = $topic;
 1229:     $filename =~ s/ /_/g;
 1230: 
 1231:     my $template = "";
 1232:     my $link;
 1233:     
 1234:     $topic=~s/\W/\_/g;
 1235: 
 1236:     if (!$stayOnPage) {
 1237: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1238:     } elsif ($stayOnPage eq 'popup') {
 1239:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1240:     } else {
 1241: 	$link = "/adm/help/${filename}.hlp";
 1242:     }
 1243: 
 1244:     # Add the text
 1245:     if ($text ne "") {	
 1246: 	$template.='<span class="LC_help_open_topic">'
 1247:                   .'<a target="_top" href="'.$link.'">'
 1248:                   .$text.'</a>';
 1249:     }
 1250: 
 1251:     # (Always) Add the graphic
 1252:     my $title = &mt('Online Help');
 1253:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1254:     if ($imgid ne '') {
 1255:         $imgid = ' id="'.$imgid.'"';
 1256:     }
 1257:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1258:               .'<img src="'.$helpicon.'" border="0"'
 1259:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1260:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1261:               .' /></a>';
 1262:     if ($text ne "") {	
 1263:         $template.='</span>';
 1264:     }
 1265:     return $template;
 1266: 
 1267: }
 1268: 
 1269: # This is a quicky function for Latex cheatsheet editing, since it 
 1270: # appears in at least four places
 1271: sub helpLatexCheatsheet {
 1272:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1273:     my $out;
 1274:     my $addOther = '';
 1275:     if ($topic) {
 1276: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1277:     }
 1278:     $out = '<span>' # Start cheatsheet
 1279: 	  .$addOther
 1280:           .'<span>'
 1281: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1282: 	  .'</span> <span>'
 1283: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1284: 	  .'</span>';
 1285:     unless ($not_author) {
 1286:         $out .= ' <span>'
 1287: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1288: 	       .'</span>';
 1289:     }
 1290:     $out .= '</span>'; # End cheatsheet
 1291:     return $out;
 1292: }
 1293: 
 1294: sub general_help {
 1295:     my $helptopic='Student_Intro';
 1296:     if ($env{'request.role'}=~/^(ca|au)/) {
 1297: 	$helptopic='Authoring_Intro';
 1298:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1299: 	$helptopic='Course_Coordination_Intro';
 1300:     } elsif ($env{'request.role'}=~/^dc/) {
 1301:         $helptopic='Domain_Coordination_Intro';
 1302:     }
 1303:     return $helptopic;
 1304: }
 1305: 
 1306: sub update_help_link {
 1307:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1308:     my $origurl = $ENV{'REQUEST_URI'};
 1309:     $origurl=~s|^/~|/priv/|;
 1310:     my $timestamp = time;
 1311:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1312:         $$datum = &escape($$datum);
 1313:     }
 1314: 
 1315:     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";
 1316:     my $output .= <<"ENDOUTPUT";
 1317: <script type="text/javascript">
 1318: // <![CDATA[
 1319: banner_link = '$banner_link';
 1320: // ]]>
 1321: </script>
 1322: ENDOUTPUT
 1323:     return $output;
 1324: }
 1325: 
 1326: # now just updates the help link and generates a blue icon
 1327: sub help_open_menu {
 1328:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1329: 	= @_;    
 1330:     $stayOnPage = 1;
 1331:     my $output;
 1332:     if ($component_help) {
 1333: 	if (!$text) {
 1334: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1335: 				       $width,$height);
 1336: 	} else {
 1337: 	    my $help_text;
 1338: 	    $help_text=&unescape($topic);
 1339: 	    $output='<table><tr><td>'.
 1340: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1341: 				 $width,$height).'</td></tr></table>';
 1342: 	}
 1343:     }
 1344:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1345:     return $output.$banner_link;
 1346: }
 1347: 
 1348: sub top_nav_help {
 1349:     my ($text) = @_;
 1350:     $text = &mt($text);
 1351:     my $stay_on_page = 1;
 1352: 
 1353:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1354: 	                     : "javascript:helpMenu('open')";
 1355:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1356: 
 1357:     my $title = &mt('Get help');
 1358: 
 1359:     return <<"END";
 1360: $banner_link
 1361:  <a href="$link" title="$title">$text</a>
 1362: END
 1363: }
 1364: 
 1365: sub help_menu_js {
 1366:     my ($text) = @_;
 1367:     my $stayOnPage = 1;
 1368:     my $width = 620;
 1369:     my $height = 600;
 1370:     my $helptopic=&general_help();
 1371:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1372:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1373:     my $start_page =
 1374:         &Apache::loncommon::start_page('Help Menu', undef,
 1375: 				       {'frameset'    => 1,
 1376: 					'js_ready'    => 1,
 1377: 					'add_entries' => {
 1378: 					    'border' => '0',
 1379: 					    'rows'   => "110,*",},});
 1380:     my $end_page =
 1381:         &Apache::loncommon::end_page({'frameset' => 1,
 1382: 				      'js_ready' => 1,});
 1383: 
 1384:     my $template .= <<"ENDTEMPLATE";
 1385: <script type="text/javascript">
 1386: // <![CDATA[
 1387: // <!-- BEGIN LON-CAPA Internal
 1388: var banner_link = '';
 1389: function helpMenu(target) {
 1390:     var caller = this;
 1391:     if (target == 'open') {
 1392:         var newWindow = null;
 1393:         try {
 1394:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1395:         }
 1396:         catch(error) {
 1397:             writeHelp(caller);
 1398:             return;
 1399:         }
 1400:         if (newWindow) {
 1401:             caller = newWindow;
 1402:         }
 1403:     }
 1404:     writeHelp(caller);
 1405:     return;
 1406: }
 1407: function writeHelp(caller) {
 1408:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1409:     caller.document.close()
 1410:     caller.focus()
 1411: }
 1412: // END LON-CAPA Internal -->
 1413: // ]]>
 1414: </script>
 1415: ENDTEMPLATE
 1416:     return $template;
 1417: }
 1418: 
 1419: sub help_open_bug {
 1420:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1421:     unless ($env{'user.adv'}) { return ''; }
 1422:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1423:     $text = "" if (not defined $text);
 1424: 	$stayOnPage=1;
 1425:     $width = 600 if (not defined $width);
 1426:     $height = 600 if (not defined $height);
 1427: 
 1428:     $topic=~s/\W+/\+/g;
 1429:     my $link='';
 1430:     my $template='';
 1431:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1432: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1433:     if (!$stayOnPage)
 1434:     {
 1435: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1436:     }
 1437:     else
 1438:     {
 1439: 	$link = $url;
 1440:     }
 1441:     # Add the text
 1442:     if ($text ne "")
 1443:     {
 1444: 	$template .= 
 1445:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1446:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1447:     }
 1448: 
 1449:     # Add the graphic
 1450:     my $title = &mt('Report a Bug');
 1451:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1452:     $template .= <<"ENDTEMPLATE";
 1453:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1454: ENDTEMPLATE
 1455:     if ($text ne '') { $template.='</td></tr></table>' };
 1456:     return $template;
 1457: 
 1458: }
 1459: 
 1460: sub help_open_faq {
 1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1462:     unless ($env{'user.adv'}) { return ''; }
 1463:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1464:     $text = "" if (not defined $text);
 1465: 	$stayOnPage=1;
 1466:     $width = 350 if (not defined $width);
 1467:     $height = 400 if (not defined $height);
 1468: 
 1469:     $topic=~s/\W+/\+/g;
 1470:     my $link='';
 1471:     my $template='';
 1472:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1473:     if (!$stayOnPage)
 1474:     {
 1475: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1476:     }
 1477:     else
 1478:     {
 1479: 	$link = $url;
 1480:     }
 1481: 
 1482:     # Add the text
 1483:     if ($text ne "")
 1484:     {
 1485: 	$template .= 
 1486:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1487:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1488:     }
 1489: 
 1490:     # Add the graphic
 1491:     my $title = &mt('View the FAQ');
 1492:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1493:     $template .= <<"ENDTEMPLATE";
 1494:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1495: ENDTEMPLATE
 1496:     if ($text ne '') { $template.='</td></tr></table>' };
 1497:     return $template;
 1498: 
 1499: }
 1500: 
 1501: ###############################################################
 1502: ###############################################################
 1503: 
 1504: =pod
 1505: 
 1506: =item * &change_content_javascript():
 1507: 
 1508: This and the next function allow you to create small sections of an
 1509: otherwise static HTML page that you can update on the fly with
 1510: Javascript, even in Netscape 4.
 1511: 
 1512: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1513: must be written to the HTML page once. It will prove the Javascript
 1514: function "change(name, content)". Calling the change function with the
 1515: name of the section 
 1516: you want to update, matching the name passed to C<changable_area>, and
 1517: the new content you want to put in there, will put the content into
 1518: that area.
 1519: 
 1520: B<Note>: Netscape 4 only reserves enough space for the changable area
 1521: to contain room for the original contents. You need to "make space"
 1522: for whatever changes you wish to make, and be B<sure> to check your
 1523: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1524: it's adequate for updating a one-line status display, but little more.
 1525: This script will set the space to 100% width, so you only need to
 1526: worry about height in Netscape 4.
 1527: 
 1528: Modern browsers are much less limiting, and if you can commit to the
 1529: user not using Netscape 4, this feature may be used freely with
 1530: pretty much any HTML.
 1531: 
 1532: =cut
 1533: 
 1534: sub change_content_javascript {
 1535:     # If we're on Netscape 4, we need to use Layer-based code
 1536:     if ($env{'browser.type'} eq 'netscape' &&
 1537: 	$env{'browser.version'} =~ /^4\./) {
 1538: 	return (<<NETSCAPE4);
 1539: 	function change(name, content) {
 1540: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1541: 	    doc.open();
 1542: 	    doc.write(content);
 1543: 	    doc.close();
 1544: 	}
 1545: NETSCAPE4
 1546:     } else {
 1547: 	# Otherwise, we need to use semi-standards-compliant code
 1548: 	# (technically, "innerHTML" isn't standard but the equivalent
 1549: 	# is really scary, and every useful browser supports it
 1550: 	return (<<DOMBASED);
 1551: 	function change(name, content) {
 1552: 	    element = document.getElementById(name);
 1553: 	    element.innerHTML = content;
 1554: 	}
 1555: DOMBASED
 1556:     }
 1557: }
 1558: 
 1559: =pod
 1560: 
 1561: =item * &changable_area($name,$origContent):
 1562: 
 1563: This provides a "changable area" that can be modified on the fly via
 1564: the Javascript code provided in C<change_content_javascript>. $name is
 1565: the name you will use to reference the area later; do not repeat the
 1566: same name on a given HTML page more then once. $origContent is what
 1567: the area will originally contain, which can be left blank.
 1568: 
 1569: =cut
 1570: 
 1571: sub changable_area {
 1572:     my ($name, $origContent) = @_;
 1573: 
 1574:     if ($env{'browser.type'} eq 'netscape' &&
 1575: 	$env{'browser.version'} =~ /^4\./) {
 1576: 	# If this is netscape 4, we need to use the Layer tag
 1577: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1578:     } else {
 1579: 	return "<span id='$name'>$origContent</span>";
 1580:     }
 1581: }
 1582: 
 1583: =pod
 1584: 
 1585: =item * &viewport_geometry_js 
 1586: 
 1587: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1588: 
 1589: =cut
 1590: 
 1591: 
 1592: sub viewport_geometry_js { 
 1593:     return <<"GEOMETRY";
 1594: var Geometry = {};
 1595: function init_geometry() {
 1596:     if (Geometry.init) { return };
 1597:     Geometry.init=1;
 1598:     if (window.innerHeight) {
 1599:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1600:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1601:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1602:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1603:     }
 1604:     else if (document.documentElement && document.documentElement.clientHeight) {
 1605:         Geometry.getViewportHeight =
 1606:             function() { return document.documentElement.clientHeight; };
 1607:         Geometry.getViewportWidth =
 1608:             function() { return document.documentElement.clientWidth; };
 1609: 
 1610:         Geometry.getHorizontalScroll =
 1611:             function() { return document.documentElement.scrollLeft; };
 1612:         Geometry.getVerticalScroll =
 1613:             function() { return document.documentElement.scrollTop; };
 1614:     }
 1615:     else if (document.body.clientHeight) {
 1616:         Geometry.getViewportHeight =
 1617:             function() { return document.body.clientHeight; };
 1618:         Geometry.getViewportWidth =
 1619:             function() { return document.body.clientWidth; };
 1620:         Geometry.getHorizontalScroll =
 1621:             function() { return document.body.scrollLeft; };
 1622:         Geometry.getVerticalScroll =
 1623:             function() { return document.body.scrollTop; };
 1624:     }
 1625: }
 1626: 
 1627: GEOMETRY
 1628: }
 1629: 
 1630: =pod
 1631: 
 1632: =item * &viewport_size_js()
 1633: 
 1634: 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. 
 1635: 
 1636: =cut
 1637: 
 1638: sub viewport_size_js {
 1639:     my $geometry = &viewport_geometry_js();
 1640:     return <<"DIMS";
 1641: 
 1642: $geometry
 1643: 
 1644: function getViewportDims(width,height) {
 1645:     init_geometry();
 1646:     width.value = Geometry.getViewportWidth();
 1647:     height.value = Geometry.getViewportHeight();
 1648:     return;
 1649: }
 1650: 
 1651: DIMS
 1652: }
 1653: 
 1654: =pod
 1655: 
 1656: =item * &resize_textarea_js()
 1657: 
 1658: emits the needed javascript to resize a textarea to be as big as possible
 1659: 
 1660: creates a function resize_textrea that takes two IDs first should be
 1661: the id of the element to resize, second should be the id of a div that
 1662: surrounds everything that comes after the textarea, this routine needs
 1663: to be attached to the <body> for the onload and onresize events.
 1664: 
 1665: =back
 1666: 
 1667: =cut
 1668: 
 1669: sub resize_textarea_js {
 1670:     my $geometry = &viewport_geometry_js();
 1671:     return <<"RESIZE";
 1672:     <script type="text/javascript">
 1673: // <![CDATA[
 1674: $geometry
 1675: 
 1676: function getX(element) {
 1677:     var x = 0;
 1678:     while (element) {
 1679: 	x += element.offsetLeft;
 1680: 	element = element.offsetParent;
 1681:     }
 1682:     return x;
 1683: }
 1684: function getY(element) {
 1685:     var y = 0;
 1686:     while (element) {
 1687: 	y += element.offsetTop;
 1688: 	element = element.offsetParent;
 1689:     }
 1690:     return y;
 1691: }
 1692: 
 1693: 
 1694: function resize_textarea(textarea_id,bottom_id) {
 1695:     init_geometry();
 1696:     var textarea        = document.getElementById(textarea_id);
 1697:     //alert(textarea);
 1698: 
 1699:     var textarea_top    = getY(textarea);
 1700:     var textarea_height = textarea.offsetHeight;
 1701:     var bottom          = document.getElementById(bottom_id);
 1702:     var bottom_top      = getY(bottom);
 1703:     var bottom_height   = bottom.offsetHeight;
 1704:     var window_height   = Geometry.getViewportHeight();
 1705:     var fudge           = 23;
 1706:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1707:     if (new_height < 300) {
 1708: 	new_height = 300;
 1709:     }
 1710:     textarea.style.height=new_height+'px';
 1711: }
 1712: // ]]>
 1713: </script>
 1714: RESIZE
 1715: 
 1716: }
 1717: 
 1718: =pod
 1719: 
 1720: =head1 Excel and CSV file utility routines
 1721: 
 1722: =over 4
 1723: 
 1724: =cut
 1725: 
 1726: ###############################################################
 1727: ###############################################################
 1728: 
 1729: =pod
 1730: 
 1731: =item * &csv_translate($text) 
 1732: 
 1733: Translate $text to allow it to be output as a 'comma separated values' 
 1734: format.
 1735: 
 1736: =cut
 1737: 
 1738: ###############################################################
 1739: ###############################################################
 1740: sub csv_translate {
 1741:     my $text = shift;
 1742:     $text =~ s/\"/\"\"/g;
 1743:     $text =~ s/\n/ /g;
 1744:     return $text;
 1745: }
 1746: 
 1747: ###############################################################
 1748: ###############################################################
 1749: 
 1750: =pod
 1751: 
 1752: =item * &define_excel_formats()
 1753: 
 1754: Define some commonly used Excel cell formats.
 1755: 
 1756: Currently supported formats:
 1757: 
 1758: =over 4
 1759: 
 1760: =item header
 1761: 
 1762: =item bold
 1763: 
 1764: =item h1
 1765: 
 1766: =item h2
 1767: 
 1768: =item h3
 1769: 
 1770: =item h4
 1771: 
 1772: =item i
 1773: 
 1774: =item date
 1775: 
 1776: =back
 1777: 
 1778: Inputs: $workbook
 1779: 
 1780: Returns: $format, a hash reference.
 1781: 
 1782: 
 1783: =cut
 1784: 
 1785: ###############################################################
 1786: ###############################################################
 1787: sub define_excel_formats {
 1788:     my ($workbook) = @_;
 1789:     my $format;
 1790:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1791:                                                 bottom    => 1,
 1792:                                                 align     => 'center');
 1793:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1794:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1795:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1796:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1797:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1798:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1799:     $format->{'date'} = $workbook->add_format(num_format=>
 1800:                                             'mm/dd/yyyy hh:mm:ss');
 1801:     return $format;
 1802: }
 1803: 
 1804: ###############################################################
 1805: ###############################################################
 1806: 
 1807: =pod
 1808: 
 1809: =item * &create_workbook()
 1810: 
 1811: Create an Excel worksheet.  If it fails, output message on the
 1812: request object and return undefs.
 1813: 
 1814: Inputs: Apache request object
 1815: 
 1816: Returns (undef) on failure, 
 1817:     Excel worksheet object, scalar with filename, and formats 
 1818:     from &Apache::loncommon::define_excel_formats on success
 1819: 
 1820: =cut
 1821: 
 1822: ###############################################################
 1823: ###############################################################
 1824: sub create_workbook {
 1825:     my ($r) = @_;
 1826:         #
 1827:     # Create the excel spreadsheet
 1828:     my $filename = '/prtspool/'.
 1829:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1830:         time.'_'.rand(1000000000).'.xls';
 1831:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1832:     if (! defined($workbook)) {
 1833:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1834:         $r->print(
 1835:             '<p class="LC_error">'
 1836:            .&mt('Problems occurred in creating the new Excel file.')
 1837:            .' '.&mt('This error has been logged.')
 1838:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1839:            .'</p>'
 1840:         );
 1841:         return (undef);
 1842:     }
 1843:     #
 1844:     $workbook->set_tempdir(LONCAPA::tempdir());
 1845:     #
 1846:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1847:     return ($workbook,$filename,$format);
 1848: }
 1849: 
 1850: ###############################################################
 1851: ###############################################################
 1852: 
 1853: =pod
 1854: 
 1855: =item * &create_text_file()
 1856: 
 1857: Create a file to write to and eventually make available to the user.
 1858: If file creation fails, outputs an error message on the request object and 
 1859: return undefs.
 1860: 
 1861: Inputs: Apache request object, and file suffix
 1862: 
 1863: Returns (undef) on failure, 
 1864:     Filehandle and filename on success.
 1865: 
 1866: =cut
 1867: 
 1868: ###############################################################
 1869: ###############################################################
 1870: sub create_text_file {
 1871:     my ($r,$suffix) = @_;
 1872:     if (! defined($suffix)) { $suffix = 'txt'; };
 1873:     my $fh;
 1874:     my $filename = '/prtspool/'.
 1875:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1876:         time.'_'.rand(1000000000).'.'.$suffix;
 1877:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1878:     if (! defined($fh)) {
 1879:         $r->log_error("Couldn't open $filename for output $!");
 1880:         $r->print(
 1881:             '<p class="LC_error">'
 1882:            .&mt('Problems occurred in creating the output file.')
 1883:            .' '.&mt('This error has been logged.')
 1884:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1885:            .'</p>'
 1886:         );
 1887:     }
 1888:     return ($fh,$filename)
 1889: }
 1890: 
 1891: 
 1892: =pod 
 1893: 
 1894: =back
 1895: 
 1896: =cut
 1897: 
 1898: ###############################################################
 1899: ##        Home server <option> list generating code          ##
 1900: ###############################################################
 1901: 
 1902: # ------------------------------------------
 1903: 
 1904: sub domain_select {
 1905:     my ($name,$value,$multiple)=@_;
 1906:     my %domains=map { 
 1907: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1908:     } &Apache::lonnet::all_domains();
 1909:     if ($multiple) {
 1910: 	$domains{''}=&mt('Any domain');
 1911: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1912: 	return &multiple_select_form($name,$value,4,\%domains);
 1913:     } else {
 1914: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1915: 	return &select_form($name,$value,\%domains);
 1916:     }
 1917: }
 1918: 
 1919: #-------------------------------------------
 1920: 
 1921: =pod
 1922: 
 1923: =head1 Routines for form select boxes
 1924: 
 1925: =over 4
 1926: 
 1927: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1928: 
 1929: Returns a string containing a <select> element int multiple mode
 1930: 
 1931: 
 1932: Args:
 1933:   $name - name of the <select> element
 1934:   $value - scalar or array ref of values that should already be selected
 1935:   $size - number of rows long the select element is
 1936:   $hash - the elements should be 'option' => 'shown text'
 1937:           (shown text should already have been &mt())
 1938:   $order - (optional) array ref of the order to show the elements in
 1939: 
 1940: =cut
 1941: 
 1942: #-------------------------------------------
 1943: sub multiple_select_form {
 1944:     my ($name,$value,$size,$hash,$order)=@_;
 1945:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1946:     my $output='';
 1947:     if (! defined($size)) {
 1948:         $size = 4;
 1949:         if (scalar(keys(%$hash))<4) {
 1950:             $size = scalar(keys(%$hash));
 1951:         }
 1952:     }
 1953:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1954:     my @order;
 1955:     if (ref($order) eq 'ARRAY')  {
 1956:         @order = @{$order};
 1957:     } else {
 1958:         @order = sort(keys(%$hash));
 1959:     }
 1960:     if (exists($$hash{'select_form_order'})) {
 1961:         @order = @{$$hash{'select_form_order'}};
 1962:     }
 1963:         
 1964:     foreach my $key (@order) {
 1965:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1966:         $output.='selected="selected" ' if ($selected{$key});
 1967:         $output.='>'.$hash->{$key}."</option>\n";
 1968:     }
 1969:     $output.="</select>\n";
 1970:     return $output;
 1971: }
 1972: 
 1973: #-------------------------------------------
 1974: 
 1975: =pod
 1976: 
 1977: =item * &select_form($defdom,$name,$hashref,$onchange)
 1978: 
 1979: Returns a string containing a <select name='$name' size='1'> form to 
 1980: allow a user to select options from a ref to a hash containing:
 1981: option_name => displayed text. An optional $onchange can include
 1982: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1983: 
 1984: See lonrights.pm for an example invocation and use.
 1985: 
 1986: =cut
 1987: 
 1988: #-------------------------------------------
 1989: sub select_form {
 1990:     my ($def,$name,$hashref,$onchange) = @_;
 1991:     return unless (ref($hashref) eq 'HASH');
 1992:     if ($onchange) {
 1993:         $onchange = ' onchange="'.$onchange.'"';
 1994:     }
 1995:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1996:     my @keys;
 1997:     if (exists($hashref->{'select_form_order'})) {
 1998: 	@keys=@{$hashref->{'select_form_order'}};
 1999:     } else {
 2000: 	@keys=sort(keys(%{$hashref}));
 2001:     }
 2002:     foreach my $key (@keys) {
 2003:         $selectform.=
 2004: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2005:             ($key eq $def ? 'selected="selected" ' : '').
 2006:                 ">".$hashref->{$key}."</option>\n";
 2007:     }
 2008:     $selectform.="</select>";
 2009:     return $selectform;
 2010: }
 2011: 
 2012: # For display filters
 2013: 
 2014: sub display_filter {
 2015:     my ($context) = @_;
 2016:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2017:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2018:     my $phraseinput = 'hidden';
 2019:     my $includeinput = 'hidden';
 2020:     my ($checked,$includetypestext);
 2021:     if ($env{'form.displayfilter'} eq 'containing') {
 2022:         $phraseinput = 'text'; 
 2023:         if ($context eq 'parmslog') {
 2024:             $includeinput = 'checkbox';
 2025:             if ($env{'form.includetypes'}) {
 2026:                 $checked = ' checked="checked"';
 2027:             }
 2028:             $includetypestext = &mt('Include parameter types');
 2029:         }
 2030:     } else {
 2031:         $includetypestext = '&nbsp;';
 2032:     }
 2033:     my ($additional,$secondid,$thirdid);
 2034:     if ($context eq 'parmslog') {
 2035:         $additional = 
 2036:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2037:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2038:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2039:             '</label>';
 2040:         $secondid = 'includetypes';
 2041:         $thirdid = 'includetypestext';
 2042:     }
 2043:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2044:                                                     '$secondid','$thirdid')";
 2045:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2046: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2047: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2048: 	   '</label></span> <span class="LC_nobreak">'.
 2049:            &mt('Filter: [_1]',
 2050: 	   &select_form($env{'form.displayfilter'},
 2051: 			'displayfilter',
 2052: 			{'currentfolder' => 'Current folder/page',
 2053: 			 'containing' => 'Containing phrase',
 2054: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2055: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2056:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2057:                          '" />'.$additional;
 2058: }
 2059: 
 2060: sub display_filter_js {
 2061:     my $includetext = &mt('Include parameter types');
 2062:     return <<"ENDJS";
 2063:   
 2064: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2065:     var firstType = 'hidden';
 2066:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2067:         firstType = 'text';
 2068:     }
 2069:     firstObject = document.getElementById(firstid);
 2070:     if (typeof(firstObject) == 'object') {
 2071:         if (firstObject.type != firstType) {
 2072:             changeInputType(firstObject,firstType);
 2073:         }
 2074:     }
 2075:     if (context == 'parmslog') {
 2076:         var secondType = 'hidden';
 2077:         if (firstType == 'text') {
 2078:             secondType = 'checkbox';
 2079:         }
 2080:         secondObject = document.getElementById(secondid);  
 2081:         if (typeof(secondObject) == 'object') {
 2082:             if (secondObject.type != secondType) {
 2083:                 changeInputType(secondObject,secondType);
 2084:             }
 2085:         }
 2086:         var textItem = document.getElementById(thirdid);
 2087:         var currtext = textItem.innerHTML;
 2088:         var newtext;
 2089:         if (firstType == 'text') {
 2090:             newtext = '$includetext';
 2091:         } else {
 2092:             newtext = '&nbsp;';
 2093:         }
 2094:         if (currtext != newtext) {
 2095:             textItem.innerHTML = newtext;
 2096:         }
 2097:     }
 2098:     return;
 2099: }
 2100: 
 2101: function changeInputType(oldObject,newType) {
 2102:     var newObject = document.createElement('input');
 2103:     newObject.type = newType;
 2104:     if (oldObject.size) {
 2105:         newObject.size = oldObject.size;
 2106:     }
 2107:     if (oldObject.value) {
 2108:         newObject.value = oldObject.value;
 2109:     }
 2110:     if (oldObject.name) {
 2111:         newObject.name = oldObject.name;
 2112:     }
 2113:     if (oldObject.id) {
 2114:         newObject.id = oldObject.id;
 2115:     }
 2116:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2117:     return;
 2118: }
 2119: 
 2120: ENDJS
 2121: }
 2122: 
 2123: sub gradeleveldescription {
 2124:     my $gradelevel=shift;
 2125:     my %gradelevels=(0 => 'Not specified',
 2126: 		     1 => 'Grade 1',
 2127: 		     2 => 'Grade 2',
 2128: 		     3 => 'Grade 3',
 2129: 		     4 => 'Grade 4',
 2130: 		     5 => 'Grade 5',
 2131: 		     6 => 'Grade 6',
 2132: 		     7 => 'Grade 7',
 2133: 		     8 => 'Grade 8',
 2134: 		     9 => 'Grade 9',
 2135: 		     10 => 'Grade 10',
 2136: 		     11 => 'Grade 11',
 2137: 		     12 => 'Grade 12',
 2138: 		     13 => 'Grade 13',
 2139: 		     14 => '100 Level',
 2140: 		     15 => '200 Level',
 2141: 		     16 => '300 Level',
 2142: 		     17 => '400 Level',
 2143: 		     18 => 'Graduate Level');
 2144:     return &mt($gradelevels{$gradelevel});
 2145: }
 2146: 
 2147: sub select_level_form {
 2148:     my ($deflevel,$name)=@_;
 2149:     unless ($deflevel) { $deflevel=0; }
 2150:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2151:     for (my $i=0; $i<=18; $i++) {
 2152:         $selectform.="<option value=\"$i\" ".
 2153:             ($i==$deflevel ? 'selected="selected" ' : '').
 2154:                 ">".&gradeleveldescription($i)."</option>\n";
 2155:     }
 2156:     $selectform.="</select>";
 2157:     return $selectform;
 2158: }
 2159: 
 2160: #-------------------------------------------
 2161: 
 2162: =pod
 2163: 
 2164: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2165: 
 2166: Returns a string containing a <select name='$name' size='1'> form to 
 2167: allow a user to select the domain to preform an operation in.  
 2168: See loncreateuser.pm for an example invocation and use.
 2169: 
 2170: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2171: selected");
 2172: 
 2173: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2174: 
 2175: 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.
 2176: 
 2177: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2178: 
 2179: =cut
 2180: 
 2181: #-------------------------------------------
 2182: sub select_dom_form {
 2183:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2184:     if ($onchange) {
 2185:         $onchange = ' onchange="'.$onchange.'"';
 2186:     }
 2187:     my @domains;
 2188:     if (ref($incdoms) eq 'ARRAY') {
 2189:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2190:     } else {
 2191:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2192:     }
 2193:     if ($includeempty) { @domains=('',@domains); }
 2194:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2195:     foreach my $dom (@domains) {
 2196:         $selectdomain.="<option value=\"$dom\" ".
 2197:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2198:         if ($showdomdesc) {
 2199:             if ($dom ne '') {
 2200:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2201:                 if ($domdesc ne '') {
 2202:                     $selectdomain .= ' ('.$domdesc.')';
 2203:                 }
 2204:             } 
 2205:         }
 2206:         $selectdomain .= "</option>\n";
 2207:     }
 2208:     $selectdomain.="</select>";
 2209:     return $selectdomain;
 2210: }
 2211: 
 2212: #-------------------------------------------
 2213: 
 2214: =pod
 2215: 
 2216: =item * &home_server_form_item($domain,$name,$defaultflag)
 2217: 
 2218: input: 4 arguments (two required, two optional) - 
 2219:     $domain - domain of new user
 2220:     $name - name of form element
 2221:     $default - Value of 'default' causes a default item to be first 
 2222:                             option, and selected by default. 
 2223:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2224:                             if 1 server found, or default, if 0 found.
 2225: output: returns 2 items: 
 2226: (a) form element which contains either:
 2227:    (i) <select name="$name">
 2228:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2229:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2230:        </select>
 2231:        form item if there are multiple library servers in $domain, or
 2232:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2233:        if there is only one library server in $domain.
 2234: 
 2235: (b) number of library servers found.
 2236: 
 2237: See loncreateuser.pm for example of use.
 2238: 
 2239: =cut
 2240: 
 2241: #-------------------------------------------
 2242: sub home_server_form_item {
 2243:     my ($domain,$name,$default,$hide) = @_;
 2244:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2245:     my $result;
 2246:     my $numlib = keys(%servers);
 2247:     if ($numlib > 1) {
 2248:         $result .= '<select name="'.$name.'" />'."\n";
 2249:         if ($default) {
 2250:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2251:                        '</option>'."\n";
 2252:         }
 2253:         foreach my $hostid (sort(keys(%servers))) {
 2254:             $result.= '<option value="'.$hostid.'">'.
 2255: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2256:         }
 2257:         $result .= '</select>'."\n";
 2258:     } elsif ($numlib == 1) {
 2259:         my $hostid;
 2260:         foreach my $item (keys(%servers)) {
 2261:             $hostid = $item;
 2262:         }
 2263:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2264:                    $hostid.'" />';
 2265:                    if (!$hide) {
 2266:                        $result .= $hostid.' '.$servers{$hostid};
 2267:                    }
 2268:                    $result .= "\n";
 2269:     } elsif ($default) {
 2270:         $result .= '<input type="hidden" name="'.$name.
 2271:                    '" value="default" />';
 2272:                    if (!$hide) {
 2273:                        $result .= &mt('default');
 2274:                    }
 2275:                    $result .= "\n";
 2276:     }
 2277:     return ($result,$numlib);
 2278: }
 2279: 
 2280: =pod
 2281: 
 2282: =back 
 2283: 
 2284: =cut
 2285: 
 2286: ###############################################################
 2287: ##                  Decoding User Agent                      ##
 2288: ###############################################################
 2289: 
 2290: =pod
 2291: 
 2292: =head1 Decoding the User Agent
 2293: 
 2294: =over 4
 2295: 
 2296: =item * &decode_user_agent()
 2297: 
 2298: Inputs: $r
 2299: 
 2300: Outputs:
 2301: 
 2302: =over 4
 2303: 
 2304: =item * $httpbrowser
 2305: 
 2306: =item * $clientbrowser
 2307: 
 2308: =item * $clientversion
 2309: 
 2310: =item * $clientmathml
 2311: 
 2312: =item * $clientunicode
 2313: 
 2314: =item * $clientos
 2315: 
 2316: =back
 2317: 
 2318: =back 
 2319: 
 2320: =cut
 2321: 
 2322: ###############################################################
 2323: ###############################################################
 2324: sub decode_user_agent {
 2325:     my ($r)=@_;
 2326:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2327:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2328:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2329:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2330:     my $clientbrowser='unknown';
 2331:     my $clientversion='0';
 2332:     my $clientmathml='';
 2333:     my $clientunicode='0';
 2334:     for (my $i=0;$i<=$#browsertype;$i++) {
 2335:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2336: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2337: 	    $clientbrowser=$bname;
 2338:             $httpbrowser=~/$vreg/i;
 2339: 	    $clientversion=$1;
 2340:             $clientmathml=($clientversion>=$minv);
 2341:             $clientunicode=($clientversion>=$univ);
 2342: 	}
 2343:     }
 2344:     my $clientos='unknown';
 2345:     if (($httpbrowser=~/linux/i) ||
 2346:         ($httpbrowser=~/unix/i) ||
 2347:         ($httpbrowser=~/ux/i) ||
 2348:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2349:     if (($httpbrowser=~/vax/i) ||
 2350:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2351:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2352:     if (($httpbrowser=~/mac/i) ||
 2353:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2354:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2355:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2356:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2357:             $clientunicode,$clientos,);
 2358: }
 2359: 
 2360: ###############################################################
 2361: ##    Authentication changing form generation subroutines    ##
 2362: ###############################################################
 2363: ##
 2364: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2365: ## hash, and have reasonable default values.
 2366: ##
 2367: ##    formname = the name given in the <form> tag.
 2368: #-------------------------------------------
 2369: 
 2370: =pod
 2371: 
 2372: =head1 Authentication Routines
 2373: 
 2374: =over 4
 2375: 
 2376: =item * &authform_xxxxxx()
 2377: 
 2378: The authform_xxxxxx subroutines provide javascript and html forms which 
 2379: handle some of the conveniences required for authentication forms.  
 2380: This is not an optimal method, but it works.  
 2381: 
 2382: =over 4
 2383: 
 2384: =item * authform_header
 2385: 
 2386: =item * authform_authorwarning
 2387: 
 2388: =item * authform_nochange
 2389: 
 2390: =item * authform_kerberos
 2391: 
 2392: =item * authform_internal
 2393: 
 2394: =item * authform_filesystem
 2395: 
 2396: =back
 2397: 
 2398: See loncreateuser.pm for invocation and use examples.
 2399: 
 2400: =cut
 2401: 
 2402: #-------------------------------------------
 2403: sub authform_header{  
 2404:     my %in = (
 2405:         formname => 'cu',
 2406:         kerb_def_dom => '',
 2407:         @_,
 2408:     );
 2409:     $in{'formname'} = 'document.' . $in{'formname'};
 2410:     my $result='';
 2411: 
 2412: #---------------------------------------------- Code for upper case translation
 2413:     my $Javascript_toUpperCase;
 2414:     unless ($in{kerb_def_dom}) {
 2415:         $Javascript_toUpperCase =<<"END";
 2416:         switch (choice) {
 2417:            case 'krb': currentform.elements[choicearg].value =
 2418:                currentform.elements[choicearg].value.toUpperCase();
 2419:                break;
 2420:            default:
 2421:         }
 2422: END
 2423:     } else {
 2424:         $Javascript_toUpperCase = "";
 2425:     }
 2426: 
 2427:     my $radioval = "'nochange'";
 2428:     if (defined($in{'curr_authtype'})) {
 2429:         if ($in{'curr_authtype'} ne '') {
 2430:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2431:         }
 2432:     }
 2433:     my $argfield = 'null';
 2434:     if (defined($in{'mode'})) {
 2435:         if ($in{'mode'} eq 'modifycourse')  {
 2436:             if (defined($in{'curr_autharg'})) {
 2437:                 if ($in{'curr_autharg'} ne '') {
 2438:                     $argfield = "'$in{'curr_autharg'}'";
 2439:                 }
 2440:             }
 2441:         }
 2442:     }
 2443: 
 2444:     $result.=<<"END";
 2445: var current = new Object();
 2446: current.radiovalue = $radioval;
 2447: current.argfield = $argfield;
 2448: 
 2449: function changed_radio(choice,currentform) {
 2450:     var choicearg = choice + 'arg';
 2451:     // If a radio button in changed, we need to change the argfield
 2452:     if (current.radiovalue != choice) {
 2453:         current.radiovalue = choice;
 2454:         if (current.argfield != null) {
 2455:             currentform.elements[current.argfield].value = '';
 2456:         }
 2457:         if (choice == 'nochange') {
 2458:             current.argfield = null;
 2459:         } else {
 2460:             current.argfield = choicearg;
 2461:             switch(choice) {
 2462:                 case 'krb': 
 2463:                     currentform.elements[current.argfield].value = 
 2464:                         "$in{'kerb_def_dom'}";
 2465:                 break;
 2466:               default:
 2467:                 break;
 2468:             }
 2469:         }
 2470:     }
 2471:     return;
 2472: }
 2473: 
 2474: function changed_text(choice,currentform) {
 2475:     var choicearg = choice + 'arg';
 2476:     if (currentform.elements[choicearg].value !='') {
 2477:         $Javascript_toUpperCase
 2478:         // clear old field
 2479:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2480:             currentform.elements[current.argfield].value = '';
 2481:         }
 2482:         current.argfield = choicearg;
 2483:     }
 2484:     set_auth_radio_buttons(choice,currentform);
 2485:     return;
 2486: }
 2487: 
 2488: function set_auth_radio_buttons(newvalue,currentform) {
 2489:     var numauthchoices = currentform.login.length;
 2490:     if (typeof numauthchoices  == "undefined") {
 2491:         return;
 2492:     } 
 2493:     var i=0;
 2494:     while (i < numauthchoices) {
 2495:         if (currentform.login[i].value == newvalue) { break; }
 2496:         i++;
 2497:     }
 2498:     if (i == numauthchoices) {
 2499:         return;
 2500:     }
 2501:     current.radiovalue = newvalue;
 2502:     currentform.login[i].checked = true;
 2503:     return;
 2504: }
 2505: END
 2506:     return $result;
 2507: }
 2508: 
 2509: sub authform_authorwarning {
 2510:     my $result='';
 2511:     $result='<i>'.
 2512:         &mt('As a general rule, only authors or co-authors should be '.
 2513:             'filesystem authenticated '.
 2514:             '(which allows access to the server filesystem).')."</i>\n";
 2515:     return $result;
 2516: }
 2517: 
 2518: sub authform_nochange {
 2519:     my %in = (
 2520:               formname => 'document.cu',
 2521:               kerb_def_dom => 'MSU.EDU',
 2522:               @_,
 2523:           );
 2524:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2525:     my $result;
 2526:     if (!$authnum) {
 2527:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2528:     } else {
 2529:         $result = '<label>'.&mt('[_1] Do not change login data',
 2530:                   '<input type="radio" name="login" value="nochange" '.
 2531:                   'checked="checked" onclick="'.
 2532:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2533: 	    '</label>';
 2534:     }
 2535:     return $result;
 2536: }
 2537: 
 2538: sub authform_kerberos {
 2539:     my %in = (
 2540:               formname => 'document.cu',
 2541:               kerb_def_dom => 'MSU.EDU',
 2542:               kerb_def_auth => 'krb4',
 2543:               @_,
 2544:               );
 2545:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2546:         $autharg,$jscall);
 2547:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2548:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2549:        $check5 = ' checked="checked"';
 2550:     } else {
 2551:        $check4 = ' checked="checked"';
 2552:     }
 2553:     $krbarg = $in{'kerb_def_dom'};
 2554:     if (defined($in{'curr_authtype'})) {
 2555:         if ($in{'curr_authtype'} eq 'krb') {
 2556:             $krbcheck = ' checked="checked"';
 2557:             if (defined($in{'mode'})) {
 2558:                 if ($in{'mode'} eq 'modifyuser') {
 2559:                     $krbcheck = '';
 2560:                 }
 2561:             }
 2562:             if (defined($in{'curr_kerb_ver'})) {
 2563:                 if ($in{'curr_krb_ver'} eq '5') {
 2564:                     $check5 = ' checked="checked"';
 2565:                     $check4 = '';
 2566:                 } else {
 2567:                     $check4 = ' checked="checked"';
 2568:                     $check5 = '';
 2569:                 }
 2570:             }
 2571:             if (defined($in{'curr_autharg'})) {
 2572:                 $krbarg = $in{'curr_autharg'};
 2573:             }
 2574:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2575:                 if (defined($in{'curr_autharg'})) {
 2576:                     $result = 
 2577:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2578:         $in{'curr_autharg'},$krbver);
 2579:                 } else {
 2580:                     $result =
 2581:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2582:                 }
 2583:                 return $result; 
 2584:             }
 2585:         }
 2586:     } else {
 2587:         if ($authnum == 1) {
 2588:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2589:         }
 2590:     }
 2591:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2592:         return;
 2593:     } elsif ($authtype eq '') {
 2594:         if (defined($in{'mode'})) {
 2595:             if ($in{'mode'} eq 'modifycourse') {
 2596:                 if ($authnum == 1) {
 2597:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2598:                 }
 2599:             }
 2600:         }
 2601:     }
 2602:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2603:     if ($authtype eq '') {
 2604:         $authtype = '<input type="radio" name="login" value="krb" '.
 2605:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2606:                     $krbcheck.' />';
 2607:     }
 2608:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2609:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2610:          $in{'curr_authtype'} eq 'krb5') ||
 2611:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2612:          $in{'curr_authtype'} eq 'krb4')) {
 2613:         $result .= &mt
 2614:         ('[_1] Kerberos authenticated with domain [_2] '.
 2615:          '[_3] Version 4 [_4] Version 5 [_5]',
 2616:          '<label>'.$authtype,
 2617:          '</label><input type="text" size="10" name="krbarg" '.
 2618:              'value="'.$krbarg.'" '.
 2619:              'onchange="'.$jscall.'" />',
 2620:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2621:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2622: 	 '</label>');
 2623:     } elsif ($can_assign{'krb4'}) {
 2624:         $result .= &mt
 2625:         ('[_1] Kerberos authenticated with domain [_2] '.
 2626:          '[_3] Version 4 [_4]',
 2627:          '<label>'.$authtype,
 2628:          '</label><input type="text" size="10" name="krbarg" '.
 2629:              'value="'.$krbarg.'" '.
 2630:              'onchange="'.$jscall.'" />',
 2631:          '<label><input type="hidden" name="krbver" value="4" />',
 2632:          '</label>');
 2633:     } elsif ($can_assign{'krb5'}) {
 2634:         $result .= &mt
 2635:         ('[_1] Kerberos authenticated with domain [_2] '.
 2636:          '[_3] Version 5 [_4]',
 2637:          '<label>'.$authtype,
 2638:          '</label><input type="text" size="10" name="krbarg" '.
 2639:              'value="'.$krbarg.'" '.
 2640:              'onchange="'.$jscall.'" />',
 2641:          '<label><input type="hidden" name="krbver" value="5" />',
 2642:          '</label>');
 2643:     }
 2644:     return $result;
 2645: }
 2646: 
 2647: sub authform_internal {
 2648:     my %in = (
 2649:                 formname => 'document.cu',
 2650:                 kerb_def_dom => 'MSU.EDU',
 2651:                 @_,
 2652:                 );
 2653:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2654:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2655:     if (defined($in{'curr_authtype'})) {
 2656:         if ($in{'curr_authtype'} eq 'int') {
 2657:             if ($can_assign{'int'}) {
 2658:                 $intcheck = 'checked="checked" ';
 2659:                 if (defined($in{'mode'})) {
 2660:                     if ($in{'mode'} eq 'modifyuser') {
 2661:                         $intcheck = '';
 2662:                     }
 2663:                 }
 2664:                 if (defined($in{'curr_autharg'})) {
 2665:                     $intarg = $in{'curr_autharg'};
 2666:                 }
 2667:             } else {
 2668:                 $result = &mt('Currently internally authenticated.');
 2669:                 return $result;
 2670:             }
 2671:         }
 2672:     } else {
 2673:         if ($authnum == 1) {
 2674:             $authtype = '<input type="hidden" name="login" value="int" />';
 2675:         }
 2676:     }
 2677:     if (!$can_assign{'int'}) {
 2678:         return;
 2679:     } elsif ($authtype eq '') {
 2680:         if (defined($in{'mode'})) {
 2681:             if ($in{'mode'} eq 'modifycourse') {
 2682:                 if ($authnum == 1) {
 2683:                     $authtype = '<input type="radio" name="login" value="int" />';
 2684:                 }
 2685:             }
 2686:         }
 2687:     }
 2688:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2689:     if ($authtype eq '') {
 2690:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2691:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2692:     }
 2693:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2694:                $intarg.'" onchange="'.$jscall.'" />';
 2695:     $result = &mt
 2696:         ('[_1] Internally authenticated (with initial password [_2])',
 2697:          '<label>'.$authtype,'</label>'.$autharg);
 2698:     $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>';
 2699:     return $result;
 2700: }
 2701: 
 2702: sub authform_local {
 2703:     my %in = (
 2704:               formname => 'document.cu',
 2705:               kerb_def_dom => 'MSU.EDU',
 2706:               @_,
 2707:               );
 2708:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2709:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2710:     if (defined($in{'curr_authtype'})) {
 2711:         if ($in{'curr_authtype'} eq 'loc') {
 2712:             if ($can_assign{'loc'}) {
 2713:                 $loccheck = 'checked="checked" ';
 2714:                 if (defined($in{'mode'})) {
 2715:                     if ($in{'mode'} eq 'modifyuser') {
 2716:                         $loccheck = '';
 2717:                     }
 2718:                 }
 2719:                 if (defined($in{'curr_autharg'})) {
 2720:                     $locarg = $in{'curr_autharg'};
 2721:                 }
 2722:             } else {
 2723:                 $result = &mt('Currently using local (institutional) authentication.');
 2724:                 return $result;
 2725:             }
 2726:         }
 2727:     } else {
 2728:         if ($authnum == 1) {
 2729:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2730:         }
 2731:     }
 2732:     if (!$can_assign{'loc'}) {
 2733:         return;
 2734:     } elsif ($authtype eq '') {
 2735:         if (defined($in{'mode'})) {
 2736:             if ($in{'mode'} eq 'modifycourse') {
 2737:                 if ($authnum == 1) {
 2738:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2739:                 }
 2740:             }
 2741:         }
 2742:     }
 2743:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2744:     if ($authtype eq '') {
 2745:         $authtype = '<input type="radio" name="login" value="loc" '.
 2746:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2747:                     $jscall.'" />';
 2748:     }
 2749:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2750:                $locarg.'" onchange="'.$jscall.'" />';
 2751:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2752:                   '<label>'.$authtype,'</label>'.$autharg);
 2753:     return $result;
 2754: }
 2755: 
 2756: sub authform_filesystem {
 2757:     my %in = (
 2758:               formname => 'document.cu',
 2759:               kerb_def_dom => 'MSU.EDU',
 2760:               @_,
 2761:               );
 2762:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2763:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2764:     if (defined($in{'curr_authtype'})) {
 2765:         if ($in{'curr_authtype'} eq 'fsys') {
 2766:             if ($can_assign{'fsys'}) {
 2767:                 $fsyscheck = 'checked="checked" ';
 2768:                 if (defined($in{'mode'})) {
 2769:                     if ($in{'mode'} eq 'modifyuser') {
 2770:                         $fsyscheck = '';
 2771:                     }
 2772:                 }
 2773:             } else {
 2774:                 $result = &mt('Currently Filesystem Authenticated.');
 2775:                 return $result;
 2776:             }           
 2777:         }
 2778:     } else {
 2779:         if ($authnum == 1) {
 2780:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2781:         }
 2782:     }
 2783:     if (!$can_assign{'fsys'}) {
 2784:         return;
 2785:     } elsif ($authtype eq '') {
 2786:         if (defined($in{'mode'})) {
 2787:             if ($in{'mode'} eq 'modifycourse') {
 2788:                 if ($authnum == 1) {
 2789:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2790:                 }
 2791:             }
 2792:         }
 2793:     }
 2794:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2795:     if ($authtype eq '') {
 2796:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2797:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2798:                     $jscall.'" />';
 2799:     }
 2800:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2801:                ' onchange="'.$jscall.'" />';
 2802:     $result = &mt
 2803:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2804:          '<label><input type="radio" name="login" value="fsys" '.
 2805:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2806:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2807:                   'onchange="'.$jscall.'" />');
 2808:     return $result;
 2809: }
 2810: 
 2811: sub get_assignable_auth {
 2812:     my ($dom) = @_;
 2813:     if ($dom eq '') {
 2814:         $dom = $env{'request.role.domain'};
 2815:     }
 2816:     my %can_assign = (
 2817:                           krb4 => 1,
 2818:                           krb5 => 1,
 2819:                           int  => 1,
 2820:                           loc  => 1,
 2821:                      );
 2822:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2823:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2824:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2825:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2826:             my $context;
 2827:             if ($env{'request.role'} =~ /^au/) {
 2828:                 $context = 'author';
 2829:             } elsif ($env{'request.role'} =~ /^dc/) {
 2830:                 $context = 'domain';
 2831:             } elsif ($env{'request.course.id'}) {
 2832:                 $context = 'course';
 2833:             }
 2834:             if ($context) {
 2835:                 if (ref($authhash->{$context}) eq 'HASH') {
 2836:                    %can_assign = %{$authhash->{$context}}; 
 2837:                 }
 2838:             }
 2839:         }
 2840:     }
 2841:     my $authnum = 0;
 2842:     foreach my $key (keys(%can_assign)) {
 2843:         if ($can_assign{$key}) {
 2844:             $authnum ++;
 2845:         }
 2846:     }
 2847:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2848:         $authnum --;
 2849:     }
 2850:     return ($authnum,%can_assign);
 2851: }
 2852: 
 2853: ###############################################################
 2854: ##    Get Kerberos Defaults for Domain                 ##
 2855: ###############################################################
 2856: ##
 2857: ## Returns default kerberos version and an associated argument
 2858: ## as listed in file domain.tab. If not listed, provides
 2859: ## appropriate default domain and kerberos version.
 2860: ##
 2861: #-------------------------------------------
 2862: 
 2863: =pod
 2864: 
 2865: =item * &get_kerberos_defaults()
 2866: 
 2867: get_kerberos_defaults($target_domain) returns the default kerberos
 2868: version and domain. If not found, it defaults to version 4 and the 
 2869: domain of the server.
 2870: 
 2871: =over 4
 2872: 
 2873: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2874: 
 2875: =back
 2876: 
 2877: =back
 2878: 
 2879: =cut
 2880: 
 2881: #-------------------------------------------
 2882: sub get_kerberos_defaults {
 2883:     my $domain=shift;
 2884:     my ($krbdef,$krbdefdom);
 2885:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2886:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2887:         $krbdef = $domdefaults{'auth_def'};
 2888:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2889:     } else {
 2890:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2891:         my $krbdefdom=$1;
 2892:         $krbdefdom=~tr/a-z/A-Z/;
 2893:         $krbdef = "krb4";
 2894:     }
 2895:     return ($krbdef,$krbdefdom);
 2896: }
 2897: 
 2898: 
 2899: ###############################################################
 2900: ##                Thesaurus Functions                        ##
 2901: ###############################################################
 2902: 
 2903: =pod
 2904: 
 2905: =head1 Thesaurus Functions
 2906: 
 2907: =over 4
 2908: 
 2909: =item * &initialize_keywords()
 2910: 
 2911: Initializes the package variable %Keywords if it is empty.  Uses the
 2912: package variable $thesaurus_db_file.
 2913: 
 2914: =cut
 2915: 
 2916: ###################################################
 2917: 
 2918: sub initialize_keywords {
 2919:     return 1 if (scalar keys(%Keywords));
 2920:     # If we are here, %Keywords is empty, so fill it up
 2921:     #   Make sure the file we need exists...
 2922:     if (! -e $thesaurus_db_file) {
 2923:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2924:                                  " failed because it does not exist");
 2925:         return 0;
 2926:     }
 2927:     #   Set up the hash as a database
 2928:     my %thesaurus_db;
 2929:     if (! tie(%thesaurus_db,'GDBM_File',
 2930:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2931:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2932:                                  $thesaurus_db_file);
 2933:         return 0;
 2934:     } 
 2935:     #  Get the average number of appearances of a word.
 2936:     my $avecount = $thesaurus_db{'average.count'};
 2937:     #  Put keywords (those that appear > average) into %Keywords
 2938:     while (my ($word,$data)=each (%thesaurus_db)) {
 2939:         my ($count,undef) = split /:/,$data;
 2940:         $Keywords{$word}++ if ($count > $avecount);
 2941:     }
 2942:     untie %thesaurus_db;
 2943:     # Remove special values from %Keywords.
 2944:     foreach my $value ('total.count','average.count') {
 2945:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2946:   }
 2947:     return 1;
 2948: }
 2949: 
 2950: ###################################################
 2951: 
 2952: =pod
 2953: 
 2954: =item * &keyword($word)
 2955: 
 2956: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2957: than the average number of times in the thesaurus database.  Calls 
 2958: &initialize_keywords
 2959: 
 2960: =cut
 2961: 
 2962: ###################################################
 2963: 
 2964: sub keyword {
 2965:     return if (!&initialize_keywords());
 2966:     my $word=lc(shift());
 2967:     $word=~s/\W//g;
 2968:     return exists($Keywords{$word});
 2969: }
 2970: 
 2971: ###############################################################
 2972: 
 2973: =pod 
 2974: 
 2975: =item * &get_related_words()
 2976: 
 2977: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2978: an array of words.  If the keyword is not in the thesaurus, an empty array
 2979: will be returned.  The order of the words returned is determined by the
 2980: database which holds them.
 2981: 
 2982: Uses global $thesaurus_db_file.
 2983: 
 2984: 
 2985: =cut
 2986: 
 2987: ###############################################################
 2988: sub get_related_words {
 2989:     my $keyword = shift;
 2990:     my %thesaurus_db;
 2991:     if (! -e $thesaurus_db_file) {
 2992:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2993:                                  "failed because the file does not exist");
 2994:         return ();
 2995:     }
 2996:     if (! tie(%thesaurus_db,'GDBM_File',
 2997:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2998:         return ();
 2999:     } 
 3000:     my @Words=();
 3001:     my $count=0;
 3002:     if (exists($thesaurus_db{$keyword})) {
 3003: 	# The first element is the number of times
 3004: 	# the word appears.  We do not need it now.
 3005: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3006: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3007: 	my $threshold=$mostfrequentcount/10;
 3008:         foreach my $possibleword (@RelatedWords) {
 3009:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3010:             if ($wordcount>$threshold) {
 3011: 		push(@Words,$word);
 3012:                 $count++;
 3013:                 if ($count>10) { last; }
 3014: 	    }
 3015:         }
 3016:     }
 3017:     untie %thesaurus_db;
 3018:     return @Words;
 3019: }
 3020: 
 3021: =pod
 3022: 
 3023: =back
 3024: 
 3025: =cut
 3026: 
 3027: # -------------------------------------------------------------- Plaintext name
 3028: =pod
 3029: 
 3030: =head1 User Name Functions
 3031: 
 3032: =over 4
 3033: 
 3034: =item * &plainname($uname,$udom,$first)
 3035: 
 3036: Takes a users logon name and returns it as a string in
 3037: "first middle last generation" form 
 3038: if $first is set to 'lastname' then it returns it as
 3039: 'lastname generation, firstname middlename' if their is a lastname
 3040: 
 3041: =cut
 3042: 
 3043: 
 3044: ###############################################################
 3045: sub plainname {
 3046:     my ($uname,$udom,$first)=@_;
 3047:     return if (!defined($uname) || !defined($udom));
 3048:     my %names=&getnames($uname,$udom);
 3049:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3050: 					  $names{'middlename'},
 3051: 					  $names{'lastname'},
 3052: 					  $names{'generation'},$first);
 3053:     $name=~s/^\s+//;
 3054:     $name=~s/\s+$//;
 3055:     $name=~s/\s+/ /g;
 3056:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3057:     return $name;
 3058: }
 3059: 
 3060: # -------------------------------------------------------------------- Nickname
 3061: =pod
 3062: 
 3063: =item * &nickname($uname,$udom)
 3064: 
 3065: Gets a users name and returns it as a string as
 3066: 
 3067: "&quot;nickname&quot;"
 3068: 
 3069: if the user has a nickname or
 3070: 
 3071: "first middle last generation"
 3072: 
 3073: if the user does not
 3074: 
 3075: =cut
 3076: 
 3077: sub nickname {
 3078:     my ($uname,$udom)=@_;
 3079:     return if (!defined($uname) || !defined($udom));
 3080:     my %names=&getnames($uname,$udom);
 3081:     my $name=$names{'nickname'};
 3082:     if ($name) {
 3083:        $name='&quot;'.$name.'&quot;'; 
 3084:     } else {
 3085:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3086: 	     $names{'lastname'}.' '.$names{'generation'};
 3087:        $name=~s/\s+$//;
 3088:        $name=~s/\s+/ /g;
 3089:     }
 3090:     return $name;
 3091: }
 3092: 
 3093: sub getnames {
 3094:     my ($uname,$udom)=@_;
 3095:     return if (!defined($uname) || !defined($udom));
 3096:     if ($udom eq 'public' && $uname eq 'public') {
 3097: 	return ('lastname' => &mt('Public'));
 3098:     }
 3099:     my $id=$uname.':'.$udom;
 3100:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3101:     if ($cached) {
 3102: 	return %{$names};
 3103:     } else {
 3104: 	my %loadnames=&Apache::lonnet::get('environment',
 3105:                     ['firstname','middlename','lastname','generation','nickname'],
 3106: 					 $udom,$uname);
 3107: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3108: 	return %loadnames;
 3109:     }
 3110: }
 3111: 
 3112: # -------------------------------------------------------------------- getemails
 3113: 
 3114: =pod
 3115: 
 3116: =item * &getemails($uname,$udom)
 3117: 
 3118: Gets a user's email information and returns it as a hash with keys:
 3119: notification, critnotification, permanentemail
 3120: 
 3121: For notification and critnotification, values are comma-separated lists 
 3122: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3123:  
 3124: 
 3125: =cut
 3126: 
 3127: 
 3128: sub getemails {
 3129:     my ($uname,$udom)=@_;
 3130:     if ($udom eq 'public' && $uname eq 'public') {
 3131: 	return;
 3132:     }
 3133:     if (!$udom) { $udom=$env{'user.domain'}; }
 3134:     if (!$uname) { $uname=$env{'user.name'}; }
 3135:     my $id=$uname.':'.$udom;
 3136:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3137:     if ($cached) {
 3138: 	return %{$names};
 3139:     } else {
 3140: 	my %loadnames=&Apache::lonnet::get('environment',
 3141:                     			   ['notification','critnotification',
 3142: 					    'permanentemail'],
 3143: 					   $udom,$uname);
 3144: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3145: 	return %loadnames;
 3146:     }
 3147: }
 3148: 
 3149: sub flush_email_cache {
 3150:     my ($uname,$udom)=@_;
 3151:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3152:     if (!$uname) { $uname=$env{'user.name'};   }
 3153:     return if ($udom eq 'public' && $uname eq 'public');
 3154:     my $id=$uname.':'.$udom;
 3155:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3156: }
 3157: 
 3158: # -------------------------------------------------------------------- getlangs
 3159: 
 3160: =pod
 3161: 
 3162: =item * &getlangs($uname,$udom)
 3163: 
 3164: Gets a user's language preference and returns it as a hash with key:
 3165: language.
 3166: 
 3167: =cut
 3168: 
 3169: 
 3170: sub getlangs {
 3171:     my ($uname,$udom) = @_;
 3172:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3173:     if (!$uname) { $uname=$env{'user.name'};   }
 3174:     my $id=$uname.':'.$udom;
 3175:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3176:     if ($cached) {
 3177:         return %{$langs};
 3178:     } else {
 3179:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3180:                                            $udom,$uname);
 3181:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3182:         return %loadlangs;
 3183:     }
 3184: }
 3185: 
 3186: sub flush_langs_cache {
 3187:     my ($uname,$udom)=@_;
 3188:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3189:     if (!$uname) { $uname=$env{'user.name'};   }
 3190:     return if ($udom eq 'public' && $uname eq 'public');
 3191:     my $id=$uname.':'.$udom;
 3192:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3193: }
 3194: 
 3195: # ------------------------------------------------------------------ Screenname
 3196: 
 3197: =pod
 3198: 
 3199: =item * &screenname($uname,$udom)
 3200: 
 3201: Gets a users screenname and returns it as a string
 3202: 
 3203: =cut
 3204: 
 3205: sub screenname {
 3206:     my ($uname,$udom)=@_;
 3207:     if ($uname eq $env{'user.name'} &&
 3208: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3209:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3210:     return $names{'screenname'};
 3211: }
 3212: 
 3213: 
 3214: # ------------------------------------------------------------- Confirm Wrapper
 3215: =pod
 3216: 
 3217: =item confirmwrapper
 3218: 
 3219: Wrap messages about completion of operation in box
 3220: 
 3221: =cut
 3222: 
 3223: sub confirmwrapper {
 3224:     my ($message)=@_;
 3225:     if ($message) {
 3226:         return "\n".'<div class="LC_confirm_box">'."\n"
 3227:                .$message."\n"
 3228:                .'</div>'."\n";
 3229:     } else {
 3230:         return $message;
 3231:     }
 3232: }
 3233: 
 3234: # ------------------------------------------------------------- Message Wrapper
 3235: 
 3236: sub messagewrapper {
 3237:     my ($link,$username,$domain,$subject,$text)=@_;
 3238:     return 
 3239:         '<a href="/adm/email?compose=individual&amp;'.
 3240:         'recname='.$username.'&amp;recdom='.$domain.
 3241: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3242:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3243: }
 3244: 
 3245: # --------------------------------------------------------------- Notes Wrapper
 3246: 
 3247: sub noteswrapper {
 3248:     my ($link,$un,$do)=@_;
 3249:     return 
 3250: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3251: }
 3252: 
 3253: # ------------------------------------------------------------- Aboutme Wrapper
 3254: 
 3255: sub aboutmewrapper {
 3256:     my ($link,$username,$domain,$target,$class)=@_;
 3257:     if (!defined($username)  && !defined($domain)) {
 3258:         return;
 3259:     }
 3260:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3261: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3262: }
 3263: 
 3264: # ------------------------------------------------------------ Syllabus Wrapper
 3265: 
 3266: sub syllabuswrapper {
 3267:     my ($linktext,$coursedir,$domain)=@_;
 3268:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3269: }
 3270: 
 3271: # -----------------------------------------------------------------------------
 3272: 
 3273: sub track_student_link {
 3274:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3275:     my $link ="/adm/trackstudent?";
 3276:     my $title = 'View recent activity';
 3277:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3278:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3279:         $link .= "selected_student=$sname:$sdom";
 3280:         $title .= ' of this student';
 3281:     } 
 3282:     if (defined($target) && $target !~ /^\s*$/) {
 3283:         $target = qq{target="$target"};
 3284:     } else {
 3285:         $target = '';
 3286:     }
 3287:     if ($start) { $link.='&amp;start='.$start; }
 3288:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3289:     $title = &mt($title);
 3290:     $linktext = &mt($linktext);
 3291:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3292: 	&help_open_topic('View_recent_activity');
 3293: }
 3294: 
 3295: sub slot_reservations_link {
 3296:     my ($linktext,$sname,$sdom,$target) = @_;
 3297:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3298:     my $title = 'View slot reservation history';
 3299:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3300:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3301:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3302:         $title .= ' of this student';
 3303:     }
 3304:     if (defined($target) && $target !~ /^\s*$/) {
 3305:         $target = qq{target="$target"};
 3306:     } else {
 3307:         $target = '';
 3308:     }
 3309:     $title = &mt($title);
 3310:     $linktext = &mt($linktext);
 3311:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3312: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3313: 
 3314: }
 3315: 
 3316: # ===================================================== Display a student photo
 3317: 
 3318: 
 3319: sub student_image_tag {
 3320:     my ($domain,$user)=@_;
 3321:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3322:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3323: 	return '<img src="'.$imgsrc.'" align="right" />';
 3324:     } else {
 3325: 	return '';
 3326:     }
 3327: }
 3328: 
 3329: =pod
 3330: 
 3331: =back
 3332: 
 3333: =head1 Access .tab File Data
 3334: 
 3335: =over 4
 3336: 
 3337: =item * &languageids() 
 3338: 
 3339: returns list of all language ids
 3340: 
 3341: =cut
 3342: 
 3343: sub languageids {
 3344:     return sort(keys(%language));
 3345: }
 3346: 
 3347: =pod
 3348: 
 3349: =item * &languagedescription() 
 3350: 
 3351: returns description of a specified language id
 3352: 
 3353: =cut
 3354: 
 3355: sub languagedescription {
 3356:     my $code=shift;
 3357:     return  ($supported_language{$code}?'* ':'').
 3358:             $language{$code}.
 3359: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3360: }
 3361: 
 3362: =pod
 3363: 
 3364: =item * &plainlanguagedescription
 3365: 
 3366: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3367: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3368: 
 3369: =cut
 3370: 
 3371: sub plainlanguagedescription {
 3372:     my $code=shift;
 3373:     return $language{$code};
 3374: }
 3375: 
 3376: =pod
 3377: 
 3378: =item * &supportedlanguagecode
 3379: 
 3380: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3381: code.
 3382: 
 3383: =cut
 3384: 
 3385: sub supportedlanguagecode {
 3386:     my $code=shift;
 3387:     return $supported_language{$code};
 3388: }
 3389: 
 3390: =pod
 3391: 
 3392: =item * &latexlanguage()
 3393: 
 3394: Given a language key code returns the correspondnig language to use
 3395: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3396: is no supported hyphenation for the language code.
 3397: 
 3398: =cut
 3399: 
 3400: sub latexlanguage {
 3401:     my $code = shift;
 3402:     return $latex_language{$code};
 3403: }
 3404: 
 3405: =pod
 3406: 
 3407: =item * &latexhyphenation()
 3408: 
 3409: Same as above but what's supplied is the language as it might be stored
 3410: in the metadata.
 3411: 
 3412: =cut
 3413: 
 3414: sub latexhyphenation {
 3415:     my $key = shift;
 3416:     return $latex_language_bykey{$key};
 3417: }
 3418: 
 3419: =pod
 3420: 
 3421: =item * &copyrightids() 
 3422: 
 3423: returns list of all copyrights
 3424: 
 3425: =cut
 3426: 
 3427: sub copyrightids {
 3428:     return sort(keys(%cprtag));
 3429: }
 3430: 
 3431: =pod
 3432: 
 3433: =item * &copyrightdescription() 
 3434: 
 3435: returns description of a specified copyright id
 3436: 
 3437: =cut
 3438: 
 3439: sub copyrightdescription {
 3440:     return &mt($cprtag{shift(@_)});
 3441: }
 3442: 
 3443: =pod
 3444: 
 3445: =item * &source_copyrightids() 
 3446: 
 3447: returns list of all source copyrights
 3448: 
 3449: =cut
 3450: 
 3451: sub source_copyrightids {
 3452:     return sort(keys(%scprtag));
 3453: }
 3454: 
 3455: =pod
 3456: 
 3457: =item * &source_copyrightdescription() 
 3458: 
 3459: returns description of a specified source copyright id
 3460: 
 3461: =cut
 3462: 
 3463: sub source_copyrightdescription {
 3464:     return &mt($scprtag{shift(@_)});
 3465: }
 3466: 
 3467: =pod
 3468: 
 3469: =item * &filecategories() 
 3470: 
 3471: returns list of all file categories
 3472: 
 3473: =cut
 3474: 
 3475: sub filecategories {
 3476:     return sort(keys(%category_extensions));
 3477: }
 3478: 
 3479: =pod
 3480: 
 3481: =item * &filecategorytypes() 
 3482: 
 3483: returns list of file types belonging to a given file
 3484: category
 3485: 
 3486: =cut
 3487: 
 3488: sub filecategorytypes {
 3489:     my ($cat) = @_;
 3490:     return @{$category_extensions{lc($cat)}};
 3491: }
 3492: 
 3493: =pod
 3494: 
 3495: =item * &fileembstyle() 
 3496: 
 3497: returns embedding style for a specified file type
 3498: 
 3499: =cut
 3500: 
 3501: sub fileembstyle {
 3502:     return $fe{lc(shift(@_))};
 3503: }
 3504: 
 3505: sub filemimetype {
 3506:     return $fm{lc(shift(@_))};
 3507: }
 3508: 
 3509: 
 3510: sub filecategoryselect {
 3511:     my ($name,$value)=@_;
 3512:     return &select_form($value,$name,
 3513:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3514: }
 3515: 
 3516: =pod
 3517: 
 3518: =item * &filedescription() 
 3519: 
 3520: returns description for a specified file type
 3521: 
 3522: =cut
 3523: 
 3524: sub filedescription {
 3525:     my $file_description = $fd{lc(shift())};
 3526:     $file_description =~ s:([\[\]]):~$1:g;
 3527:     return &mt($file_description);
 3528: }
 3529: 
 3530: =pod
 3531: 
 3532: =item * &filedescriptionex() 
 3533: 
 3534: returns description for a specified file type with
 3535: extra formatting
 3536: 
 3537: =cut
 3538: 
 3539: sub filedescriptionex {
 3540:     my $ex=shift;
 3541:     my $file_description = $fd{lc($ex)};
 3542:     $file_description =~ s:([\[\]]):~$1:g;
 3543:     return '.'.$ex.' '.&mt($file_description);
 3544: }
 3545: 
 3546: # End of .tab access
 3547: =pod
 3548: 
 3549: =back
 3550: 
 3551: =cut
 3552: 
 3553: # ------------------------------------------------------------------ File Types
 3554: sub fileextensions {
 3555:     return sort(keys(%fe));
 3556: }
 3557: 
 3558: # ----------------------------------------------------------- Display Languages
 3559: # returns a hash with all desired display languages
 3560: #
 3561: 
 3562: sub display_languages {
 3563:     my %languages=();
 3564:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3565: 	$languages{$lang}=1;
 3566:     }
 3567:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3568:     if ($env{'form.displaylanguage'}) {
 3569: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3570: 	    $languages{$lang}=1;
 3571:         }
 3572:     }
 3573:     return %languages;
 3574: }
 3575: 
 3576: sub languages {
 3577:     my ($possible_langs) = @_;
 3578:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3579:     if (!ref($possible_langs)) {
 3580: 	if( wantarray ) {
 3581: 	    return @preferred_langs;
 3582: 	} else {
 3583: 	    return $preferred_langs[0];
 3584: 	}
 3585:     }
 3586:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3587:     my @preferred_possibilities;
 3588:     foreach my $preferred_lang (@preferred_langs) {
 3589: 	if (exists($possibilities{$preferred_lang})) {
 3590: 	    push(@preferred_possibilities, $preferred_lang);
 3591: 	}
 3592:     }
 3593:     if( wantarray ) {
 3594: 	return @preferred_possibilities;
 3595:     }
 3596:     return $preferred_possibilities[0];
 3597: }
 3598: 
 3599: sub user_lang {
 3600:     my ($touname,$toudom,$fromcid) = @_;
 3601:     my @userlangs;
 3602:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3603:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3604:                     $env{'course.'.$fromcid.'.languages'}));
 3605:     } else {
 3606:         my %langhash = &getlangs($touname,$toudom);
 3607:         if ($langhash{'languages'} ne '') {
 3608:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3609:         } else {
 3610:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3611:             if ($domdefs{'lang_def'} ne '') {
 3612:                 @userlangs = ($domdefs{'lang_def'});
 3613:             }
 3614:         }
 3615:     }
 3616:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3617:     my $user_lh = Apache::localize->get_handle(@languages);
 3618:     return $user_lh;
 3619: }
 3620: 
 3621: 
 3622: ###############################################################
 3623: ##               Student Answer Attempts                     ##
 3624: ###############################################################
 3625: 
 3626: =pod
 3627: 
 3628: =head1 Alternate Problem Views
 3629: 
 3630: =over 4
 3631: 
 3632: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3633:     $getattempt, $regexp, $gradesub)
 3634: 
 3635: Return string with previous attempt on problem. Arguments:
 3636: 
 3637: =over 4
 3638: 
 3639: =item * $symb: Problem, including path
 3640: 
 3641: =item * $username: username of the desired student
 3642: 
 3643: =item * $domain: domain of the desired student
 3644: 
 3645: =item * $course: Course ID
 3646: 
 3647: =item * $getattempt: Leave blank for all attempts, otherwise put
 3648:     something
 3649: 
 3650: =item * $regexp: if string matches this regexp, the string will be
 3651:     sent to $gradesub
 3652: 
 3653: =item * $gradesub: routine that processes the string if it matches $regexp
 3654: 
 3655: =back
 3656: 
 3657: The output string is a table containing all desired attempts, if any.
 3658: 
 3659: =cut
 3660: 
 3661: sub get_previous_attempt {
 3662:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3663:   my $prevattempts='';
 3664:   no strict 'refs';
 3665:   if ($symb) {
 3666:     my (%returnhash)=
 3667:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3668:     if ($returnhash{'version'}) {
 3669:       my %lasthash=();
 3670:       my $version;
 3671:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3672:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3673: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3674:         }
 3675:       }
 3676:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3677:       $prevattempts.='<th>'.&mt('History').'</th>';
 3678:       my (%typeparts,%lasthidden);
 3679:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3680:       foreach my $key (sort(keys(%lasthash))) {
 3681: 	my ($ign,@parts) = split(/\./,$key);
 3682: 	if ($#parts > 0) {
 3683: 	  my $data=$parts[-1];
 3684:           next if ($data eq 'foilorder');
 3685: 	  pop(@parts);
 3686:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3687:           if ($data eq 'type') {
 3688:               unless ($showsurv) {
 3689:                   my $id = join(',',@parts);
 3690:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3691:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3692:                       $lasthidden{$ign.'.'.$id} = 1;
 3693:                   }
 3694:               }
 3695:           } 
 3696: 	} else {
 3697: 	  if ($#parts == 0) {
 3698: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3699: 	  } else {
 3700: 	    $prevattempts.='<th>'.$ign.'</th>';
 3701: 	  }
 3702: 	}
 3703:       }
 3704:       $prevattempts.=&end_data_table_header_row();
 3705:       if ($getattempt eq '') {
 3706: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3707:             my @hidden;
 3708:             if (%typeparts) {
 3709:                 foreach my $id (keys(%typeparts)) {
 3710:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3711:                         push(@hidden,$id);
 3712:                     }
 3713:                 }
 3714:             }
 3715:             $prevattempts.=&start_data_table_row().
 3716:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3717:             if (@hidden) {
 3718:                 foreach my $key (sort(keys(%lasthash))) {
 3719:                     next if ($key =~ /\.foilorder$/);
 3720:                     my $hide;
 3721:                     foreach my $id (@hidden) {
 3722:                         if ($key =~ /^\Q$id\E/) {
 3723:                             $hide = 1;
 3724:                             last;
 3725:                         }
 3726:                     }
 3727:                     if ($hide) {
 3728:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3729:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3730:                             my $value = &format_previous_attempt_value($key,
 3731:                                              $returnhash{$version.':'.$key});
 3732:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3733:                         } else {
 3734:                             $prevattempts.='<td>&nbsp;</td>';
 3735:                         }
 3736:                     } else {
 3737:                         if ($key =~ /\./) {
 3738:                             my $value = &format_previous_attempt_value($key,
 3739:                                               $returnhash{$version.':'.$key});
 3740:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3741:                         } else {
 3742:                             $prevattempts.='<td>&nbsp;</td>';
 3743:                         }
 3744:                     }
 3745:                 }
 3746:             } else {
 3747: 	        foreach my $key (sort(keys(%lasthash))) {
 3748:                     next if ($key =~ /\.foilorder$/);
 3749: 		    my $value = &format_previous_attempt_value($key,
 3750: 			            $returnhash{$version.':'.$key});
 3751: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3752: 	        }
 3753:             }
 3754: 	    $prevattempts.=&end_data_table_row();
 3755: 	 }
 3756:       }
 3757:       my @currhidden = keys(%lasthidden);
 3758:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3759:       foreach my $key (sort(keys(%lasthash))) {
 3760:           next if ($key =~ /\.foilorder$/);
 3761:           if (%typeparts) {
 3762:               my $hidden;
 3763:               foreach my $id (@currhidden) {
 3764:                   if ($key =~ /^\Q$id\E/) {
 3765:                       $hidden = 1;
 3766:                       last;
 3767:                   }
 3768:               }
 3769:               if ($hidden) {
 3770:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3771:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3772:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3773:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3774:                           $value = &$gradesub($value);
 3775:                       }
 3776:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3777:                   } else {
 3778:                       $prevattempts.='<td>&nbsp;</td>';
 3779:                   }
 3780:               } else {
 3781:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3782:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3783:                       $value = &$gradesub($value);
 3784:                   }
 3785:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3786:               }
 3787:           } else {
 3788: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3789: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3790:                   $value = &$gradesub($value);
 3791:               }
 3792: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3793:           }
 3794:       }
 3795:       $prevattempts.= &end_data_table_row().&end_data_table();
 3796:     } else {
 3797:       $prevattempts=
 3798: 	  &start_data_table().&start_data_table_row().
 3799: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3800: 	  &end_data_table_row().&end_data_table();
 3801:     }
 3802:   } else {
 3803:     $prevattempts=
 3804: 	  &start_data_table().&start_data_table_row().
 3805: 	  '<td>'.&mt('No data.').'</td>'.
 3806: 	  &end_data_table_row().&end_data_table();
 3807:   }
 3808: }
 3809: 
 3810: sub format_previous_attempt_value {
 3811:     my ($key,$value) = @_;
 3812:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3813: 	$value = &Apache::lonlocal::locallocaltime($value);
 3814:     } elsif (ref($value) eq 'ARRAY') {
 3815: 	$value = '('.join(', ', @{ $value }).')';
 3816:     } elsif ($key =~ /answerstring$/) {
 3817:         my %answers = &Apache::lonnet::str2hash($value);
 3818:         my @anskeys = sort(keys(%answers));
 3819:         if (@anskeys == 1) {
 3820:             my $answer = $answers{$anskeys[0]};
 3821:             if ($answer =~ m{\0}) {
 3822:                 $answer =~ s{\0}{,}g;
 3823:             }
 3824:             my $tag_internal_answer_name = 'INTERNAL';
 3825:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3826:                 $value = $answer; 
 3827:             } else {
 3828:                 $value = $anskeys[0].'='.$answer;
 3829:             }
 3830:         } else {
 3831:             foreach my $ans (@anskeys) {
 3832:                 my $answer = $answers{$ans};
 3833:                 if ($answer =~ m{\0}) {
 3834:                     $answer =~ s{\0}{,}g;
 3835:                 }
 3836:                 $value .=  $ans.'='.$answer.'<br />';;
 3837:             } 
 3838:         }
 3839:     } else {
 3840: 	$value = &unescape($value);
 3841:     }
 3842:     return $value;
 3843: }
 3844: 
 3845: 
 3846: sub relative_to_absolute {
 3847:     my ($url,$output)=@_;
 3848:     my $parser=HTML::TokeParser->new(\$output);
 3849:     my $token;
 3850:     my $thisdir=$url;
 3851:     my @rlinks=();
 3852:     while ($token=$parser->get_token) {
 3853: 	if ($token->[0] eq 'S') {
 3854: 	    if ($token->[1] eq 'a') {
 3855: 		if ($token->[2]->{'href'}) {
 3856: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3857: 		}
 3858: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3859: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3860: 	    } elsif ($token->[1] eq 'base') {
 3861: 		$thisdir=$token->[2]->{'href'};
 3862: 	    }
 3863: 	}
 3864:     }
 3865:     $thisdir=~s-/[^/]*$--;
 3866:     foreach my $link (@rlinks) {
 3867: 	unless (($link=~/^https?\:\/\//i) ||
 3868: 		($link=~/^\//) ||
 3869: 		($link=~/^javascript:/i) ||
 3870: 		($link=~/^mailto:/i) ||
 3871: 		($link=~/^\#/)) {
 3872: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3873: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3874: 	}
 3875:     }
 3876: # -------------------------------------------------- Deal with Applet codebases
 3877:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3878:     return $output;
 3879: }
 3880: 
 3881: =pod
 3882: 
 3883: =item * &get_student_view()
 3884: 
 3885: show a snapshot of what student was looking at
 3886: 
 3887: =cut
 3888: 
 3889: sub get_student_view {
 3890:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3891:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3892:   my (%form);
 3893:   my @elements=('symb','courseid','domain','username');
 3894:   foreach my $element (@elements) {
 3895:       $form{'grade_'.$element}=eval '$'.$element #'
 3896:   }
 3897:   if (defined($moreenv)) {
 3898:       %form=(%form,%{$moreenv});
 3899:   }
 3900:   if (defined($target)) { $form{'grade_target'} = $target; }
 3901:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3902:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3903:   $userview=~s/\<body[^\>]*\>//gi;
 3904:   $userview=~s/\<\/body\>//gi;
 3905:   $userview=~s/\<html\>//gi;
 3906:   $userview=~s/\<\/html\>//gi;
 3907:   $userview=~s/\<head\>//gi;
 3908:   $userview=~s/\<\/head\>//gi;
 3909:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3910:   $userview=&relative_to_absolute($feedurl,$userview);
 3911:   if (wantarray) {
 3912:      return ($userview,$response);
 3913:   } else {
 3914:      return $userview;
 3915:   }
 3916: }
 3917: 
 3918: sub get_student_view_with_retries {
 3919:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3920: 
 3921:     my $ok = 0;                 # True if we got a good response.
 3922:     my $content;
 3923:     my $response;
 3924: 
 3925:     # Try to get the student_view done. within the retries count:
 3926:     
 3927:     do {
 3928:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3929:          $ok      = $response->is_success;
 3930:          if (!$ok) {
 3931:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3932:          }
 3933:          $retries--;
 3934:     } while (!$ok && ($retries > 0));
 3935:     
 3936:     if (!$ok) {
 3937:        $content = '';          # On error return an empty content.
 3938:     }
 3939:     if (wantarray) {
 3940:        return ($content, $response);
 3941:     } else {
 3942:        return $content;
 3943:     }
 3944: }
 3945: 
 3946: =pod
 3947: 
 3948: =item * &get_student_answers() 
 3949: 
 3950: show a snapshot of how student was answering problem
 3951: 
 3952: =cut
 3953: 
 3954: sub get_student_answers {
 3955:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3956:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3957:   my (%moreenv);
 3958:   my @elements=('symb','courseid','domain','username');
 3959:   foreach my $element (@elements) {
 3960:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3961:   }
 3962:   $moreenv{'grade_target'}='answer';
 3963:   %moreenv=(%form,%moreenv);
 3964:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3965:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3966:   return $userview;
 3967: }
 3968: 
 3969: =pod
 3970: 
 3971: =item * &submlink()
 3972: 
 3973: Inputs: $text $uname $udom $symb $target
 3974: 
 3975: Returns: A link to grades.pm such as to see the SUBM view of a student
 3976: 
 3977: =cut
 3978: 
 3979: ###############################################
 3980: sub submlink {
 3981:     my ($text,$uname,$udom,$symb,$target)=@_;
 3982:     if (!($uname && $udom)) {
 3983: 	(my $cursymb, my $courseid,$udom,$uname)=
 3984: 	    &Apache::lonnet::whichuser($symb);
 3985: 	if (!$symb) { $symb=$cursymb; }
 3986:     }
 3987:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3988:     $symb=&escape($symb);
 3989:     if ($target) { $target=" target=\"$target\""; }
 3990:     return
 3991:         '<a href="/adm/grades?command=submission'.
 3992:         '&amp;symb='.$symb.
 3993:         '&amp;student='.$uname.
 3994:         '&amp;userdom='.$udom.'"'.
 3995:         $target.'>'.$text.'</a>';
 3996: }
 3997: ##############################################
 3998: 
 3999: =pod
 4000: 
 4001: =item * &pgrdlink()
 4002: 
 4003: Inputs: $text $uname $udom $symb $target
 4004: 
 4005: Returns: A link to grades.pm such as to see the PGRD view of a student
 4006: 
 4007: =cut
 4008: 
 4009: ###############################################
 4010: sub pgrdlink {
 4011:     my $link=&submlink(@_);
 4012:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4013:     return $link;
 4014: }
 4015: ##############################################
 4016: 
 4017: =pod
 4018: 
 4019: =item * &pprmlink()
 4020: 
 4021: Inputs: $text $uname $udom $symb $target
 4022: 
 4023: Returns: A link to parmset.pm such as to see the PPRM view of a
 4024: student and a specific resource
 4025: 
 4026: =cut
 4027: 
 4028: ###############################################
 4029: sub pprmlink {
 4030:     my ($text,$uname,$udom,$symb,$target)=@_;
 4031:     if (!($uname && $udom)) {
 4032: 	(my $cursymb, my $courseid,$udom,$uname)=
 4033: 	    &Apache::lonnet::whichuser($symb);
 4034: 	if (!$symb) { $symb=$cursymb; }
 4035:     }
 4036:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4037:     $symb=&escape($symb);
 4038:     if ($target) { $target="target=\"$target\""; }
 4039:     return '<a href="/adm/parmset?command=set&amp;'.
 4040: 	'symb='.$symb.'&amp;uname='.$uname.
 4041: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4042: }
 4043: ##############################################
 4044: 
 4045: =pod
 4046: 
 4047: =back
 4048: 
 4049: =cut
 4050: 
 4051: ###############################################
 4052: 
 4053: 
 4054: sub timehash {
 4055:     my ($thistime) = @_;
 4056:     my $timezone = &Apache::lonlocal::gettimezone();
 4057:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4058:                      ->set_time_zone($timezone);
 4059:     my $wday = $dt->day_of_week();
 4060:     if ($wday == 7) { $wday = 0; }
 4061:     return ( 'second' => $dt->second(),
 4062:              'minute' => $dt->minute(),
 4063:              'hour'   => $dt->hour(),
 4064:              'day'     => $dt->day_of_month(),
 4065:              'month'   => $dt->month(),
 4066:              'year'    => $dt->year(),
 4067:              'weekday' => $wday,
 4068:              'dayyear' => $dt->day_of_year(),
 4069:              'dlsav'   => $dt->is_dst() );
 4070: }
 4071: 
 4072: sub utc_string {
 4073:     my ($date)=@_;
 4074:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4075: }
 4076: 
 4077: sub maketime {
 4078:     my %th=@_;
 4079:     my ($epoch_time,$timezone,$dt);
 4080:     $timezone = &Apache::lonlocal::gettimezone();
 4081:     eval {
 4082:         $dt = DateTime->new( year   => $th{'year'},
 4083:                              month  => $th{'month'},
 4084:                              day    => $th{'day'},
 4085:                              hour   => $th{'hour'},
 4086:                              minute => $th{'minute'},
 4087:                              second => $th{'second'},
 4088:                              time_zone => $timezone,
 4089:                          );
 4090:     };
 4091:     if (!$@) {
 4092:         $epoch_time = $dt->epoch;
 4093:         if ($epoch_time) {
 4094:             return $epoch_time;
 4095:         }
 4096:     }
 4097:     return POSIX::mktime(
 4098:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4099:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4100: }
 4101: 
 4102: #########################################
 4103: 
 4104: sub findallcourses {
 4105:     my ($roles,$uname,$udom) = @_;
 4106:     my %roles;
 4107:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4108:     my %courses;
 4109:     my $now=time;
 4110:     if (!defined($uname)) {
 4111:         $uname = $env{'user.name'};
 4112:     }
 4113:     if (!defined($udom)) {
 4114:         $udom = $env{'user.domain'};
 4115:     }
 4116:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4117:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4118:         if (!%roles) {
 4119:             %roles = (
 4120:                        cc => 1,
 4121:                        co => 1,
 4122:                        in => 1,
 4123:                        ep => 1,
 4124:                        ta => 1,
 4125:                        cr => 1,
 4126:                        st => 1,
 4127:              );
 4128:         }
 4129:         foreach my $entry (keys(%roleshash)) {
 4130:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4131:             if ($trole =~ /^cr/) { 
 4132:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4133:             } else {
 4134:                 next if (!exists($roles{$trole}));
 4135:             }
 4136:             if ($tend) {
 4137:                 next if ($tend < $now);
 4138:             }
 4139:             if ($tstart) {
 4140:                 next if ($tstart > $now);
 4141:             }
 4142:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4143:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4144:             my $value = $trole.'/'.$cdom.'/';
 4145:             if ($secpart eq '') {
 4146:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4147:                 $sec = 'none';
 4148:                 $value .= $cnum.'/';
 4149:             } else {
 4150:                 $cnum = $cnumpart;
 4151:                 ($sec,$role) = split(/_/,$secpart);
 4152:                 $value .= $cnum.'/'.$sec;
 4153:             }
 4154:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4155:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4156:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4157:                 }
 4158:             } else {
 4159:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4160:             }
 4161:         }
 4162:     } else {
 4163:         foreach my $key (keys(%env)) {
 4164: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4165:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4166: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4167: 	        next if ($role eq 'ca' || $role eq 'aa');
 4168: 	        next if (%roles && !exists($roles{$role}));
 4169: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4170:                 my $active=1;
 4171:                 if ($starttime) {
 4172: 		    if ($now<$starttime) { $active=0; }
 4173:                 }
 4174:                 if ($endtime) {
 4175:                     if ($now>$endtime) { $active=0; }
 4176:                 }
 4177:                 if ($active) {
 4178:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4179:                     if ($sec eq '') {
 4180:                         $sec = 'none';
 4181:                     } else {
 4182:                         $value .= $sec;
 4183:                     }
 4184:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4185:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4186:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4187:                         }
 4188:                     } else {
 4189:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4190:                     }
 4191:                 }
 4192:             }
 4193:         }
 4194:     }
 4195:     return %courses;
 4196: }
 4197: 
 4198: ###############################################
 4199: 
 4200: sub blockcheck {
 4201:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4202: 
 4203:     if (!defined($udom)) {
 4204:         $udom = $env{'user.domain'};
 4205:     }
 4206:     if (!defined($uname)) {
 4207:         $uname = $env{'user.name'};
 4208:     }
 4209: 
 4210:     # If uname and udom are for a course, check for blocks in the course.
 4211: 
 4212:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4213:         my ($startblock,$endblock,$triggerblock) = 
 4214:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4215:         return ($startblock,$endblock,$triggerblock);
 4216:     }
 4217: 
 4218:     my $startblock = 0;
 4219:     my $endblock = 0;
 4220:     my $triggerblock = '';
 4221:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4222: 
 4223:     # If uname is for a user, and activity is course-specific, i.e.,
 4224:     # boards, chat or groups, check for blocking in current course only.
 4225: 
 4226:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4227:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4228:         foreach my $key (keys(%live_courses)) {
 4229:             if ($key ne $env{'request.course.id'}) {
 4230:                 delete($live_courses{$key});
 4231:             }
 4232:         }
 4233:     }
 4234: 
 4235:     my $otheruser = 0;
 4236:     my %own_courses;
 4237:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4238:         # Resource belongs to user other than current user.
 4239:         $otheruser = 1;
 4240:         # Gather courses for current user
 4241:         %own_courses = 
 4242:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4243:     }
 4244: 
 4245:     # Gather active course roles - course coordinator, instructor, 
 4246:     # exam proctor, ta, student, or custom role.
 4247: 
 4248:     foreach my $course (keys(%live_courses)) {
 4249:         my ($cdom,$cnum);
 4250:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4251:             $cdom = $env{'course.'.$course.'.domain'};
 4252:             $cnum = $env{'course.'.$course.'.num'};
 4253:         } else {
 4254:             ($cdom,$cnum) = split(/_/,$course); 
 4255:         }
 4256:         my $no_ownblock = 0;
 4257:         my $no_userblock = 0;
 4258:         if ($otheruser && $activity ne 'com') {
 4259:             # Check if current user has 'evb' priv for this
 4260:             if (defined($own_courses{$course})) {
 4261:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4262:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4263:                     if ($sec ne 'none') {
 4264:                         $checkrole .= '/'.$sec;
 4265:                     }
 4266:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4267:                         $no_ownblock = 1;
 4268:                         last;
 4269:                     }
 4270:                 }
 4271:             }
 4272:             # if they have 'evb' priv and are currently not playing student
 4273:             next if (($no_ownblock) &&
 4274:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4275:         }
 4276:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4277:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4278:             if ($sec ne 'none') {
 4279:                 $checkrole .= '/'.$sec;
 4280:             }
 4281:             if ($otheruser) {
 4282:                 # Resource belongs to user other than current user.
 4283:                 # Assemble privs for that user, and check for 'evb' priv.
 4284:                 my (%allroles,%userroles);
 4285:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4286:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4287:                         my ($trole,$tdom,$tnum,$tsec);
 4288:                         if ($entry =~ /^cr/) {
 4289:                             ($trole,$tdom,$tnum,$tsec) = 
 4290:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4291:                         } else {
 4292:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4293:                         }
 4294:                         my ($spec,$area,$trest);
 4295:                         $area = '/'.$tdom.'/'.$tnum;
 4296:                         $trest = $tnum;
 4297:                         if ($tsec ne '') {
 4298:                             $area .= '/'.$tsec;
 4299:                             $trest .= '/'.$tsec;
 4300:                         }
 4301:                         $spec = $trole.'.'.$area;
 4302:                         if ($trole =~ /^cr/) {
 4303:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4304:                                                               $tdom,$spec,$trest,$area);
 4305:                         } else {
 4306:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4307:                                                                 $tdom,$spec,$trest,$area);
 4308:                         }
 4309:                     }
 4310:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4311:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4312:                         if ($1) {
 4313:                             $no_userblock = 1;
 4314:                             last;
 4315:                         }
 4316:                     }
 4317:                 }
 4318:             } else {
 4319:                 # Resource belongs to current user
 4320:                 # Check for 'evb' priv via lonnet::allowed().
 4321:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4322:                     $no_ownblock = 1;
 4323:                     last;
 4324:                 }
 4325:             }
 4326:         }
 4327:         # if they have the evb priv and are currently not playing student
 4328:         next if (($no_ownblock) &&
 4329:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4330:         next if ($no_userblock);
 4331: 
 4332:         # Retrieve blocking times and identity of locker for course
 4333:         # of specified user, unless user has 'evb' privilege.
 4334:         
 4335:         my ($start,$end,$trigger) = 
 4336:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4337:         if (($start != 0) && 
 4338:             (($startblock == 0) || ($startblock > $start))) {
 4339:             $startblock = $start;
 4340:             if ($trigger ne '') {
 4341:                 $triggerblock = $trigger;
 4342:             }
 4343:         }
 4344:         if (($end != 0)  &&
 4345:             (($endblock == 0) || ($endblock < $end))) {
 4346:             $endblock = $end;
 4347:             if ($trigger ne '') {
 4348:                 $triggerblock = $trigger;
 4349:             }
 4350:         }
 4351:     }
 4352:     return ($startblock,$endblock,$triggerblock);
 4353: }
 4354: 
 4355: sub get_blocks {
 4356:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4357:     my $startblock = 0;
 4358:     my $endblock = 0;
 4359:     my $triggerblock = '';
 4360:     my $course = $cdom.'_'.$cnum;
 4361:     $setters->{$course} = {};
 4362:     $setters->{$course}{'staff'} = [];
 4363:     $setters->{$course}{'times'} = [];
 4364:     $setters->{$course}{'triggers'} = [];
 4365:     my (@blockers,%triggered);
 4366:     my $now = time;
 4367:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4368:     if ($activity eq 'docs') {
 4369:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4370:         foreach my $block (@blockers) {
 4371:             if ($block =~ /^firstaccess____(.+)$/) {
 4372:                 my $item = $1;
 4373:                 my $type = 'map';
 4374:                 my $timersymb = $item;
 4375:                 if ($item eq 'course') {
 4376:                     $type = 'course';
 4377:                 } elsif ($item =~ /___\d+___/) {
 4378:                     $type = 'resource';
 4379:                 } else {
 4380:                     $timersymb = &Apache::lonnet::symbread($item);
 4381:                 }
 4382:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4383:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4384:                 $triggered{$block} = {
 4385:                                        start => $start,
 4386:                                        end   => $end,
 4387:                                        type  => $type,
 4388:                                      };
 4389:             }
 4390:         }
 4391:     } else {
 4392:         foreach my $block (keys(%commblocks)) {
 4393:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4394:                 my ($start,$end) = ($1,$2);
 4395:                 if ($start <= time && $end >= time) {
 4396:                     if (ref($commblocks{$block}) eq 'HASH') {
 4397:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4398:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4399:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4400:                                     push(@blockers,$block);
 4401:                                 }
 4402:                             }
 4403:                         }
 4404:                     }
 4405:                 }
 4406:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4407:                 my $item = $1;
 4408:                 my $timersymb = $item; 
 4409:                 my $type = 'map';
 4410:                 if ($item eq 'course') {
 4411:                     $type = 'course';
 4412:                 } elsif ($item =~ /___\d+___/) {
 4413:                     $type = 'resource';
 4414:                 } else {
 4415:                     $timersymb = &Apache::lonnet::symbread($item);
 4416:                 }
 4417:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4418:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4419:                 if ($start && $end) {
 4420:                     if (($start <= time) && ($end >= time)) {
 4421:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4422:                             push(@blockers,$block);
 4423:                             $triggered{$block} = {
 4424:                                                    start => $start,
 4425:                                                    end   => $end,
 4426:                                                    type  => $type,
 4427:                                                  };
 4428:                         }
 4429:                     }
 4430:                 }
 4431:             }
 4432:         }
 4433:     }
 4434:     foreach my $blocker (@blockers) {
 4435:         my ($staff_name,$staff_dom,$title,$blocks) =
 4436:             &parse_block_record($commblocks{$blocker});
 4437:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4438:         my ($start,$end,$triggertype);
 4439:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4440:             ($start,$end) = ($1,$2);
 4441:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4442:             $start = $triggered{$blocker}{'start'};
 4443:             $end = $triggered{$blocker}{'end'};
 4444:             $triggertype = $triggered{$blocker}{'type'};
 4445:         }
 4446:         if ($start) {
 4447:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4448:             if ($triggertype) {
 4449:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4450:             } else {
 4451:                 push(@{$$setters{$course}{'triggers'}},0);
 4452:             }
 4453:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4454:                 $startblock = $start;
 4455:                 if ($triggertype) {
 4456:                     $triggerblock = $blocker;
 4457:                 }
 4458:             }
 4459:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4460:                $endblock = $end;
 4461:                if ($triggertype) {
 4462:                    $triggerblock = $blocker;
 4463:                }
 4464:             }
 4465:         }
 4466:     }
 4467:     return ($startblock,$endblock,$triggerblock);
 4468: }
 4469: 
 4470: sub parse_block_record {
 4471:     my ($record) = @_;
 4472:     my ($setuname,$setudom,$title,$blocks);
 4473:     if (ref($record) eq 'HASH') {
 4474:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4475:         $title = &unescape($record->{'event'});
 4476:         $blocks = $record->{'blocks'};
 4477:     } else {
 4478:         my @data = split(/:/,$record,3);
 4479:         if (scalar(@data) eq 2) {
 4480:             $title = $data[1];
 4481:             ($setuname,$setudom) = split(/@/,$data[0]);
 4482:         } else {
 4483:             ($setuname,$setudom,$title) = @data;
 4484:         }
 4485:         $blocks = { 'com' => 'on' };
 4486:     }
 4487:     return ($setuname,$setudom,$title,$blocks);
 4488: }
 4489: 
 4490: sub blocking_status {
 4491:     my ($activity,$uname,$udom,$url) = @_;
 4492:     my %setters;
 4493: 
 4494: # check for active blocking
 4495:     my ($startblock,$endblock,$triggerblock) = 
 4496:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4497:     my $blocked = 0;
 4498:     if ($startblock && $endblock) {
 4499:         $blocked = 1;
 4500:     }
 4501: 
 4502: # caller just wants to know whether a block is active
 4503:     if (!wantarray) { return $blocked; }
 4504: 
 4505: # build a link to a popup window containing the details
 4506:     my $querystring  = "?activity=$activity";
 4507: # $uname and $udom decide whose portfolio the user is trying to look at
 4508:     if ($activity eq 'port') {
 4509:         $querystring .= "&amp;udom=$udom"      if $udom;
 4510:         $querystring .= "&amp;uname=$uname"    if $uname;
 4511:     } elsif ($activity eq 'docs') {
 4512:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4513:     }
 4514: 
 4515:     my $output .= <<'END_MYBLOCK';
 4516: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4517:     var options = "width=" + w + ",height=" + h + ",";
 4518:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4519:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4520:     var newWin = window.open(url, wdwName, options);
 4521:     newWin.focus();
 4522: }
 4523: END_MYBLOCK
 4524: 
 4525:     $output = Apache::lonhtmlcommon::scripttag($output);
 4526:   
 4527:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4528:     my $text = &mt('Communication Blocked');
 4529:     if ($activity eq 'docs') {
 4530:         $text = &mt('Content Access Blocked');
 4531:     } elsif ($activity eq 'printout') {
 4532:         $text = &mt('Printing Blocked');
 4533:     }
 4534:     $output .= <<"END_BLOCK";
 4535: <div class='LC_comblock'>
 4536:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4537:   title='$text'>
 4538:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4539:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4540:   title='$text'>$text</a>
 4541: </div>
 4542: 
 4543: END_BLOCK
 4544: 
 4545:     return ($blocked, $output);
 4546: }
 4547: 
 4548: ###############################################
 4549: 
 4550: sub check_ip_acc {
 4551:     my ($acc)=@_;
 4552:     &Apache::lonxml::debug("acc is $acc");
 4553:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4554:         return 1;
 4555:     }
 4556:     my $allowed=0;
 4557:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4558: 
 4559:     my $name;
 4560:     foreach my $pattern (split(',',$acc)) {
 4561:         $pattern =~ s/^\s*//;
 4562:         $pattern =~ s/\s*$//;
 4563:         if ($pattern =~ /\*$/) {
 4564:             #35.8.*
 4565:             $pattern=~s/\*//;
 4566:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4567:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4568:             #35.8.3.[34-56]
 4569:             my $low=$2;
 4570:             my $high=$3;
 4571:             $pattern=$1;
 4572:             if ($ip =~ /^\Q$pattern\E/) {
 4573:                 my $last=(split(/\./,$ip))[3];
 4574:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4575:             }
 4576:         } elsif ($pattern =~ /^\*/) {
 4577:             #*.msu.edu
 4578:             $pattern=~s/\*//;
 4579:             if (!defined($name)) {
 4580:                 use Socket;
 4581:                 my $netaddr=inet_aton($ip);
 4582:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4583:             }
 4584:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4585:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4586:             #127.0.0.1
 4587:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4588:         } else {
 4589:             #some.name.com
 4590:             if (!defined($name)) {
 4591:                 use Socket;
 4592:                 my $netaddr=inet_aton($ip);
 4593:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4594:             }
 4595:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4596:         }
 4597:         if ($allowed) { last; }
 4598:     }
 4599:     return $allowed;
 4600: }
 4601: 
 4602: ###############################################
 4603: 
 4604: =pod
 4605: 
 4606: =head1 Domain Template Functions
 4607: 
 4608: =over 4
 4609: 
 4610: =item * &determinedomain()
 4611: 
 4612: Inputs: $domain (usually will be undef)
 4613: 
 4614: Returns: Determines which domain should be used for designs
 4615: 
 4616: =cut
 4617: 
 4618: ###############################################
 4619: sub determinedomain {
 4620:     my $domain=shift;
 4621:     if (! $domain) {
 4622:         # Determine domain if we have not been given one
 4623:         $domain = &Apache::lonnet::default_login_domain();
 4624:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4625:         if ($env{'request.role.domain'}) { 
 4626:             $domain=$env{'request.role.domain'}; 
 4627:         }
 4628:     }
 4629:     return $domain;
 4630: }
 4631: ###############################################
 4632: 
 4633: sub devalidate_domconfig_cache {
 4634:     my ($udom)=@_;
 4635:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4636: }
 4637: 
 4638: # ---------------------- Get domain configuration for a domain
 4639: sub get_domainconf {
 4640:     my ($udom) = @_;
 4641:     my $cachetime=1800;
 4642:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4643:     if (defined($cached)) { return %{$result}; }
 4644: 
 4645:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4646: 					     ['login','rolecolors','autoenroll'],$udom);
 4647:     my (%designhash,%legacy);
 4648:     if (keys(%domconfig) > 0) {
 4649:         if (ref($domconfig{'login'}) eq 'HASH') {
 4650:             if (keys(%{$domconfig{'login'}})) {
 4651:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4652:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4653:                         if ($key eq 'loginvia') {
 4654:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4655:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4656:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4657:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4658:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4659:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4660:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4661: 
 4662:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4663:                                             } else {
 4664:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4665:                                             }
 4666:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4667:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4668:                                             }
 4669:                                         }
 4670:                                     }
 4671:                                 }
 4672:                             }
 4673:                         } else {
 4674:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4675:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4676:                                     $domconfig{'login'}{$key}{$img};
 4677:                             }
 4678:                         }
 4679:                     } else {
 4680:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4681:                     }
 4682:                 }
 4683:             } else {
 4684:                 $legacy{'login'} = 1;
 4685:             }
 4686:         } else {
 4687:             $legacy{'login'} = 1;
 4688:         }
 4689:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4690:             if (keys(%{$domconfig{'rolecolors'}})) {
 4691:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4692:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4693:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4694:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4695:                         }
 4696:                     }
 4697:                 }
 4698:             } else {
 4699:                 $legacy{'rolecolors'} = 1;
 4700:             }
 4701:         } else {
 4702:             $legacy{'rolecolors'} = 1;
 4703:         }
 4704:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4705:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4706:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4707:             }
 4708:         }
 4709:         if (keys(%legacy) > 0) {
 4710:             my %legacyhash = &get_legacy_domconf($udom);
 4711:             foreach my $item (keys(%legacyhash)) {
 4712:                 if ($item =~ /^\Q$udom\E\.login/) {
 4713:                     if ($legacy{'login'}) { 
 4714:                         $designhash{$item} = $legacyhash{$item};
 4715:                     }
 4716:                 } else {
 4717:                     if ($legacy{'rolecolors'}) {
 4718:                         $designhash{$item} = $legacyhash{$item};
 4719:                     }
 4720:                 }
 4721:             }
 4722:         }
 4723:     } else {
 4724:         %designhash = &get_legacy_domconf($udom); 
 4725:     }
 4726:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4727: 				  $cachetime);
 4728:     return %designhash;
 4729: }
 4730: 
 4731: sub get_legacy_domconf {
 4732:     my ($udom) = @_;
 4733:     my %legacyhash;
 4734:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4735:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4736:     if (-e $designfile) {
 4737:         if ( open (my $fh,"<$designfile") ) {
 4738:             while (my $line = <$fh>) {
 4739:                 next if ($line =~ /^\#/);
 4740:                 chomp($line);
 4741:                 my ($key,$val)=(split(/\=/,$line));
 4742:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4743:             }
 4744:             close($fh);
 4745:         }
 4746:     }
 4747:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4748:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4749:     }
 4750:     return %legacyhash;
 4751: }
 4752: 
 4753: =pod
 4754: 
 4755: =item * &domainlogo()
 4756: 
 4757: Inputs: $domain (usually will be undef)
 4758: 
 4759: Returns: A link to a domain logo, if the domain logo exists.
 4760: If the domain logo does not exist, a description of the domain.
 4761: 
 4762: =cut
 4763: 
 4764: ###############################################
 4765: sub domainlogo {
 4766:     my $domain = &determinedomain(shift);
 4767:     my %designhash = &get_domainconf($domain);    
 4768:     # See if there is a logo
 4769:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4770:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4771:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4772: 	    if ($imgsrc =~ m{^/res/}) {
 4773: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4774: 		&Apache::lonnet::repcopy($local_name);
 4775: 	    }
 4776: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4777:         } 
 4778:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4779:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4780:         return &Apache::lonnet::domain($domain,'description');
 4781:     } else {
 4782:         return '';
 4783:     }
 4784: }
 4785: ##############################################
 4786: 
 4787: =pod
 4788: 
 4789: =item * &designparm()
 4790: 
 4791: Inputs: $which parameter; $domain (usually will be undef)
 4792: 
 4793: Returns: value of designparamter $which
 4794: 
 4795: =cut
 4796: 
 4797: 
 4798: ##############################################
 4799: sub designparm {
 4800:     my ($which,$domain)=@_;
 4801:     if (exists($env{'environment.color.'.$which})) {
 4802:         return $env{'environment.color.'.$which};
 4803:     }
 4804:     $domain=&determinedomain($domain);
 4805:     my %domdesign;
 4806:     unless ($domain eq 'public') {
 4807:         %domdesign = &get_domainconf($domain);
 4808:     }
 4809:     my $output;
 4810:     if ($domdesign{$domain.'.'.$which} ne '') {
 4811:         $output = $domdesign{$domain.'.'.$which};
 4812:     } else {
 4813:         $output = $defaultdesign{$which};
 4814:     }
 4815:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4816:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4817:         if ($output =~ m{^/(adm|res)/}) {
 4818:             if ($output =~ m{^/res/}) {
 4819:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4820:                 &Apache::lonnet::repcopy($local_name);
 4821:             }
 4822:             $output = &lonhttpdurl($output);
 4823:         }
 4824:     }
 4825:     return $output;
 4826: }
 4827: 
 4828: ##############################################
 4829: =pod
 4830: 
 4831: =item * &authorspace()
 4832: 
 4833: Inputs: $url (usually will be undef).
 4834: 
 4835: Returns: Path to Construction Space containing the resource or 
 4836:          directory being viewed (or for which action is being taken). 
 4837:          If $url is provided, and begins /priv/<domain>/<uname>
 4838:          the path will be that portion of the $context argument.
 4839:          Otherwise the path will be for the author space of the current
 4840:          user when the current role is author, or for that of the 
 4841:          co-author/assistant co-author space when the current role 
 4842:          is co-author or assistant co-author.
 4843: 
 4844: =cut
 4845: 
 4846: sub authorspace {
 4847:     my ($url) = @_;
 4848:     if ($url ne '') {
 4849:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4850:            return $1;
 4851:         }
 4852:     }
 4853:     my $caname = '';
 4854:     my $cadom = '';
 4855:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4856:         ($cadom,$caname) =
 4857:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4858:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4859:         $caname = $env{'user.name'};
 4860:         $cadom = $env{'user.domain'};
 4861:     }
 4862:     if (($caname ne '') && ($cadom ne '')) {
 4863:         return "/priv/$cadom/$caname/";
 4864:     }
 4865:     return;
 4866: }
 4867: 
 4868: ##############################################
 4869: =pod
 4870: 
 4871: =item * &head_subbox()
 4872: 
 4873: Inputs: $content (contains HTML code with page functions, etc.)
 4874: 
 4875: Returns: HTML div with $content
 4876:          To be included in page header
 4877: 
 4878: =cut
 4879: 
 4880: sub head_subbox {
 4881:     my ($content)=@_;
 4882:     my $output =
 4883:         '<div class="LC_head_subbox">'
 4884:        .$content
 4885:        .'</div>'
 4886: }
 4887: 
 4888: ##############################################
 4889: =pod
 4890: 
 4891: =item * &CSTR_pageheader()
 4892: 
 4893: Input: (optional) filename from which breadcrumb trail is built.
 4894:        In most cases no input as needed, as $env{'request.filename'}
 4895:        is appropriate for use in building the breadcrumb trail.
 4896: 
 4897: Returns: HTML div with CSTR path and recent box
 4898:          To be included on Construction Space pages
 4899: 
 4900: =cut
 4901: 
 4902: sub CSTR_pageheader {
 4903:     my ($trailfile) = @_;
 4904:     if ($trailfile eq '') {
 4905:         $trailfile = $env{'request.filename'};
 4906:     }
 4907: 
 4908: # this is for resources; directories have customtitle, and crumbs
 4909: # and select recent are created in lonpubdir.pm
 4910: 
 4911:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4912:     my ($udom,$uname,$thisdisfn)=
 4913:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 4914:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4915:     $formaction =~ s{/+}{/}g;
 4916: 
 4917:     my $parentpath = '';
 4918:     my $lastitem = '';
 4919:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4920:         $parentpath = $1;
 4921:         $lastitem = $2;
 4922:     } else {
 4923:         $lastitem = $thisdisfn;
 4924:     }
 4925: 
 4926:     my $output =
 4927:          '<div>'
 4928:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4929:         .'<b>'.&mt('Construction Space:').'</b> '
 4930:         .'<form name="dirs" method="post" action="'.$formaction
 4931:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4932:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4933: 
 4934:     if ($lastitem) {
 4935:         $output .=
 4936:              '<span class="LC_filename">'
 4937:             .$lastitem
 4938:             .'</span>';
 4939:     }
 4940:     $output .=
 4941:          '<br />'
 4942:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4943:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4944:         .'</form>'
 4945:         .&Apache::lonmenu::constspaceform()
 4946:         .'</div>';
 4947: 
 4948:     return $output;
 4949: }
 4950: 
 4951: ###############################################
 4952: ###############################################
 4953: 
 4954: =pod
 4955: 
 4956: =back
 4957: 
 4958: =head1 HTML Helpers
 4959: 
 4960: =over 4
 4961: 
 4962: =item * &bodytag()
 4963: 
 4964: Returns a uniform header for LON-CAPA web pages.
 4965: 
 4966: Inputs: 
 4967: 
 4968: =over 4
 4969: 
 4970: =item * $title, A title to be displayed on the page.
 4971: 
 4972: =item * $function, the current role (can be undef).
 4973: 
 4974: =item * $addentries, extra parameters for the <body> tag.
 4975: 
 4976: =item * $bodyonly, if defined, only return the <body> tag.
 4977: 
 4978: =item * $domain, if defined, force a given domain.
 4979: 
 4980: =item * $forcereg, if page should register as content page (relevant for 
 4981:             text interface only)
 4982: 
 4983: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4984:                      navigational links
 4985: 
 4986: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4987: 
 4988: =item * $no_inline_link, if true and in remote mode, don't show the
 4989:          'Switch To Inline Menu' link
 4990: 
 4991: =item * $args, optional argument valid values are
 4992:             no_auto_mt_title -> prevents &mt()ing the title arg
 4993:             inherit_jsmath -> when creating popup window in a page,
 4994:                               should it have jsmath forced on by the
 4995:                               current page
 4996: 
 4997: =item * $advtoolsref, optional argument, ref to an array containing
 4998:             inlineremote items to be added in "Functions" menu below
 4999:             breadcrumbs.
 5000: 
 5001: =back
 5002: 
 5003: Returns: A uniform header for LON-CAPA web pages.  
 5004: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5005: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5006: other decorations will be returned.
 5007: 
 5008: =cut
 5009: 
 5010: sub bodytag {
 5011:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5012:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5013: 
 5014:     my $public;
 5015:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5016:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5017:         $public = 1;
 5018:     }
 5019:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5020: 
 5021:     $function = &get_users_function() if (!$function);
 5022:     my $img =    &designparm($function.'.img',$domain);
 5023:     my $font =   &designparm($function.'.font',$domain);
 5024:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5025: 
 5026:     my %design = ( 'style'   => 'margin-top: 0',
 5027: 		   'bgcolor' => $pgbg,
 5028: 		   'text'    => $font,
 5029:                    'alink'   => &designparm($function.'.alink',$domain),
 5030: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5031: 		   'link'    => &designparm($function.'.link',$domain),);
 5032:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5033: 
 5034:  # role and realm
 5035:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5036:     if ($role  eq 'ca') {
 5037:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5038:         $realm = &plainname($rname,$rdom);
 5039:     } 
 5040: # realm
 5041:     if ($env{'request.course.id'}) {
 5042:         if ($env{'request.role'} !~ /^cr/) {
 5043:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5044:         }
 5045:         if ($env{'request.course.sec'}) {
 5046:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5047:         }   
 5048: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5049:     } else {
 5050:         $role = &Apache::lonnet::plaintext($role);
 5051:     }
 5052: 
 5053:     if (!$realm) { $realm='&nbsp;'; }
 5054: 
 5055:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5056: 
 5057: # construct main body tag
 5058:     my $bodytag = "<body $extra_body_attr>".
 5059: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5060: 
 5061:     if ($bodyonly) {
 5062:         return $bodytag;
 5063:     } 
 5064: 
 5065:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5066:     if ($public) {
 5067: 	undef($role);
 5068:     } else {
 5069: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5070:                                 undef,'LC_menubuttons_link');
 5071:     }
 5072:     
 5073:     my $titleinfo = '<h1>'.$title.'</h1>';
 5074:     #
 5075:     # Extra info if you are the DC
 5076:     my $dc_info = '';
 5077:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5078:                         $env{'course.'.$env{'request.course.id'}.
 5079:                                  '.domain'}.'/'})) {
 5080:         my $cid = $env{'request.course.id'};
 5081:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5082:         $dc_info =~ s/\s+$//;
 5083:     }
 5084: 
 5085:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5086:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5087: 
 5088:     if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 5089:         return $bodytag; 
 5090:     }
 5091: 
 5092:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5093: 
 5094:     my $funclist;
 5095:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5096:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions(), 'start')."\n".
 5097:                     Apache::lonmenu::serverform();
 5098:         my $forbodytag;
 5099:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5100:                                             $forcereg,$args->{'group'},
 5101:                                             $args->{'bread_crumbs'},
 5102:                                             $advtoolsref,'',\$forbodytag);
 5103:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5104:             $funclist = $forbodytag;
 5105:         }
 5106:     } else {
 5107: 
 5108:         #    if ($env{'request.state'} eq 'construct') {
 5109:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5110:         #    }
 5111: 
 5112: 
 5113: 
 5114:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5115:             if ($dc_info) {
 5116:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5117:             }
 5118:             $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 5119:                            <em>$realm</em> $dc_info</div>|;
 5120:             return $bodytag;
 5121:         }
 5122: 
 5123:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5124:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 5125:         }
 5126: 
 5127:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5128:             Apache::lonmenu::utilityfunctions(), 'start');
 5129: 
 5130:         $bodytag .= Apache::lonmenu::primary_menu();
 5131: 
 5132:         if ($dc_info) {
 5133:             $dc_info = &dc_courseid_toggle($dc_info);
 5134:         }
 5135:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5136: 
 5137:         #don't show menus for public users
 5138:         if (!$public){
 5139:             $bodytag .= Apache::lonmenu::secondary_menu();
 5140:             $bodytag .= Apache::lonmenu::serverform();
 5141:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5142:             if ($env{'request.state'} eq 'construct') {
 5143:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5144:                                 $args->{'bread_crumbs'});
 5145:             } elsif ($forcereg) { 
 5146:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5147:                                                             $args->{'group'});
 5148:             } else {
 5149:                 my $forbodytag;
 5150:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5151:                                                     $forcereg,$args->{'group'},
 5152:                                                     $args->{'bread_crumbs'},
 5153:                                                     $advtoolsref,'',\$forbodytag);
 5154:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5155:                     $bodytag .= $forbodytag;
 5156:                 }
 5157:             }
 5158:         }else{
 5159:             # this is to seperate menu from content when there's no secondary
 5160:             # menu. Especially needed for public accessible ressources.
 5161:             $bodytag .= '<hr style="clear:both" />';
 5162:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5163:         }
 5164: 
 5165:         return $bodytag;
 5166:     }
 5167: 
 5168: #
 5169: # Top frame rendering, Remote is up
 5170: #
 5171: 
 5172:     my $imgsrc = $img;
 5173:     if ($img =~ /^\/adm/) {
 5174:         $imgsrc = &lonhttpdurl($img);
 5175:     }
 5176:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5177: 
 5178:     # Explicit link to get inline menu
 5179:     my $menu= ($no_inline_link?''
 5180:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5181: 
 5182:     if ($dc_info) {
 5183:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5184:     }
 5185: 
 5186:     unless ($env{'form.inhibitmenu'}) {
 5187:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5188:                        <ol class="LC_primary_menu LC_right">
 5189:                        <li>$menu</li>
 5190:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5191:     }
 5192:     if ($env{'request.state'} eq 'construct') {
 5193:         if (!$public){
 5194:             if ($env{'request.state'} eq 'construct') {
 5195:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5196:                                 &Apache::lonmenu::utilityfunctions(), 'start').
 5197:                             &Apache::lonhtmlcommon::scripttag('','end').
 5198:                             &Apache::lonmenu::innerregister($forcereg,
 5199:                                                             $args->{'bread_crumbs'});
 5200:             }
 5201:         }
 5202:     }
 5203:     return $bodytag."\n".$funclist;
 5204: }
 5205: 
 5206: sub dc_courseid_toggle {
 5207:     my ($dc_info) = @_;
 5208:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5209:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5210:            &mt('(More ...)').'</a></span>'.
 5211:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5212: }
 5213: 
 5214: sub make_attr_string {
 5215:     my ($register,$attr_ref) = @_;
 5216: 
 5217:     if ($attr_ref && !ref($attr_ref)) {
 5218: 	die("addentries Must be a hash ref ".
 5219: 	    join(':',caller(1))." ".
 5220: 	    join(':',caller(0))." ");
 5221:     }
 5222: 
 5223:     if ($register) {
 5224: 	my ($on_load,$on_unload);
 5225: 	foreach my $key (keys(%{$attr_ref})) {
 5226: 	    if      (lc($key) eq 'onload') {
 5227: 		$on_load.=$attr_ref->{$key}.';';
 5228: 		delete($attr_ref->{$key});
 5229: 
 5230: 	    } elsif (lc($key) eq 'onunload') {
 5231: 		$on_unload.=$attr_ref->{$key}.';';
 5232: 		delete($attr_ref->{$key});
 5233: 	    }
 5234: 	}
 5235:         if ($env{'environment.remote'} eq 'on') {
 5236:             $attr_ref->{'onload'}  =
 5237:                 &Apache::lonmenu::loadevents().  $on_load;
 5238:             $attr_ref->{'onunload'}=
 5239:                 &Apache::lonmenu::unloadevents().$on_unload;
 5240:         } else {  
 5241: 	    $attr_ref->{'onload'}  = $on_load;
 5242: 	    $attr_ref->{'onunload'}= $on_unload;
 5243:         }
 5244:     }
 5245: 
 5246:     my $attr_string;
 5247:     foreach my $attr (keys(%$attr_ref)) {
 5248: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5249:     }
 5250:     return $attr_string;
 5251: }
 5252: 
 5253: 
 5254: ###############################################
 5255: ###############################################
 5256: 
 5257: =pod
 5258: 
 5259: =item * &endbodytag()
 5260: 
 5261: Returns a uniform footer for LON-CAPA web pages.
 5262: 
 5263: Inputs: 1 - optional reference to an args hash
 5264: If in the hash, key for noredirectlink has a value which evaluates to true,
 5265: a 'Continue' link is not displayed if the page contains an
 5266: internal redirect in the <head></head> section,
 5267: i.e., $env{'internal.head.redirect'} exists   
 5268: 
 5269: =cut
 5270: 
 5271: sub endbodytag {
 5272:     my ($args) = @_;
 5273:     my $endbodytag;
 5274:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5275:         $endbodytag='</body>';
 5276:     }
 5277:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5278:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5279:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5280: 	    $endbodytag=
 5281: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5282: 	        &mt('Continue').'</a>'.
 5283: 	        $endbodytag;
 5284:         }
 5285:     }
 5286:     return $endbodytag;
 5287: }
 5288: 
 5289: =pod
 5290: 
 5291: =item * &standard_css()
 5292: 
 5293: Returns a style sheet
 5294: 
 5295: Inputs: (all optional)
 5296:             domain         -> force to color decorate a page for a specific
 5297:                                domain
 5298:             function       -> force usage of a specific rolish color scheme
 5299:             bgcolor        -> override the default page bgcolor
 5300: 
 5301: =cut
 5302: 
 5303: sub standard_css {
 5304:     my ($function,$domain,$bgcolor) = @_;
 5305:     $function  = &get_users_function() if (!$function);
 5306:     my $img    = &designparm($function.'.img',   $domain);
 5307:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5308:     my $font   = &designparm($function.'.font',  $domain);
 5309:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5310: #second colour for later usage
 5311:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5312:     my $pgbg_or_bgcolor =
 5313: 	         $bgcolor ||
 5314: 	         &designparm($function.'.pgbg',  $domain);
 5315:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5316:     my $alink  = &designparm($function.'.alink', $domain);
 5317:     my $vlink  = &designparm($function.'.vlink', $domain);
 5318:     my $link   = &designparm($function.'.link',  $domain);
 5319: 
 5320:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5321:     my $mono                 = 'monospace';
 5322:     my $data_table_head      = $sidebg;
 5323:     my $data_table_light     = '#FAFAFA';
 5324:     my $data_table_dark      = '#E0E0E0';
 5325:     my $data_table_darker    = '#CCCCCC';
 5326:     my $data_table_highlight = '#FFFF00';
 5327:     my $mail_new             = '#FFBB77';
 5328:     my $mail_new_hover       = '#DD9955';
 5329:     my $mail_read            = '#BBBB77';
 5330:     my $mail_read_hover      = '#999944';
 5331:     my $mail_replied         = '#AAAA88';
 5332:     my $mail_replied_hover   = '#888855';
 5333:     my $mail_other           = '#99BBBB';
 5334:     my $mail_other_hover     = '#669999';
 5335:     my $table_header         = '#DDDDDD';
 5336:     my $feedback_link_bg     = '#BBBBBB';
 5337:     my $lg_border_color      = '#C8C8C8';
 5338:     my $button_hover         = '#BF2317';
 5339: 
 5340:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5341:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5342:                                              : '0 3px 0 4px';
 5343: 
 5344: 
 5345:     return <<END;
 5346: 
 5347: /* needed for iframe to allow 100% height in FF */
 5348: body, html { 
 5349:     margin: 0;
 5350:     padding: 0 0.5%;
 5351:     height: 99%; /* to avoid scrollbars */
 5352: }
 5353: 
 5354: body {
 5355:   font-family: $sans;
 5356:   line-height:130%;
 5357:   font-size:0.83em;
 5358:   color:$font;
 5359: }
 5360: 
 5361: a:focus,
 5362: a:focus img {
 5363:   color: red;
 5364: }
 5365: 
 5366: form, .inline {
 5367:   display: inline;
 5368: }
 5369: 
 5370: .LC_right {
 5371:   text-align:right;
 5372: }
 5373: 
 5374: .LC_middle {
 5375:   vertical-align:middle;
 5376: }
 5377: 
 5378: .LC_400Box {
 5379:   width:400px;
 5380: }
 5381: 
 5382: .LC_iframecontainer {
 5383:     width: 98%;
 5384:     margin: 0;
 5385:     position: fixed;
 5386:     top: 8.5em;
 5387:     bottom: 0;
 5388: }
 5389: 
 5390: .LC_iframecontainer iframe{
 5391:     border: none;
 5392:     width: 100%;
 5393:     height: 100%;
 5394: }
 5395: 
 5396: .LC_filename {
 5397:   font-family: $mono;
 5398:   white-space:pre;
 5399:   font-size: 120%;
 5400: }
 5401: 
 5402: .LC_fileicon {
 5403:   border: none;
 5404:   height: 1.3em;
 5405:   vertical-align: text-bottom;
 5406:   margin-right: 0.3em;
 5407:   text-decoration:none;
 5408: }
 5409: 
 5410: .LC_setting {
 5411:   text-decoration:underline;
 5412: }
 5413: 
 5414: .LC_error {
 5415:   color: red;
 5416: }
 5417: 
 5418: .LC_warning {
 5419:   color: darkorange;
 5420: }
 5421: 
 5422: .LC_diff_removed {
 5423:   color: red;
 5424: }
 5425: 
 5426: .LC_info,
 5427: .LC_success,
 5428: .LC_diff_added {
 5429:   color: green;
 5430: }
 5431: 
 5432: div.LC_confirm_box {
 5433:   background-color: #FAFAFA;
 5434:   border: 1px solid $lg_border_color;
 5435:   margin-right: 0;
 5436:   padding: 5px;
 5437: }
 5438: 
 5439: div.LC_confirm_box .LC_error img,
 5440: div.LC_confirm_box .LC_success img {
 5441:   vertical-align: middle;
 5442: }
 5443: 
 5444: .LC_icon {
 5445:   border: none;
 5446:   vertical-align: middle;
 5447: }
 5448: 
 5449: .LC_docs_spacer {
 5450:   width: 25px;
 5451:   height: 1px;
 5452:   border: none;
 5453: }
 5454: 
 5455: .LC_internal_info {
 5456:   color: #999999;
 5457: }
 5458: 
 5459: .LC_discussion {
 5460:   background: $data_table_dark;
 5461:   border: 1px solid black;
 5462:   margin: 2px;
 5463: }
 5464: 
 5465: .LC_disc_action_left {
 5466:   background: $sidebg;
 5467:   text-align: left;
 5468:   padding: 4px;
 5469:   margin: 2px;
 5470: }
 5471: 
 5472: .LC_disc_action_right {
 5473:   background: $sidebg;
 5474:   text-align: right;
 5475:   padding: 4px;
 5476:   margin: 2px;
 5477: }
 5478: 
 5479: .LC_disc_new_item {
 5480:   background: white;
 5481:   border: 2px solid red;
 5482:   margin: 4px;
 5483:   padding: 4px;
 5484: }
 5485: 
 5486: .LC_disc_old_item {
 5487:   background: white;
 5488:   margin: 4px;
 5489:   padding: 4px;
 5490: }
 5491: 
 5492: table.LC_pastsubmission {
 5493:   border: 1px solid black;
 5494:   margin: 2px;
 5495: }
 5496: 
 5497: table#LC_menubuttons {
 5498:   width: 100%;
 5499:   background: $pgbg;
 5500:   border: 2px;
 5501:   border-collapse: separate;
 5502:   padding: 0;
 5503: }
 5504: 
 5505: table#LC_title_bar a {
 5506:   color: $fontmenu;
 5507: }
 5508: 
 5509: table#LC_title_bar {
 5510:   clear: both;
 5511:   display: none;
 5512: }
 5513: 
 5514: table#LC_title_bar,
 5515: table.LC_breadcrumbs, /* obsolete? */
 5516: table#LC_title_bar.LC_with_remote {
 5517:   width: 100%;
 5518:   border-color: $pgbg;
 5519:   border-style: solid;
 5520:   border-width: $border;
 5521:   background: $pgbg;
 5522:   color: $fontmenu;
 5523:   border-collapse: collapse;
 5524:   padding: 0;
 5525:   margin: 0;
 5526: }
 5527: 
 5528: ul.LC_breadcrumb_tools_outerlist {
 5529:     margin: 0;
 5530:     padding: 0;
 5531:     position: relative;
 5532:     list-style: none;
 5533: }
 5534: ul.LC_breadcrumb_tools_outerlist li {
 5535:     display: inline;
 5536: }
 5537: 
 5538: .LC_breadcrumb_tools_navigation {
 5539:     padding: 0;
 5540:     margin: 0;
 5541:     float: left;
 5542: }
 5543: .LC_breadcrumb_tools_tools {
 5544:     padding: 0;
 5545:     margin: 0;
 5546:     float: right;
 5547: }
 5548: 
 5549: table#LC_title_bar td {
 5550:   background: $tabbg;
 5551: }
 5552: 
 5553: table#LC_menubuttons img {
 5554:   border: none;
 5555: }
 5556: 
 5557: .LC_breadcrumbs_component {
 5558:   float: right;
 5559:   margin: 0 1em;
 5560: }
 5561: .LC_breadcrumbs_component img {
 5562:   vertical-align: middle;
 5563: }
 5564: 
 5565: td.LC_table_cell_checkbox {
 5566:   text-align: center;
 5567: }
 5568: 
 5569: .LC_fontsize_small {
 5570:   font-size: 70%;
 5571: }
 5572: 
 5573: #LC_breadcrumbs {
 5574:   clear:both;
 5575:   background: $sidebg;
 5576:   border-bottom: 1px solid $lg_border_color;
 5577:   line-height: 2.5em;
 5578:   overflow: hidden;
 5579:   margin: 0;
 5580:   padding: 0;
 5581:   text-align: left;
 5582: }
 5583: 
 5584: .LC_head_subbox, .LC_actionbox {
 5585:   clear:both;
 5586:   background: #F8F8F8; /* $sidebg; */
 5587:   border: 1px solid $sidebg;
 5588:   margin: 0 0 10px 0;
 5589:   padding: 3px;
 5590:   text-align: left;
 5591: }
 5592: 
 5593: .LC_fontsize_medium {
 5594:   font-size: 85%;
 5595: }
 5596: 
 5597: .LC_fontsize_large {
 5598:   font-size: 120%;
 5599: }
 5600: 
 5601: .LC_menubuttons_inline_text {
 5602:   color: $font;
 5603:   font-size: 90%;
 5604:   padding-left:3px;
 5605: }
 5606: 
 5607: .LC_menubuttons_inline_text img{
 5608:   vertical-align: middle;
 5609: }
 5610: 
 5611: li.LC_menubuttons_inline_text img {
 5612:   cursor:pointer;
 5613:   text-decoration: none;
 5614: }
 5615: 
 5616: .LC_menubuttons_link {
 5617:   text-decoration: none;
 5618: }
 5619: 
 5620: .LC_menubuttons_category {
 5621:   color: $font;
 5622:   background: $pgbg;
 5623:   font-size: larger;
 5624:   font-weight: bold;
 5625: }
 5626: 
 5627: td.LC_menubuttons_text {
 5628:   color: $font;
 5629: }
 5630: 
 5631: .LC_current_location {
 5632:   background: $tabbg;
 5633: }
 5634: 
 5635: table.LC_data_table {
 5636:   border: 1px solid #000000;
 5637:   border-collapse: separate;
 5638:   border-spacing: 1px;
 5639:   background: $pgbg;
 5640: }
 5641: 
 5642: .LC_data_table_dense {
 5643:   font-size: small;
 5644: }
 5645: 
 5646: table.LC_nested_outer {
 5647:   border: 1px solid #000000;
 5648:   border-collapse: collapse;
 5649:   border-spacing: 0;
 5650:   width: 100%;
 5651: }
 5652: 
 5653: table.LC_innerpickbox,
 5654: table.LC_nested {
 5655:   border: none;
 5656:   border-collapse: collapse;
 5657:   border-spacing: 0;
 5658:   width: 100%;
 5659: }
 5660: 
 5661: table.LC_data_table tr th,
 5662: table.LC_calendar tr th,
 5663: table.LC_prior_tries tr th,
 5664: table.LC_innerpickbox tr th {
 5665:   font-weight: bold;
 5666:   background-color: $data_table_head;
 5667:   color:$fontmenu;
 5668:   font-size:90%;
 5669: }
 5670: 
 5671: table.LC_innerpickbox tr th,
 5672: table.LC_innerpickbox tr td {
 5673:   vertical-align: top;
 5674: }
 5675: 
 5676: table.LC_data_table tr.LC_info_row > td {
 5677:   background-color: #CCCCCC;
 5678:   font-weight: bold;
 5679:   text-align: left;
 5680: }
 5681: 
 5682: table.LC_data_table tr.LC_odd_row > td {
 5683:   background-color: $data_table_light;
 5684:   padding: 2px;
 5685:   vertical-align: top;
 5686: }
 5687: 
 5688: table.LC_pick_box tr > td.LC_odd_row {
 5689:   background-color: $data_table_light;
 5690:   vertical-align: top;
 5691: }
 5692: 
 5693: table.LC_data_table tr.LC_even_row > td {
 5694:   background-color: $data_table_dark;
 5695:   padding: 2px;
 5696:   vertical-align: top;
 5697: }
 5698: 
 5699: table.LC_pick_box tr > td.LC_even_row {
 5700:   background-color: $data_table_dark;
 5701:   vertical-align: top;
 5702: }
 5703: 
 5704: table.LC_data_table tr.LC_data_table_highlight td {
 5705:   background-color: $data_table_darker;
 5706: }
 5707: 
 5708: table.LC_data_table tr td.LC_leftcol_header {
 5709:   background-color: $data_table_head;
 5710:   font-weight: bold;
 5711: }
 5712: 
 5713: table.LC_data_table tr.LC_empty_row td,
 5714: table.LC_nested tr.LC_empty_row td {
 5715:   font-weight: bold;
 5716:   font-style: italic;
 5717:   text-align: center;
 5718:   padding: 8px;
 5719: }
 5720: 
 5721: table.LC_data_table tr.LC_empty_row td,
 5722: table.LC_data_table tr.LC_footer_row td {
 5723:   background-color: $sidebg;
 5724: }
 5725: 
 5726: table.LC_nested tr.LC_empty_row td {
 5727:   background-color: #FFFFFF;
 5728: }
 5729: 
 5730: table.LC_caption {
 5731: }
 5732: 
 5733: table.LC_nested tr.LC_empty_row td {
 5734:   padding: 4ex
 5735: }
 5736: 
 5737: table.LC_nested_outer tr th {
 5738:   font-weight: bold;
 5739:   color:$fontmenu;
 5740:   background-color: $data_table_head;
 5741:   font-size: small;
 5742:   border-bottom: 1px solid #000000;
 5743: }
 5744: 
 5745: table.LC_nested_outer tr td.LC_subheader {
 5746:   background-color: $data_table_head;
 5747:   font-weight: bold;
 5748:   font-size: small;
 5749:   border-bottom: 1px solid #000000;
 5750:   text-align: right;
 5751: }
 5752: 
 5753: table.LC_nested tr.LC_info_row td {
 5754:   background-color: #CCCCCC;
 5755:   font-weight: bold;
 5756:   font-size: small;
 5757:   text-align: center;
 5758: }
 5759: 
 5760: table.LC_nested tr.LC_info_row td.LC_left_item,
 5761: table.LC_nested_outer tr th.LC_left_item {
 5762:   text-align: left;
 5763: }
 5764: 
 5765: table.LC_nested td {
 5766:   background-color: #FFFFFF;
 5767:   font-size: small;
 5768: }
 5769: 
 5770: table.LC_nested_outer tr th.LC_right_item,
 5771: table.LC_nested tr.LC_info_row td.LC_right_item,
 5772: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5773: table.LC_nested tr td.LC_right_item {
 5774:   text-align: right;
 5775: }
 5776: 
 5777: table.LC_nested tr.LC_odd_row td {
 5778:   background-color: #EEEEEE;
 5779: }
 5780: 
 5781: table.LC_createuser {
 5782: }
 5783: 
 5784: table.LC_createuser tr.LC_section_row td {
 5785:   font-size: small;
 5786: }
 5787: 
 5788: table.LC_createuser tr.LC_info_row td  {
 5789:   background-color: #CCCCCC;
 5790:   font-weight: bold;
 5791:   text-align: center;
 5792: }
 5793: 
 5794: table.LC_calendar {
 5795:   border: 1px solid #000000;
 5796:   border-collapse: collapse;
 5797:   width: 98%;
 5798: }
 5799: 
 5800: table.LC_calendar_pickdate {
 5801:   font-size: xx-small;
 5802: }
 5803: 
 5804: table.LC_calendar tr td {
 5805:   border: 1px solid #000000;
 5806:   vertical-align: top;
 5807:   width: 14%;
 5808: }
 5809: 
 5810: table.LC_calendar tr td.LC_calendar_day_empty {
 5811:   background-color: $data_table_dark;
 5812: }
 5813: 
 5814: table.LC_calendar tr td.LC_calendar_day_current {
 5815:   background-color: $data_table_highlight;
 5816: }
 5817: 
 5818: table.LC_data_table tr td.LC_mail_new {
 5819:   background-color: $mail_new;
 5820: }
 5821: 
 5822: table.LC_data_table tr.LC_mail_new:hover {
 5823:   background-color: $mail_new_hover;
 5824: }
 5825: 
 5826: table.LC_data_table tr td.LC_mail_read {
 5827:   background-color: $mail_read;
 5828: }
 5829: 
 5830: /*
 5831: table.LC_data_table tr.LC_mail_read:hover {
 5832:   background-color: $mail_read_hover;
 5833: }
 5834: */
 5835: 
 5836: table.LC_data_table tr td.LC_mail_replied {
 5837:   background-color: $mail_replied;
 5838: }
 5839: 
 5840: /*
 5841: table.LC_data_table tr.LC_mail_replied:hover {
 5842:   background-color: $mail_replied_hover;
 5843: }
 5844: */
 5845: 
 5846: table.LC_data_table tr td.LC_mail_other {
 5847:   background-color: $mail_other;
 5848: }
 5849: 
 5850: /*
 5851: table.LC_data_table tr.LC_mail_other:hover {
 5852:   background-color: $mail_other_hover;
 5853: }
 5854: */
 5855: 
 5856: table.LC_data_table tr > td.LC_browser_file,
 5857: table.LC_data_table tr > td.LC_browser_file_published {
 5858:   background: #AAEE77;
 5859: }
 5860: 
 5861: table.LC_data_table tr > td.LC_browser_file_locked,
 5862: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5863:   background: #FFAA99;
 5864: }
 5865: 
 5866: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5867:   background: #888888;
 5868: }
 5869: 
 5870: table.LC_data_table tr > td.LC_browser_file_modified,
 5871: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5872:   background: #F8F866;
 5873: }
 5874: 
 5875: table.LC_data_table tr.LC_browser_folder > td {
 5876:   background: #E0E8FF;
 5877: }
 5878: 
 5879: table.LC_data_table tr > td.LC_roles_is {
 5880:   /* background: #77FF77; */
 5881: }
 5882: 
 5883: table.LC_data_table tr > td.LC_roles_future {
 5884:   border-right: 8px solid #FFFF77;
 5885: }
 5886: 
 5887: table.LC_data_table tr > td.LC_roles_will {
 5888:   border-right: 8px solid #FFAA77;
 5889: }
 5890: 
 5891: table.LC_data_table tr > td.LC_roles_expired {
 5892:   border-right: 8px solid #FF7777;
 5893: }
 5894: 
 5895: table.LC_data_table tr > td.LC_roles_will_not {
 5896:   border-right: 8px solid #AAFF77;
 5897: }
 5898: 
 5899: table.LC_data_table tr > td.LC_roles_selected {
 5900:   border-right: 8px solid #11CC55;
 5901: }
 5902: 
 5903: span.LC_current_location {
 5904:   font-size:larger;
 5905:   background: $pgbg;
 5906: }
 5907: 
 5908: span.LC_current_nav_location {
 5909:   font-weight:bold;
 5910:   background: $sidebg;
 5911: }
 5912: 
 5913: span.LC_parm_menu_item {
 5914:   font-size: larger;
 5915: }
 5916: 
 5917: span.LC_parm_scope_all {
 5918:   color: red;
 5919: }
 5920: 
 5921: span.LC_parm_scope_folder {
 5922:   color: green;
 5923: }
 5924: 
 5925: span.LC_parm_scope_resource {
 5926:   color: orange;
 5927: }
 5928: 
 5929: span.LC_parm_part {
 5930:   color: blue;
 5931: }
 5932: 
 5933: span.LC_parm_folder,
 5934: span.LC_parm_symb {
 5935:   font-size: x-small;
 5936:   font-family: $mono;
 5937:   color: #AAAAAA;
 5938: }
 5939: 
 5940: ul.LC_parm_parmlist li {
 5941:   display: inline-block;
 5942:   padding: 0.3em 0.8em;
 5943:   vertical-align: top;
 5944:   width: 150px;
 5945:   border-top:1px solid $lg_border_color;
 5946: }
 5947: 
 5948: td.LC_parm_overview_level_menu,
 5949: td.LC_parm_overview_map_menu,
 5950: td.LC_parm_overview_parm_selectors,
 5951: td.LC_parm_overview_restrictions  {
 5952:   border: 1px solid black;
 5953:   border-collapse: collapse;
 5954: }
 5955: 
 5956: table.LC_parm_overview_restrictions td {
 5957:   border-width: 1px 4px 1px 4px;
 5958:   border-style: solid;
 5959:   border-color: $pgbg;
 5960:   text-align: center;
 5961: }
 5962: 
 5963: table.LC_parm_overview_restrictions th {
 5964:   background: $tabbg;
 5965:   border-width: 1px 4px 1px 4px;
 5966:   border-style: solid;
 5967:   border-color: $pgbg;
 5968: }
 5969: 
 5970: table#LC_helpmenu {
 5971:   border: none;
 5972:   height: 55px;
 5973:   border-spacing: 0;
 5974: }
 5975: 
 5976: table#LC_helpmenu fieldset legend {
 5977:   font-size: larger;
 5978: }
 5979: 
 5980: table#LC_helpmenu_links {
 5981:   width: 100%;
 5982:   border: 1px solid black;
 5983:   background: $pgbg;
 5984:   padding: 0;
 5985:   border-spacing: 1px;
 5986: }
 5987: 
 5988: table#LC_helpmenu_links tr td {
 5989:   padding: 1px;
 5990:   background: $tabbg;
 5991:   text-align: center;
 5992:   font-weight: bold;
 5993: }
 5994: 
 5995: table#LC_helpmenu_links a:link,
 5996: table#LC_helpmenu_links a:visited,
 5997: table#LC_helpmenu_links a:active {
 5998:   text-decoration: none;
 5999:   color: $font;
 6000: }
 6001: 
 6002: table#LC_helpmenu_links a:hover {
 6003:   text-decoration: underline;
 6004:   color: $vlink;
 6005: }
 6006: 
 6007: .LC_chrt_popup_exists {
 6008:   border: 1px solid #339933;
 6009:   margin: -1px;
 6010: }
 6011: 
 6012: .LC_chrt_popup_up {
 6013:   border: 1px solid yellow;
 6014:   margin: -1px;
 6015: }
 6016: 
 6017: .LC_chrt_popup {
 6018:   border: 1px solid #8888FF;
 6019:   background: #CCCCFF;
 6020: }
 6021: 
 6022: table.LC_pick_box {
 6023:   border-collapse: separate;
 6024:   background: white;
 6025:   border: 1px solid black;
 6026:   border-spacing: 1px;
 6027: }
 6028: 
 6029: table.LC_pick_box td.LC_pick_box_title {
 6030:   background: $sidebg;
 6031:   font-weight: bold;
 6032:   text-align: left;
 6033:   vertical-align: top;
 6034:   width: 184px;
 6035:   padding: 8px;
 6036: }
 6037: 
 6038: table.LC_pick_box td.LC_pick_box_value {
 6039:   text-align: left;
 6040:   padding: 8px;
 6041: }
 6042: 
 6043: table.LC_pick_box td.LC_pick_box_select {
 6044:   text-align: left;
 6045:   padding: 8px;
 6046: }
 6047: 
 6048: table.LC_pick_box td.LC_pick_box_separator {
 6049:   padding: 0;
 6050:   height: 1px;
 6051:   background: black;
 6052: }
 6053: 
 6054: table.LC_pick_box td.LC_pick_box_submit {
 6055:   text-align: right;
 6056: }
 6057: 
 6058: table.LC_pick_box td.LC_evenrow_value {
 6059:   text-align: left;
 6060:   padding: 8px;
 6061:   background-color: $data_table_light;
 6062: }
 6063: 
 6064: table.LC_pick_box td.LC_oddrow_value {
 6065:   text-align: left;
 6066:   padding: 8px;
 6067:   background-color: $data_table_light;
 6068: }
 6069: 
 6070: span.LC_helpform_receipt_cat {
 6071:   font-weight: bold;
 6072: }
 6073: 
 6074: table.LC_group_priv_box {
 6075:   background: white;
 6076:   border: 1px solid black;
 6077:   border-spacing: 1px;
 6078: }
 6079: 
 6080: table.LC_group_priv_box td.LC_pick_box_title {
 6081:   background: $tabbg;
 6082:   font-weight: bold;
 6083:   text-align: right;
 6084:   width: 184px;
 6085: }
 6086: 
 6087: table.LC_group_priv_box td.LC_groups_fixed {
 6088:   background: $data_table_light;
 6089:   text-align: center;
 6090: }
 6091: 
 6092: table.LC_group_priv_box td.LC_groups_optional {
 6093:   background: $data_table_dark;
 6094:   text-align: center;
 6095: }
 6096: 
 6097: table.LC_group_priv_box td.LC_groups_functionality {
 6098:   background: $data_table_darker;
 6099:   text-align: center;
 6100:   font-weight: bold;
 6101: }
 6102: 
 6103: table.LC_group_priv td {
 6104:   text-align: left;
 6105:   padding: 0;
 6106: }
 6107: 
 6108: .LC_navbuttons {
 6109:   margin: 2ex 0ex 2ex 0ex;
 6110: }
 6111: 
 6112: .LC_topic_bar {
 6113:   font-weight: bold;
 6114:   background: $tabbg;
 6115:   margin: 1em 0em 1em 2em;
 6116:   padding: 3px;
 6117:   font-size: 1.2em;
 6118: }
 6119: 
 6120: .LC_topic_bar span {
 6121:   left: 0.5em;
 6122:   position: absolute;
 6123:   vertical-align: middle;
 6124:   font-size: 1.2em;
 6125: }
 6126: 
 6127: table.LC_course_group_status {
 6128:   margin: 20px;
 6129: }
 6130: 
 6131: table.LC_status_selector td {
 6132:   vertical-align: top;
 6133:   text-align: center;
 6134:   padding: 4px;
 6135: }
 6136: 
 6137: div.LC_feedback_link {
 6138:   clear: both;
 6139:   background: $sidebg;
 6140:   width: 100%;
 6141:   padding-bottom: 10px;
 6142:   border: 1px $tabbg solid;
 6143:   height: 22px;
 6144:   line-height: 22px;
 6145:   padding-top: 5px;
 6146: }
 6147: 
 6148: div.LC_feedback_link img {
 6149:   height: 22px;
 6150:   vertical-align:middle;
 6151: }
 6152: 
 6153: div.LC_feedback_link a {
 6154:   text-decoration: none;
 6155: }
 6156: 
 6157: div.LC_comblock {
 6158:   display:inline;
 6159:   color:$font;
 6160:   font-size:90%;
 6161: }
 6162: 
 6163: div.LC_feedback_link div.LC_comblock {
 6164:   padding-left:5px;
 6165: }
 6166: 
 6167: div.LC_feedback_link div.LC_comblock a {
 6168:   color:$font;
 6169: }
 6170: 
 6171: span.LC_feedback_link {
 6172:   /* background: $feedback_link_bg; */
 6173:   font-size: larger;
 6174: }
 6175: 
 6176: span.LC_message_link {
 6177:   /* background: $feedback_link_bg; */
 6178:   font-size: larger;
 6179:   position: absolute;
 6180:   right: 1em;
 6181: }
 6182: 
 6183: table.LC_prior_tries {
 6184:   border: 1px solid #000000;
 6185:   border-collapse: separate;
 6186:   border-spacing: 1px;
 6187: }
 6188: 
 6189: table.LC_prior_tries td {
 6190:   padding: 2px;
 6191: }
 6192: 
 6193: .LC_answer_correct {
 6194:   background: lightgreen;
 6195:   color: darkgreen;
 6196:   padding: 6px;
 6197: }
 6198: 
 6199: .LC_answer_charged_try {
 6200:   background: #FFAAAA;
 6201:   color: darkred;
 6202:   padding: 6px;
 6203: }
 6204: 
 6205: .LC_answer_not_charged_try,
 6206: .LC_answer_no_grade,
 6207: .LC_answer_late {
 6208:   background: lightyellow;
 6209:   color: black;
 6210:   padding: 6px;
 6211: }
 6212: 
 6213: .LC_answer_previous {
 6214:   background: lightblue;
 6215:   color: darkblue;
 6216:   padding: 6px;
 6217: }
 6218: 
 6219: .LC_answer_no_message {
 6220:   background: #FFFFFF;
 6221:   color: black;
 6222:   padding: 6px;
 6223: }
 6224: 
 6225: .LC_answer_unknown {
 6226:   background: orange;
 6227:   color: black;
 6228:   padding: 6px;
 6229: }
 6230: 
 6231: span.LC_prior_numerical,
 6232: span.LC_prior_string,
 6233: span.LC_prior_custom,
 6234: span.LC_prior_reaction,
 6235: span.LC_prior_math {
 6236:   font-family: $mono;
 6237:   white-space: pre;
 6238: }
 6239: 
 6240: span.LC_prior_string {
 6241:   font-family: $mono;
 6242:   white-space: pre;
 6243: }
 6244: 
 6245: table.LC_prior_option {
 6246:   width: 100%;
 6247:   border-collapse: collapse;
 6248: }
 6249: 
 6250: table.LC_prior_rank,
 6251: table.LC_prior_match {
 6252:   border-collapse: collapse;
 6253: }
 6254: 
 6255: table.LC_prior_option tr td,
 6256: table.LC_prior_rank tr td,
 6257: table.LC_prior_match tr td {
 6258:   border: 1px solid #000000;
 6259: }
 6260: 
 6261: .LC_nobreak {
 6262:   white-space: nowrap;
 6263: }
 6264: 
 6265: span.LC_cusr_emph {
 6266:   font-style: italic;
 6267: }
 6268: 
 6269: span.LC_cusr_subheading {
 6270:   font-weight: normal;
 6271:   font-size: 85%;
 6272: }
 6273: 
 6274: div.LC_docs_entry_move {
 6275:   border: 1px solid #BBBBBB;
 6276:   background: #DDDDDD;
 6277:   width: 22px;
 6278:   padding: 1px;
 6279:   margin: 0;
 6280: }
 6281: 
 6282: table.LC_data_table tr > td.LC_docs_entry_commands,
 6283: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6284:   font-size: x-small;
 6285: }
 6286: 
 6287: .LC_docs_entry_parameter {
 6288:   white-space: nowrap;
 6289: }
 6290: 
 6291: .LC_docs_copy {
 6292:   color: #000099;
 6293: }
 6294: 
 6295: .LC_docs_cut {
 6296:   color: #550044;
 6297: }
 6298: 
 6299: .LC_docs_rename {
 6300:   color: #009900;
 6301: }
 6302: 
 6303: .LC_docs_remove {
 6304:   color: #990000;
 6305: }
 6306: 
 6307: .LC_docs_reinit_warn,
 6308: .LC_docs_ext_edit {
 6309:   font-size: x-small;
 6310: }
 6311: 
 6312: table.LC_docs_adddocs td,
 6313: table.LC_docs_adddocs th {
 6314:   border: 1px solid #BBBBBB;
 6315:   padding: 4px;
 6316:   background: #DDDDDD;
 6317: }
 6318: 
 6319: table.LC_sty_begin {
 6320:   background: #BBFFBB;
 6321: }
 6322: 
 6323: table.LC_sty_end {
 6324:   background: #FFBBBB;
 6325: }
 6326: 
 6327: table.LC_double_column {
 6328:   border-width: 0;
 6329:   border-collapse: collapse;
 6330:   width: 100%;
 6331:   padding: 2px;
 6332: }
 6333: 
 6334: table.LC_double_column tr td.LC_left_col {
 6335:   top: 2px;
 6336:   left: 2px;
 6337:   width: 47%;
 6338:   vertical-align: top;
 6339: }
 6340: 
 6341: table.LC_double_column tr td.LC_right_col {
 6342:   top: 2px;
 6343:   right: 2px;
 6344:   width: 47%;
 6345:   vertical-align: top;
 6346: }
 6347: 
 6348: div.LC_left_float {
 6349:   float: left;
 6350:   padding-right: 5%;
 6351:   padding-bottom: 4px;
 6352: }
 6353: 
 6354: div.LC_clear_float_header {
 6355:   padding-bottom: 2px;
 6356: }
 6357: 
 6358: div.LC_clear_float_footer {
 6359:   padding-top: 10px;
 6360:   clear: both;
 6361: }
 6362: 
 6363: div.LC_grade_show_user {
 6364: /*  border-left: 5px solid $sidebg; */
 6365:   border-top: 5px solid #000000;
 6366:   margin: 50px 0 0 0;
 6367:   padding: 15px 0 5px 10px;
 6368: }
 6369: 
 6370: div.LC_grade_show_user_odd_row {
 6371: /*  border-left: 5px solid #000000; */
 6372: }
 6373: 
 6374: div.LC_grade_show_user div.LC_Box {
 6375:   margin-right: 50px;
 6376: }
 6377: 
 6378: div.LC_grade_submissions,
 6379: div.LC_grade_message_center,
 6380: div.LC_grade_info_links {
 6381:   margin: 5px;
 6382:   width: 99%;
 6383:   background: #FFFFFF;
 6384: }
 6385: 
 6386: div.LC_grade_submissions_header,
 6387: div.LC_grade_message_center_header {
 6388:   font-weight: bold;
 6389:   font-size: large;
 6390: }
 6391: 
 6392: div.LC_grade_submissions_body,
 6393: div.LC_grade_message_center_body {
 6394:   border: 1px solid black;
 6395:   width: 99%;
 6396:   background: #FFFFFF;
 6397: }
 6398: 
 6399: table.LC_scantron_action {
 6400:   width: 100%;
 6401: }
 6402: 
 6403: table.LC_scantron_action tr th {
 6404:   font-weight:bold;
 6405:   font-style:normal;
 6406: }
 6407: 
 6408: .LC_edit_problem_header,
 6409: div.LC_edit_problem_footer {
 6410:   font-weight: normal;
 6411:   font-size:  medium;
 6412:   margin: 2px;
 6413:   background-color: $sidebg;
 6414: }
 6415: 
 6416: div.LC_edit_problem_header,
 6417: div.LC_edit_problem_header div,
 6418: div.LC_edit_problem_footer,
 6419: div.LC_edit_problem_footer div,
 6420: div.LC_edit_problem_editxml_header,
 6421: div.LC_edit_problem_editxml_header div {
 6422:   margin-top: 5px;
 6423: }
 6424: 
 6425: div.LC_edit_problem_header_title {
 6426:   font-weight: bold;
 6427:   font-size: larger;
 6428:   background: $tabbg;
 6429:   padding: 3px;
 6430:   margin: 0 0 5px 0;
 6431: }
 6432: 
 6433: table.LC_edit_problem_header_title {
 6434:   width: 100%;
 6435:   background: $tabbg;
 6436: }
 6437: 
 6438: div.LC_edit_problem_discards {
 6439:   float: left;
 6440:   padding-bottom: 5px;
 6441: }
 6442: 
 6443: div.LC_edit_problem_saves {
 6444:   float: right;
 6445:   padding-bottom: 5px;
 6446: }
 6447: 
 6448: img.stift {
 6449:   border-width: 0;
 6450:   vertical-align: middle;
 6451: }
 6452: 
 6453: table td.LC_mainmenu_col_fieldset {
 6454:   vertical-align: top;
 6455: }
 6456: 
 6457: div.LC_createcourse {
 6458:   margin: 10px 10px 10px 10px;
 6459: }
 6460: 
 6461: .LC_dccid {
 6462:   margin: 0.2em 0 0 0;
 6463:   padding: 0;
 6464:   font-size: 90%;
 6465:   display:none;
 6466: }
 6467: 
 6468: ol.LC_primary_menu a:hover,
 6469: ol#LC_MenuBreadcrumbs a:hover,
 6470: ol#LC_PathBreadcrumbs a:hover,
 6471: ul#LC_secondary_menu a:hover,
 6472: .LC_FormSectionClearButton input:hover
 6473: ul.LC_TabContent   li:hover a {
 6474:   color:$button_hover;
 6475:   text-decoration:none;
 6476: }
 6477: 
 6478: h1 {
 6479:   padding: 0;
 6480:   line-height:130%;
 6481: }
 6482: 
 6483: h2,
 6484: h3,
 6485: h4,
 6486: h5,
 6487: h6 {
 6488:   margin: 5px 0 5px 0;
 6489:   padding: 0;
 6490:   line-height:130%;
 6491: }
 6492: 
 6493: .LC_hcell {
 6494:   padding:3px 15px 3px 15px;
 6495:   margin: 0;
 6496:   background-color:$tabbg;
 6497:   color:$fontmenu;
 6498:   border-bottom:solid 1px $lg_border_color;
 6499: }
 6500: 
 6501: .LC_Box > .LC_hcell {
 6502:   margin: 0 -10px 10px -10px;
 6503: }
 6504: 
 6505: .LC_noBorder {
 6506:   border: 0;
 6507: }
 6508: 
 6509: .LC_FormSectionClearButton input {
 6510:   background-color:transparent;
 6511:   border: none;
 6512:   cursor:pointer;
 6513:   text-decoration:underline;
 6514: }
 6515: 
 6516: .LC_help_open_topic {
 6517:   color: #FFFFFF;
 6518:   background-color: #EEEEFF;
 6519:   margin: 1px;
 6520:   padding: 4px;
 6521:   border: 1px solid #000033;
 6522:   white-space: nowrap;
 6523:   /* vertical-align: middle; */
 6524: }
 6525: 
 6526: dl,
 6527: ul,
 6528: div,
 6529: fieldset {
 6530:   margin: 10px 10px 10px 0;
 6531:   /* overflow: hidden; */
 6532: }
 6533: 
 6534: fieldset > legend {
 6535:   font-weight: bold;
 6536:   padding: 0 5px 0 5px;
 6537: }
 6538: 
 6539: #LC_nav_bar {
 6540:   float: left;
 6541:   background-color: $pgbg_or_bgcolor;
 6542:   margin: 0 0 2px 0;
 6543: }
 6544: 
 6545: #LC_realm {
 6546:   margin: 0.2em 0 0 0;
 6547:   padding: 0;
 6548:   font-weight: bold;
 6549:   text-align: center;
 6550:   background-color: $pgbg_or_bgcolor;
 6551: }
 6552: 
 6553: #LC_nav_bar em {
 6554:   font-weight: bold;
 6555:   font-style: normal;
 6556: }
 6557: 
 6558: ol.LC_primary_menu {
 6559:   float: right;
 6560:   margin: 0;
 6561:   padding: 0;
 6562:   background-color: $pgbg_or_bgcolor;
 6563: }
 6564: 
 6565: ol#LC_PathBreadcrumbs {
 6566:   margin: 0;
 6567: }
 6568: 
 6569: ol.LC_primary_menu li {
 6570:   color: RGB(80, 80, 80);
 6571:   vertical-align: middle;
 6572:   text-align: left;
 6573:   list-style: none;
 6574:   float: left;
 6575: }
 6576: 
 6577: ol.LC_primary_menu li a {
 6578:   display: block;
 6579:   margin: 0;
 6580:   padding: 0 5px 0 10px;
 6581:   text-decoration: none;
 6582: }
 6583: 
 6584: ol.LC_primary_menu li ul {
 6585:   display: none;
 6586:   width: 10em;
 6587:   background-color: $data_table_light;
 6588: }
 6589: 
 6590: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6591:   display: block;
 6592:   position: absolute;
 6593:   margin: 0;
 6594:   padding: 0;
 6595:   z-index: 2;
 6596: }
 6597: 
 6598: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6599:   font-size: 90%;
 6600:   vertical-align: top;
 6601:   float: none;
 6602:   border-left: 1px solid black;
 6603:   border-right: 1px solid black;
 6604: }
 6605: 
 6606: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6607:   background-color:$data_table_light;
 6608: }
 6609: 
 6610: ol.LC_primary_menu li li a:hover {
 6611:    color:$button_hover;
 6612:    background-color:$data_table_dark;
 6613: }
 6614: 
 6615: ol.LC_primary_menu li img {
 6616:   vertical-align: bottom;
 6617:   height: 1.1em;
 6618:   margin: 0.2em 0 0 0;
 6619: }
 6620: 
 6621: ol.LC_primary_menu a {
 6622:   color: RGB(80, 80, 80);
 6623:   text-decoration: none;
 6624: }
 6625: 
 6626: ol.LC_primary_menu a.LC_new_message {
 6627:   font-weight:bold;
 6628:   color: darkred;
 6629: }
 6630: 
 6631: ol.LC_docs_parameters {
 6632:   margin-left: 0;
 6633:   padding: 0;
 6634:   list-style: none;
 6635: }
 6636: 
 6637: ol.LC_docs_parameters li {
 6638:   margin: 0;
 6639:   padding-right: 20px;
 6640:   display: inline;
 6641: }
 6642: 
 6643: ol.LC_docs_parameters li:before {
 6644:   content: "\\002022 \\0020";
 6645: }
 6646: 
 6647: li.LC_docs_parameters_title {
 6648:   font-weight: bold;
 6649: }
 6650: 
 6651: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6652:   content: "";
 6653: }
 6654: 
 6655: ul#LC_secondary_menu {
 6656:   clear: right;
 6657:   color: $fontmenu;
 6658:   background: $tabbg;
 6659:   list-style: none;
 6660:   padding: 0;
 6661:   margin: 0;
 6662:   width: 100%;
 6663:   text-align: left;
 6664:   float: left;
 6665: }
 6666: 
 6667: ul#LC_secondary_menu li {
 6668:   font-weight: bold;
 6669:   line-height: 1.8em;
 6670:   border-right: 1px solid black;
 6671:   vertical-align: middle;
 6672:   float: left;
 6673: }
 6674: 
 6675: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6676:   background-color: $data_table_light;
 6677: }
 6678: 
 6679: ul#LC_secondary_menu li a {
 6680:   padding: 0 0.8em;
 6681: }
 6682: 
 6683: ul#LC_secondary_menu li ul {
 6684:   display: none;
 6685: }
 6686: 
 6687: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6688:   display: block;
 6689:   position: absolute;
 6690:   margin: 0;
 6691:   padding: 0;
 6692:   list-style:none;
 6693:   float: none;
 6694:   background-color: $data_table_light;
 6695:   z-index: 2;
 6696:   margin-left: -1px;
 6697: }
 6698: 
 6699: ul#LC_secondary_menu li ul li {
 6700:   font-size: 90%;
 6701:   vertical-align: top;
 6702:   border-left: 1px solid black;
 6703:   border-right: 1px solid black;
 6704:   background-color: $data_table_light
 6705:   list-style:none;
 6706:   float: none;
 6707: }
 6708: 
 6709: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6710:   background-color: $data_table_dark;
 6711: }
 6712: 
 6713: ul.LC_TabContent {
 6714:   display:block;
 6715:   background: $sidebg;
 6716:   border-bottom: solid 1px $lg_border_color;
 6717:   list-style:none;
 6718:   margin: -1px -10px 0 -10px;
 6719:   padding: 0;
 6720: }
 6721: 
 6722: ul.LC_TabContent li,
 6723: ul.LC_TabContentBigger li {
 6724:   float:left;
 6725: }
 6726: 
 6727: ul#LC_secondary_menu li a {
 6728:   color: $fontmenu;
 6729:   text-decoration: none;
 6730: }
 6731: 
 6732: ul.LC_TabContent {
 6733:   min-height:20px;
 6734: }
 6735: 
 6736: ul.LC_TabContent li {
 6737:   vertical-align:middle;
 6738:   padding: 0 16px 0 10px;
 6739:   background-color:$tabbg;
 6740:   border-bottom:solid 1px $lg_border_color;
 6741:   border-left: solid 1px $font;
 6742: }
 6743: 
 6744: ul.LC_TabContent .right {
 6745:   float:right;
 6746: }
 6747: 
 6748: ul.LC_TabContent li a,
 6749: ul.LC_TabContent li {
 6750:   color:rgb(47,47,47);
 6751:   text-decoration:none;
 6752:   font-size:95%;
 6753:   font-weight:bold;
 6754:   min-height:20px;
 6755: }
 6756: 
 6757: ul.LC_TabContent li a:hover,
 6758: ul.LC_TabContent li a:focus {
 6759:   color: $button_hover;
 6760:   background:none;
 6761:   outline:none;
 6762: }
 6763: 
 6764: ul.LC_TabContent li:hover {
 6765:   color: $button_hover;
 6766:   cursor:pointer;
 6767: }
 6768: 
 6769: ul.LC_TabContent li.active {
 6770:   color: $font;
 6771:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6772:   border-bottom:solid 1px #FFFFFF;
 6773:   cursor: default;
 6774: }
 6775: 
 6776: ul.LC_TabContent li.active a {
 6777:   color:$font;
 6778:   background:#FFFFFF;
 6779:   outline: none;
 6780: }
 6781: 
 6782: ul.LC_TabContent li.goback {
 6783:   float: left;
 6784:   border-left: none;
 6785: }
 6786: 
 6787: #maincoursedoc {
 6788:   clear:both;
 6789: }
 6790: 
 6791: ul.LC_TabContentBigger {
 6792:   display:block;
 6793:   list-style:none;
 6794:   padding: 0;
 6795: }
 6796: 
 6797: ul.LC_TabContentBigger li {
 6798:   vertical-align:bottom;
 6799:   height: 30px;
 6800:   font-size:110%;
 6801:   font-weight:bold;
 6802:   color: #737373;
 6803: }
 6804: 
 6805: ul.LC_TabContentBigger li.active {
 6806:   position: relative;
 6807:   top: 1px;
 6808: }
 6809: 
 6810: ul.LC_TabContentBigger li a {
 6811:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6812:   height: 30px;
 6813:   line-height: 30px;
 6814:   text-align: center;
 6815:   display: block;
 6816:   text-decoration: none;
 6817:   outline: none;  
 6818: }
 6819: 
 6820: ul.LC_TabContentBigger li.active a {
 6821:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6822:   color:$font;
 6823: }
 6824: 
 6825: ul.LC_TabContentBigger li b {
 6826:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6827:   display: block;
 6828:   float: left;
 6829:   padding: 0 30px;
 6830:   border-bottom: 1px solid $lg_border_color;
 6831: }
 6832: 
 6833: ul.LC_TabContentBigger li:hover b {
 6834:   color:$button_hover;
 6835: }
 6836: 
 6837: ul.LC_TabContentBigger li.active b {
 6838:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6839:   color:$font;
 6840:   border: 0;
 6841: }
 6842: 
 6843: 
 6844: ul.LC_CourseBreadcrumbs {
 6845:   background: $sidebg;
 6846:   height: 2em;
 6847:   padding-left: 10px;
 6848:   margin: 0;
 6849:   list-style-position: inside;
 6850: }
 6851: 
 6852: ol#LC_MenuBreadcrumbs,
 6853: ol#LC_PathBreadcrumbs {
 6854:   padding-left: 10px;
 6855:   margin: 0;
 6856:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6857: }
 6858: 
 6859: ol#LC_MenuBreadcrumbs li,
 6860: ol#LC_PathBreadcrumbs li,
 6861: ul.LC_CourseBreadcrumbs li {
 6862:   display: inline;
 6863:   white-space: normal;  
 6864: }
 6865: 
 6866: ol#LC_MenuBreadcrumbs li a,
 6867: ul.LC_CourseBreadcrumbs li a {
 6868:   text-decoration: none;
 6869:   font-size:90%;
 6870: }
 6871: 
 6872: ol#LC_MenuBreadcrumbs h1 {
 6873:   display: inline;
 6874:   font-size: 90%;
 6875:   line-height: 2.5em;
 6876:   margin: 0;
 6877:   padding: 0;
 6878: }
 6879: 
 6880: ol#LC_PathBreadcrumbs li a {
 6881:   text-decoration:none;
 6882:   font-size:100%;
 6883:   font-weight:bold;
 6884: }
 6885: 
 6886: .LC_Box {
 6887:   border: solid 1px $lg_border_color;
 6888:   padding: 0 10px 10px 10px;
 6889: }
 6890: 
 6891: .LC_DocsBox {
 6892:   border: solid 1px $lg_border_color;
 6893:   padding: 0 0 10px 10px;
 6894: }
 6895: 
 6896: .LC_AboutMe_Image {
 6897:   float:left;
 6898:   margin-right:10px;
 6899: }
 6900: 
 6901: .LC_Clear_AboutMe_Image {
 6902:   clear:left;
 6903: }
 6904: 
 6905: dl.LC_ListStyleClean dt {
 6906:   padding-right: 5px;
 6907:   display: table-header-group;
 6908: }
 6909: 
 6910: dl.LC_ListStyleClean dd {
 6911:   display: table-row;
 6912: }
 6913: 
 6914: .LC_ListStyleClean,
 6915: .LC_ListStyleSimple,
 6916: .LC_ListStyleNormal,
 6917: .LC_ListStyleSpecial {
 6918:   /* display:block; */
 6919:   list-style-position: inside;
 6920:   list-style-type: none;
 6921:   overflow: hidden;
 6922:   padding: 0;
 6923: }
 6924: 
 6925: .LC_ListStyleSimple li,
 6926: .LC_ListStyleSimple dd,
 6927: .LC_ListStyleNormal li,
 6928: .LC_ListStyleNormal dd,
 6929: .LC_ListStyleSpecial li,
 6930: .LC_ListStyleSpecial dd {
 6931:   margin: 0;
 6932:   padding: 5px 5px 5px 10px;
 6933:   clear: both;
 6934: }
 6935: 
 6936: .LC_ListStyleClean li,
 6937: .LC_ListStyleClean dd {
 6938:   padding-top: 0;
 6939:   padding-bottom: 0;
 6940: }
 6941: 
 6942: .LC_ListStyleSimple dd,
 6943: .LC_ListStyleSimple li {
 6944:   border-bottom: solid 1px $lg_border_color;
 6945: }
 6946: 
 6947: .LC_ListStyleSpecial li,
 6948: .LC_ListStyleSpecial dd {
 6949:   list-style-type: none;
 6950:   background-color: RGB(220, 220, 220);
 6951:   margin-bottom: 4px;
 6952: }
 6953: 
 6954: table.LC_SimpleTable {
 6955:   margin:5px;
 6956:   border:solid 1px $lg_border_color;
 6957: }
 6958: 
 6959: table.LC_SimpleTable tr {
 6960:   padding: 0;
 6961:   border:solid 1px $lg_border_color;
 6962: }
 6963: 
 6964: table.LC_SimpleTable thead {
 6965:   background:rgb(220,220,220);
 6966: }
 6967: 
 6968: div.LC_columnSection {
 6969:   display: block;
 6970:   clear: both;
 6971:   overflow: hidden;
 6972:   margin: 0;
 6973: }
 6974: 
 6975: div.LC_columnSection>* {
 6976:   float: left;
 6977:   margin: 10px 20px 10px 0;
 6978:   overflow:hidden;
 6979: }
 6980: 
 6981: table em {
 6982:   font-weight: bold;
 6983:   font-style: normal;
 6984: }
 6985: 
 6986: table.LC_tableBrowseRes,
 6987: table.LC_tableOfContent {
 6988:   border:none;
 6989:   border-spacing: 1px;
 6990:   padding: 3px;
 6991:   background-color: #FFFFFF;
 6992:   font-size: 90%;
 6993: }
 6994: 
 6995: table.LC_tableOfContent {
 6996:   border-collapse: collapse;
 6997: }
 6998: 
 6999: table.LC_tableBrowseRes a,
 7000: table.LC_tableOfContent a {
 7001:   background-color: transparent;
 7002:   text-decoration: none;
 7003: }
 7004: 
 7005: table.LC_tableOfContent img {
 7006:   border: none;
 7007:   height: 1.3em;
 7008:   vertical-align: text-bottom;
 7009:   margin-right: 0.3em;
 7010: }
 7011: 
 7012: a#LC_content_toolbar_firsthomework {
 7013:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7014: }
 7015: 
 7016: a#LC_content_toolbar_everything {
 7017:   background-image:url(/res/adm/pages/show-all.gif);
 7018: }
 7019: 
 7020: a#LC_content_toolbar_uncompleted {
 7021:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7022: }
 7023: 
 7024: #LC_content_toolbar_clearbubbles {
 7025:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7026: }
 7027: 
 7028: a#LC_content_toolbar_changefolder {
 7029:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7030: }
 7031: 
 7032: a#LC_content_toolbar_changefolder_toggled {
 7033:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7034: }
 7035: 
 7036: a#LC_content_toolbar_edittoplevel {
 7037:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7038: }
 7039: 
 7040: ul#LC_toolbar li a:hover {
 7041:   background-position: bottom center;
 7042: }
 7043: 
 7044: ul#LC_toolbar {
 7045:   padding: 0;
 7046:   margin: 2px;
 7047:   list-style:none;
 7048:   position:relative;
 7049:   background-color:white;
 7050:   overflow: auto;
 7051: }
 7052: 
 7053: ul#LC_toolbar li {
 7054:   border:1px solid white;
 7055:   padding: 0;
 7056:   margin: 0;
 7057:   float: left;
 7058:   display:inline;
 7059:   vertical-align:middle;
 7060:   white-space: nowrap;
 7061: }
 7062: 
 7063: 
 7064: a.LC_toolbarItem {
 7065:   display:block;
 7066:   padding: 0;
 7067:   margin: 0;
 7068:   height: 32px;
 7069:   width: 32px;
 7070:   color:white;
 7071:   border: none;
 7072:   background-repeat:no-repeat;
 7073:   background-color:transparent;
 7074: }
 7075: 
 7076: ul.LC_funclist {
 7077:     margin: 0;
 7078:     padding: 0.5em 1em 0.5em 0;
 7079: }
 7080: 
 7081: ul.LC_funclist > li:first-child {
 7082:     font-weight:bold; 
 7083:     margin-left:0.8em;
 7084: }
 7085: 
 7086: ul.LC_funclist + ul.LC_funclist {
 7087:     /* 
 7088:        left border as a seperator if we have more than
 7089:        one list 
 7090:     */
 7091:     border-left: 1px solid $sidebg;
 7092:     /* 
 7093:        this hides the left border behind the border of the 
 7094:        outer box if element is wrapped to the next 'line' 
 7095:     */
 7096:     margin-left: -1px;
 7097: }
 7098: 
 7099: ul.LC_funclist li {
 7100:   display: inline;
 7101:   white-space: nowrap;
 7102:   margin: 0 0 0 25px;
 7103:   line-height: 150%;
 7104: }
 7105: 
 7106: .LC_hidden {
 7107:   display: none;
 7108: }
 7109: 
 7110: .LCmodal-overlay {
 7111: 		position:fixed;
 7112: 		top:0;
 7113: 		right:0;
 7114: 		bottom:0;
 7115: 		left:0;
 7116: 		height:100%;
 7117: 		width:100%;
 7118: 		margin:0;
 7119: 		padding:0;
 7120: 		background:#999;
 7121: 		opacity:.75;
 7122: 		filter: alpha(opacity=75);
 7123: 		-moz-opacity: 0.75;
 7124: 		z-index:101;
 7125: }
 7126: 
 7127: * html .LCmodal-overlay {   
 7128: 		position: absolute;
 7129: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7130: }
 7131: 
 7132: .LCmodal-window {
 7133: 		position:fixed;
 7134: 		top:50%;
 7135: 		left:50%;
 7136: 		margin:0;
 7137: 		padding:0;
 7138: 		z-index:102;
 7139: 	}
 7140: 
 7141: * html .LCmodal-window {
 7142: 		position:absolute;
 7143: }
 7144: 
 7145: .LCclose-window {
 7146: 		position:absolute;
 7147: 		width:32px;
 7148: 		height:32px;
 7149: 		right:8px;
 7150: 		top:8px;
 7151: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7152: 		text-indent:-99999px;
 7153: 		overflow:hidden;
 7154: 		cursor:pointer;
 7155: }
 7156: 
 7157: /*
 7158:   styles used by TTH when "Default set of options to pass to tth/m
 7159:   when converting TeX" in course settings has been set
 7160: 
 7161:   option passed: -t
 7162: 
 7163: */
 7164: 
 7165: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7166: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7167: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7168: td div.norm {line-height:normal;}
 7169: 
 7170: /*
 7171:   option passed -y3
 7172: */
 7173: 
 7174: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7175: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7176: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7177: 
 7178: END
 7179: }
 7180: 
 7181: =pod
 7182: 
 7183: =item * &headtag()
 7184: 
 7185: Returns a uniform footer for LON-CAPA web pages.
 7186: 
 7187: Inputs: $title - optional title for the head
 7188:         $head_extra - optional extra HTML to put inside the <head>
 7189:         $args - optional arguments
 7190:             force_register - if is true call registerurl so the remote is 
 7191:                              informed
 7192:             redirect       -> array ref of
 7193:                                    1- seconds before redirect occurs
 7194:                                    2- url to redirect to
 7195:                                    3- whether the side effect should occur
 7196:                            (side effect of setting 
 7197:                                $env{'internal.head.redirect'} to the url 
 7198:                                redirected too)
 7199:             domain         -> force to color decorate a page for a specific
 7200:                                domain
 7201:             function       -> force usage of a specific rolish color scheme
 7202:             bgcolor        -> override the default page bgcolor
 7203:             no_auto_mt_title
 7204:                            -> prevent &mt()ing the title arg
 7205: 
 7206: =cut
 7207: 
 7208: sub headtag {
 7209:     my ($title,$head_extra,$args) = @_;
 7210:     
 7211:     my $function = $args->{'function'} || &get_users_function();
 7212:     my $domain   = $args->{'domain'}   || &determinedomain();
 7213:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7214:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7215: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7216: 		   #time(),
 7217: 		   $env{'environment.color.timestamp'},
 7218: 		   $function,$domain,$bgcolor);
 7219: 
 7220:     $url = '/adm/css/'.&escape($url).'.css';
 7221: 
 7222:     my $result =
 7223: 	'<head>'.
 7224: 	&font_settings();
 7225: 
 7226:     my $inhibitprint = &print_suppression();
 7227: 
 7228:     if (!$args->{'frameset'}) {
 7229: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7230:     }
 7231:     if ($args->{'force_register'}) {
 7232:         $result .= &Apache::lonmenu::registerurl(1);
 7233:     }
 7234:     if (!$args->{'no_nav_bar'} 
 7235: 	&& !$args->{'only_body'}
 7236: 	&& !$args->{'frameset'}) {
 7237: 	$result .= &help_menu_js();
 7238:         $result.=&modal_window();
 7239:         $result.=&togglebox_script();
 7240:         $result.=&wishlist_window();
 7241:         $result.=&LCprogressbarUpdate_script();
 7242:     } else {
 7243:         if ($args->{'add_modal'}) {
 7244:            $result.=&modal_window();
 7245:         }
 7246:         if ($args->{'add_wishlist'}) {
 7247:            $result.=&wishlist_window();
 7248:         }
 7249:         if ($args->{'add_togglebox'}) {
 7250:            $result.=&togglebox_script();
 7251:         }
 7252:         if ($args->{'add_progressbar'}) {
 7253:            $result.=&LCprogressbarUpdate_script();
 7254:         }
 7255:     }
 7256:     if (ref($args->{'redirect'})) {
 7257: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7258: 	$url = &Apache::lonenc::check_encrypt($url);
 7259: 	if (!$inhibit_continue) {
 7260: 	    $env{'internal.head.redirect'} = $url;
 7261: 	}
 7262: 	$result.=<<ADDMETA
 7263: <meta http-equiv="pragma" content="no-cache" />
 7264: <meta http-equiv="Refresh" content="$time; url=$url" />
 7265: ADDMETA
 7266:     }
 7267:     if (!defined($title)) {
 7268: 	$title = 'The LearningOnline Network with CAPA';
 7269:     }
 7270:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7271:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7272: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7273:         .$inhibitprint
 7274: 	.$head_extra;
 7275:     return $result.'</head>';
 7276: }
 7277: 
 7278: =pod
 7279: 
 7280: =item * &font_settings()
 7281: 
 7282: Returns neccessary <meta> to set the proper encoding
 7283: 
 7284: Inputs: none
 7285: 
 7286: =cut
 7287: 
 7288: sub font_settings {
 7289:     my $headerstring='';
 7290:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 7291: 	$headerstring.=
 7292: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 7293:     }
 7294:     return $headerstring;
 7295: }
 7296: 
 7297: =pod
 7298: 
 7299: =item * &print_suppression()
 7300: 
 7301: In course context returns css which causes the body to be blank when media="print",
 7302: if printout generation is unavailable for the current resource.
 7303: 
 7304: This could be because:
 7305: 
 7306: (a) printstartdate is in the future
 7307: 
 7308: (b) printenddate is in the past
 7309: 
 7310: (c) there is an active exam block with "printout"
 7311: functionality blocked
 7312: 
 7313: Users with pav, pfo or evb privileges are exempt.
 7314: 
 7315: Inputs: none
 7316: 
 7317: =cut
 7318: 
 7319: 
 7320: sub print_suppression {
 7321:     my $noprint;
 7322:     if ($env{'request.course.id'}) {
 7323:         my $scope = $env{'request.course.id'};
 7324:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7325:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7326:             return;
 7327:         }
 7328:         if ($env{'request.course.sec'} ne '') {
 7329:             $scope .= "/$env{'request.course.sec'}";
 7330:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7331:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7332:                 return;
 7333:             }
 7334:         }
 7335:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7336:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7337:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7338:         if ($blocked) {
 7339:             my $checkrole = "cm./$cdom/$cnum";
 7340:             if ($env{'request.course.sec'} ne '') {
 7341:                 $checkrole .= "/$env{'request.course.sec'}";
 7342:             }
 7343:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7344:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7345:                 $noprint = 1;
 7346:             }
 7347:         }
 7348:         unless ($noprint) {
 7349:             my $symb = &Apache::lonnet::symbread();
 7350:             if ($symb ne '') {
 7351:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7352:                 if (ref($navmap)) {
 7353:                     my $res = $navmap->getBySymb($symb);
 7354:                     if (ref($res)) {
 7355:                         if (!$res->resprintable()) {
 7356:                             $noprint = 1;
 7357:                         }
 7358:                     }
 7359:                 }
 7360:             }
 7361:         }
 7362:         if ($noprint) {
 7363:             return <<"ENDSTYLE";
 7364: <style type="text/css" media="print">
 7365:     body { display:none }
 7366: </style>
 7367: ENDSTYLE
 7368:         }
 7369:     }
 7370:     return;
 7371: }
 7372: 
 7373: =pod
 7374: 
 7375: =item * &xml_begin()
 7376: 
 7377: Returns the needed doctype and <html>
 7378: 
 7379: Inputs: none
 7380: 
 7381: =cut
 7382: 
 7383: sub xml_begin {
 7384:     my $output='';
 7385: 
 7386:     if ($env{'browser.mathml'}) {
 7387: 	$output='<?xml version="1.0"?>'
 7388:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7389: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7390:             
 7391: #	    .'<!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">] >'
 7392: 	    .'<!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">'
 7393:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7394: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7395:     } else {
 7396: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7397:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7398:     }
 7399:     return $output;
 7400: }
 7401: 
 7402: =pod
 7403: 
 7404: =item * &start_page()
 7405: 
 7406: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7407: 
 7408: Inputs:
 7409: 
 7410: =over 4
 7411: 
 7412: $title - optional title for the page
 7413: 
 7414: $head_extra - optional extra HTML to incude inside the <head>
 7415: 
 7416: $args - additional optional args supported are:
 7417: 
 7418: =over 8
 7419: 
 7420:              only_body      -> is true will set &bodytag() onlybodytag
 7421:                                     arg on
 7422:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7423:              add_entries    -> additional attributes to add to the  <body>
 7424:              domain         -> force to color decorate a page for a 
 7425:                                     specific domain
 7426:              function       -> force usage of a specific rolish color
 7427:                                     scheme
 7428:              redirect       -> see &headtag()
 7429:              bgcolor        -> override the default page bg color
 7430:              js_ready       -> return a string ready for being used in 
 7431:                                     a javascript writeln
 7432:              html_encode    -> return a string ready for being used in 
 7433:                                     a html attribute
 7434:              force_register -> if is true will turn on the &bodytag()
 7435:                                     $forcereg arg
 7436:              frameset       -> if true will start with a <frameset>
 7437:                                     rather than <body>
 7438:              skip_phases    -> hash ref of 
 7439:                                     head -> skip the <html><head> generation
 7440:                                     body -> skip all <body> generation
 7441:              no_inline_link -> if true and in remote mode, don't show the
 7442:                                     'Switch To Inline Menu' link
 7443:              no_auto_mt_title -> prevent &mt()ing the title arg
 7444:              inherit_jsmath -> when creating popup window in a page,
 7445:                                     should it have jsmath forced on by the
 7446:                                     current page
 7447:              bread_crumbs ->             Array containing breadcrumbs
 7448:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7449:              group          -> includes the current group, if page is for a
 7450:                                specific group
 7451: 
 7452: =back
 7453: 
 7454: =back
 7455: 
 7456: =cut
 7457: 
 7458: sub start_page {
 7459:     my ($title,$head_extra,$args) = @_;
 7460:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7461: 
 7462:     $env{'internal.start_page'}++;
 7463:     my ($result,@advtools);
 7464: 
 7465:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7466:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7467:     }
 7468:     
 7469:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7470: 	if ($args->{'frameset'}) {
 7471: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7472: 						$args->{'add_entries'});
 7473: 	    $result .= "\n<frameset $attr_string>\n";
 7474:         } else {
 7475:             $result .=
 7476:                 &bodytag($title, 
 7477:                          $args->{'function'},       $args->{'add_entries'},
 7478:                          $args->{'only_body'},      $args->{'domain'},
 7479:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7480:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7481:                          $args,                     \@advtools);
 7482:         }
 7483:     }
 7484: 
 7485:     if ($args->{'js_ready'}) {
 7486: 		$result = &js_ready($result);
 7487:     }
 7488:     if ($args->{'html_encode'}) {
 7489: 		$result = &html_encode($result);
 7490:     }
 7491: 
 7492:     # Preparation for new and consistent functionlist at top of screen
 7493:     # if ($args->{'functionlist'}) {
 7494:     #            $result .= &build_functionlist();
 7495:     #}
 7496: 
 7497:     # Don't add anything more if only_body wanted or in const space
 7498:     return $result if    $args->{'only_body'} 
 7499:                       || $env{'request.state'} eq 'construct';
 7500: 
 7501:     #Breadcrumbs
 7502:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7503: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7504: 		#if any br links exists, add them to the breadcrumbs
 7505: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7506: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7507: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7508: 			}
 7509: 		}
 7510:                 # if @advtools array contains items add then to the breadcrumbs
 7511:                 if (@advtools > 0) {
 7512:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7513:                 }
 7514: 
 7515: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7516: 		if(exists($args->{'bread_crumbs_component'})){
 7517: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7518: 		}else{
 7519: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7520: 		}
 7521:     } elsif (($env{'environment.remote'} eq 'on') &&
 7522:              ($env{'form.inhibitmenu'} ne 'yes') &&
 7523:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 7524:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 7525:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 7526:     }
 7527:     return $result;
 7528: }
 7529: 
 7530: sub end_page {
 7531:     my ($args) = @_;
 7532:     $env{'internal.end_page'}++;
 7533:     my $result;
 7534:     if ($args->{'discussion'}) {
 7535: 	my ($target,$parser);
 7536: 	if (ref($args->{'discussion'})) {
 7537: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7538: 				$args->{'discussion'}{'parser'});
 7539: 	}
 7540: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7541:     }
 7542:     if ($args->{'frameset'}) {
 7543: 	$result .= '</frameset>';
 7544:     } else {
 7545: 	$result .= &endbodytag($args);
 7546:     }
 7547:     unless ($args->{'notbody'}) {
 7548:         $result .= "\n</html>";
 7549:     }
 7550: 
 7551:     if ($args->{'js_ready'}) {
 7552: 	$result = &js_ready($result);
 7553:     }
 7554: 
 7555:     if ($args->{'html_encode'}) {
 7556: 	$result = &html_encode($result);
 7557:     }
 7558: 
 7559:     return $result;
 7560: }
 7561: 
 7562: sub wishlist_window {
 7563:     return(<<'ENDWISHLIST');
 7564: <script type="text/javascript">
 7565: // <![CDATA[
 7566: // <!-- BEGIN LON-CAPA Internal
 7567: function set_wishlistlink(title, path) {
 7568:     if (!title) {
 7569:         title = document.title;
 7570:         title = title.replace(/^LON-CAPA /,'');
 7571:     }
 7572:     if (!path) {
 7573:         path = location.pathname;
 7574:     }
 7575:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7576:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7577: }
 7578: // END LON-CAPA Internal -->
 7579: // ]]>
 7580: </script>
 7581: ENDWISHLIST
 7582: }
 7583: 
 7584: sub modal_window {
 7585:     return(<<'ENDMODAL');
 7586: <script type="text/javascript">
 7587: // <![CDATA[
 7588: // <!-- BEGIN LON-CAPA Internal
 7589: var modalWindow = {
 7590: 	parent:"body",
 7591: 	windowId:null,
 7592: 	content:null,
 7593: 	width:null,
 7594: 	height:null,
 7595: 	close:function()
 7596: 	{
 7597: 	        $(".LCmodal-window").remove();
 7598: 	        $(".LCmodal-overlay").remove();
 7599: 	},
 7600: 	open:function()
 7601: 	{
 7602: 		var modal = "";
 7603: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7604: 		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;\">";
 7605: 		modal += this.content;
 7606: 		modal += "</div>";	
 7607: 
 7608: 		$(this.parent).append(modal);
 7609: 
 7610: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7611: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7612: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7613: 	}
 7614: };
 7615: 	var openMyModal = function(source,width,height,scrolling)
 7616: 	{
 7617: 		modalWindow.windowId = "myModal";
 7618: 		modalWindow.width = width;
 7619: 		modalWindow.height = height;
 7620: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
 7621: 		modalWindow.open();
 7622: 	};	
 7623: // END LON-CAPA Internal -->
 7624: // ]]>
 7625: </script>
 7626: ENDMODAL
 7627: }
 7628: 
 7629: sub modal_link {
 7630:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
 7631:     unless ($width) { $width=480; }
 7632:     unless ($height) { $height=400; }
 7633:     unless ($scrolling) { $scrolling='yes'; }
 7634:     my $target_attr;
 7635:     if (defined($target)) {
 7636:         $target_attr = 'target="'.$target.'"';
 7637:     }
 7638:     return <<"ENDLINK";
 7639: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
 7640:            $linktext</a>
 7641: ENDLINK
 7642: }
 7643: 
 7644: sub modal_adhoc_script {
 7645:     my ($funcname,$width,$height,$content)=@_;
 7646:     return (<<ENDADHOC);
 7647: <script type="text/javascript">
 7648: // <![CDATA[
 7649:         var $funcname = function()
 7650:         {
 7651:                 modalWindow.windowId = "myModal";
 7652:                 modalWindow.width = $width;
 7653:                 modalWindow.height = $height;
 7654:                 modalWindow.content = '$content';
 7655:                 modalWindow.open();
 7656:         };  
 7657: // ]]>
 7658: </script>
 7659: ENDADHOC
 7660: }
 7661: 
 7662: sub modal_adhoc_inner {
 7663:     my ($funcname,$width,$height,$content)=@_;
 7664:     my $innerwidth=$width-20;
 7665:     $content=&js_ready(
 7666:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7667:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
 7668:                     $content.
 7669:                  &end_scrollbox().
 7670:                &end_page()
 7671:              );
 7672:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7673: }
 7674: 
 7675: sub modal_adhoc_window {
 7676:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7677:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7678:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7679: }
 7680: 
 7681: sub modal_adhoc_launch {
 7682:     my ($funcname,$width,$height,$content)=@_;
 7683:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7684: <script type="text/javascript">
 7685: // <![CDATA[
 7686: $funcname();
 7687: // ]]>
 7688: </script>
 7689: ENDLAUNCH
 7690: }
 7691: 
 7692: sub modal_adhoc_close {
 7693:     return (<<ENDCLOSE);
 7694: <script type="text/javascript">
 7695: // <![CDATA[
 7696: modalWindow.close();
 7697: // ]]>
 7698: </script>
 7699: ENDCLOSE
 7700: }
 7701: 
 7702: sub togglebox_script {
 7703:    return(<<ENDTOGGLE);
 7704: <script type="text/javascript"> 
 7705: // <![CDATA[
 7706: function LCtoggleDisplay(id,hidetext,showtext) {
 7707:    link = document.getElementById(id + "link").childNodes[0];
 7708:    with (document.getElementById(id).style) {
 7709:       if (display == "none" ) {
 7710:           display = "inline";
 7711:           link.nodeValue = hidetext;
 7712:         } else {
 7713:           display = "none";
 7714:           link.nodeValue = showtext;
 7715:        }
 7716:    }
 7717: }
 7718: // ]]>
 7719: </script>
 7720: ENDTOGGLE
 7721: }
 7722: 
 7723: sub start_togglebox {
 7724:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7725:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7726:     unless ($showtext) { $showtext=&mt('show'); }
 7727:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7728:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7729:     return &start_data_table().
 7730:            &start_data_table_header_row().
 7731:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7732:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7733:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7734:            &end_data_table_header_row().
 7735:            '<tr id="'.$id.'" style="display:none""><td>';
 7736: }
 7737: 
 7738: sub end_togglebox {
 7739:     return '</td></tr>'.&end_data_table();
 7740: }
 7741: 
 7742: sub LCprogressbar_script {
 7743:    my ($id)=@_;
 7744:    return(<<ENDPROGRESS);
 7745: <script type="text/javascript">
 7746: // <![CDATA[
 7747: \$('#progressbar$id').progressbar({
 7748:   value: 0,
 7749:   change: function(event, ui) {
 7750:     var newVal = \$(this).progressbar('option', 'value');
 7751:     \$('.pblabel', this).text(LCprogressTxt);
 7752:   }
 7753: });
 7754: // ]]>
 7755: </script>
 7756: ENDPROGRESS
 7757: }
 7758: 
 7759: sub LCprogressbarUpdate_script {
 7760:    return(<<ENDPROGRESSUPDATE);
 7761: <style type="text/css">
 7762: .ui-progressbar { position:relative; }
 7763: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7764: </style>
 7765: <script type="text/javascript">
 7766: // <![CDATA[
 7767: var LCprogressTxt='---';
 7768: 
 7769: function LCupdateProgress(percent,progresstext,id) {
 7770:    LCprogressTxt=progresstext;
 7771:    \$('#progressbar'+id).progressbar('value',percent);
 7772: }
 7773: // ]]>
 7774: </script>
 7775: ENDPROGRESSUPDATE
 7776: }
 7777: 
 7778: my $LClastpercent;
 7779: my $LCidcnt;
 7780: my $LCcurrentid;
 7781: 
 7782: sub LCprogressbar {
 7783:     my ($r)=(@_);
 7784:     $LClastpercent=0;
 7785:     $LCidcnt++;
 7786:     $LCcurrentid=$$.'_'.$LCidcnt;
 7787:     my $starting=&mt('Starting');
 7788:     my $content=(<<ENDPROGBAR);
 7789: <p>
 7790:   <div id="progressbar$LCcurrentid">
 7791:     <span class="pblabel">$starting</span>
 7792:   </div>
 7793: </p>
 7794: ENDPROGBAR
 7795:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7796: }
 7797: 
 7798: sub LCprogressbarUpdate {
 7799:     my ($r,$val,$text)=@_;
 7800:     unless ($val) { 
 7801:        if ($LClastpercent) {
 7802:            $val=$LClastpercent;
 7803:        } else {
 7804:            $val=0;
 7805:        }
 7806:     }
 7807:     if ($val<0) { $val=0; }
 7808:     if ($val>100) { $val=0; }
 7809:     $LClastpercent=$val;
 7810:     unless ($text) { $text=$val.'%'; }
 7811:     $text=&js_ready($text);
 7812:     &r_print($r,<<ENDUPDATE);
 7813: <script type="text/javascript">
 7814: // <![CDATA[
 7815: LCupdateProgress($val,'$text','$LCcurrentid');
 7816: // ]]>
 7817: </script>
 7818: ENDUPDATE
 7819: }
 7820: 
 7821: sub LCprogressbarClose {
 7822:     my ($r)=@_;
 7823:     $LClastpercent=0;
 7824:     &r_print($r,<<ENDCLOSE);
 7825: <script type="text/javascript">
 7826: // <![CDATA[
 7827: \$("#progressbar$LCcurrentid").hide('slow'); 
 7828: // ]]>
 7829: </script>
 7830: ENDCLOSE
 7831: }
 7832: 
 7833: sub r_print {
 7834:     my ($r,$to_print)=@_;
 7835:     if ($r) {
 7836:       $r->print($to_print);
 7837:       $r->rflush();
 7838:     } else {
 7839:       print($to_print);
 7840:     }
 7841: }
 7842: 
 7843: sub html_encode {
 7844:     my ($result) = @_;
 7845: 
 7846:     $result = &HTML::Entities::encode($result,'<>&"');
 7847:     
 7848:     return $result;
 7849: }
 7850: 
 7851: sub js_ready {
 7852:     my ($result) = @_;
 7853: 
 7854:     $result =~ s/[\n\r]/ /xmsg;
 7855:     $result =~ s/\\/\\\\/xmsg;
 7856:     $result =~ s/'/\\'/xmsg;
 7857:     $result =~ s{</}{<\\/}xmsg;
 7858:     
 7859:     return $result;
 7860: }
 7861: 
 7862: sub validate_page {
 7863:     if (  exists($env{'internal.start_page'})
 7864: 	  &&     $env{'internal.start_page'} > 1) {
 7865: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7866: 				 $env{'internal.start_page'}.' '.
 7867: 				 $ENV{'request.filename'});
 7868:     }
 7869:     if (  exists($env{'internal.end_page'})
 7870: 	  &&     $env{'internal.end_page'} > 1) {
 7871: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7872: 				 $env{'internal.end_page'}.' '.
 7873: 				 $env{'request.filename'});
 7874:     }
 7875:     if (     exists($env{'internal.start_page'})
 7876: 	&& ! exists($env{'internal.end_page'})) {
 7877: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7878: 				 $env{'request.filename'});
 7879:     }
 7880:     if (   ! exists($env{'internal.start_page'})
 7881: 	&&   exists($env{'internal.end_page'})) {
 7882: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7883: 				 $env{'request.filename'});
 7884:     }
 7885: }
 7886: 
 7887: 
 7888: sub start_scrollbox {
 7889:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
 7890:     unless ($outerwidth) { $outerwidth='520px'; }
 7891:     unless ($width) { $width='500px'; }
 7892:     unless ($height) { $height='200px'; }
 7893:     my ($table_id,$div_id,$tdcol);
 7894:     if ($id ne '') {
 7895:         $table_id = " id='table_$id'";
 7896:         $div_id = " id='div_$id'";
 7897:     }
 7898:     if ($bgcolor ne '') {
 7899:         $tdcol = "background-color: $bgcolor;";
 7900:     }
 7901:     return <<"END";
 7902: <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>
 7903: END
 7904: }
 7905: 
 7906: sub end_scrollbox {
 7907:     return '</div></td></tr></table>';
 7908: }
 7909: 
 7910: sub simple_error_page {
 7911:     my ($r,$title,$msg) = @_;
 7912:     my $page =
 7913: 	&Apache::loncommon::start_page($title).
 7914: 	'<p class="LC_error">'.&mt($msg).'</p>'.
 7915: 	&Apache::loncommon::end_page();
 7916:     if (ref($r)) {
 7917: 	$r->print($page);
 7918: 	return;
 7919:     }
 7920:     return $page;
 7921: }
 7922: 
 7923: {
 7924:     my @row_count;
 7925: 
 7926:     sub start_data_table_count {
 7927:         unshift(@row_count, 0);
 7928:         return;
 7929:     }
 7930: 
 7931:     sub end_data_table_count {
 7932:         shift(@row_count);
 7933:         return;
 7934:     }
 7935: 
 7936:     sub start_data_table {
 7937: 	my ($add_class,$id) = @_;
 7938: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7939:         my $table_id;
 7940:         if (defined($id)) {
 7941:             $table_id = ' id="'.$id.'"';
 7942:         }
 7943: 	&start_data_table_count();
 7944: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 7945:     }
 7946: 
 7947:     sub end_data_table {
 7948: 	&end_data_table_count();
 7949: 	return '</table>'."\n";;
 7950:     }
 7951: 
 7952:     sub start_data_table_row {
 7953: 	my ($add_class, $id) = @_;
 7954: 	$row_count[0]++;
 7955: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7956: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7957:         $id = (' id="'.$id.'"') unless ($id eq '');
 7958:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7959:     }
 7960:     
 7961:     sub continue_data_table_row {
 7962: 	my ($add_class, $id) = @_;
 7963: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7964: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7965:         $id = (' id="'.$id.'"') unless ($id eq '');
 7966:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7967:     }
 7968: 
 7969:     sub end_data_table_row {
 7970: 	return '</tr>'."\n";;
 7971:     }
 7972: 
 7973:     sub start_data_table_empty_row {
 7974: #	$row_count[0]++;
 7975: 	return  '<tr class="LC_empty_row" >'."\n";;
 7976:     }
 7977: 
 7978:     sub end_data_table_empty_row {
 7979: 	return '</tr>'."\n";;
 7980:     }
 7981: 
 7982:     sub start_data_table_header_row {
 7983: 	return  '<tr class="LC_header_row">'."\n";;
 7984:     }
 7985: 
 7986:     sub end_data_table_header_row {
 7987: 	return '</tr>'."\n";;
 7988:     }
 7989: 
 7990:     sub data_table_caption {
 7991:         my $caption = shift;
 7992:         return "<caption class=\"LC_caption\">$caption</caption>";
 7993:     }
 7994: }
 7995: 
 7996: =pod
 7997: 
 7998: =item * &inhibit_menu_check($arg)
 7999: 
 8000: Checks for a inhibitmenu state and generates output to preserve it
 8001: 
 8002: Inputs:         $arg - can be any of
 8003:                      - undef - in which case the return value is a string 
 8004:                                to add  into arguments list of a uri
 8005:                      - 'input' - in which case the return value is a HTML
 8006:                                  <form> <input> field of type hidden to
 8007:                                  preserve the value
 8008:                      - a url - in which case the return value is the url with
 8009:                                the neccesary cgi args added to preserve the
 8010:                                inhibitmenu state
 8011:                      - a ref to a url - no return value, but the string is
 8012:                                         updated to include the neccessary cgi
 8013:                                         args to preserve the inhibitmenu state
 8014: 
 8015: =cut
 8016: 
 8017: sub inhibit_menu_check {
 8018:     my ($arg) = @_;
 8019:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8020:     if ($arg eq 'input') {
 8021: 	if ($env{'form.inhibitmenu'}) {
 8022: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8023: 	} else {
 8024: 	    return
 8025: 	}
 8026:     }
 8027:     if ($env{'form.inhibitmenu'}) {
 8028: 	if (ref($arg)) {
 8029: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8030: 	} elsif ($arg eq '') {
 8031: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8032: 	} else {
 8033: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8034: 	}
 8035:     }
 8036:     if (!ref($arg)) {
 8037: 	return $arg;
 8038:     }
 8039: }
 8040: 
 8041: ###############################################
 8042: 
 8043: =pod
 8044: 
 8045: =back
 8046: 
 8047: =head1 User Information Routines
 8048: 
 8049: =over 4
 8050: 
 8051: =item * &get_users_function()
 8052: 
 8053: Used by &bodytag to determine the current users primary role.
 8054: Returns either 'student','coordinator','admin', or 'author'.
 8055: 
 8056: =cut
 8057: 
 8058: ###############################################
 8059: sub get_users_function {
 8060:     my $function = 'norole';
 8061:     if ($env{'request.role'}=~/^(st)/) {
 8062:         $function='student';
 8063:     }
 8064:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8065:         $function='coordinator';
 8066:     }
 8067:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8068:         $function='admin';
 8069:     }
 8070:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8071:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8072:         $function='author';
 8073:     }
 8074:     return $function;
 8075: }
 8076: 
 8077: ###############################################
 8078: 
 8079: =pod
 8080: 
 8081: =item * &show_course()
 8082: 
 8083: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8084: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8085: 
 8086: Inputs:
 8087: None
 8088: 
 8089: Outputs:
 8090: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8091: 
 8092: =cut
 8093: 
 8094: ###############################################
 8095: sub show_course {
 8096:     my $course = !$env{'user.adv'};
 8097:     if (!$env{'user.adv'}) {
 8098:         foreach my $env (keys(%env)) {
 8099:             next if ($env !~ m/^user\.priv\./);
 8100:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8101:                 $course = 0;
 8102:                 last;
 8103:             }
 8104:         }
 8105:     }
 8106:     return $course;
 8107: }
 8108: 
 8109: ###############################################
 8110: 
 8111: =pod
 8112: 
 8113: =item * &check_user_status()
 8114: 
 8115: Determines current status of supplied role for a
 8116: specific user. Roles can be active, previous or future.
 8117: 
 8118: Inputs: 
 8119: user's domain, user's username, course's domain,
 8120: course's number, optional section ID.
 8121: 
 8122: Outputs:
 8123: role status: active, previous or future. 
 8124: 
 8125: =cut
 8126: 
 8127: sub check_user_status {
 8128:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8129:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8130:     my @uroles = keys %userinfo;
 8131:     my $srchstr;
 8132:     my $active_chk = 'none';
 8133:     my $now = time;
 8134:     if (@uroles > 0) {
 8135:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8136:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8137:         } else {
 8138:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8139:         }
 8140:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8141:             my $role_end = 0;
 8142:             my $role_start = 0;
 8143:             $active_chk = 'active';
 8144:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8145:                 $role_end = $1;
 8146:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8147:                     $role_start = $1;
 8148:                 }
 8149:             }
 8150:             if ($role_start > 0) {
 8151:                 if ($now < $role_start) {
 8152:                     $active_chk = 'future';
 8153:                 }
 8154:             }
 8155:             if ($role_end > 0) {
 8156:                 if ($now > $role_end) {
 8157:                     $active_chk = 'previous';
 8158:                 }
 8159:             }
 8160:         }
 8161:     }
 8162:     return $active_chk;
 8163: }
 8164: 
 8165: ###############################################
 8166: 
 8167: =pod
 8168: 
 8169: =item * &get_sections()
 8170: 
 8171: Determines all the sections for a course including
 8172: sections with students and sections containing other roles.
 8173: Incoming parameters: 
 8174: 
 8175: 1. domain
 8176: 2. course number 
 8177: 3. reference to array containing roles for which sections should 
 8178: be gathered (optional).
 8179: 4. reference to array containing status types for which sections 
 8180: should be gathered (optional).
 8181: 
 8182: If the third argument is undefined, sections are gathered for any role. 
 8183: If the fourth argument is undefined, sections are gathered for any status.
 8184: Permissible values are 'active' or 'future' or 'previous'.
 8185:  
 8186: Returns section hash (keys are section IDs, values are
 8187: number of users in each section), subject to the
 8188: optional roles filter, optional status filter 
 8189: 
 8190: =cut
 8191: 
 8192: ###############################################
 8193: sub get_sections {
 8194:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8195:     if (!defined($cdom) || !defined($cnum)) {
 8196:         my $cid =  $env{'request.course.id'};
 8197: 
 8198: 	return if (!defined($cid));
 8199: 
 8200:         $cdom = $env{'course.'.$cid.'.domain'};
 8201:         $cnum = $env{'course.'.$cid.'.num'};
 8202:     }
 8203: 
 8204:     my %sectioncount;
 8205:     my $now = time;
 8206: 
 8207:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 8208: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8209: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8210: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8211:         my $start_index = &Apache::loncoursedata::CL_START();
 8212:         my $end_index = &Apache::loncoursedata::CL_END();
 8213:         my $status;
 8214: 	while (my ($student,$data) = each(%$classlist)) {
 8215: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8216: 				                     $data->[$status_index],
 8217:                                                      $data->[$start_index],
 8218:                                                      $data->[$end_index]);
 8219:             if ($stu_status eq 'Active') {
 8220:                 $status = 'active';
 8221:             } elsif ($end < $now) {
 8222:                 $status = 'previous';
 8223:             } elsif ($start > $now) {
 8224:                 $status = 'future';
 8225:             } 
 8226: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8227:                 if ((!defined($possible_status)) || (($status ne '') && 
 8228:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8229: 		    $sectioncount{$section}++;
 8230:                 }
 8231: 	    }
 8232: 	}
 8233:     }
 8234:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8235:     foreach my $user (sort(keys(%courseroles))) {
 8236: 	if ($user !~ /^(\w{2})/) { next; }
 8237: 	my ($role) = ($user =~ /^(\w{2})/);
 8238: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8239: 	my ($section,$status);
 8240: 	if ($role eq 'cr' &&
 8241: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8242: 	    $section=$1;
 8243: 	}
 8244: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8245: 	if (!defined($section) || $section eq '-1') { next; }
 8246:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8247:         if ($end == -1 && $start == -1) {
 8248:             next; #deleted role
 8249:         }
 8250:         if (!defined($possible_status)) { 
 8251:             $sectioncount{$section}++;
 8252:         } else {
 8253:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8254:                 $status = 'active';
 8255:             } elsif ($end < $now) {
 8256:                 $status = 'future';
 8257:             } elsif ($start > $now) {
 8258:                 $status = 'previous';
 8259:             }
 8260:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8261:                 $sectioncount{$section}++;
 8262:             }
 8263:         }
 8264:     }
 8265:     return %sectioncount;
 8266: }
 8267: 
 8268: ###############################################
 8269: 
 8270: =pod
 8271: 
 8272: =item * &get_course_users()
 8273: 
 8274: Retrieves usernames:domains for users in the specified course
 8275: with specific role(s), and access status. 
 8276: 
 8277: Incoming parameters:
 8278: 1. course domain
 8279: 2. course number
 8280: 3. access status: users must have - either active, 
 8281: previous, future, or all.
 8282: 4. reference to array of permissible roles
 8283: 5. reference to array of section restrictions (optional)
 8284: 6. reference to results object (hash of hashes).
 8285: 7. reference to optional userdata hash
 8286: 8. reference to optional statushash
 8287: 9. flag if privileged users (except those set to unhide in
 8288:    course settings) should be excluded    
 8289: Keys of top level results hash are roles.
 8290: Keys of inner hashes are username:domain, with 
 8291: values set to access type.
 8292: Optional userdata hash returns an array with arguments in the 
 8293: same order as loncoursedata::get_classlist() for student data.
 8294: 
 8295: Optional statushash returns
 8296: 
 8297: Entries for end, start, section and status are blank because
 8298: of the possibility of multiple values for non-student roles.
 8299: 
 8300: =cut
 8301: 
 8302: ###############################################
 8303: 
 8304: sub get_course_users {
 8305:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8306:     my %idx = ();
 8307:     my %seclists;
 8308: 
 8309:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8310:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8311:     $idx{end} = &Apache::loncoursedata::CL_END();
 8312:     $idx{start} = &Apache::loncoursedata::CL_START();
 8313:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8314:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8315:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8316:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8317: 
 8318:     if (grep(/^st$/,@{$roles})) {
 8319:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8320:         my $now = time;
 8321:         foreach my $student (keys(%{$classlist})) {
 8322:             my $match = 0;
 8323:             my $secmatch = 0;
 8324:             my $section = $$classlist{$student}[$idx{section}];
 8325:             my $status = $$classlist{$student}[$idx{status}];
 8326:             if ($section eq '') {
 8327:                 $section = 'none';
 8328:             }
 8329:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8330:                 if (grep(/^all$/,@{$sections})) {
 8331:                     $secmatch = 1;
 8332:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8333:                     if (grep(/^none$/,@{$sections})) {
 8334:                         $secmatch = 1;
 8335:                     }
 8336:                 } else {  
 8337: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8338: 		        $secmatch = 1;
 8339:                     }
 8340: 		}
 8341:                 if (!$secmatch) {
 8342:                     next;
 8343:                 }
 8344:             }
 8345:             if (defined($$types{'active'})) {
 8346:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8347:                     push(@{$$users{st}{$student}},'active');
 8348:                     $match = 1;
 8349:                 }
 8350:             }
 8351:             if (defined($$types{'previous'})) {
 8352:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8353:                     push(@{$$users{st}{$student}},'previous');
 8354:                     $match = 1;
 8355:                 }
 8356:             }
 8357:             if (defined($$types{'future'})) {
 8358:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8359:                     push(@{$$users{st}{$student}},'future');
 8360:                     $match = 1;
 8361:                 }
 8362:             }
 8363:             if ($match) {
 8364:                 push(@{$seclists{$student}},$section);
 8365:                 if (ref($userdata) eq 'HASH') {
 8366:                     $$userdata{$student} = $$classlist{$student};
 8367:                 }
 8368:                 if (ref($statushash) eq 'HASH') {
 8369:                     $statushash->{$student}{'st'}{$section} = $status;
 8370:                 }
 8371:             }
 8372:         }
 8373:     }
 8374:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8375:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8376:         my $now = time;
 8377:         my %displaystatus = ( previous => 'Expired',
 8378:                               active   => 'Active',
 8379:                               future   => 'Future',
 8380:                             );
 8381:         my %nothide;
 8382:         if ($hidepriv) {
 8383:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8384:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8385:                 if ($user !~ /:/) {
 8386:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8387:                 } else {
 8388:                     $nothide{$user} = 1;
 8389:                 }
 8390:             }
 8391:         }
 8392:         foreach my $person (sort(keys(%coursepersonnel))) {
 8393:             my $match = 0;
 8394:             my $secmatch = 0;
 8395:             my $status;
 8396:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8397:             $user =~ s/:$//;
 8398:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8399:             if ($end == -1 || $start == -1) {
 8400:                 next;
 8401:             }
 8402:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8403:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8404:                 my ($uname,$udom) = split(/:/,$user);
 8405:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8406:                     if (grep(/^all$/,@{$sections})) {
 8407:                         $secmatch = 1;
 8408:                     } elsif ($usec eq '') {
 8409:                         if (grep(/^none$/,@{$sections})) {
 8410:                             $secmatch = 1;
 8411:                         }
 8412:                     } else {
 8413:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8414:                             $secmatch = 1;
 8415:                         }
 8416:                     }
 8417:                     if (!$secmatch) {
 8418:                         next;
 8419:                     }
 8420:                 }
 8421:                 if ($usec eq '') {
 8422:                     $usec = 'none';
 8423:                 }
 8424:                 if ($uname ne '' && $udom ne '') {
 8425:                     if ($hidepriv) {
 8426:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 8427:                             (!$nothide{$uname.':'.$udom})) {
 8428:                             next;
 8429:                         }
 8430:                     }
 8431:                     if ($end > 0 && $end < $now) {
 8432:                         $status = 'previous';
 8433:                     } elsif ($start > $now) {
 8434:                         $status = 'future';
 8435:                     } else {
 8436:                         $status = 'active';
 8437:                     }
 8438:                     foreach my $type (keys(%{$types})) { 
 8439:                         if ($status eq $type) {
 8440:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8441:                                 push(@{$$users{$role}{$user}},$type);
 8442:                             }
 8443:                             $match = 1;
 8444:                         }
 8445:                     }
 8446:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8447:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8448: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8449:                         }
 8450:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8451:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8452:                         }
 8453:                         if (ref($statushash) eq 'HASH') {
 8454:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8455:                         }
 8456:                     }
 8457:                 }
 8458:             }
 8459:         }
 8460:         if (grep(/^ow$/,@{$roles})) {
 8461:             if ((defined($cdom)) && (defined($cnum))) {
 8462:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8463:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8464:                     my $owner = $csettings{'internal.courseowner'};
 8465:                     next if ($owner eq '');
 8466:                     my ($ownername,$ownerdom);
 8467:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8468:                         $ownername = $1;
 8469:                         $ownerdom = $2;
 8470:                     } else {
 8471:                         $ownername = $owner;
 8472:                         $ownerdom = $cdom;
 8473:                         $owner = $ownername.':'.$ownerdom;
 8474:                     }
 8475:                     @{$$users{'ow'}{$owner}} = 'any';
 8476:                     if (defined($userdata) && 
 8477: 			!exists($$userdata{$owner})) {
 8478: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8479:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8480:                             push(@{$seclists{$owner}},'none');
 8481:                         }
 8482:                         if (ref($statushash) eq 'HASH') {
 8483:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8484:                         }
 8485: 		    }
 8486:                 }
 8487:             }
 8488:         }
 8489:         foreach my $user (keys(%seclists)) {
 8490:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8491:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8492:         }
 8493:     }
 8494:     return;
 8495: }
 8496: 
 8497: sub get_user_info {
 8498:     my ($udom,$uname,$idx,$userdata) = @_;
 8499:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8500: 	&plainname($uname,$udom,'lastname');
 8501:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8502:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8503:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8504:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8505:     return;
 8506: }
 8507: 
 8508: ###############################################
 8509: 
 8510: =pod
 8511: 
 8512: =item * &get_user_quota()
 8513: 
 8514: Retrieves quota assigned for storage of portfolio files for a user  
 8515: 
 8516: Incoming parameters:
 8517: 1. user's username
 8518: 2. user's domain
 8519: 
 8520: Returns:
 8521: 1. Disk quota (in Mb) assigned to student.
 8522: 2. (Optional) Type of setting: custom or default
 8523:    (individually assigned or default for user's 
 8524:    institutional status).
 8525: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8526:    or student - types as defined in localenroll::inst_usertypes 
 8527:    for user's domain, which determines default quota for user.
 8528: 4. (Optional) - Default quota which would apply to the user.
 8529: 
 8530: If a value has been stored in the user's environment, 
 8531: it will return that, otherwise it returns the maximal default
 8532: defined for the user's instituional status(es) in the domain.
 8533: 
 8534: =cut
 8535: 
 8536: ###############################################
 8537: 
 8538: 
 8539: sub get_user_quota {
 8540:     my ($uname,$udom) = @_;
 8541:     my ($quota,$quotatype,$settingstatus,$defquota);
 8542:     if (!defined($udom)) {
 8543:         $udom = $env{'user.domain'};
 8544:     }
 8545:     if (!defined($uname)) {
 8546:         $uname = $env{'user.name'};
 8547:     }
 8548:     if (($udom eq '' || $uname eq '') ||
 8549:         ($udom eq 'public') && ($uname eq 'public')) {
 8550:         $quota = 0;
 8551:         $quotatype = 'default';
 8552:         $defquota = 0; 
 8553:     } else {
 8554:         my $inststatus;
 8555:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8556:             $quota = $env{'environment.portfolioquota'};
 8557:             $inststatus = $env{'environment.inststatus'};
 8558:         } else {
 8559:             my %userenv = 
 8560:                 &Apache::lonnet::get('environment',['portfolioquota',
 8561:                                      'inststatus'],$udom,$uname);
 8562:             my ($tmp) = keys(%userenv);
 8563:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8564:                 $quota = $userenv{'portfolioquota'};
 8565:                 $inststatus = $userenv{'inststatus'};
 8566:             } else {
 8567:                 undef(%userenv);
 8568:             }
 8569:         }
 8570:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 8571:         if ($quota eq '') {
 8572:             $quota = $defquota;
 8573:             $quotatype = 'default';
 8574:         } else {
 8575:             $quotatype = 'custom';
 8576:         }
 8577:     }
 8578:     if (wantarray) {
 8579:         return ($quota,$quotatype,$settingstatus,$defquota);
 8580:     } else {
 8581:         return $quota;
 8582:     }
 8583: }
 8584: 
 8585: ###############################################
 8586: 
 8587: =pod
 8588: 
 8589: =item * &default_quota()
 8590: 
 8591: Retrieves default quota assigned for storage of user portfolio files,
 8592: given an (optional) user's institutional status.
 8593: 
 8594: Incoming parameters:
 8595: 1. domain
 8596: 2. (Optional) institutional status(es).  This is a : separated list of 
 8597:    status types (e.g., faculty, staff, student etc.)
 8598:    which apply to the user for whom the default is being retrieved.
 8599:    If the institutional status string in undefined, the domain
 8600:    default quota will be returned. 
 8601: 
 8602: Returns:
 8603: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8604: 2. (Optional) institutional type which determined the value of the
 8605:    default quota.
 8606: 
 8607: If a value has been stored in the domain's configuration db,
 8608: it will return that, otherwise it returns 20 (for backwards 
 8609: compatibility with domains which have not set up a configuration
 8610: db file; the original statically defined portfolio quota was 20 Mb). 
 8611: 
 8612: If the user's status includes multiple types (e.g., staff and student),
 8613: the largest default quota which applies to the user determines the
 8614: default quota returned.
 8615: 
 8616: =back
 8617: 
 8618: =cut
 8619: 
 8620: ###############################################
 8621: 
 8622: 
 8623: sub default_quota {
 8624:     my ($udom,$inststatus) = @_;
 8625:     my ($defquota,$settingstatus);
 8626:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8627:                                             ['quotas'],$udom);
 8628:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8629:         if ($inststatus ne '') {
 8630:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8631:             foreach my $item (@statuses) {
 8632:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8633:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 8634:                         if ($defquota eq '') {
 8635:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8636:                             $settingstatus = $item;
 8637:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 8638:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8639:                             $settingstatus = $item;
 8640:                         }
 8641:                     }
 8642:                 } else {
 8643:                     if ($quotahash{'quotas'}{$item} ne '') {
 8644:                         if ($defquota eq '') {
 8645:                             $defquota = $quotahash{'quotas'}{$item};
 8646:                             $settingstatus = $item;
 8647:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8648:                             $defquota = $quotahash{'quotas'}{$item};
 8649:                             $settingstatus = $item;
 8650:                         }
 8651:                     }
 8652:                 }
 8653:             }
 8654:         }
 8655:         if ($defquota eq '') {
 8656:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8657:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 8658:             } else {
 8659:                 $defquota = $quotahash{'quotas'}{'default'};
 8660:             }
 8661:             $settingstatus = 'default';
 8662:         }
 8663:     } else {
 8664:         $settingstatus = 'default';
 8665:         $defquota = 20;
 8666:     }
 8667:     if (wantarray) {
 8668:         return ($defquota,$settingstatus);
 8669:     } else {
 8670:         return $defquota;
 8671:     }
 8672: }
 8673: 
 8674: sub get_secgrprole_info {
 8675:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8676:     my %sections_count = &get_sections($cdom,$cnum);
 8677:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8678:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8679:     my @groups = sort(keys(%curr_groups));
 8680:     my $allroles = [];
 8681:     my $rolehash;
 8682:     my $accesshash = {
 8683:                      active => 'Currently has access',
 8684:                      future => 'Will have future access',
 8685:                      previous => 'Previously had access',
 8686:                   };
 8687:     if ($needroles) {
 8688:         $rolehash = {'all' => 'all'};
 8689:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8690: 	if (&Apache::lonnet::error(%user_roles)) {
 8691: 	    undef(%user_roles);
 8692: 	}
 8693:         foreach my $item (keys(%user_roles)) {
 8694:             my ($role)=split(/\:/,$item,2);
 8695:             if ($role eq 'cr') { next; }
 8696:             if ($role =~ /^cr/) {
 8697:                 $$rolehash{$role} = (split('/',$role))[3];
 8698:             } else {
 8699:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8700:             }
 8701:         }
 8702:         foreach my $key (sort(keys(%{$rolehash}))) {
 8703:             push(@{$allroles},$key);
 8704:         }
 8705:         push (@{$allroles},'st');
 8706:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8707:     }
 8708:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8709: }
 8710: 
 8711: sub user_picker {
 8712:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8713:     my $currdom = $dom;
 8714:     my %curr_selected = (
 8715:                         srchin => 'dom',
 8716:                         srchby => 'lastname',
 8717:                       );
 8718:     my $srchterm;
 8719:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8720:         if ($srch->{'srchby'} ne '') {
 8721:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8722:         }
 8723:         if ($srch->{'srchin'} ne '') {
 8724:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8725:         }
 8726:         if ($srch->{'srchtype'} ne '') {
 8727:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8728:         }
 8729:         if ($srch->{'srchdomain'} ne '') {
 8730:             $currdom = $srch->{'srchdomain'};
 8731:         }
 8732:         $srchterm = $srch->{'srchterm'};
 8733:     }
 8734:     my %lt=&Apache::lonlocal::texthash(
 8735:                     'usr'       => 'Search criteria',
 8736:                     'doma'      => 'Domain/institution to search',
 8737:                     'uname'     => 'username',
 8738:                     'lastname'  => 'last name',
 8739:                     'lastfirst' => 'last name, first name',
 8740:                     'crs'       => 'in this course',
 8741:                     'dom'       => 'in selected LON-CAPA domain', 
 8742:                     'alc'       => 'all LON-CAPA',
 8743:                     'instd'     => 'in institutional directory for selected domain',
 8744:                     'exact'     => 'is',
 8745:                     'contains'  => 'contains',
 8746:                     'begins'    => 'begins with',
 8747:                     'youm'      => "You must include some text to search for.",
 8748:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 8749:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 8750:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 8751:                     'ymcd'      => "You must choose a domain when using a domain search.",
 8752:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 8753:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 8754:                      'thfo'     => "The following need to be corrected before the search can be run:",
 8755:                                        );
 8756:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 8757:     my $srchinsel = ' <select name="srchin">';
 8758: 
 8759:     my @srchins = ('crs','dom','alc','instd');
 8760: 
 8761:     foreach my $option (@srchins) {
 8762:         # FIXME 'alc' option unavailable until 
 8763:         #       loncreateuser::print_user_query_page()
 8764:         #       has been completed.
 8765:         next if ($option eq 'alc');
 8766:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 8767:         next if ($option eq 'crs' && !$env{'request.course.id'});
 8768:         if ($curr_selected{'srchin'} eq $option) {
 8769:             $srchinsel .= ' 
 8770:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8771:         } else {
 8772:             $srchinsel .= '
 8773:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8774:         }
 8775:     }
 8776:     $srchinsel .= "\n  </select>\n";
 8777: 
 8778:     my $srchbysel =  ' <select name="srchby">';
 8779:     foreach my $option ('lastname','lastfirst','uname') {
 8780:         if ($curr_selected{'srchby'} eq $option) {
 8781:             $srchbysel .= '
 8782:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8783:         } else {
 8784:             $srchbysel .= '
 8785:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8786:          }
 8787:     }
 8788:     $srchbysel .= "\n  </select>\n";
 8789: 
 8790:     my $srchtypesel = ' <select name="srchtype">';
 8791:     foreach my $option ('begins','contains','exact') {
 8792:         if ($curr_selected{'srchtype'} eq $option) {
 8793:             $srchtypesel .= '
 8794:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8795:         } else {
 8796:             $srchtypesel .= '
 8797:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8798:         }
 8799:     }
 8800:     $srchtypesel .= "\n  </select>\n";
 8801: 
 8802:     my ($newuserscript,$new_user_create);
 8803:     my $context_dom = $env{'request.role.domain'};
 8804:     if ($context eq 'requestcrs') {
 8805:         if ($env{'form.coursedom'} ne '') { 
 8806:             $context_dom = $env{'form.coursedom'};
 8807:         }
 8808:     }
 8809:     if ($forcenewuser) {
 8810:         if (ref($srch) eq 'HASH') {
 8811:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 8812:                 if ($cancreate) {
 8813:                     $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>';
 8814:                 } else {
 8815:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 8816:                     my %usertypetext = (
 8817:                         official   => 'institutional',
 8818:                         unofficial => 'non-institutional',
 8819:                     );
 8820:                     $new_user_create = '<p class="LC_warning">'
 8821:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8822:                                       .' '
 8823:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8824:                                           ,'<a href="'.$helplink.'">','</a>')
 8825:                                       .'</p><br />';
 8826:                 }
 8827:             }
 8828:         }
 8829: 
 8830:         $newuserscript = <<"ENDSCRIPT";
 8831: 
 8832: function setSearch(createnew,callingForm) {
 8833:     if (createnew == 1) {
 8834:         for (var i=0; i<callingForm.srchby.length; i++) {
 8835:             if (callingForm.srchby.options[i].value == 'uname') {
 8836:                 callingForm.srchby.selectedIndex = i;
 8837:             }
 8838:         }
 8839:         for (var i=0; i<callingForm.srchin.length; i++) {
 8840:             if ( callingForm.srchin.options[i].value == 'dom') {
 8841: 		callingForm.srchin.selectedIndex = i;
 8842:             }
 8843:         }
 8844:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8845:             if (callingForm.srchtype.options[i].value == 'exact') {
 8846:                 callingForm.srchtype.selectedIndex = i;
 8847:             }
 8848:         }
 8849:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8850:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8851:                 callingForm.srchdomain.selectedIndex = i;
 8852:             }
 8853:         }
 8854:     }
 8855: }
 8856: ENDSCRIPT
 8857: 
 8858:     }
 8859: 
 8860:     my $output = <<"END_BLOCK";
 8861: <script type="text/javascript">
 8862: // <![CDATA[
 8863: function validateEntry(callingForm) {
 8864: 
 8865:     var checkok = 1;
 8866:     var srchin;
 8867:     for (var i=0; i<callingForm.srchin.length; i++) {
 8868: 	if ( callingForm.srchin[i].checked ) {
 8869: 	    srchin = callingForm.srchin[i].value;
 8870: 	}
 8871:     }
 8872: 
 8873:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8874:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8875:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8876:     var srchterm =  callingForm.srchterm.value;
 8877:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8878:     var msg = "";
 8879: 
 8880:     if (srchterm == "") {
 8881:         checkok = 0;
 8882:         msg += "$lt{'youm'}\\n";
 8883:     }
 8884: 
 8885:     if (srchtype== 'begins') {
 8886:         if (srchterm.length < 2) {
 8887:             checkok = 0;
 8888:             msg += "$lt{'thte'}\\n";
 8889:         }
 8890:     }
 8891: 
 8892:     if (srchtype== 'contains') {
 8893:         if (srchterm.length < 3) {
 8894:             checkok = 0;
 8895:             msg += "$lt{'thet'}\\n";
 8896:         }
 8897:     }
 8898:     if (srchin == 'instd') {
 8899:         if (srchdomain == '') {
 8900:             checkok = 0;
 8901:             msg += "$lt{'yomc'}\\n";
 8902:         }
 8903:     }
 8904:     if (srchin == 'dom') {
 8905:         if (srchdomain == '') {
 8906:             checkok = 0;
 8907:             msg += "$lt{'ymcd'}\\n";
 8908:         }
 8909:     }
 8910:     if (srchby == 'lastfirst') {
 8911:         if (srchterm.indexOf(",") == -1) {
 8912:             checkok = 0;
 8913:             msg += "$lt{'whus'}\\n";
 8914:         }
 8915:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8916:             checkok = 0;
 8917:             msg += "$lt{'whse'}\\n";
 8918:         }
 8919:     }
 8920:     if (checkok == 0) {
 8921:         alert("$lt{'thfo'}\\n"+msg);
 8922:         return;
 8923:     }
 8924:     if (checkok == 1) {
 8925:         callingForm.submit();
 8926:     }
 8927: }
 8928: 
 8929: $newuserscript
 8930: 
 8931: // ]]>
 8932: </script>
 8933: 
 8934: $new_user_create
 8935: 
 8936: END_BLOCK
 8937: 
 8938:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8939:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8940:                $domform.
 8941:                &Apache::lonhtmlcommon::row_closure().
 8942:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8943:                $srchbysel.
 8944:                $srchtypesel. 
 8945:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8946:                $srchinsel.
 8947:                &Apache::lonhtmlcommon::row_closure(1). 
 8948:                &Apache::lonhtmlcommon::end_pick_box().
 8949:                '<br />';
 8950:     return $output;
 8951: }
 8952: 
 8953: sub user_rule_check {
 8954:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8955:     my $response;
 8956:     if (ref($usershash) eq 'HASH') {
 8957:         foreach my $user (keys(%{$usershash})) {
 8958:             my ($uname,$udom) = split(/:/,$user);
 8959:             next if ($udom eq '' || $uname eq '');
 8960:             my ($id,$newuser);
 8961:             if (ref($usershash->{$user}) eq 'HASH') {
 8962:                 $newuser = $usershash->{$user}->{'newuser'};
 8963:                 $id = $usershash->{$user}->{'id'};
 8964:             }
 8965:             my $inst_response;
 8966:             if (ref($checks) eq 'HASH') {
 8967:                 if (defined($checks->{'username'})) {
 8968:                     ($inst_response,%{$inst_results->{$user}}) = 
 8969:                         &Apache::lonnet::get_instuser($udom,$uname);
 8970:                 } elsif (defined($checks->{'id'})) {
 8971:                     ($inst_response,%{$inst_results->{$user}}) =
 8972:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8973:                 }
 8974:             } else {
 8975:                 ($inst_response,%{$inst_results->{$user}}) =
 8976:                     &Apache::lonnet::get_instuser($udom,$uname);
 8977:                 return;
 8978:             }
 8979:             if (!$got_rules->{$udom}) {
 8980:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8981:                                                   ['usercreation'],$udom);
 8982:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8983:                     foreach my $item ('username','id') {
 8984:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8985:                             $$curr_rules{$udom}{$item} = 
 8986:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8987:                         }
 8988:                     }
 8989:                 }
 8990:                 $got_rules->{$udom} = 1;  
 8991:             }
 8992:             foreach my $item (keys(%{$checks})) {
 8993:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8994:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8995:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8996:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8997:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8998:                                 if ($rule_check{$rule}) {
 8999:                                     $$rulematch{$user}{$item} = $rule;
 9000:                                     if ($inst_response eq 'ok') {
 9001:                                         if (ref($inst_results) eq 'HASH') {
 9002:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9003:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9004:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9005:                                                 }
 9006:                                             }
 9007:                                         }
 9008:                                     }
 9009:                                     last;
 9010:                                 }
 9011:                             }
 9012:                         }
 9013:                     }
 9014:                 }
 9015:             }
 9016:         }
 9017:     }
 9018:     return;
 9019: }
 9020: 
 9021: sub user_rule_formats {
 9022:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9023:     my %text = ( 
 9024:                  'username' => 'Usernames',
 9025:                  'id'       => 'IDs',
 9026:                );
 9027:     my $output;
 9028:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9029:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9030:         if (@{$ruleorder} > 0) {
 9031:             $output = '<br />'.
 9032:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9033:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9034:                       ' <ul>';
 9035:             foreach my $rule (@{$ruleorder}) {
 9036:                 if (ref($curr_rules) eq 'ARRAY') {
 9037:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9038:                         if (ref($rules->{$rule}) eq 'HASH') {
 9039:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9040:                                         $rules->{$rule}{'desc'}.'</li>';
 9041:                         }
 9042:                     }
 9043:                 }
 9044:             }
 9045:             $output .= '</ul>';
 9046:         }
 9047:     }
 9048:     return $output;
 9049: }
 9050: 
 9051: sub instrule_disallow_msg {
 9052:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9053:     my $response;
 9054:     my %text = (
 9055:                   item   => 'username',
 9056:                   items  => 'usernames',
 9057:                   match  => 'matches',
 9058:                   do     => 'does',
 9059:                   action => 'a username',
 9060:                   one    => 'one',
 9061:                );
 9062:     if ($count > 1) {
 9063:         $text{'item'} = 'usernames';
 9064:         $text{'match'} ='match';
 9065:         $text{'do'} = 'do';
 9066:         $text{'action'} = 'usernames',
 9067:         $text{'one'} = 'ones';
 9068:     }
 9069:     if ($checkitem eq 'id') {
 9070:         $text{'items'} = 'IDs';
 9071:         $text{'item'} = 'ID';
 9072:         $text{'action'} = 'an ID';
 9073:         if ($count > 1) {
 9074:             $text{'item'} = 'IDs';
 9075:             $text{'action'} = 'IDs';
 9076:         }
 9077:     }
 9078:     $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 />';
 9079:     if ($mode eq 'upload') {
 9080:         if ($checkitem eq 'username') {
 9081:             $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'}.");
 9082:         } elsif ($checkitem eq 'id') {
 9083:             $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.");
 9084:         }
 9085:     } elsif ($mode eq 'selfcreate') {
 9086:         if ($checkitem eq 'id') {
 9087:             $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.");
 9088:         }
 9089:     } else {
 9090:         if ($checkitem eq 'username') {
 9091:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9092:         } elsif ($checkitem eq 'id') {
 9093:             $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.");
 9094:         }
 9095:     }
 9096:     return $response;
 9097: }
 9098: 
 9099: sub personal_data_fieldtitles {
 9100:     my %fieldtitles = &Apache::lonlocal::texthash (
 9101:                         id => 'Student/Employee ID',
 9102:                         permanentemail => 'E-mail address',
 9103:                         lastname => 'Last Name',
 9104:                         firstname => 'First Name',
 9105:                         middlename => 'Middle Name',
 9106:                         generation => 'Generation',
 9107:                         gen => 'Generation',
 9108:                         inststatus => 'Affiliation',
 9109:                    );
 9110:     return %fieldtitles;
 9111: }
 9112: 
 9113: sub sorted_inst_types {
 9114:     my ($dom) = @_;
 9115:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9116:     my $othertitle = &mt('All users');
 9117:     if ($env{'request.course.id'}) {
 9118:         $othertitle  = &mt('Any users');
 9119:     }
 9120:     my @types;
 9121:     if (ref($order) eq 'ARRAY') {
 9122:         @types = @{$order};
 9123:     }
 9124:     if (@types == 0) {
 9125:         if (ref($usertypes) eq 'HASH') {
 9126:             @types = sort(keys(%{$usertypes}));
 9127:         }
 9128:     }
 9129:     if (keys(%{$usertypes}) > 0) {
 9130:         $othertitle = &mt('Other users');
 9131:     }
 9132:     return ($othertitle,$usertypes,\@types);
 9133: }
 9134: 
 9135: sub get_institutional_codes {
 9136:     my ($settings,$allcourses,$LC_code) = @_;
 9137: # Get complete list of course sections to update
 9138:     my @currsections = ();
 9139:     my @currxlists = ();
 9140:     my $coursecode = $$settings{'internal.coursecode'};
 9141: 
 9142:     if ($$settings{'internal.sectionnums'} ne '') {
 9143:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9144:     }
 9145: 
 9146:     if ($$settings{'internal.crosslistings'} ne '') {
 9147:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9148:     }
 9149: 
 9150:     if (@currxlists > 0) {
 9151:         foreach (@currxlists) {
 9152:             if (m/^([^:]+):(\w*)$/) {
 9153:                 unless (grep/^$1$/,@{$allcourses}) {
 9154:                     push @{$allcourses},$1;
 9155:                     $$LC_code{$1} = $2;
 9156:                 }
 9157:             }
 9158:         }
 9159:     }
 9160:  
 9161:     if (@currsections > 0) {
 9162:         foreach (@currsections) {
 9163:             if (m/^(\w+):(\w*)$/) {
 9164:                 my $sec = $coursecode.$1;
 9165:                 my $lc_sec = $2;
 9166:                 unless (grep/^$sec$/,@{$allcourses}) {
 9167:                     push @{$allcourses},$sec;
 9168:                     $$LC_code{$sec} = $lc_sec;
 9169:                 }
 9170:             }
 9171:         }
 9172:     }
 9173:     return;
 9174: }
 9175: 
 9176: sub get_standard_codeitems {
 9177:     return ('Year','Semester','Department','Number','Section');
 9178: }
 9179: 
 9180: =pod
 9181: 
 9182: =head1 Slot Helpers
 9183: 
 9184: =over 4
 9185: 
 9186: =item * sorted_slots()
 9187: 
 9188: Sorts an array of slot names in order of an optional sort key,
 9189: default sort is by slot start time (earliest first). 
 9190: 
 9191: Inputs:
 9192: 
 9193: =over 4
 9194: 
 9195: slotsarr  - Reference to array of unsorted slot names.
 9196: 
 9197: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9198: 
 9199: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9200: 
 9201: =back
 9202: 
 9203: Returns:
 9204: 
 9205: =over 4
 9206: 
 9207: sorted   - An array of slot names sorted by a specified sort key 
 9208:            (default sort key is start time of the slot).
 9209: 
 9210: =back
 9211: 
 9212: =cut
 9213: 
 9214: 
 9215: sub sorted_slots {
 9216:     my ($slotsarr,$slots,$sortkey) = @_;
 9217:     if ($sortkey eq '') {
 9218:         $sortkey = 'starttime';
 9219:     }
 9220:     my @sorted;
 9221:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9222:         @sorted =
 9223:             sort {
 9224:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9225:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9226:                      }
 9227:                      if (ref($slots->{$a})) { return -1;}
 9228:                      if (ref($slots->{$b})) { return 1;}
 9229:                      return 0;
 9230:                  } @{$slotsarr};
 9231:     }
 9232:     return @sorted;
 9233: }
 9234: 
 9235: =pod
 9236: 
 9237: =item * get_future_slots()
 9238: 
 9239: Inputs:
 9240: 
 9241: =over 4
 9242: 
 9243: cnum - course number
 9244: 
 9245: cdom - course domain
 9246: 
 9247: now - current UNIX time
 9248: 
 9249: symb - optional symb
 9250: 
 9251: =back
 9252: 
 9253: Returns:
 9254: 
 9255: =over 4
 9256: 
 9257: sorted_reservable - ref to array of student_schedulable slots currently 
 9258:                     reservable, ordered by end date of reservation period.
 9259: 
 9260: reservable_now - ref to hash of student_schedulable slots currently
 9261:                  reservable.
 9262: 
 9263:     Keys in inner hash are:
 9264:     (a) symb: either blank or symb to which slot use is restricted.
 9265:     (b) endreserve: end date of reservation period. 
 9266: 
 9267: sorted_future - ref to array of student_schedulable slots reservable in
 9268:                 the future, ordered by start date of reservation period.
 9269: 
 9270: future_reservable - ref to hash of student_schedulable slots reservable
 9271:                     in the future.
 9272: 
 9273:     Keys in inner hash are:
 9274:     (a) symb: either blank or symb to which slot use is restricted.
 9275:     (b) startreserve:  start date of reservation period.
 9276: 
 9277: =back
 9278: 
 9279: =cut
 9280: 
 9281: sub get_future_slots {
 9282:     my ($cnum,$cdom,$now,$symb) = @_;
 9283:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9284:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9285:     foreach my $slot (keys(%slots)) {
 9286:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9287:         if ($symb) {
 9288:             next if (($slots{$slot}->{'symb'} ne '') && 
 9289:                      ($slots{$slot}->{'symb'} ne $symb));
 9290:         }
 9291:         if (($slots{$slot}->{'starttime'} > $now) &&
 9292:             ($slots{$slot}->{'endtime'} > $now)) {
 9293:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9294:                 my $userallowed = 0;
 9295:                 if ($slots{$slot}->{'allowedsections'}) {
 9296:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9297:                     if (!defined($env{'request.role.sec'})
 9298:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9299:                         $userallowed=1;
 9300:                     } else {
 9301:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9302:                             $userallowed=1;
 9303:                         }
 9304:                     }
 9305:                     unless ($userallowed) {
 9306:                         if (defined($env{'request.course.groups'})) {
 9307:                             my @groups = split(/:/,$env{'request.course.groups'});
 9308:                             foreach my $group (@groups) {
 9309:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9310:                                     $userallowed=1;
 9311:                                     last;
 9312:                                 }
 9313:                             }
 9314:                         }
 9315:                     }
 9316:                 }
 9317:                 if ($slots{$slot}->{'allowedusers'}) {
 9318:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9319:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9320:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9321:                         $userallowed = 1;
 9322:                     }
 9323:                 }
 9324:                 next unless($userallowed);
 9325:             }
 9326:             my $startreserve = $slots{$slot}->{'startreserve'};
 9327:             my $endreserve = $slots{$slot}->{'endreserve'};
 9328:             my $symb = $slots{$slot}->{'symb'};
 9329:             if (($startreserve < $now) &&
 9330:                 (!$endreserve || $endreserve > $now)) {
 9331:                 my $lastres = $endreserve;
 9332:                 if (!$lastres) {
 9333:                     $lastres = $slots{$slot}->{'starttime'};
 9334:                 }
 9335:                 $reservable_now{$slot} = {
 9336:                                            symb       => $symb,
 9337:                                            endreserve => $lastres
 9338:                                          };
 9339:             } elsif (($startreserve > $now) &&
 9340:                      (!$endreserve || $endreserve > $startreserve)) {
 9341:                 $future_reservable{$slot} = {
 9342:                                               symb         => $symb,
 9343:                                               startreserve => $startreserve
 9344:                                             };
 9345:             }
 9346:         }
 9347:     }
 9348:     my @unsorted_reservable = keys(%reservable_now);
 9349:     if (@unsorted_reservable > 0) {
 9350:         @sorted_reservable = 
 9351:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9352:     }
 9353:     my @unsorted_future = keys(%future_reservable);
 9354:     if (@unsorted_future > 0) {
 9355:         @sorted_future =
 9356:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9357:     }
 9358:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9359: }
 9360: 
 9361: =pod
 9362: 
 9363: =back
 9364: 
 9365: =head1 HTTP Helpers
 9366: 
 9367: =over 4
 9368: 
 9369: =item * &get_unprocessed_cgi($query,$possible_names)
 9370: 
 9371: Modify the %env hash to contain unprocessed CGI form parameters held in
 9372: $query.  The parameters listed in $possible_names (an array reference),
 9373: will be set in $env{'form.name'} if they do not already exist.
 9374: 
 9375: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9376: $possible_names is an ref to an array of form element names.  As an example:
 9377: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9378: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9379: 
 9380: =cut
 9381: 
 9382: sub get_unprocessed_cgi {
 9383:   my ($query,$possible_names)= @_;
 9384:   # $Apache::lonxml::debug=1;
 9385:   foreach my $pair (split(/&/,$query)) {
 9386:     my ($name, $value) = split(/=/,$pair);
 9387:     $name = &unescape($name);
 9388:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9389:       $value =~ tr/+/ /;
 9390:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9391:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9392:     }
 9393:   }
 9394: }
 9395: 
 9396: =pod
 9397: 
 9398: =item * &cacheheader() 
 9399: 
 9400: returns cache-controlling header code
 9401: 
 9402: =cut
 9403: 
 9404: sub cacheheader {
 9405:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9406:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9407:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9408:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9409:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9410:     return $output;
 9411: }
 9412: 
 9413: =pod
 9414: 
 9415: =item * &no_cache($r) 
 9416: 
 9417: specifies header code to not have cache
 9418: 
 9419: =cut
 9420: 
 9421: sub no_cache {
 9422:     my ($r) = @_;
 9423:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9424: 	$env{'request.method'} ne 'GET') { return ''; }
 9425:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9426:     $r->no_cache(1);
 9427:     $r->header_out("Expires" => $date);
 9428:     $r->header_out("Pragma" => "no-cache");
 9429: }
 9430: 
 9431: sub content_type {
 9432:     my ($r,$type,$charset) = @_;
 9433:     if ($r) {
 9434: 	#  Note that printout.pl calls this with undef for $r.
 9435: 	&no_cache($r);
 9436:     }
 9437:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9438:     unless ($charset) {
 9439: 	$charset=&Apache::lonlocal::current_encoding;
 9440:     }
 9441:     if ($charset) { $type.='; charset='.$charset; }
 9442:     if ($r) {
 9443: 	$r->content_type($type);
 9444:     } else {
 9445: 	print("Content-type: $type\n\n");
 9446:     }
 9447: }
 9448: 
 9449: =pod
 9450: 
 9451: =item * &add_to_env($name,$value) 
 9452: 
 9453: adds $name to the %env hash with value
 9454: $value, if $name already exists, the entry is converted to an array
 9455: reference and $value is added to the array.
 9456: 
 9457: =cut
 9458: 
 9459: sub add_to_env {
 9460:   my ($name,$value)=@_;
 9461:   if (defined($env{$name})) {
 9462:     if (ref($env{$name})) {
 9463:       #already have multiple values
 9464:       push(@{ $env{$name} },$value);
 9465:     } else {
 9466:       #first time seeing multiple values, convert hash entry to an arrayref
 9467:       my $first=$env{$name};
 9468:       undef($env{$name});
 9469:       push(@{ $env{$name} },$first,$value);
 9470:     }
 9471:   } else {
 9472:     $env{$name}=$value;
 9473:   }
 9474: }
 9475: 
 9476: =pod
 9477: 
 9478: =item * &get_env_multiple($name) 
 9479: 
 9480: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9481: values may be defined and end up as an array ref.
 9482: 
 9483: returns an array of values
 9484: 
 9485: =cut
 9486: 
 9487: sub get_env_multiple {
 9488:     my ($name) = @_;
 9489:     my @values;
 9490:     if (defined($env{$name})) {
 9491:         # exists is it an array
 9492:         if (ref($env{$name})) {
 9493:             @values=@{ $env{$name} };
 9494:         } else {
 9495:             $values[0]=$env{$name};
 9496:         }
 9497:     }
 9498:     return(@values);
 9499: }
 9500: 
 9501: sub ask_for_embedded_content {
 9502:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9503:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9504:         %currsubfile,%unused,$rem);
 9505:     my $counter = 0;
 9506:     my $numnew = 0;
 9507:     my $numremref = 0;
 9508:     my $numinvalid = 0;
 9509:     my $numpathchg = 0;
 9510:     my $numexisting = 0;
 9511:     my $numunused = 0;
 9512:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9513:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9514:     my $heading = &mt('Upload embedded files');
 9515:     my $buttontext = &mt('Upload');
 9516: 
 9517:     my $navmap;
 9518:     if ($env{'request.course.id'}) {
 9519:         $navmap = Apache::lonnavmaps::navmap->new();
 9520:     }
 9521:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9522:         my $current_path='/';
 9523:         if ($env{'form.currentpath'}) {
 9524:             $current_path = $env{'form.currentpath'};
 9525:         }
 9526:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9527:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9528:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 9529:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9530:         } else {
 9531:             $udom = $env{'user.domain'};
 9532:             $uname = $env{'user.name'};
 9533:             $url = '/userfiles/portfolio';
 9534:         }
 9535:         $toplevel = $url.'/';
 9536:         $url .= $current_path;
 9537:         $getpropath = 1;
 9538:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9539:              ($actionurl eq '/adm/imsimport')) { 
 9540:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9541:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9542:         $toplevel = $url;
 9543:         if ($rest ne '') {
 9544:             $url .= $rest;
 9545:         }
 9546:     } elsif ($actionurl eq '/adm/coursedocs') {
 9547:         if (ref($args) eq 'HASH') {
 9548:             $url = $args->{'docs_url'};
 9549:             $toplevel = $url;
 9550:             if ($args->{'context'} eq 'paste') {
 9551:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9552:                 ($path) =
 9553:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9554:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9555:                 $fileloc =~ s{^/}{};
 9556:             }
 9557:         }
 9558:     } elsif ($actionurl eq '/adm/dependencies') {
 9559:         if ($env{'request.course.id'} ne '') {
 9560:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9561:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
 9562:             if (ref($args) eq 'HASH') {
 9563:                 $url = $args->{'docs_url'};
 9564:                 $title = $args->{'docs_title'};
 9565:                 $toplevel = "/$url";
 9566:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9567:                 ($path) =  
 9568:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9569:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9570:                 $fileloc =~ s{^/}{};
 9571:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9572:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9573:             }
 9574:         }
 9575:     }
 9576:     my $now = time();
 9577:     foreach my $embed_file (keys(%{$allfiles})) {
 9578:         my $absolutepath;
 9579:         if ($embed_file =~ m{^\w+://}) {
 9580:             $newfiles{$embed_file} = 1;
 9581:             $mapping{$embed_file} = $embed_file;
 9582:         } else {
 9583:             if ($embed_file =~ m{^/}) {
 9584:                 $absolutepath = $embed_file;
 9585:                 $embed_file =~ s{^(/+)}{};
 9586:             }
 9587:             if ($embed_file =~ m{/}) {
 9588:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 9589:                 $path = &check_for_traversal($path,$url,$toplevel);
 9590:                 my $item = $fname;
 9591:                 if ($path ne '') {
 9592:                     $item = $path.'/'.$fname;
 9593:                     $subdependencies{$path}{$fname} = 1;
 9594:                 } else {
 9595:                     $dependencies{$item} = 1;
 9596:                 }
 9597:                 if ($absolutepath) {
 9598:                     $mapping{$item} = $absolutepath;
 9599:                 } else {
 9600:                     $mapping{$item} = $embed_file;
 9601:                 }
 9602:             } else {
 9603:                 $dependencies{$embed_file} = 1;
 9604:                 if ($absolutepath) {
 9605:                     $mapping{$embed_file} = $absolutepath;
 9606:                 } else {
 9607:                     $mapping{$embed_file} = $embed_file;
 9608:                 }
 9609:             }
 9610:         }
 9611:     }
 9612:     my $dirptr = 16384;
 9613:     foreach my $path (keys(%subdependencies)) {
 9614:         $currsubfile{$path} = {};
 9615:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9616:             my ($sublistref,$listerror) =
 9617:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9618:             if (ref($sublistref) eq 'ARRAY') {
 9619:                 foreach my $line (@{$sublistref}) {
 9620:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9621:                     $currsubfile{$path}{$file_name} = 1;
 9622:                 }
 9623:             }
 9624:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9625:             if (opendir(my $dir,$url.'/'.$path)) {
 9626:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9627:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9628:             }
 9629:         } elsif (($actionurl eq '/adm/dependencies') ||
 9630:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9631:                   ($args->{'context'} eq 'paste'))) {
 9632:             if ($env{'request.course.id'} ne '') {
 9633:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9634:                 if ($dir ne '') {
 9635:                     my ($sublistref,$listerror) =
 9636:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9637:                     if (ref($sublistref) eq 'ARRAY') {
 9638:                         foreach my $line (@{$sublistref}) {
 9639:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9640:                                 undef,$mtime)=split(/\&/,$line,12);
 9641:                             unless (($testdir&$dirptr) ||
 9642:                                     ($file_name =~ /^\.\.?$/)) {
 9643:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9644:                             }
 9645:                         }
 9646:                     }
 9647:                 }
 9648:             }
 9649:         }
 9650:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9651:             if (exists($currsubfile{$path}{$file})) {
 9652:                 my $item = $path.'/'.$file;
 9653:                 unless ($mapping{$item} eq $item) {
 9654:                     $pathchanges{$item} = 1;
 9655:                 }
 9656:                 $existing{$item} = 1;
 9657:                 $numexisting ++;
 9658:             } else {
 9659:                 $newfiles{$path.'/'.$file} = 1;
 9660:             }
 9661:         }
 9662:         if ($actionurl eq '/adm/dependencies') {
 9663:             foreach my $path (keys(%currsubfile)) {
 9664:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9665:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9666:                          unless ($subdependencies{$path}{$file}) {
 9667:                              next if (($rem ne '') &&
 9668:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9669:                                        (ref($navmap) &&
 9670:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9671:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9672:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9673:                              $unused{$path.'/'.$file} = 1; 
 9674:                          }
 9675:                     }
 9676:                 }
 9677:             }
 9678:         }
 9679:     }
 9680:     my %currfile;
 9681:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9682:         my ($dirlistref,$listerror) =
 9683:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9684:         if (ref($dirlistref) eq 'ARRAY') {
 9685:             foreach my $line (@{$dirlistref}) {
 9686:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9687:                 $currfile{$file_name} = 1;
 9688:             }
 9689:         }
 9690:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9691:         if (opendir(my $dir,$url)) {
 9692:             my @dir_list = grep(!/^\./,readdir($dir));
 9693:             map {$currfile{$_} = 1;} @dir_list;
 9694:         }
 9695:     } elsif (($actionurl eq '/adm/dependencies') ||
 9696:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9697:               ($args->{'context'} eq 'paste'))) {
 9698:         if ($env{'request.course.id'} ne '') {
 9699:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9700:             if ($dir ne '') {
 9701:                 my ($dirlistref,$listerror) =
 9702:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9703:                 if (ref($dirlistref) eq 'ARRAY') {
 9704:                     foreach my $line (@{$dirlistref}) {
 9705:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9706:                             $size,undef,$mtime)=split(/\&/,$line,12);
 9707:                         unless (($testdir&$dirptr) ||
 9708:                                 ($file_name =~ /^\.\.?$/)) {
 9709:                             $currfile{$file_name} = [$size,$mtime];
 9710:                         }
 9711:                     }
 9712:                 }
 9713:             }
 9714:         }
 9715:     }
 9716:     foreach my $file (keys(%dependencies)) {
 9717:         if (exists($currfile{$file})) {
 9718:             unless ($mapping{$file} eq $file) {
 9719:                 $pathchanges{$file} = 1;
 9720:             }
 9721:             $existing{$file} = 1;
 9722:             $numexisting ++;
 9723:         } else {
 9724:             $newfiles{$file} = 1;
 9725:         }
 9726:     }
 9727:     foreach my $file (keys(%currfile)) {
 9728:         unless (($file eq $filename) ||
 9729:                 ($file eq $filename.'.bak') ||
 9730:                 ($dependencies{$file})) {
 9731:             if ($actionurl eq '/adm/dependencies') {
 9732:                 next if (($rem ne '') &&
 9733:                          (($env{"httpref.$rem".$file} ne '') ||
 9734:                           (ref($navmap) &&
 9735:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
 9736:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9737:                             ($navmap->getResourceByUrl($rem.$1)))))));
 9738:             }
 9739:             $unused{$file} = 1;
 9740:         }
 9741:     }
 9742:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9743:         ($args->{'context'} eq 'paste')) {
 9744:         $counter = scalar(keys(%existing));
 9745:         $numpathchg = scalar(keys(%pathchanges));
 9746:         return ($output,$counter,$numpathchg,\%existing);
 9747:     }
 9748:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 9749:         if ($actionurl eq '/adm/dependencies') {
 9750:             next if ($embed_file =~ m{^\w+://});
 9751:         }
 9752:         $upload_output .= &start_data_table_row().
 9753:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
 9754:                           '<span class="LC_filename">'.$embed_file.'</span>';
 9755:         unless ($mapping{$embed_file} eq $embed_file) {
 9756:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 9757:         }
 9758:         $upload_output .= '</td><td>';
 9759:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
 9760:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 9761:             $numremref++;
 9762:         } elsif ($args->{'error_on_invalid_names'}
 9763:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 9764:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 9765:             $numinvalid++;
 9766:         } else {
 9767:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
 9768:                                                      $embed_file,\%mapping,
 9769:                                                      $allfiles,$codebase,'upload');
 9770:             $counter ++;
 9771:             $numnew ++;
 9772:         }
 9773:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 9774:     }
 9775:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 9776:         if ($actionurl eq '/adm/dependencies') {
 9777:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
 9778:             $modify_output .= &start_data_table_row().
 9779:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
 9780:                               '<img src="'.&icon($embed_file).'" border="0" />'.
 9781:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
 9782:                               '<td>'.$size.'</td>'.
 9783:                               '<td>'.$mtime.'</td>'.
 9784:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
 9785:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
 9786:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
 9787:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
 9788:                               &embedded_file_element('upload_embedded',$counter,
 9789:                                                      $embed_file,\%mapping,
 9790:                                                      $allfiles,$codebase,'modify').
 9791:                               '</div></td>'.
 9792:                               &end_data_table_row()."\n";
 9793:             $counter ++;
 9794:         } else {
 9795:             $upload_output .= &start_data_table_row().
 9796:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
 9797:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 9798:                               &Apache::loncommon::end_data_table_row()."\n";
 9799:         }
 9800:     }
 9801:     my $delidx = $counter;
 9802:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
 9803:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
 9804:         $delete_output .= &start_data_table_row().
 9805:                           '<td><img src="'.&icon($oldfile).'" />'.
 9806:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
 9807:                           '<td>'.$size.'</td>'.
 9808:                           '<td>'.$mtime.'</td>'.
 9809:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
 9810:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
 9811:                           &embedded_file_element('upload_embedded',$delidx,
 9812:                                                  $oldfile,\%mapping,$allfiles,
 9813:                                                  $codebase,'delete').'</td>'.
 9814:                           &end_data_table_row()."\n"; 
 9815:         $numunused ++;
 9816:         $delidx ++;
 9817:     }
 9818:     if ($upload_output) {
 9819:         $upload_output = &start_data_table().
 9820:                          $upload_output.
 9821:                          &end_data_table()."\n";
 9822:     }
 9823:     if ($modify_output) {
 9824:         $modify_output = &start_data_table().
 9825:                          &start_data_table_header_row().
 9826:                          '<th>'.&mt('File').'</th>'.
 9827:                          '<th>'.&mt('Size (KB)').'</th>'.
 9828:                          '<th>'.&mt('Modified').'</th>'.
 9829:                          '<th>'.&mt('Upload replacement?').'</th>'.
 9830:                          &end_data_table_header_row().
 9831:                          $modify_output.
 9832:                          &end_data_table()."\n";
 9833:     }
 9834:     if ($delete_output) {
 9835:         $delete_output = &start_data_table().
 9836:                          &start_data_table_header_row().
 9837:                          '<th>'.&mt('File').'</th>'.
 9838:                          '<th>'.&mt('Size (KB)').'</th>'.
 9839:                          '<th>'.&mt('Modified').'</th>'.
 9840:                          '<th>'.&mt('Delete?').'</th>'.
 9841:                          &end_data_table_header_row().
 9842:                          $delete_output.
 9843:                          &end_data_table()."\n";
 9844:     }
 9845:     my $applies = 0;
 9846:     if ($numremref) {
 9847:         $applies ++;
 9848:     }
 9849:     if ($numinvalid) {
 9850:         $applies ++;
 9851:     }
 9852:     if ($numexisting) {
 9853:         $applies ++;
 9854:     }
 9855:     if ($counter || $numunused) {
 9856:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 9857:                   ' method="post" enctype="multipart/form-data">'."\n".
 9858:                   $state.'<h3>'.$heading.'</h3>'; 
 9859:         if ($actionurl eq '/adm/dependencies') {
 9860:             if ($numnew) {
 9861:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
 9862:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
 9863:                            $upload_output.'<br />'."\n";
 9864:             }
 9865:             if ($numexisting) {
 9866:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
 9867:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
 9868:                            $modify_output.'<br />'."\n";
 9869:                            $buttontext = &mt('Save changes');
 9870:             }
 9871:             if ($numunused) {
 9872:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
 9873:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
 9874:                            $delete_output.'<br />'."\n";
 9875:                            $buttontext = &mt('Save changes');
 9876:             }
 9877:         } else {
 9878:             $output .= $upload_output.'<br />'."\n";
 9879:         }
 9880:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
 9881:                    $counter.'" />'."\n";
 9882:         if ($actionurl eq '/adm/dependencies') { 
 9883:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
 9884:                        $numnew.'" />'."\n";
 9885:         } elsif ($actionurl eq '') {
 9886:             $output .=  '<input type="hidden" name="phase" value="three" />';
 9887:         }
 9888:     } elsif ($applies) {
 9889:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 9890:         if ($applies > 1) {
 9891:             $output .=  
 9892:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 9893:             if ($numremref) {
 9894:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 9895:             }
 9896:             if ($numinvalid) {
 9897:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 9898:             }
 9899:             if ($numexisting) {
 9900:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 9901:             }
 9902:             $output .= '</ul><br />';
 9903:         } elsif ($numremref) {
 9904:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 9905:         } elsif ($numinvalid) {
 9906:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 9907:         } elsif ($numexisting) {
 9908:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 9909:         }
 9910:         $output .= $upload_output.'<br />';
 9911:     }
 9912:     my ($pathchange_output,$chgcount);
 9913:     $chgcount = $counter;
 9914:     if (keys(%pathchanges) > 0) {
 9915:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 9916:             if ($counter) {
 9917:                 $output .= &embedded_file_element('pathchange',$chgcount,
 9918:                                                   $embed_file,\%mapping,
 9919:                                                   $allfiles,$codebase,'change');
 9920:             } else {
 9921:                 $pathchange_output .= 
 9922:                     &start_data_table_row().
 9923:                     '<td><input type ="checkbox" name="namechange" value="'.
 9924:                     $chgcount.'" checked="checked" /></td>'.
 9925:                     '<td>'.$mapping{$embed_file}.'</td>'.
 9926:                     '<td>'.$embed_file.
 9927:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 9928:                                            \%mapping,$allfiles,$codebase,'change').
 9929:                     '</td>'.&end_data_table_row();
 9930:             }
 9931:             $numpathchg ++;
 9932:             $chgcount ++;
 9933:         }
 9934:     }
 9935:     if ($counter) {
 9936:         if ($numpathchg) {
 9937:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 9938:                        $numpathchg.'" />'."\n";
 9939:         }
 9940:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 9941:             ($actionurl eq '/adm/imsimport')) {
 9942:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 9943:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 9944:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 9945:         } elsif ($actionurl eq '/adm/dependencies') {
 9946:             $output .= '<input type="hidden" name="action" value="process_changes" />';
 9947:         }
 9948:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
 9949:     } elsif ($numpathchg) {
 9950:         my %pathchange = ();
 9951:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 9952:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9953:             $output .= '<p>'.&mt('or').'</p>'; 
 9954:         } 
 9955:     }
 9956:     return ($output,$counter,$numpathchg);
 9957: }
 9958: 
 9959: sub embedded_file_element {
 9960:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
 9961:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 9962:                    (ref($codebase) eq 'HASH'));
 9963:     my $output;
 9964:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
 9965:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 9966:     }
 9967:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 9968:                &escape($embed_file).'" />';
 9969:     unless (($context eq 'upload_embedded') && 
 9970:             ($mapping->{$embed_file} eq $embed_file)) {
 9971:         $output .='
 9972:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 9973:     }
 9974:     my $attrib;
 9975:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 9976:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 9977:     }
 9978:     $output .=
 9979:         "\n\t\t".
 9980:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 9981:         $attrib.'" />';
 9982:     if (exists($codebase->{$mapping->{$embed_file}})) {
 9983:         $output .=
 9984:             "\n\t\t".
 9985:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 9986:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 9987:     }
 9988:     return $output;
 9989: }
 9990: 
 9991: sub get_dependency_details {
 9992:     my ($currfile,$currsubfile,$embed_file) = @_;
 9993:     my ($size,$mtime,$showsize,$showmtime);
 9994:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
 9995:         if ($embed_file =~ m{/}) {
 9996:             my ($path,$fname) = split(/\//,$embed_file);
 9997:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
 9998:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
 9999:             }
10000:         } else {
10001:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10002:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10003:             }
10004:         }
10005:         $showsize = $size/1024.0;
10006:         $showsize = sprintf("%.1f",$showsize);
10007:         if ($mtime > 0) {
10008:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10009:         }
10010:     }
10011:     return ($showsize,$showmtime);
10012: }
10013: 
10014: sub ask_embedded_js {
10015:     return <<"END";
10016: <script type="text/javascript"">
10017: // <![CDATA[
10018: function toggleBrowse(counter) {
10019:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10020:     var fileid = document.getElementById('embedded_item_'+counter);
10021:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10022:     if (chkboxid.checked == true) {
10023:         uploaddivid.style.display='block';
10024:     } else {
10025:         uploaddivid.style.display='none';
10026:         fileid.value = '';
10027:     }
10028: }
10029: // ]]>
10030: </script>
10031: 
10032: END
10033: }
10034: 
10035: sub upload_embedded {
10036:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10037:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10038:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10039:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10040:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10041:         my $orig_uploaded_filename =
10042:             $env{'form.embedded_item_'.$i.'.filename'};
10043:         foreach my $type ('orig','ref','attrib','codebase') {
10044:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10045:                 $env{'form.embedded_'.$type.'_'.$i} =
10046:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10047:             }
10048:         }
10049:         my ($path,$fname) =
10050:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10051:         # no path, whole string is fname
10052:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10053:         $fname = &Apache::lonnet::clean_filename($fname);
10054:         # See if there is anything left
10055:         next if ($fname eq '');
10056: 
10057:         # Check if file already exists as a file or directory.
10058:         my ($state,$msg);
10059:         if ($context eq 'portfolio') {
10060:             my $port_path = $dirpath;
10061:             if ($group ne '') {
10062:                 $port_path = "groups/$group/$port_path";
10063:             }
10064:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10065:                                               $fname,$group,'embedded_item_'.$i,
10066:                                               $dir_root,$port_path,$disk_quota,
10067:                                               $current_disk_usage,$uname,$udom);
10068:             if ($state eq 'will_exceed_quota'
10069:                 || $state eq 'file_locked') {
10070:                 $output .= $msg;
10071:                 next;
10072:             }
10073:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10074:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10075:             if ($state eq 'exists') {
10076:                 $output .= $msg;
10077:                 next;
10078:             }
10079:         }
10080:         # Check if extension is valid
10081:         if (($fname =~ /\.(\w+)$/) &&
10082:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10083:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
10084:             next;
10085:         } elsif (($fname =~ /\.(\w+)$/) &&
10086:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10087:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10088:             next;
10089:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10090:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10091:             next;
10092:         }
10093:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10094:         if ($context eq 'portfolio') {
10095:             my $result;
10096:             if ($state eq 'existingfile') {
10097:                 $result=
10098:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10099:                                                     $dirpath.$env{'form.currentpath'}.$path);
10100:             } else {
10101:                 $result=
10102:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10103:                                                     $dirpath.
10104:                                                     $env{'form.currentpath'}.$path);
10105:                 if ($result !~ m|^/uploaded/|) {
10106:                     $output .= '<span class="LC_error">'
10107:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10108:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10109:                                .'</span><br />';
10110:                     next;
10111:                 } else {
10112:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10113:                                $path.$fname.'</span>').'<br />';     
10114:                 }
10115:             }
10116:         } elsif ($context eq 'coursedoc') {
10117:             my $result =
10118:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
10119:                                                 $dirpath.'/'.$path);
10120:             if ($result !~ m|^/uploaded/|) {
10121:                 $output .= '<span class="LC_error">'
10122:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10123:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10124:                            .'</span><br />';
10125:                     next;
10126:             } else {
10127:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10128:                            $path.$fname.'</span>').'<br />';
10129:             }
10130:         } else {
10131: # Save the file
10132:             my $target = $env{'form.embedded_item_'.$i};
10133:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10134:             my $dest = $fullpath.$fname;
10135:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10136:             my @parts=split(/\//,"$dirpath/$path");
10137:             my $count;
10138:             my $filepath = $dir_root;
10139:             foreach my $subdir (@parts) {
10140:                 $filepath .= "/$subdir";
10141:                 if (!-e $filepath) {
10142:                     mkdir($filepath,0770);
10143:                 }
10144:             }
10145:             my $fh;
10146:             if (!open($fh,'>'.$dest)) {
10147:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10148:                 $output .= '<span class="LC_error">'.
10149:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10150:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10151:                            '</span><br />';
10152:             } else {
10153:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10154:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10155:                     $output .= '<span class="LC_error">'.
10156:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10157:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10158:                               '</span><br />';
10159:                 } else {
10160:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10161:                                $url.'</span>').'<br />';
10162:                     unless ($context eq 'testbank') {
10163:                         $footer .= &mt('View embedded file: [_1]',
10164:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10165:                     }
10166:                 }
10167:                 close($fh);
10168:             }
10169:         }
10170:         if ($env{'form.embedded_ref_'.$i}) {
10171:             $pathchange{$i} = 1;
10172:         }
10173:     }
10174:     if ($output) {
10175:         $output = '<p>'.$output.'</p>';
10176:     }
10177:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10178:     $returnflag = 'ok';
10179:     my $numpathchgs = scalar(keys(%pathchange));
10180:     if ($numpathchgs > 0) {
10181:         if ($context eq 'portfolio') {
10182:             $output .= '<p>'.&mt('or').'</p>';
10183:         } elsif ($context eq 'testbank') {
10184:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10185:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10186:             $returnflag = 'modify_orightml';
10187:         }
10188:     }
10189:     return ($output.$footer,$returnflag,$numpathchgs);
10190: }
10191: 
10192: sub modify_html_form {
10193:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10194:     my $end = 0;
10195:     my $modifyform;
10196:     if ($context eq 'upload_embedded') {
10197:         return unless (ref($pathchange) eq 'HASH');
10198:         if ($env{'form.number_embedded_items'}) {
10199:             $end += $env{'form.number_embedded_items'};
10200:         }
10201:         if ($env{'form.number_pathchange_items'}) {
10202:             $end += $env{'form.number_pathchange_items'};
10203:         }
10204:         if ($end) {
10205:             for (my $i=0; $i<$end; $i++) {
10206:                 if ($i < $env{'form.number_embedded_items'}) {
10207:                     next unless($pathchange->{$i});
10208:                 }
10209:                 $modifyform .=
10210:                     &start_data_table_row().
10211:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10212:                     'checked="checked" /></td>'.
10213:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10214:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10215:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10216:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10217:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10218:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10219:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10220:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10221:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10222:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10223:                     &end_data_table_row();
10224:             }
10225:         }
10226:     } else {
10227:         $modifyform = $pathchgtable;
10228:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10229:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10230:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10231:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10232:         }
10233:     }
10234:     if ($modifyform) {
10235:         if ($actionurl eq '/adm/dependencies') {
10236:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10237:         }
10238:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10239:                '<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".
10240:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10241:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10242:                '</ol></p>'."\n".'<p>'.
10243:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10244:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10245:                &start_data_table()."\n".
10246:                &start_data_table_header_row().
10247:                '<th>'.&mt('Change?').'</th>'.
10248:                '<th>'.&mt('Current reference').'</th>'.
10249:                '<th>'.&mt('Required reference').'</th>'.
10250:                &end_data_table_header_row()."\n".
10251:                $modifyform.
10252:                &end_data_table().'<br />'."\n".$hiddenstate.
10253:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10254:                '</form>'."\n";
10255:     }
10256:     return;
10257: }
10258: 
10259: sub modify_html_refs {
10260:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
10261:     my $container;
10262:     if ($context eq 'portfolio') {
10263:         $container = $env{'form.container'};
10264:     } elsif ($context eq 'coursedoc') {
10265:         $container = $env{'form.primaryurl'};
10266:     } elsif ($context eq 'manage_dependencies') {
10267:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10268:         $container = "/$container";
10269:     } else {
10270:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10271:     }
10272:     my (%allfiles,%codebase,$output,$content);
10273:     my @changes = &get_env_multiple('form.namechange');
10274:     unless (@changes > 0) {
10275:         if (wantarray) {
10276:             return ('',0,0); 
10277:         } else {
10278:             return;
10279:         }
10280:     }
10281:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10282:         ($context eq 'manage_dependencies')) {
10283:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10284:             if (wantarray) {
10285:                 return ('',0,0);
10286:             } else {
10287:                 return;
10288:             }
10289:         } 
10290:         $content = &Apache::lonnet::getfile($container);
10291:         if ($content eq '-1') {
10292:             if (wantarray) {
10293:                 return ('',0,0);
10294:             } else {
10295:                 return;
10296:             }
10297:         }
10298:     } else {
10299:         unless ($container =~ /^\Q$dir_root\E/) {
10300:             if (wantarray) {
10301:                 return ('',0,0);
10302:             } else {
10303:                 return;
10304:             }
10305:         } 
10306:         if (open(my $fh,"<$container")) {
10307:             $content = join('', <$fh>);
10308:             close($fh);
10309:         } else {
10310:             if (wantarray) {
10311:                 return ('',0,0);
10312:             } else {
10313:                 return;
10314:             }
10315:         }
10316:     }
10317:     my ($count,$codebasecount) = (0,0);
10318:     my $mm = new File::MMagic;
10319:     my $mime_type = $mm->checktype_contents($content);
10320:     if ($mime_type eq 'text/html') {
10321:         my $parse_result = 
10322:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10323:                                                     \%codebase,\$content);
10324:         if ($parse_result eq 'ok') {
10325:             foreach my $i (@changes) {
10326:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10327:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10328:                 if ($allfiles{$ref}) {
10329:                     my $newname =  $orig;
10330:                     my ($attrib_regexp,$codebase);
10331:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10332:                     if ($attrib_regexp =~ /:/) {
10333:                         $attrib_regexp =~ s/\:/|/g;
10334:                     }
10335:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10336:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10337:                         $count += $numchg;
10338:                     }
10339:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10340:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10341:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10342:                         $codebasecount ++;
10343:                     }
10344:                 }
10345:             }
10346:             if ($count || $codebasecount) {
10347:                 my $saveresult;
10348:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10349:                     ($context eq 'manage_dependencies')) {
10350:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10351:                     if ($url eq $container) {
10352:                         my ($fname) = ($container =~ m{/([^/]+)$});
10353:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10354:                                             $count,'<span class="LC_filename">'.
10355:                                             $fname.'</span>').'</p>';
10356:                     } else {
10357:                          $output = '<p class="LC_error">'.
10358:                                    &mt('Error: update failed for: [_1].',
10359:                                    '<span class="LC_filename">'.
10360:                                    $container.'</span>').'</p>';
10361:                     }
10362:                 } else {
10363:                     if (open(my $fh,">$container")) {
10364:                         print $fh $content;
10365:                         close($fh);
10366:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10367:                                   $count,'<span class="LC_filename">'.
10368:                                   $container.'</span>').'</p>';
10369:                     } else {
10370:                          $output = '<p class="LC_error">'.
10371:                                    &mt('Error: could not update [_1].',
10372:                                    '<span class="LC_filename">'.
10373:                                    $container.'</span>').'</p>';
10374:                     }
10375:                 }
10376:             }
10377:         } else {
10378:             &logthis('Failed to parse '.$container.
10379:                      ' to modify references: '.$parse_result);
10380:         }
10381:     }
10382:     if (wantarray) {
10383:         return ($output,$count,$codebasecount);
10384:     } else {
10385:         return $output;
10386:     }
10387: }
10388: 
10389: sub check_for_existing {
10390:     my ($path,$fname,$element) = @_;
10391:     my ($state,$msg);
10392:     if (-d $path.'/'.$fname) {
10393:         $state = 'exists';
10394:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10395:     } elsif (-e $path.'/'.$fname) {
10396:         $state = 'exists';
10397:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10398:     }
10399:     if ($state eq 'exists') {
10400:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10401:     }
10402:     return ($state,$msg);
10403: }
10404: 
10405: sub check_for_upload {
10406:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10407:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10408:     my $filesize = length($env{'form.'.$element});
10409:     if (!$filesize) {
10410:         my $msg = '<span class="LC_error">'.
10411:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10412:                       '<span class="LC_filename">'.$fname.'</span>',
10413:                       $filesize).'<br />'.
10414:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10415:                   '</span>';
10416:         return ('zero_bytes',$msg);
10417:     }
10418:     $filesize =  $filesize/1000; #express in k (1024?)
10419:     my $getpropath = 1;
10420:     my ($dirlistref,$listerror) =
10421:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10422:     my $found_file = 0;
10423:     my $locked_file = 0;
10424:     my @lockers;
10425:     my $navmap;
10426:     if ($env{'request.course.id'}) {
10427:         $navmap = Apache::lonnavmaps::navmap->new();
10428:     }
10429:     if (ref($dirlistref) eq 'ARRAY') {
10430:         foreach my $line (@{$dirlistref}) {
10431:             my ($file_name,$rest)=split(/\&/,$line,2);
10432:             if ($file_name eq $fname){
10433:                 $file_name = $path.$file_name;
10434:                 if ($group ne '') {
10435:                     $file_name = $group.$file_name;
10436:                 }
10437:                 $found_file = 1;
10438:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10439:                     foreach my $lock (@lockers) {
10440:                         if (ref($lock) eq 'ARRAY') {
10441:                             my ($symb,$crsid) = @{$lock};
10442:                             if ($crsid eq $env{'request.course.id'}) {
10443:                                 if (ref($navmap)) {
10444:                                     my $res = $navmap->getBySymb($symb);
10445:                                     foreach my $part (@{$res->parts()}) { 
10446:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10447:                                         unless (($slot_status == $res->RESERVED) ||
10448:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10449:                                             $locked_file = 1;
10450:                                         }
10451:                                     }
10452:                                 } else {
10453:                                     $locked_file = 1;
10454:                                 }
10455:                             } else {
10456:                                 $locked_file = 1;
10457:                             }
10458:                         }
10459:                    }
10460:                 } else {
10461:                     my @info = split(/\&/,$rest);
10462:                     my $currsize = $info[6]/1000;
10463:                     if ($currsize < $filesize) {
10464:                         my $extra = $filesize - $currsize;
10465:                         if (($current_disk_usage + $extra) > $disk_quota) {
10466:                             my $msg = '<span class="LC_error">'.
10467:                                       &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.',
10468:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10469:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10470:                                                    $disk_quota,$current_disk_usage);
10471:                             return ('will_exceed_quota',$msg);
10472:                         }
10473:                     }
10474:                 }
10475:             }
10476:         }
10477:     }
10478:     if (($current_disk_usage + $filesize) > $disk_quota){
10479:         my $msg = '<span class="LC_error">'.
10480:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10481:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10482:         return ('will_exceed_quota',$msg);
10483:     } elsif ($found_file) {
10484:         if ($locked_file) {
10485:             my $msg = '<span class="LC_error">';
10486:             $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>');
10487:             $msg .= '</span><br />';
10488:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10489:             return ('file_locked',$msg);
10490:         } else {
10491:             my $msg = '<span class="LC_error">';
10492:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10493:             $msg .= '</span>';
10494:             return ('existingfile',$msg);
10495:         }
10496:     }
10497: }
10498: 
10499: sub check_for_traversal {
10500:     my ($path,$url,$toplevel) = @_;
10501:     my @parts=split(/\//,$path);
10502:     my $cleanpath;
10503:     my $fullpath = $url;
10504:     for (my $i=0;$i<@parts;$i++) {
10505:         next if ($parts[$i] eq '.');
10506:         if ($parts[$i] eq '..') {
10507:             $fullpath =~ s{([^/]+/)$}{};
10508:         } else {
10509:             $fullpath .= $parts[$i].'/';
10510:         }
10511:     }
10512:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10513:         $cleanpath = $1;
10514:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10515:         my $curr_toprel = $1;
10516:         my @parts = split(/\//,$curr_toprel);
10517:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10518:         my @urlparts = split(/\//,$url_toprel);
10519:         my $doubledots;
10520:         my $startdiff = -1;
10521:         for (my $i=0; $i<@urlparts; $i++) {
10522:             if ($startdiff == -1) {
10523:                 unless ($urlparts[$i] eq $parts[$i]) {
10524:                     $startdiff = $i;
10525:                     $doubledots .= '../';
10526:                 }
10527:             } else {
10528:                 $doubledots .= '../';
10529:             }
10530:         }
10531:         if ($startdiff > -1) {
10532:             $cleanpath = $doubledots;
10533:             for (my $i=$startdiff; $i<@parts; $i++) {
10534:                 $cleanpath .= $parts[$i].'/';
10535:             }
10536:         }
10537:     }
10538:     $cleanpath =~ s{(/)$}{};
10539:     return $cleanpath;
10540: }
10541: 
10542: sub is_archive_file {
10543:     my ($mimetype) = @_;
10544:     if (($mimetype eq 'application/octet-stream') ||
10545:         ($mimetype eq 'application/x-stuffit') ||
10546:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10547:         return 1;
10548:     }
10549:     return;
10550: }
10551: 
10552: sub decompress_form {
10553:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10554:     my %lt = &Apache::lonlocal::texthash (
10555:         this => 'This file is an archive file.',
10556:         camt => 'This file is a Camtasia archive file.',
10557:         itsc => 'Its contents are as follows:',
10558:         youm => 'You may wish to extract its contents.',
10559:         extr => 'Extract contents',
10560:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10561:         proa => 'Process automatically?',
10562:         yes  => 'Yes',
10563:         no   => 'No',
10564:         fold => 'Title for folder containing movie',
10565:         movi => 'Title for page containing embedded movie', 
10566:     );
10567:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10568:     my ($is_camtasia,$topdir,%toplevel,@paths);
10569:     my $info = &list_archive_contents($fileloc,\@paths);
10570:     if (@paths) {
10571:         foreach my $path (@paths) {
10572:             $path =~ s{^/}{};
10573:             if ($path =~ m{^([^/]+)/$}) {
10574:                 $topdir = $1;
10575:             }
10576:             if ($path =~ m{^([^/]+)/}) {
10577:                 $toplevel{$1} = $path;
10578:             } else {
10579:                 $toplevel{$path} = $path;
10580:             }
10581:         }
10582:     }
10583:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10584:         my @camtasia = ("$topdir/","$topdir/index.html",
10585:                         "$topdir/media/",
10586:                         "$topdir/media/$topdir.mp4",
10587:                         "$topdir/media/FirstFrame.png",
10588:                         "$topdir/media/player.swf",
10589:                         "$topdir/media/swfobject.js",
10590:                         "$topdir/media/expressInstall.swf");
10591:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10592:         if (@diffs == 0) {
10593:             $is_camtasia = 1;
10594:         }
10595:     }
10596:     my $output;
10597:     if ($is_camtasia) {
10598:         $output = <<"ENDCAM";
10599: <script type="text/javascript" language="Javascript">
10600: // <![CDATA[
10601: 
10602: function camtasiaToggle() {
10603:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10604:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10605:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10606: 
10607:                 document.getElementById('camtasia_titles').style.display='block';
10608:             } else {
10609:                 document.getElementById('camtasia_titles').style.display='none';
10610:             }
10611:         }
10612:     }
10613:     return;
10614: }
10615: 
10616: // ]]>
10617: </script>
10618: <p>$lt{'camt'}</p>
10619: ENDCAM
10620:     } else {
10621:         $output = '<p>'.$lt{'this'};
10622:         if ($info eq '') {
10623:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
10624:         } else {
10625:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10626:                        '<div><pre>'.$info.'</pre></div>';
10627:         }
10628:     }
10629:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10630:     my $duplicates;
10631:     my $num = 0;
10632:     if (ref($dirlist) eq 'ARRAY') {
10633:         foreach my $item (@{$dirlist}) {
10634:             if (ref($item) eq 'ARRAY') {
10635:                 if (exists($toplevel{$item->[0]})) {
10636:                     $duplicates .= 
10637:                         &start_data_table_row().
10638:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10639:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
10640:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
10641:                         'value="1" />'.&mt('Yes').'</label>'.
10642:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10643:                         '<td>'.$item->[0].'</td>';
10644:                     if ($item->[2]) {
10645:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
10646:                     } else {
10647:                         $duplicates .= '<td>'.&mt('File').'</td>';
10648:                     }
10649:                     $duplicates .= '<td>'.$item->[3].'</td>'.
10650:                                    '<td>'.
10651:                                    &Apache::lonlocal::locallocaltime($item->[4]).
10652:                                    '</td>'.
10653:                                    &end_data_table_row();
10654:                     $num ++;
10655:                 }
10656:             }
10657:         }
10658:     }
10659:     my $itemcount;
10660:     if (@paths > 0) {
10661:         $itemcount = scalar(@paths);
10662:     } else {
10663:         $itemcount = 1;
10664:     }
10665:     if ($is_camtasia) {
10666:         $output .= $lt{'auto'}.'<br />'.
10667:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10668:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10669:                    $lt{'yes'}.'</label>&nbsp;<label>'.
10670:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10671:                    $lt{'no'}.'</label></span><br />'.
10672:                    '<div id="camtasia_titles" style="display:block">'.
10673:                    &Apache::lonhtmlcommon::start_pick_box().
10674:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10675:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10676:                    &Apache::lonhtmlcommon::row_closure().
10677:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10678:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10679:                    &Apache::lonhtmlcommon::row_closure(1).
10680:                    &Apache::lonhtmlcommon::end_pick_box().
10681:                    '</div>';
10682:     }
10683:     $output .= 
10684:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10685:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10686:         "\n";
10687:     if ($duplicates ne '') {
10688:         $output .= '<p><span class="LC_warning">'.
10689:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
10690:                    &start_data_table().
10691:                    &start_data_table_header_row().
10692:                    '<th>'.&mt('Overwrite?').'</th>'.
10693:                    '<th>'.&mt('Name').'</th>'.
10694:                    '<th>'.&mt('Type').'</th>'.
10695:                    '<th>'.&mt('Size').'</th>'.
10696:                    '<th>'.&mt('Last modified').'</th>'.
10697:                    &end_data_table_header_row().
10698:                    $duplicates.
10699:                    &end_data_table().
10700:                    '</p>';
10701:     }
10702:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10703:     if (ref($hiddenelements) eq 'HASH') {
10704:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10705:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10706:         }
10707:     }
10708:     $output .= <<"END";
10709: <br />
10710: <input type="submit" name="decompress" value="$lt{'extr'}" />
10711: </form>
10712: $noextract
10713: END
10714:     return $output;
10715: }
10716: 
10717: sub decompression_utility {
10718:     my ($program) = @_;
10719:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
10720:     my $location;
10721:     if (grep(/^\Q$program\E$/,@utilities)) { 
10722:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10723:                          '/usr/sbin/') {
10724:             if (-x $dir.$program) {
10725:                 $location = $dir.$program;
10726:                 last;
10727:             }
10728:         }
10729:     }
10730:     return $location;
10731: }
10732: 
10733: sub list_archive_contents {
10734:     my ($file,$pathsref) = @_;
10735:     my (@cmd,$output);
10736:     my $needsregexp;
10737:     if ($file =~ /\.zip$/) {
10738:         @cmd = (&decompression_utility('unzip'),"-l");
10739:         $needsregexp = 1;
10740:     } elsif (($file =~ m/\.tar\.gz$/) ||
10741:              ($file =~ /\.tgz$/)) {
10742:         @cmd = (&decompression_utility('tar'),"-ztf");
10743:     } elsif ($file =~ /\.tar\.bz2$/) {
10744:         @cmd = (&decompression_utility('tar'),"-jtf");
10745:     } elsif ($file =~ m|\.tar$|) {
10746:         @cmd = (&decompression_utility('tar'),"-tf");
10747:     }
10748:     if (@cmd) {
10749:         undef($!);
10750:         undef($@);
10751:         if (open(my $fh,"-|", @cmd, $file)) {
10752:             while (my $line = <$fh>) {
10753:                 $output .= $line;
10754:                 chomp($line);
10755:                 my $item;
10756:                 if ($needsregexp) {
10757:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
10758:                 } else {
10759:                     $item = $line;
10760:                 }
10761:                 if ($item ne '') {
10762:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10763:                         push(@{$pathsref},$item);
10764:                     } 
10765:                 }
10766:             }
10767:             close($fh);
10768:         }
10769:     }
10770:     return $output;
10771: }
10772: 
10773: sub decompress_uploaded_file {
10774:     my ($file,$dir) = @_;
10775:     &Apache::lonnet::appenv({'cgi.file' => $file});
10776:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
10777:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10778:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10779:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10780:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10781:     my $decompressed = $env{'cgi.decompressed'};
10782:     &Apache::lonnet::delenv('cgi.file');
10783:     &Apache::lonnet::delenv('cgi.dir');
10784:     &Apache::lonnet::delenv('cgi.decompressed');
10785:     return ($decompressed,$result);
10786: }
10787: 
10788: sub process_decompression {
10789:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10790:     my ($dir,$error,$warning,$output);
10791:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10792:         $error = &mt('File name not a supported archive file type.').
10793:                  '<br />'.&mt('File name should end with one of: [_1].',
10794:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10795:     } else {
10796:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10797:         if ($docuhome eq 'no_host') {
10798:             $error = &mt('Could not determine home server for course.');
10799:         } else {
10800:             my @ids=&Apache::lonnet::current_machine_ids();
10801:             my $currdir = "$dir_root/$destination";
10802:             if (grep(/^\Q$docuhome\E$/,@ids)) {
10803:                 $dir = &LONCAPA::propath($docudom,$docuname).
10804:                        "$dir_root/$destination";
10805:             } else {
10806:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10807:                        "$dir_root/$docudom/$docuname/$destination";
10808:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10809:                     $error = &mt('Archive file not found.');
10810:                 }
10811:             }
10812:             my (@to_overwrite,@to_skip);
10813:             if ($env{'form.archive_overwrite_total'} > 0) {
10814:                 my $total = $env{'form.archive_overwrite_total'};
10815:                 for (my $i=0; $i<$total; $i++) {
10816:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
10817:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10818:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10819:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10820:                     }
10821:                 }
10822:             }
10823:             my $numskip = scalar(@to_skip);
10824:             if (($numskip > 0) && 
10825:                 ($numskip == $env{'form.archive_itemcount'})) {
10826:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
10827:             } elsif ($dir eq '') {
10828:                 $error = &mt('Directory containing archive file unavailable.');
10829:             } elsif (!$error) {
10830:                 my ($decompressed,$display);
10831:                 if ($numskip > 0) {
10832:                     my $tempdir = time.'_'.$$.int(rand(10000));
10833:                     mkdir("$dir/$tempdir",0755);
10834:                     system("mv $dir/$file $dir/$tempdir/$file");
10835:                     ($decompressed,$display) = 
10836:                         &decompress_uploaded_file($file,"$dir/$tempdir");
10837:                     foreach my $item (@to_skip) {
10838:                         if (($item ne '') && ($item !~ /\.\./)) {
10839:                             if (-f "$dir/$tempdir/$item") { 
10840:                                 unlink("$dir/$tempdir/$item");
10841:                             } elsif (-d "$dir/$tempdir/$item") {
10842:                                 system("rm -rf $dir/$tempdir/$item");
10843:                             }
10844:                         }
10845:                     }
10846:                     system("mv $dir/$tempdir/* $dir");
10847:                     rmdir("$dir/$tempdir");   
10848:                 } else {
10849:                     ($decompressed,$display) = 
10850:                         &decompress_uploaded_file($file,$dir);
10851:                 }
10852:                 if ($decompressed eq 'ok') {
10853:                     $output = '<p class="LC_info">'.
10854:                               &mt('Files extracted successfully from archive.').
10855:                               '</p>'."\n";
10856:                     my ($warning,$result,@contents);
10857:                     my ($newdirlistref,$newlisterror) =
10858:                         &Apache::lonnet::dirlist($currdir,$docudom,
10859:                                                  $docuname,1);
10860:                     my (%is_dir,%changes,@newitems);
10861:                     my $dirptr = 16384;
10862:                     if (ref($newdirlistref) eq 'ARRAY') {
10863:                         foreach my $dir_line (@{$newdirlistref}) {
10864:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10865:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
10866:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10867:                                 push(@newitems,$item);
10868:                                 if ($dirptr&$testdir) {
10869:                                     $is_dir{$item} = 1;
10870:                                 }
10871:                                 $changes{$item} = 1;
10872:                             }
10873:                         }
10874:                     }
10875:                     if (keys(%changes) > 0) {
10876:                         foreach my $item (sort(@newitems)) {
10877:                             if ($changes{$item}) {
10878:                                 push(@contents,$item);
10879:                             }
10880:                         }
10881:                     }
10882:                     if (@contents > 0) {
10883:                         my $wantform;
10884:                         unless ($env{'form.autoextract_camtasia'}) {
10885:                             $wantform = 1;
10886:                         }
10887:                         my (%children,%parent,%dirorder,%titles);
10888:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
10889:                                                                 $currdir,\%is_dir,
10890:                                                                 \%children,\%parent,
10891:                                                                 \@contents,\%dirorder,
10892:                                                                 \%titles,$wantform);
10893:                         if ($datatable ne '') {
10894:                             $output .= &archive_options_form('decompressed',$datatable,
10895:                                                              $count,$hiddenelem);
10896:                             my $startcount = 6;
10897:                             $output .= &archive_javascript($startcount,$count,
10898:                                                            \%titles,\%children);
10899:                         }
10900:                         if ($env{'form.autoextract_camtasia'}) {
10901:                             my %displayed;
10902:                             my $total = 1;
10903:                             $env{'form.archive_directory'} = [];
10904:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
10905:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
10906:                                 $path =~ s{/$}{};
10907:                                 my $item;
10908:                                 if ($path ne '') {
10909:                                     $item = "$path/$titles{$i}";
10910:                                 } else {
10911:                                     $item = $titles{$i};
10912:                                 }
10913:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
10914:                                 if ($item eq $contents[0]) {
10915:                                     push(@{$env{'form.archive_directory'}},$i);
10916:                                     $env{'form.archive_'.$i} = 'display';
10917:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
10918:                                     $displayed{'folder'} = $i;
10919:                                 } elsif ($item eq "$contents[0]/index.html") {
10920:                                     $env{'form.archive_'.$i} = 'display';
10921:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
10922:                                     $displayed{'web'} = $i;
10923:                                 } else {
10924:                                     if ($item eq "$contents[0]/media") {
10925:                                         push(@{$env{'form.archive_directory'}},$i);
10926:                                     }
10927:                                     $env{'form.archive_'.$i} = 'dependency';
10928:                                 }
10929:                                 $total ++;
10930:                             }
10931:                             for (my $i=1; $i<$total; $i++) {
10932:                                 next if ($i == $displayed{'web'});
10933:                                 next if ($i == $displayed{'folder'});
10934:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
10935:                             }
10936:                             $env{'form.phase'} = 'decompress_cleanup';
10937:                             $env{'form.archivedelete'} = 1;
10938:                             $env{'form.archive_count'} = $total-1;
10939:                             $output .=
10940:                                 &process_extracted_files('coursedocs',$docudom,
10941:                                                          $docuname,$destination,
10942:                                                          $dir_root,$hiddenelem);
10943:                         }
10944:                     } else {
10945:                         $warning = &mt('No new items extracted from archive file.');
10946:                     }
10947:                 } else {
10948:                     $output = $display;
10949:                     $error = &mt('An error occurred during extraction from the archive file.');
10950:                 }
10951:             }
10952:         }
10953:     }
10954:     if ($error) {
10955:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10956:                    $error.'</p>'."\n";
10957:     }
10958:     if ($warning) {
10959:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10960:     }
10961:     return $output;
10962: }
10963: 
10964: sub get_extracted {
10965:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10966:         $titles,$wantform) = @_;
10967:     my $count = 0;
10968:     my $depth = 0;
10969:     my $datatable;
10970:     my @hierarchy;
10971:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10972:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10973:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10974:     foreach my $item (@{$contents}) {
10975:         $count ++;
10976:         @{$dirorder->{$count}} = @hierarchy;
10977:         $titles->{$count} = $item;
10978:         &archive_hierarchy($depth,$count,$parent,$children);
10979:         if ($wantform) {
10980:             $datatable .= &archive_row($is_dir->{$item},$item,
10981:                                        $currdir,$depth,$count);
10982:         }
10983:         if ($is_dir->{$item}) {
10984:             $depth ++;
10985:             push(@hierarchy,$count);
10986:             $parent->{$depth} = $count;
10987:             $datatable .=
10988:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10989:                                            \$depth,\$count,\@hierarchy,$dirorder,
10990:                                            $children,$parent,$titles,$wantform);
10991:             $depth --;
10992:             pop(@hierarchy);
10993:         }
10994:     }
10995:     return ($count,$datatable);
10996: }
10997: 
10998: sub recurse_extracted_archive {
10999:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11000:         $children,$parent,$titles,$wantform) = @_;
11001:     my $result='';
11002:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11003:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11004:             (ref($dirorder) eq 'HASH')) {
11005:         return $result;
11006:     }
11007:     my $dirptr = 16384;
11008:     my ($newdirlistref,$newlisterror) =
11009:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11010:     if (ref($newdirlistref) eq 'ARRAY') {
11011:         foreach my $dir_line (@{$newdirlistref}) {
11012:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11013:             unless ($item =~ /^\.+$/) {
11014:                 $$count ++;
11015:                 @{$dirorder->{$$count}} = @{$hierarchy};
11016:                 $titles->{$$count} = $item;
11017:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11018: 
11019:                 my $is_dir;
11020:                 if ($dirptr&$testdir) {
11021:                     $is_dir = 1;
11022:                 }
11023:                 if ($wantform) {
11024:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11025:                 }
11026:                 if ($is_dir) {
11027:                     $$depth ++;
11028:                     push(@{$hierarchy},$$count);
11029:                     $parent->{$$depth} = $$count;
11030:                     $result .=
11031:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11032:                                                    $docuname,$depth,$count,
11033:                                                    $hierarchy,$dirorder,$children,
11034:                                                    $parent,$titles,$wantform);
11035:                     $$depth --;
11036:                     pop(@{$hierarchy});
11037:                 }
11038:             }
11039:         }
11040:     }
11041:     return $result;
11042: }
11043: 
11044: sub archive_hierarchy {
11045:     my ($depth,$count,$parent,$children) =@_;
11046:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11047:         if (exists($parent->{$depth})) {
11048:              $children->{$parent->{$depth}} .= $count.':';
11049:         }
11050:     }
11051:     return;
11052: }
11053: 
11054: sub archive_row {
11055:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11056:     my ($name) = ($item =~ m{([^/]+)$});
11057:     my %choices = &Apache::lonlocal::texthash (
11058:                                        'display'    => 'Add as file',
11059:                                        'dependency' => 'Include as dependency',
11060:                                        'discard'    => 'Discard',
11061:                                       );
11062:     if ($is_dir) {
11063:         $choices{'display'} = &mt('Add as folder'); 
11064:     }
11065:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11066:     my $offset = 0;
11067:     foreach my $action ('display','dependency','discard') {
11068:         $offset ++;
11069:         if ($action ne 'display') {
11070:             $offset ++;
11071:         }  
11072:         $output .= '<td><span class="LC_nobreak">'.
11073:                    '<label><input type="radio" name="archive_'.$count.
11074:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11075:         my $text = $choices{$action};
11076:         if ($is_dir) {
11077:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11078:             if ($action eq 'display') {
11079:                 $text = &mt('Add as folder');
11080:             }
11081:         } else {
11082:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11083: 
11084:         }
11085:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11086:         if ($action eq 'dependency') {
11087:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11088:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11089:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11090:                        '<option value=""></option>'."\n".
11091:                        '</select>'."\n".
11092:                        '</div>';
11093:         } elsif ($action eq 'display') {
11094:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11095:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11096:                        '</div>';
11097:         }
11098:         $output .= '</td>';
11099:     }
11100:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11101:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11102:     for (my $i=0; $i<$depth; $i++) {
11103:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11104:     }
11105:     if ($is_dir) {
11106:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11107:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11108:     } else {
11109:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11110:     }
11111:     $output .= '&nbsp;'.$name.'</td>'."\n".
11112:                &end_data_table_row();
11113:     return $output;
11114: }
11115: 
11116: sub archive_options_form {
11117:     my ($form,$display,$count,$hiddenelem) = @_;
11118:     my %lt = &Apache::lonlocal::texthash(
11119:                perm => 'Permanently remove archive file?',
11120:                hows => 'How should each extracted item be incorporated in the course?',
11121:                cont => 'Content actions for all',
11122:                addf => 'Add as folder/file',
11123:                incd => 'Include as dependency for a displayed file',
11124:                disc => 'Discard',
11125:                no   => 'No',
11126:                yes  => 'Yes',
11127:                save => 'Save',
11128:     );
11129:     my $output = <<"END";
11130: <form name="$form" method="post" action="">
11131: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11132: <label>
11133:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11134: </label>
11135: &nbsp;
11136: <label>
11137:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11138: </span>
11139: </p>
11140: <input type="hidden" name="phase" value="decompress_cleanup" />
11141: <br />$lt{'hows'}
11142: <div class="LC_columnSection">
11143:   <fieldset>
11144:     <legend>$lt{'cont'}</legend>
11145:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11146:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11147:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11148:   </fieldset>
11149: </div>
11150: END
11151:     return $output.
11152:            &start_data_table()."\n".
11153:            $display."\n".
11154:            &end_data_table()."\n".
11155:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11156:            $hiddenelem.
11157:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11158:            '</form>';
11159: }
11160: 
11161: sub archive_javascript {
11162:     my ($startcount,$numitems,$titles,$children) = @_;
11163:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11164:     my $maintitle = $env{'form.comment'};
11165:     my $scripttag = <<START;
11166: <script type="text/javascript">
11167: // <![CDATA[
11168: 
11169: function checkAll(form,prefix) {
11170:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11171:     for (var i=0; i < form.elements.length; i++) {
11172:         var id = form.elements[i].id;
11173:         if ((id != '') && (id != undefined)) {
11174:             if (idstr.test(id)) {
11175:                 if (form.elements[i].type == 'radio') {
11176:                     form.elements[i].checked = true;
11177:                     var nostart = i-$startcount;
11178:                     var offset = nostart%7;
11179:                     var count = (nostart-offset)/7;    
11180:                     dependencyCheck(form,count,offset);
11181:                 }
11182:             }
11183:         }
11184:     }
11185: }
11186: 
11187: function propagateCheck(form,count) {
11188:     if (count > 0) {
11189:         var startelement = $startcount + ((count-1) * 7);
11190:         for (var j=1; j<6; j++) {
11191:             if ((j != 2) && (j != 4)) {
11192:                 var item = startelement + j; 
11193:                 if (form.elements[item].type == 'radio') {
11194:                     if (form.elements[item].checked) {
11195:                         containerCheck(form,count,j);
11196:                         break;
11197:                     }
11198:                 }
11199:             }
11200:         }
11201:     }
11202: }
11203: 
11204: numitems = $numitems
11205: var titles = new Array(numitems);
11206: var parents = new Array(numitems);
11207: for (var i=0; i<numitems; i++) {
11208:     parents[i] = new Array;
11209: }
11210: var maintitle = '$maintitle';
11211: 
11212: START
11213: 
11214:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11215:         my @contents = split(/:/,$children->{$container});
11216:         for (my $i=0; $i<@contents; $i ++) {
11217:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11218:         }
11219:     }
11220: 
11221:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11222:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11223:     }
11224: 
11225:     $scripttag .= <<END;
11226: 
11227: function containerCheck(form,count,offset) {
11228:     if (count > 0) {
11229:         dependencyCheck(form,count,offset);
11230:         var item = (offset+$startcount)+7*(count-1);
11231:         form.elements[item].checked = true;
11232:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11233:             if (parents[count].length > 0) {
11234:                 for (var j=0; j<parents[count].length; j++) {
11235:                     containerCheck(form,parents[count][j],offset);
11236:                 }
11237:             }
11238:         }
11239:     }
11240: }
11241: 
11242: function dependencyCheck(form,count,offset) {
11243:     if (count > 0) {
11244:         var chosen = (offset+$startcount)+7*(count-1);
11245:         var depitem = $startcount + ((count-1) * 7) + 4;
11246:         var currtype = form.elements[depitem].type;
11247:         if (form.elements[chosen].value == 'dependency') {
11248:             document.getElementById('arc_depon_'+count).style.display='block'; 
11249:             form.elements[depitem].options.length = 0;
11250:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11251:             for (var i=1; i<=numitems; i++) {
11252:                 if (i == count) {
11253:                     continue;
11254:                 }
11255:                 var startelement = $startcount + (i-1) * 7;
11256:                 for (var j=1; j<6; j++) {
11257:                     if ((j != 2) && (j!= 4)) {
11258:                         var item = startelement + j;
11259:                         if (form.elements[item].type == 'radio') {
11260:                             if (form.elements[item].checked) {
11261:                                 if (form.elements[item].value == 'display') {
11262:                                     var n = form.elements[depitem].options.length;
11263:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11264:                                 }
11265:                             }
11266:                         }
11267:                     }
11268:                 }
11269:             }
11270:         } else {
11271:             document.getElementById('arc_depon_'+count).style.display='none';
11272:             form.elements[depitem].options.length = 0;
11273:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11274:         }
11275:         titleCheck(form,count,offset);
11276:     }
11277: }
11278: 
11279: function propagateSelect(form,count,offset) {
11280:     if (count > 0) {
11281:         var item = (1+offset+$startcount)+7*(count-1);
11282:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11283:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11284:             if (parents[count].length > 0) {
11285:                 for (var j=0; j<parents[count].length; j++) {
11286:                     containerSelect(form,parents[count][j],offset,picked);
11287:                 }
11288:             }
11289:         }
11290:     }
11291: }
11292: 
11293: function containerSelect(form,count,offset,picked) {
11294:     if (count > 0) {
11295:         var item = (offset+$startcount)+7*(count-1);
11296:         if (form.elements[item].type == 'radio') {
11297:             if (form.elements[item].value == 'dependency') {
11298:                 if (form.elements[item+1].type == 'select-one') {
11299:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11300:                         if (form.elements[item+1].options[i].value == picked) {
11301:                             form.elements[item+1].selectedIndex = i;
11302:                             break;
11303:                         }
11304:                     }
11305:                 }
11306:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11307:                     if (parents[count].length > 0) {
11308:                         for (var j=0; j<parents[count].length; j++) {
11309:                             containerSelect(form,parents[count][j],offset,picked);
11310:                         }
11311:                     }
11312:                 }
11313:             }
11314:         }
11315:     }
11316: }
11317: 
11318: function titleCheck(form,count,offset) {
11319:     if (count > 0) {
11320:         var chosen = (offset+$startcount)+7*(count-1);
11321:         var depitem = $startcount + ((count-1) * 7) + 2;
11322:         var currtype = form.elements[depitem].type;
11323:         if (form.elements[chosen].value == 'display') {
11324:             document.getElementById('arc_title_'+count).style.display='block';
11325:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11326:                 document.getElementById('archive_title_'+count).value=maintitle;
11327:             }
11328:         } else {
11329:             document.getElementById('arc_title_'+count).style.display='none';
11330:             if (currtype == 'text') { 
11331:                 document.getElementById('archive_title_'+count).value='';
11332:             }
11333:         }
11334:     }
11335:     return;
11336: }
11337: 
11338: // ]]>
11339: </script>
11340: END
11341:     return $scripttag;
11342: }
11343: 
11344: sub process_extracted_files {
11345:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11346:     my $numitems = $env{'form.archive_count'};
11347:     return unless ($numitems);
11348:     my @ids=&Apache::lonnet::current_machine_ids();
11349:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11350:         %folders,%containers,%mapinner,%prompttofetch);
11351:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11352:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11353:         $prefix = &LONCAPA::propath($docudom,$docuname);
11354:         $pathtocheck = "$dir_root/$destination";
11355:         $dir = $dir_root;
11356:         $ishome = 1;
11357:     } else {
11358:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11359:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11360:         $dir = "$dir_root/$docudom/$docuname";    
11361:     }
11362:     my $currdir = "$dir_root/$destination";
11363:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11364:     if ($env{'form.folderpath'}) {
11365:         my @items = split('&',$env{'form.folderpath'});
11366:         $folders{'0'} = $items[-2];
11367:         if ($env{'form.folderpath'} =~ /\:1$/) {
11368:             $containers{'0'}='page';
11369:         } else {
11370:             $containers{'0'}='sequence';
11371:         }
11372:     }
11373:     my @archdirs = &get_env_multiple('form.archive_directory');
11374:     if ($numitems) {
11375:         for (my $i=1; $i<=$numitems; $i++) {
11376:             my $path = $env{'form.archive_content_'.$i};
11377:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11378:                 my $item = $1;
11379:                 $toplevelitems{$item} = $i;
11380:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11381:                     $is_dir{$item} = 1;
11382:                 }
11383:             }
11384:         }
11385:     }
11386:     my ($output,%children,%parent,%titles,%dirorder,$result);
11387:     if (keys(%toplevelitems) > 0) {
11388:         my @contents = sort(keys(%toplevelitems));
11389:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11390:                                            \%parent,\@contents,\%dirorder,\%titles);
11391:     }
11392:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11393:     if ($numitems) {
11394:         for (my $i=1; $i<=$numitems; $i++) {
11395:             next if ($env{'form.archive_'.$i} eq 'dependency');
11396:             my $path = $env{'form.archive_content_'.$i};
11397:             if ($path =~ /^\Q$pathtocheck\E/) {
11398:                 if ($env{'form.archive_'.$i} eq 'discard') {
11399:                     if ($prefix ne '' && $path ne '') {
11400:                         if (-e $prefix.$path) {
11401:                             if ((@archdirs > 0) && 
11402:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11403:                                 $todeletedir{$prefix.$path} = 1;
11404:                             } else {
11405:                                 $todelete{$prefix.$path} = 1;
11406:                             }
11407:                         }
11408:                     }
11409:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11410:                     my ($docstitle,$title,$url,$outer);
11411:                     ($title) = ($path =~ m{/([^/]+)$});
11412:                     $docstitle = $env{'form.archive_title_'.$i};
11413:                     if ($docstitle eq '') {
11414:                         $docstitle = $title;
11415:                     }
11416:                     $outer = 0;
11417:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11418:                         if (@{$dirorder{$i}} > 0) {
11419:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11420:                                 if ($env{'form.archive_'.$item} eq 'display') {
11421:                                     $outer = $item;
11422:                                     last;
11423:                                 }
11424:                             }
11425:                         }
11426:                     }
11427:                     my ($errtext,$fatal) = 
11428:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11429:                                                '/'.$folders{$outer}.'.'.
11430:                                                $containers{$outer});
11431:                     next if ($fatal);
11432:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11433:                         if ($context eq 'coursedocs') {
11434:                             $mapinner{$i} = time;
11435:                             $folders{$i} = 'default_'.$mapinner{$i};
11436:                             $containers{$i} = 'sequence';
11437:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11438:                                       $folders{$i}.'.'.$containers{$i};
11439:                             my $newidx = &LONCAPA::map::getresidx();
11440:                             $LONCAPA::map::resources[$newidx]=
11441:                                 $docstitle.':'.$url.':false:normal:res';
11442:                             push(@LONCAPA::map::order,$newidx);
11443:                             my ($outtext,$errtext) =
11444:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11445:                                                         $docuname.'/'.$folders{$outer}.
11446:                                                         '.'.$containers{$outer},1,1);
11447:                             $newseqid{$i} = $newidx;
11448:                             unless ($errtext) {
11449:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11450:                             }
11451:                         }
11452:                     } else {
11453:                         if ($context eq 'coursedocs') {
11454:                             my $newidx=&LONCAPA::map::getresidx();
11455:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11456:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11457:                                       $title;
11458:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11459:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11460:                             }
11461:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11462:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11463:                             }
11464:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11465:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11466:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11467:                                 unless ($ishome) {
11468:                                     my $fetch = "$newdest{$i}/$title";
11469:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11470:                                     $prompttofetch{$fetch} = 1;
11471:                                 }
11472:                             }
11473:                             $LONCAPA::map::resources[$newidx]=
11474:                                 $docstitle.':'.$url.':false:normal:res';
11475:                             push(@LONCAPA::map::order, $newidx);
11476:                             my ($outtext,$errtext)=
11477:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11478:                                                         $docuname.'/'.$folders{$outer}.
11479:                                                         '.'.$containers{$outer},1,1);
11480:                             unless ($errtext) {
11481:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11482:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11483:                                 }
11484:                             }
11485:                         }
11486:                     }
11487:                 }
11488:             } else {
11489:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11490:             }
11491:         }
11492:         for (my $i=1; $i<=$numitems; $i++) {
11493:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11494:             my $path = $env{'form.archive_content_'.$i};
11495:             if ($path =~ /^\Q$pathtocheck\E/) {
11496:                 my ($title) = ($path =~ m{/([^/]+)$});
11497:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11498:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11499:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11500:                         my ($itemidx,$fullpath,$relpath);
11501:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11502:                             my $container = $dirorder{$referrer{$i}}->[-1];
11503:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11504:                                 if ($dirorder{$i}->[$j] eq $container) {
11505:                                     $itemidx = $j;
11506:                                 }
11507:                             }
11508:                         }
11509:                         if ($itemidx eq '') {
11510:                             $itemidx =  0;
11511:                         }
11512:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11513:                             if ($mapinner{$referrer{$i}}) {
11514:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11515:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11516:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11517:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11518:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11519:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11520:                                             if (!-e $fullpath) {
11521:                                                 mkdir($fullpath,0755);
11522:                                             }
11523:                                         }
11524:                                     } else {
11525:                                         last;
11526:                                     }
11527:                                 }
11528:                             }
11529:                         } elsif ($newdest{$referrer{$i}}) {
11530:                             $fullpath = $newdest{$referrer{$i}};
11531:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11532:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11533:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11534:                                     last;
11535:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11536:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11537:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11538:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11539:                                         if (!-e $fullpath) {
11540:                                             mkdir($fullpath,0755);
11541:                                         }
11542:                                     }
11543:                                 } else {
11544:                                     last;
11545:                                 }
11546:                             }
11547:                         }
11548:                         if ($fullpath ne '') {
11549:                             if (-e "$prefix$path") {
11550:                                 system("mv $prefix$path $fullpath/$title");
11551:                             }
11552:                             if (-e "$fullpath/$title") {
11553:                                 my $showpath;
11554:                                 if ($relpath ne '') {
11555:                                     $showpath = "$relpath/$title";
11556:                                 } else {
11557:                                     $showpath = "/$title";
11558:                                 }
11559:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11560:                             }
11561:                             unless ($ishome) {
11562:                                 my $fetch = "$fullpath/$title";
11563:                                 $fetch =~ s/^\Q$prefix$dir\E//;
11564:                                 $prompttofetch{$fetch} = 1;
11565:                             }
11566:                         }
11567:                     }
11568:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11569:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11570:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11571:                 }
11572:             } else {
11573:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11574:             }
11575:         }
11576:         if (keys(%todelete)) {
11577:             foreach my $key (keys(%todelete)) {
11578:                 unlink($key);
11579:             }
11580:         }
11581:         if (keys(%todeletedir)) {
11582:             foreach my $key (keys(%todeletedir)) {
11583:                 rmdir($key);
11584:             }
11585:         }
11586:         foreach my $dir (sort(keys(%is_dir))) {
11587:             if (($pathtocheck ne '') && ($dir ne ''))  {
11588:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11589:             }
11590:         }
11591:         if ($result ne '') {
11592:             $output .= '<ul>'."\n".
11593:                        $result."\n".
11594:                        '</ul>';
11595:         }
11596:         unless ($ishome) {
11597:             my $replicationfail;
11598:             foreach my $item (keys(%prompttofetch)) {
11599:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11600:                 unless ($fetchresult eq 'ok') {
11601:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
11602:                 }
11603:             }
11604:             if ($replicationfail) {
11605:                 $output .= '<p class="LC_error">'.
11606:                            &mt('Course home server failed to retrieve:').'<ul>'.
11607:                            $replicationfail.
11608:                            '</ul></p>';
11609:             }
11610:         }
11611:     } else {
11612:         $warning = &mt('No items found in archive.');
11613:     }
11614:     if ($error) {
11615:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11616:                    $error.'</p>'."\n";
11617:     }
11618:     if ($warning) {
11619:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11620:     }
11621:     return $output;
11622: }
11623: 
11624: sub cleanup_empty_dirs {
11625:     my ($path) = @_;
11626:     if (($path ne '') && (-d $path)) {
11627:         if (opendir(my $dirh,$path)) {
11628:             my @dircontents = grep(!/^\./,readdir($dirh));
11629:             my $numitems = 0;
11630:             foreach my $item (@dircontents) {
11631:                 if (-d "$path/$item") {
11632:                     &cleanup_empty_dirs("$path/$item");
11633:                     if (-e "$path/$item") {
11634:                         $numitems ++;
11635:                     }
11636:                 } else {
11637:                     $numitems ++;
11638:                 }
11639:             }
11640:             if ($numitems == 0) {
11641:                 rmdir($path);
11642:             }
11643:             closedir($dirh);
11644:         }
11645:     }
11646:     return;
11647: }
11648: 
11649: =pod
11650: 
11651: =item &get_folder_hierarchy()
11652: 
11653: Provides hierarchy of names of folders/sub-folders containing the current
11654: item,
11655: 
11656: Inputs: 3
11657:      - $navmap - navmaps object
11658: 
11659:      - $map - url for map (either the trigger itself, or map containing
11660:                            the resource, which is the trigger).
11661: 
11662:      - $showitem - 1 => show title for map itself; 0 => do not show.
11663: 
11664: Outputs: 1 @pathitems - array of folder/subfolder names.
11665: 
11666: =cut
11667: 
11668: sub get_folder_hierarchy {
11669:     my ($navmap,$map,$showitem) = @_;
11670:     my @pathitems;
11671:     if (ref($navmap)) {
11672:         my $mapres = $navmap->getResourceByUrl($map);
11673:         if (ref($mapres)) {
11674:             my $pcslist = $mapres->map_hierarchy();
11675:             if ($pcslist ne '') {
11676:                 my @pcs = split(/,/,$pcslist);
11677:                 foreach my $pc (@pcs) {
11678:                     if ($pc == 1) {
11679:                         push(@pathitems,&mt('Main Course Documents'));
11680:                     } else {
11681:                         my $res = $navmap->getByMapPc($pc);
11682:                         if (ref($res)) {
11683:                             my $title = $res->compTitle();
11684:                             $title =~ s/\W+/_/g;
11685:                             if ($title ne '') {
11686:                                 push(@pathitems,$title);
11687:                             }
11688:                         }
11689:                     }
11690:                 }
11691:             }
11692:             if ($showitem) {
11693:                 if ($mapres->{ID} eq '0.0') {
11694:                     push(@pathitems,&mt('Main Course Documents'));
11695:                 } else {
11696:                     my $maptitle = $mapres->compTitle();
11697:                     $maptitle =~ s/\W+/_/g;
11698:                     if ($maptitle ne '') {
11699:                         push(@pathitems,$maptitle);
11700:                     }
11701:                 }
11702:             }
11703:         }
11704:     }
11705:     return @pathitems;
11706: }
11707: 
11708: =pod
11709: 
11710: =item * &get_turnedin_filepath()
11711: 
11712: Determines path in a user's portfolio file for storage of files uploaded
11713: to a specific essayresponse or dropbox item.
11714: 
11715: Inputs: 3 required + 1 optional.
11716: $symb is symb for resource, $uname and $udom are for current user (required).
11717: $caller is optional (can be "submission", if routine is called when storing
11718: an upoaded file when "Submit Answer" button was pressed).
11719: 
11720: Returns array containing $path and $multiresp. 
11721: $path is path in portfolio.  $multiresp is 1 if this resource contains more
11722: than one file upload item.  Callers of routine should append partid as a 
11723: subdirectory to $path in cases where $multiresp is 1.
11724: 
11725: Called by: homework/essayresponse.pm and homework/structuretags.pm
11726: 
11727: =cut
11728: 
11729: sub get_turnedin_filepath {
11730:     my ($symb,$uname,$udom,$caller) = @_;
11731:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11732:     my $turnindir;
11733:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11734:     $turnindir = $userhash{'turnindir'};
11735:     my ($path,$multiresp);
11736:     if ($turnindir eq '') {
11737:         if ($caller eq 'submission') {
11738:             $turnindir = &mt('turned in');
11739:             $turnindir =~ s/\W+/_/g;
11740:             my %newhash = (
11741:                             'turnindir' => $turnindir,
11742:                           );
11743:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11744:         }
11745:     }
11746:     if ($turnindir ne '') {
11747:         $path = '/'.$turnindir.'/';
11748:         my ($multipart,$turnin,@pathitems);
11749:         my $navmap = Apache::lonnavmaps::navmap->new();
11750:         if (defined($navmap)) {
11751:             my $mapres = $navmap->getResourceByUrl($map);
11752:             if (ref($mapres)) {
11753:                 my $pcslist = $mapres->map_hierarchy();
11754:                 if ($pcslist ne '') {
11755:                     foreach my $pc (split(/,/,$pcslist)) {
11756:                         my $res = $navmap->getByMapPc($pc);
11757:                         if (ref($res)) {
11758:                             my $title = $res->compTitle();
11759:                             $title =~ s/\W+/_/g;
11760:                             if ($title ne '') {
11761:                                 push(@pathitems,$title);
11762:                             }
11763:                         }
11764:                     }
11765:                 }
11766:                 my $maptitle = $mapres->compTitle();
11767:                 $maptitle =~ s/\W+/_/g;
11768:                 if ($maptitle ne '') {
11769:                     push(@pathitems,$maptitle);
11770:                 }
11771:                 unless ($env{'request.state'} eq 'construct') {
11772:                     my $res = $navmap->getBySymb($symb);
11773:                     if (ref($res)) {
11774:                         my $partlist = $res->parts();
11775:                         my $totaluploads = 0;
11776:                         if (ref($partlist) eq 'ARRAY') {
11777:                             foreach my $part (@{$partlist}) {
11778:                                 my @types = $res->responseType($part);
11779:                                 my @ids = $res->responseIds($part);
11780:                                 for (my $i=0; $i < scalar(@ids); $i++) {
11781:                                     if ($types[$i] eq 'essay') {
11782:                                         my $partid = $part.'_'.$ids[$i];
11783:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11784:                                             $totaluploads ++;
11785:                                         }
11786:                                     }
11787:                                 }
11788:                             }
11789:                             if ($totaluploads > 1) {
11790:                                 $multiresp = 1;
11791:                             }
11792:                         }
11793:                     }
11794:                 }
11795:             } else {
11796:                 return;
11797:             }
11798:         } else {
11799:             return;
11800:         }
11801:         my $restitle=&Apache::lonnet::gettitle($symb);
11802:         $restitle =~ s/\W+/_/g;
11803:         if ($restitle eq '') {
11804:             $restitle = ($resurl =~ m{/[^/]+$});
11805:             if ($restitle eq '') {
11806:                 $restitle = time;
11807:             }
11808:         }
11809:         push(@pathitems,$restitle);
11810:         $path .= join('/',@pathitems);
11811:     }
11812:     return ($path,$multiresp);
11813: }
11814: 
11815: =pod
11816: 
11817: =back
11818: 
11819: =head1 CSV Upload/Handling functions
11820: 
11821: =over 4
11822: 
11823: =item * &upfile_store($r)
11824: 
11825: Store uploaded file, $r should be the HTTP Request object,
11826: needs $env{'form.upfile'}
11827: returns $datatoken to be put into hidden field
11828: 
11829: =cut
11830: 
11831: sub upfile_store {
11832:     my $r=shift;
11833:     $env{'form.upfile'}=~s/\r/\n/gs;
11834:     $env{'form.upfile'}=~s/\f/\n/gs;
11835:     $env{'form.upfile'}=~s/\n+/\n/gs;
11836:     $env{'form.upfile'}=~s/\n+$//gs;
11837: 
11838:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11839: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11840:     {
11841:         my $datafile = $r->dir_config('lonDaemons').
11842:                            '/tmp/'.$datatoken.'.tmp';
11843:         if ( open(my $fh,">$datafile") ) {
11844:             print $fh $env{'form.upfile'};
11845:             close($fh);
11846:         }
11847:     }
11848:     return $datatoken;
11849: }
11850: 
11851: =pod
11852: 
11853: =item * &load_tmp_file($r)
11854: 
11855: Load uploaded file from tmp, $r should be the HTTP Request object,
11856: needs $env{'form.datatoken'},
11857: sets $env{'form.upfile'} to the contents of the file
11858: 
11859: =cut
11860: 
11861: sub load_tmp_file {
11862:     my $r=shift;
11863:     my @studentdata=();
11864:     {
11865:         my $studentfile = $r->dir_config('lonDaemons').
11866:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
11867:         if ( open(my $fh,"<$studentfile") ) {
11868:             @studentdata=<$fh>;
11869:             close($fh);
11870:         }
11871:     }
11872:     $env{'form.upfile'}=join('',@studentdata);
11873: }
11874: 
11875: =pod
11876: 
11877: =item * &upfile_record_sep()
11878: 
11879: Separate uploaded file into records
11880: returns array of records,
11881: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11882: 
11883: =cut
11884: 
11885: sub upfile_record_sep {
11886:     if ($env{'form.upfiletype'} eq 'xml') {
11887:     } else {
11888: 	my @records;
11889: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
11890: 	    if ($line=~/^\s*$/) { next; }
11891: 	    push(@records,$line);
11892: 	}
11893: 	return @records;
11894:     }
11895: }
11896: 
11897: =pod
11898: 
11899: =item * &record_sep($record)
11900: 
11901: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11902: 
11903: =cut
11904: 
11905: sub takeleft {
11906:     my $index=shift;
11907:     return substr('0000'.$index,-4,4);
11908: }
11909: 
11910: sub record_sep {
11911:     my $record=shift;
11912:     my %components=();
11913:     if ($env{'form.upfiletype'} eq 'xml') {
11914:     } elsif ($env{'form.upfiletype'} eq 'space') {
11915:         my $i=0;
11916:         foreach my $field (split(/\s+/,$record)) {
11917:             $field=~s/^(\"|\')//;
11918:             $field=~s/(\"|\')$//;
11919:             $components{&takeleft($i)}=$field;
11920:             $i++;
11921:         }
11922:     } elsif ($env{'form.upfiletype'} eq 'tab') {
11923:         my $i=0;
11924:         foreach my $field (split(/\t/,$record)) {
11925:             $field=~s/^(\"|\')//;
11926:             $field=~s/(\"|\')$//;
11927:             $components{&takeleft($i)}=$field;
11928:             $i++;
11929:         }
11930:     } else {
11931:         my $separator=',';
11932:         if ($env{'form.upfiletype'} eq 'semisv') {
11933:             $separator=';';
11934:         }
11935:         my $i=0;
11936: # the character we are looking for to indicate the end of a quote or a record 
11937:         my $looking_for=$separator;
11938: # do not add the characters to the fields
11939:         my $ignore=0;
11940: # we just encountered a separator (or the beginning of the record)
11941:         my $just_found_separator=1;
11942: # store the field we are working on here
11943:         my $field='';
11944: # work our way through all characters in record
11945:         foreach my $character ($record=~/(.)/g) {
11946:             if ($character eq $looking_for) {
11947:                if ($character ne $separator) {
11948: # Found the end of a quote, again looking for separator
11949:                   $looking_for=$separator;
11950:                   $ignore=1;
11951:                } else {
11952: # Found a separator, store away what we got
11953:                   $components{&takeleft($i)}=$field;
11954: 	          $i++;
11955:                   $just_found_separator=1;
11956:                   $ignore=0;
11957:                   $field='';
11958:                }
11959:                next;
11960:             }
11961: # single or double quotation marks after a separator indicate beginning of a quote
11962: # we are now looking for the end of the quote and need to ignore separators
11963:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
11964:                $looking_for=$character;
11965:                next;
11966:             }
11967: # ignore would be true after we reached the end of a quote
11968:             if ($ignore) { next; }
11969:             if (($just_found_separator) && ($character=~/\s/)) { next; }
11970:             $field.=$character;
11971:             $just_found_separator=0; 
11972:         }
11973: # catch the very last entry, since we never encountered the separator
11974:         $components{&takeleft($i)}=$field;
11975:     }
11976:     return %components;
11977: }
11978: 
11979: ######################################################
11980: ######################################################
11981: 
11982: =pod
11983: 
11984: =item * &upfile_select_html()
11985: 
11986: Return HTML code to select a file from the users machine and specify 
11987: the file type.
11988: 
11989: =cut
11990: 
11991: ######################################################
11992: ######################################################
11993: sub upfile_select_html {
11994:     my %Types = (
11995:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
11996:                  semisv => &mt('Semicolon separated values'),
11997:                  space => &mt('Space separated'),
11998:                  tab   => &mt('Tabulator separated'),
11999: #                 xml   => &mt('HTML/XML'),
12000:                  );
12001:     my $Str = '<input type="file" name="upfile" size="50" />'.
12002:         '<br />'.&mt('Type').': <select name="upfiletype">';
12003:     foreach my $type (sort(keys(%Types))) {
12004:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12005:     }
12006:     $Str .= "</select>\n";
12007:     return $Str;
12008: }
12009: 
12010: sub get_samples {
12011:     my ($records,$toget) = @_;
12012:     my @samples=({});
12013:     my $got=0;
12014:     foreach my $rec (@$records) {
12015: 	my %temp = &record_sep($rec);
12016: 	if (! grep(/\S/, values(%temp))) { next; }
12017: 	if (%temp) {
12018: 	    $samples[$got]=\%temp;
12019: 	    $got++;
12020: 	    if ($got == $toget) { last; }
12021: 	}
12022:     }
12023:     return \@samples;
12024: }
12025: 
12026: ######################################################
12027: ######################################################
12028: 
12029: =pod
12030: 
12031: =item * &csv_print_samples($r,$records)
12032: 
12033: Prints a table of sample values from each column uploaded $r is an
12034: Apache Request ref, $records is an arrayref from
12035: &Apache::loncommon::upfile_record_sep
12036: 
12037: =cut
12038: 
12039: ######################################################
12040: ######################################################
12041: sub csv_print_samples {
12042:     my ($r,$records) = @_;
12043:     my $samples = &get_samples($records,5);
12044: 
12045:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12046:               &start_data_table_header_row());
12047:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12048:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12049:     $r->print(&end_data_table_header_row());
12050:     foreach my $hash (@$samples) {
12051: 	$r->print(&start_data_table_row());
12052: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12053: 	    $r->print('<td>');
12054: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12055: 	    $r->print('</td>');
12056: 	}
12057: 	$r->print(&end_data_table_row());
12058:     }
12059:     $r->print(&end_data_table().'<br />'."\n");
12060: }
12061: 
12062: ######################################################
12063: ######################################################
12064: 
12065: =pod
12066: 
12067: =item * &csv_print_select_table($r,$records,$d)
12068: 
12069: Prints a table to create associations between values and table columns.
12070: 
12071: $r is an Apache Request ref,
12072: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12073: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12074: 
12075: =cut
12076: 
12077: ######################################################
12078: ######################################################
12079: sub csv_print_select_table {
12080:     my ($r,$records,$d) = @_;
12081:     my $i=0;
12082:     my $samples = &get_samples($records,1);
12083:     $r->print(&mt('Associate columns with student attributes.')."\n".
12084: 	      &start_data_table().&start_data_table_header_row().
12085:               '<th>'.&mt('Attribute').'</th>'.
12086:               '<th>'.&mt('Column').'</th>'.
12087:               &end_data_table_header_row()."\n");
12088:     foreach my $array_ref (@$d) {
12089: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12090: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12091: 
12092: 	$r->print('<td><select name="f'.$i.'"'.
12093: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12094: 	$r->print('<option value="none"></option>');
12095: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12096: 	    $r->print('<option value="'.$sample.'"'.
12097:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12098:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12099: 	}
12100: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12101: 	$i++;
12102:     }
12103:     $r->print(&end_data_table());
12104:     $i--;
12105:     return $i;
12106: }
12107: 
12108: ######################################################
12109: ######################################################
12110: 
12111: =pod
12112: 
12113: =item * &csv_samples_select_table($r,$records,$d)
12114: 
12115: Prints a table of sample values from the upload and can make associate samples to internal names.
12116: 
12117: $r is an Apache Request ref,
12118: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12119: $d is an array of 2 element arrays (internal name, displayed name)
12120: 
12121: =cut
12122: 
12123: ######################################################
12124: ######################################################
12125: sub csv_samples_select_table {
12126:     my ($r,$records,$d) = @_;
12127:     my $i=0;
12128:     #
12129:     my $max_samples = 5;
12130:     my $samples = &get_samples($records,$max_samples);
12131:     $r->print(&start_data_table().
12132:               &start_data_table_header_row().'<th>'.
12133:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12134:               &end_data_table_header_row());
12135: 
12136:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12137: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12138: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12139: 	foreach my $option (@$d) {
12140: 	    my ($value,$display,$defaultcol)=@{ $option };
12141: 	    $r->print('<option value="'.$value.'"'.
12142:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12143:                       $display.'</option>');
12144: 	}
12145: 	$r->print('</select></td><td>');
12146: 	foreach my $line (0..($max_samples-1)) {
12147: 	    if (defined($samples->[$line]{$key})) { 
12148: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12149: 	    }
12150: 	}
12151: 	$r->print('</td>'.&end_data_table_row());
12152: 	$i++;
12153:     }
12154:     $r->print(&end_data_table());
12155:     $i--;
12156:     return($i);
12157: }
12158: 
12159: ######################################################
12160: ######################################################
12161: 
12162: =pod
12163: 
12164: =item * &clean_excel_name($name)
12165: 
12166: Returns a replacement for $name which does not contain any illegal characters.
12167: 
12168: =cut
12169: 
12170: ######################################################
12171: ######################################################
12172: sub clean_excel_name {
12173:     my ($name) = @_;
12174:     $name =~ s/[:\*\?\/\\]//g;
12175:     if (length($name) > 31) {
12176:         $name = substr($name,0,31);
12177:     }
12178:     return $name;
12179: }
12180: 
12181: =pod
12182: 
12183: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12184: 
12185: Returns either 1 or undef
12186: 
12187: 1 if the part is to be hidden, undef if it is to be shown
12188: 
12189: Arguments are:
12190: 
12191: $id the id of the part to be checked
12192: $symb, optional the symb of the resource to check
12193: $udom, optional the domain of the user to check for
12194: $uname, optional the username of the user to check for
12195: 
12196: =cut
12197: 
12198: sub check_if_partid_hidden {
12199:     my ($id,$symb,$udom,$uname) = @_;
12200:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12201: 					 $symb,$udom,$uname);
12202:     my $truth=1;
12203:     #if the string starts with !, then the list is the list to show not hide
12204:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12205:     my @hiddenlist=split(/,/,$hiddenparts);
12206:     foreach my $checkid (@hiddenlist) {
12207: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12208:     }
12209:     return !$truth;
12210: }
12211: 
12212: 
12213: ############################################################
12214: ############################################################
12215: 
12216: =pod
12217: 
12218: =back 
12219: 
12220: =head1 cgi-bin script and graphing routines
12221: 
12222: =over 4
12223: 
12224: =item * &get_cgi_id()
12225: 
12226: Inputs: none
12227: 
12228: Returns an id which can be used to pass environment variables
12229: to various cgi-bin scripts.  These environment variables will
12230: be removed from the users environment after a given time by
12231: the routine &Apache::lonnet::transfer_profile_to_env.
12232: 
12233: =cut
12234: 
12235: ############################################################
12236: ############################################################
12237: my $uniq=0;
12238: sub get_cgi_id {
12239:     $uniq=($uniq+1)%100000;
12240:     return (time.'_'.$$.'_'.$uniq);
12241: }
12242: 
12243: ############################################################
12244: ############################################################
12245: 
12246: =pod
12247: 
12248: =item * &DrawBarGraph()
12249: 
12250: Facilitates the plotting of data in a (stacked) bar graph.
12251: Puts plot definition data into the users environment in order for 
12252: graph.png to plot it.  Returns an <img> tag for the plot.
12253: The bars on the plot are labeled '1','2',...,'n'.
12254: 
12255: Inputs:
12256: 
12257: =over 4
12258: 
12259: =item $Title: string, the title of the plot
12260: 
12261: =item $xlabel: string, text describing the X-axis of the plot
12262: 
12263: =item $ylabel: string, text describing the Y-axis of the plot
12264: 
12265: =item $Max: scalar, the maximum Y value to use in the plot
12266: If $Max is < any data point, the graph will not be rendered.
12267: 
12268: =item $colors: array ref holding the colors to be used for the data sets when
12269: they are plotted.  If undefined, default values will be used.
12270: 
12271: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12272: 
12273: =item @Values: An array of array references.  Each array reference holds data
12274: to be plotted in a stacked bar chart.
12275: 
12276: =item If the final element of @Values is a hash reference the key/value
12277: pairs will be added to the graph definition.
12278: 
12279: =back
12280: 
12281: Returns:
12282: 
12283: An <img> tag which references graph.png and the appropriate identifying
12284: information for the plot.
12285: 
12286: =cut
12287: 
12288: ############################################################
12289: ############################################################
12290: sub DrawBarGraph {
12291:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12292:     #
12293:     if (! defined($colors)) {
12294:         $colors = ['#33ff00', 
12295:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12296:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12297:                   ]; 
12298:     }
12299:     my $extra_settings = {};
12300:     if (ref($Values[-1]) eq 'HASH') {
12301:         $extra_settings = pop(@Values);
12302:     }
12303:     #
12304:     my $identifier = &get_cgi_id();
12305:     my $id = 'cgi.'.$identifier;        
12306:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12307:         return '';
12308:     }
12309:     #
12310:     my @Labels;
12311:     if (defined($labels)) {
12312:         @Labels = @$labels;
12313:     } else {
12314:         for (my $i=0;$i<@{$Values[0]};$i++) {
12315:             push (@Labels,$i+1);
12316:         }
12317:     }
12318:     #
12319:     my $NumBars = scalar(@{$Values[0]});
12320:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12321:     my %ValuesHash;
12322:     my $NumSets=1;
12323:     foreach my $array (@Values) {
12324:         next if (! ref($array));
12325:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12326:             join(',',@$array);
12327:     }
12328:     #
12329:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12330:     if ($NumBars < 3) {
12331:         $width = 120+$NumBars*32;
12332:         $xskip = 1;
12333:         $bar_width = 30;
12334:     } elsif ($NumBars < 5) {
12335:         $width = 120+$NumBars*20;
12336:         $xskip = 1;
12337:         $bar_width = 20;
12338:     } elsif ($NumBars < 10) {
12339:         $width = 120+$NumBars*15;
12340:         $xskip = 1;
12341:         $bar_width = 15;
12342:     } elsif ($NumBars <= 25) {
12343:         $width = 120+$NumBars*11;
12344:         $xskip = 5;
12345:         $bar_width = 8;
12346:     } elsif ($NumBars <= 50) {
12347:         $width = 120+$NumBars*8;
12348:         $xskip = 5;
12349:         $bar_width = 4;
12350:     } else {
12351:         $width = 120+$NumBars*8;
12352:         $xskip = 5;
12353:         $bar_width = 4;
12354:     }
12355:     #
12356:     $Max = 1 if ($Max < 1);
12357:     if ( int($Max) < $Max ) {
12358:         $Max++;
12359:         $Max = int($Max);
12360:     }
12361:     $Title  = '' if (! defined($Title));
12362:     $xlabel = '' if (! defined($xlabel));
12363:     $ylabel = '' if (! defined($ylabel));
12364:     $ValuesHash{$id.'.title'}    = &escape($Title);
12365:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12366:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12367:     $ValuesHash{$id.'.y_max_value'} = $Max;
12368:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12369:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12370:     $ValuesHash{$id.'.PlotType'} = 'bar';
12371:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12372:     $ValuesHash{$id.'.height'}   = $height;
12373:     $ValuesHash{$id.'.width'}    = $width;
12374:     $ValuesHash{$id.'.xskip'}    = $xskip;
12375:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12376:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12377:     #
12378:     # Deal with other parameters
12379:     while (my ($key,$value) = each(%$extra_settings)) {
12380:         $ValuesHash{$id.'.'.$key} = $value;
12381:     }
12382:     #
12383:     &Apache::lonnet::appenv(\%ValuesHash);
12384:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12385: }
12386: 
12387: ############################################################
12388: ############################################################
12389: 
12390: =pod
12391: 
12392: =item * &DrawXYGraph()
12393: 
12394: Facilitates the plotting of data in an XY graph.
12395: Puts plot definition data into the users environment in order for 
12396: graph.png to plot it.  Returns an <img> tag for the plot.
12397: 
12398: Inputs:
12399: 
12400: =over 4
12401: 
12402: =item $Title: string, the title of the plot
12403: 
12404: =item $xlabel: string, text describing the X-axis of the plot
12405: 
12406: =item $ylabel: string, text describing the Y-axis of the plot
12407: 
12408: =item $Max: scalar, the maximum Y value to use in the plot
12409: If $Max is < any data point, the graph will not be rendered.
12410: 
12411: =item $colors: Array ref containing the hex color codes for the data to be 
12412: plotted in.  If undefined, default values will be used.
12413: 
12414: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12415: 
12416: =item $Ydata: Array ref containing Array refs.  
12417: Each of the contained arrays will be plotted as a separate curve.
12418: 
12419: =item %Values: hash indicating or overriding any default values which are 
12420: passed to graph.png.  
12421: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12422: 
12423: =back
12424: 
12425: Returns:
12426: 
12427: An <img> tag which references graph.png and the appropriate identifying
12428: information for the plot.
12429: 
12430: =cut
12431: 
12432: ############################################################
12433: ############################################################
12434: sub DrawXYGraph {
12435:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12436:     #
12437:     # Create the identifier for the graph
12438:     my $identifier = &get_cgi_id();
12439:     my $id = 'cgi.'.$identifier;
12440:     #
12441:     $Title  = '' if (! defined($Title));
12442:     $xlabel = '' if (! defined($xlabel));
12443:     $ylabel = '' if (! defined($ylabel));
12444:     my %ValuesHash = 
12445:         (
12446:          $id.'.title'  => &escape($Title),
12447:          $id.'.xlabel' => &escape($xlabel),
12448:          $id.'.ylabel' => &escape($ylabel),
12449:          $id.'.y_max_value'=> $Max,
12450:          $id.'.labels'     => join(',',@$Xlabels),
12451:          $id.'.PlotType'   => 'XY',
12452:          );
12453:     #
12454:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12455:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12456:     }
12457:     #
12458:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12459:         return '';
12460:     }
12461:     my $NumSets=1;
12462:     foreach my $array (@{$Ydata}){
12463:         next if (! ref($array));
12464:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12465:     }
12466:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12467:     #
12468:     # Deal with other parameters
12469:     while (my ($key,$value) = each(%Values)) {
12470:         $ValuesHash{$id.'.'.$key} = $value;
12471:     }
12472:     #
12473:     &Apache::lonnet::appenv(\%ValuesHash);
12474:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12475: }
12476: 
12477: ############################################################
12478: ############################################################
12479: 
12480: =pod
12481: 
12482: =item * &DrawXYYGraph()
12483: 
12484: Facilitates the plotting of data in an XY graph with two Y axes.
12485: Puts plot definition data into the users environment in order for 
12486: graph.png to plot it.  Returns an <img> tag for the plot.
12487: 
12488: Inputs:
12489: 
12490: =over 4
12491: 
12492: =item $Title: string, the title of the plot
12493: 
12494: =item $xlabel: string, text describing the X-axis of the plot
12495: 
12496: =item $ylabel: string, text describing the Y-axis of the plot
12497: 
12498: =item $colors: Array ref containing the hex color codes for the data to be 
12499: plotted in.  If undefined, default values will be used.
12500: 
12501: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12502: 
12503: =item $Ydata1: The first data set
12504: 
12505: =item $Min1: The minimum value of the left Y-axis
12506: 
12507: =item $Max1: The maximum value of the left Y-axis
12508: 
12509: =item $Ydata2: The second data set
12510: 
12511: =item $Min2: The minimum value of the right Y-axis
12512: 
12513: =item $Max2: The maximum value of the left Y-axis
12514: 
12515: =item %Values: hash indicating or overriding any default values which are 
12516: passed to graph.png.  
12517: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12518: 
12519: =back
12520: 
12521: Returns:
12522: 
12523: An <img> tag which references graph.png and the appropriate identifying
12524: information for the plot.
12525: 
12526: =cut
12527: 
12528: ############################################################
12529: ############################################################
12530: sub DrawXYYGraph {
12531:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12532:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12533:     #
12534:     # Create the identifier for the graph
12535:     my $identifier = &get_cgi_id();
12536:     my $id = 'cgi.'.$identifier;
12537:     #
12538:     $Title  = '' if (! defined($Title));
12539:     $xlabel = '' if (! defined($xlabel));
12540:     $ylabel = '' if (! defined($ylabel));
12541:     my %ValuesHash = 
12542:         (
12543:          $id.'.title'  => &escape($Title),
12544:          $id.'.xlabel' => &escape($xlabel),
12545:          $id.'.ylabel' => &escape($ylabel),
12546:          $id.'.labels' => join(',',@$Xlabels),
12547:          $id.'.PlotType' => 'XY',
12548:          $id.'.NumSets' => 2,
12549:          $id.'.two_axes' => 1,
12550:          $id.'.y1_max_value' => $Max1,
12551:          $id.'.y1_min_value' => $Min1,
12552:          $id.'.y2_max_value' => $Max2,
12553:          $id.'.y2_min_value' => $Min2,
12554:          );
12555:     #
12556:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12557:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12558:     }
12559:     #
12560:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12561:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12562:         return '';
12563:     }
12564:     my $NumSets=1;
12565:     foreach my $array ($Ydata1,$Ydata2){
12566:         next if (! ref($array));
12567:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12568:     }
12569:     #
12570:     # Deal with other parameters
12571:     while (my ($key,$value) = each(%Values)) {
12572:         $ValuesHash{$id.'.'.$key} = $value;
12573:     }
12574:     #
12575:     &Apache::lonnet::appenv(\%ValuesHash);
12576:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12577: }
12578: 
12579: ############################################################
12580: ############################################################
12581: 
12582: =pod
12583: 
12584: =back 
12585: 
12586: =head1 Statistics helper routines?  
12587: 
12588: Bad place for them but what the hell.
12589: 
12590: =over 4
12591: 
12592: =item * &chartlink()
12593: 
12594: Returns a link to the chart for a specific student.  
12595: 
12596: Inputs:
12597: 
12598: =over 4
12599: 
12600: =item $linktext: The text of the link
12601: 
12602: =item $sname: The students username
12603: 
12604: =item $sdomain: The students domain
12605: 
12606: =back
12607: 
12608: =back
12609: 
12610: =cut
12611: 
12612: ############################################################
12613: ############################################################
12614: sub chartlink {
12615:     my ($linktext, $sname, $sdomain) = @_;
12616:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12617:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
12618:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
12619:        '">'.$linktext.'</a>';
12620: }
12621: 
12622: #######################################################
12623: #######################################################
12624: 
12625: =pod
12626: 
12627: =head1 Course Environment Routines
12628: 
12629: =over 4
12630: 
12631: =item * &restore_course_settings()
12632: 
12633: =item * &store_course_settings()
12634: 
12635: Restores/Store indicated form parameters from the course environment.
12636: Will not overwrite existing values of the form parameters.
12637: 
12638: Inputs: 
12639: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12640: 
12641: a hash ref describing the data to be stored.  For example:
12642:    
12643: %Save_Parameters = ('Status' => 'scalar',
12644:     'chartoutputmode' => 'scalar',
12645:     'chartoutputdata' => 'scalar',
12646:     'Section' => 'array',
12647:     'Group' => 'array',
12648:     'StudentData' => 'array',
12649:     'Maps' => 'array');
12650: 
12651: Returns: both routines return nothing
12652: 
12653: =back
12654: 
12655: =cut
12656: 
12657: #######################################################
12658: #######################################################
12659: sub store_course_settings {
12660:     return &store_settings($env{'request.course.id'},@_);
12661: }
12662: 
12663: sub store_settings {
12664:     # save to the environment
12665:     # appenv the same items, just to be safe
12666:     my $udom  = $env{'user.domain'};
12667:     my $uname = $env{'user.name'};
12668:     my ($context,$prefix,$Settings) = @_;
12669:     my %SaveHash;
12670:     my %AppHash;
12671:     while (my ($setting,$type) = each(%$Settings)) {
12672:         my $basename = join('.','internal',$context,$prefix,$setting);
12673:         my $envname = 'environment.'.$basename;
12674:         if (exists($env{'form.'.$setting})) {
12675:             # Save this value away
12676:             if ($type eq 'scalar' &&
12677:                 (! exists($env{$envname}) || 
12678:                  $env{$envname} ne $env{'form.'.$setting})) {
12679:                 $SaveHash{$basename} = $env{'form.'.$setting};
12680:                 $AppHash{$envname}   = $env{'form.'.$setting};
12681:             } elsif ($type eq 'array') {
12682:                 my $stored_form;
12683:                 if (ref($env{'form.'.$setting})) {
12684:                     $stored_form = join(',',
12685:                                         map {
12686:                                             &escape($_);
12687:                                         } sort(@{$env{'form.'.$setting}}));
12688:                 } else {
12689:                     $stored_form = 
12690:                         &escape($env{'form.'.$setting});
12691:                 }
12692:                 # Determine if the array contents are the same.
12693:                 if ($stored_form ne $env{$envname}) {
12694:                     $SaveHash{$basename} = $stored_form;
12695:                     $AppHash{$envname}   = $stored_form;
12696:                 }
12697:             }
12698:         }
12699:     }
12700:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12701:                                           $udom,$uname);
12702:     if ($put_result !~ /^(ok|delayed)/) {
12703:         &Apache::lonnet::logthis('unable to save form parameters, '.
12704:                                  'got error:'.$put_result);
12705:     }
12706:     # Make sure these settings stick around in this session, too
12707:     &Apache::lonnet::appenv(\%AppHash);
12708:     return;
12709: }
12710: 
12711: sub restore_course_settings {
12712:     return &restore_settings($env{'request.course.id'},@_);
12713: }
12714: 
12715: sub restore_settings {
12716:     my ($context,$prefix,$Settings) = @_;
12717:     while (my ($setting,$type) = each(%$Settings)) {
12718:         next if (exists($env{'form.'.$setting}));
12719:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
12720:             '.'.$setting;
12721:         if (exists($env{$envname})) {
12722:             if ($type eq 'scalar') {
12723:                 $env{'form.'.$setting} = $env{$envname};
12724:             } elsif ($type eq 'array') {
12725:                 $env{'form.'.$setting} = [ 
12726:                                            map { 
12727:                                                &unescape($_); 
12728:                                            } split(',',$env{$envname})
12729:                                            ];
12730:             }
12731:         }
12732:     }
12733: }
12734: 
12735: #######################################################
12736: #######################################################
12737: 
12738: =pod
12739: 
12740: =head1 Domain E-mail Routines  
12741: 
12742: =over 4
12743: 
12744: =item * &build_recipient_list()
12745: 
12746: Build recipient lists for five types of e-mail:
12747: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12748: (d) Help requests, (e) Course requests needing approval,  generated by
12749: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12750: loncoursequeueadmin.pm respectively.
12751: 
12752: Inputs:
12753: defmail (scalar - email address of default recipient), 
12754: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
12755: defdom (domain for which to retrieve configuration settings),
12756: origmail (scalar - email address of recipient from loncapa.conf, 
12757: i.e., predates configuration by DC via domainprefs.pm 
12758: 
12759: Returns: comma separated list of addresses to which to send e-mail.
12760: 
12761: =back
12762: 
12763: =cut
12764: 
12765: ############################################################
12766: ############################################################
12767: sub build_recipient_list {
12768:     my ($defmail,$mailing,$defdom,$origmail) = @_;
12769:     my @recipients;
12770:     my $otheremails;
12771:     my %domconfig =
12772:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12773:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12774:         if (exists($domconfig{'contacts'}{$mailing})) {
12775:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12776:                 my @contacts = ('adminemail','supportemail');
12777:                 foreach my $item (@contacts) {
12778:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
12779:                         my $addr = $domconfig{'contacts'}{$item}; 
12780:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
12781:                             push(@recipients,$addr);
12782:                         }
12783:                     }
12784:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12785:                 }
12786:             }
12787:         } elsif ($origmail ne '') {
12788:             push(@recipients,$origmail);
12789:         }
12790:     } elsif ($origmail ne '') {
12791:         push(@recipients,$origmail);
12792:     }
12793:     if (defined($defmail)) {
12794:         if ($defmail ne '') {
12795:             push(@recipients,$defmail);
12796:         }
12797:     }
12798:     if ($otheremails) {
12799:         my @others;
12800:         if ($otheremails =~ /,/) {
12801:             @others = split(/,/,$otheremails);
12802:         } else {
12803:             push(@others,$otheremails);
12804:         }
12805:         foreach my $addr (@others) {
12806:             if (!grep(/^\Q$addr\E$/,@recipients)) {
12807:                 push(@recipients,$addr);
12808:             }
12809:         }
12810:     }
12811:     my $recipientlist = join(',',@recipients); 
12812:     return $recipientlist;
12813: }
12814: 
12815: ############################################################
12816: ############################################################
12817: 
12818: =pod
12819: 
12820: =head1 Course Catalog Routines
12821: 
12822: =over 4
12823: 
12824: =item * &gather_categories()
12825: 
12826: Converts category definitions - keys of categories hash stored in  
12827: coursecategories in configuration.db on the primary library server in a 
12828: domain - to an array.  Also generates javascript and idx hash used to 
12829: generate Domain Coordinator interface for editing Course Categories.
12830: 
12831: Inputs:
12832: 
12833: categories (reference to hash of category definitions).
12834: 
12835: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12836:       categories and subcategories).
12837: 
12838: idx (reference to hash of counters used in Domain Coordinator interface for 
12839:       editing Course Categories).
12840: 
12841: jsarray (reference to array of categories used to create Javascript arrays for
12842:          Domain Coordinator interface for editing Course Categories).
12843: 
12844: Returns: nothing
12845: 
12846: Side effects: populates cats, idx and jsarray. 
12847: 
12848: =cut
12849: 
12850: sub gather_categories {
12851:     my ($categories,$cats,$idx,$jsarray) = @_;
12852:     my %counters;
12853:     my $num = 0;
12854:     foreach my $item (keys(%{$categories})) {
12855:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12856:         if ($container eq '' && $depth == 0) {
12857:             $cats->[$depth][$categories->{$item}] = $cat;
12858:         } else {
12859:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12860:         }
12861:         my ($escitem,$tail) = split(/:/,$item,2);
12862:         if ($counters{$tail} eq '') {
12863:             $counters{$tail} = $num;
12864:             $num ++;
12865:         }
12866:         if (ref($idx) eq 'HASH') {
12867:             $idx->{$item} = $counters{$tail};
12868:         }
12869:         if (ref($jsarray) eq 'ARRAY') {
12870:             push(@{$jsarray->[$counters{$tail}]},$item);
12871:         }
12872:     }
12873:     return;
12874: }
12875: 
12876: =pod
12877: 
12878: =item * &extract_categories()
12879: 
12880: Used to generate breadcrumb trails for course categories.
12881: 
12882: Inputs:
12883: 
12884: categories (reference to hash of category definitions).
12885: 
12886: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12887:       categories and subcategories).
12888: 
12889: trails (reference to array of breacrumb trails for each category).
12890: 
12891: allitems (reference to hash - key is category key 
12892:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12893: 
12894: idx (reference to hash of counters used in Domain Coordinator interface for
12895:       editing Course Categories).
12896: 
12897: jsarray (reference to array of categories used to create Javascript arrays for
12898:          Domain Coordinator interface for editing Course Categories).
12899: 
12900: subcats (reference to hash of arrays containing all subcategories within each 
12901:          category, -recursive)
12902: 
12903: Returns: nothing
12904: 
12905: Side effects: populates trails and allitems hash references.
12906: 
12907: =cut
12908: 
12909: sub extract_categories {
12910:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12911:     if (ref($categories) eq 'HASH') {
12912:         &gather_categories($categories,$cats,$idx,$jsarray);
12913:         if (ref($cats->[0]) eq 'ARRAY') {
12914:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
12915:                 my $name = $cats->[0][$i];
12916:                 my $item = &escape($name).'::0';
12917:                 my $trailstr;
12918:                 if ($name eq 'instcode') {
12919:                     $trailstr = &mt('Official courses (with institutional codes)');
12920:                 } elsif ($name eq 'communities') {
12921:                     $trailstr = &mt('Communities');
12922:                 } else {
12923:                     $trailstr = $name;
12924:                 }
12925:                 if ($allitems->{$item} eq '') {
12926:                     push(@{$trails},$trailstr);
12927:                     $allitems->{$item} = scalar(@{$trails})-1;
12928:                 }
12929:                 my @parents = ($name);
12930:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
12931:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12932:                         my $category = $cats->[1]{$name}[$j];
12933:                         if (ref($subcats) eq 'HASH') {
12934:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12935:                         }
12936:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12937:                     }
12938:                 } else {
12939:                     if (ref($subcats) eq 'HASH') {
12940:                         $subcats->{$item} = [];
12941:                     }
12942:                 }
12943:             }
12944:         }
12945:     }
12946:     return;
12947: }
12948: 
12949: =pod
12950: 
12951: =item *&recurse_categories()
12952: 
12953: Recursively used to generate breadcrumb trails for course categories.
12954: 
12955: Inputs:
12956: 
12957: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12958:       categories and subcategories).
12959: 
12960: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12961: 
12962: category (current course category, for which breadcrumb trail is being generated).
12963: 
12964: trails (reference to array of breadcrumb trails for each category).
12965: 
12966: allitems (reference to hash - key is category key
12967:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12968: 
12969: parents (array containing containers directories for current category, 
12970:          back to top level). 
12971: 
12972: Returns: nothing
12973: 
12974: Side effects: populates trails and allitems hash references
12975: 
12976: =cut
12977: 
12978: sub recurse_categories {
12979:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12980:     my $shallower = $depth - 1;
12981:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12982:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12983:             my $name = $cats->[$depth]{$category}[$k];
12984:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12985:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
12986:             if ($allitems->{$item} eq '') {
12987:                 push(@{$trails},$trailstr);
12988:                 $allitems->{$item} = scalar(@{$trails})-1;
12989:             }
12990:             my $deeper = $depth+1;
12991:             push(@{$parents},$category);
12992:             if (ref($subcats) eq 'HASH') {
12993:                 my $subcat = &escape($name).':'.$category.':'.$depth;
12994:                 for (my $j=@{$parents}; $j>=0; $j--) {
12995:                     my $higher;
12996:                     if ($j > 0) {
12997:                         $higher = &escape($parents->[$j]).':'.
12998:                                   &escape($parents->[$j-1]).':'.$j;
12999:                     } else {
13000:                         $higher = &escape($parents->[$j]).'::'.$j;
13001:                     }
13002:                     push(@{$subcats->{$higher}},$subcat);
13003:                 }
13004:             }
13005:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13006:                                 $subcats);
13007:             pop(@{$parents});
13008:         }
13009:     } else {
13010:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13011:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13012:         if ($allitems->{$item} eq '') {
13013:             push(@{$trails},$trailstr);
13014:             $allitems->{$item} = scalar(@{$trails})-1;
13015:         }
13016:     }
13017:     return;
13018: }
13019: 
13020: =pod
13021: 
13022: =item *&assign_categories_table()
13023: 
13024: Create a datatable for display of hierarchical categories in a domain,
13025: with checkboxes to allow a course to be categorized. 
13026: 
13027: Inputs:
13028: 
13029: cathash - reference to hash of categories defined for the domain (from
13030:           configuration.db)
13031: 
13032: currcat - scalar with an & separated list of categories assigned to a course. 
13033: 
13034: type    - scalar contains course type (Course or Community).
13035: 
13036: Returns: $output (markup to be displayed) 
13037: 
13038: =cut
13039: 
13040: sub assign_categories_table {
13041:     my ($cathash,$currcat,$type) = @_;
13042:     my $output;
13043:     if (ref($cathash) eq 'HASH') {
13044:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13045:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13046:         $maxdepth = scalar(@cats);
13047:         if (@cats > 0) {
13048:             my $itemcount = 0;
13049:             if (ref($cats[0]) eq 'ARRAY') {
13050:                 my @currcategories;
13051:                 if ($currcat ne '') {
13052:                     @currcategories = split('&',$currcat);
13053:                 }
13054:                 my $table;
13055:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13056:                     my $parent = $cats[0][$i];
13057:                     next if ($parent eq 'instcode');
13058:                     if ($type eq 'Community') {
13059:                         next unless ($parent eq 'communities');
13060:                     } else {
13061:                         next if ($parent eq 'communities');
13062:                     }
13063:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13064:                     my $item = &escape($parent).'::0';
13065:                     my $checked = '';
13066:                     if (@currcategories > 0) {
13067:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13068:                             $checked = ' checked="checked"';
13069:                         }
13070:                     }
13071:                     my $parent_title = $parent;
13072:                     if ($parent eq 'communities') {
13073:                         $parent_title = &mt('Communities');
13074:                     }
13075:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13076:                               '<input type="checkbox" name="usecategory" value="'.
13077:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13078:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13079:                     my $depth = 1;
13080:                     push(@path,$parent);
13081:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13082:                     pop(@path);
13083:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13084:                     $itemcount ++;
13085:                 }
13086:                 if ($itemcount) {
13087:                     $output = &Apache::loncommon::start_data_table().
13088:                               $table.
13089:                               &Apache::loncommon::end_data_table();
13090:                 }
13091:             }
13092:         }
13093:     }
13094:     return $output;
13095: }
13096: 
13097: =pod
13098: 
13099: =item *&assign_category_rows()
13100: 
13101: Create a datatable row for display of nested categories in a domain,
13102: with checkboxes to allow a course to be categorized,called recursively.
13103: 
13104: Inputs:
13105: 
13106: itemcount - track row number for alternating colors
13107: 
13108: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13109:       categories and subcategories.
13110: 
13111: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13112: 
13113: parent - parent of current category item
13114: 
13115: path - Array containing all categories back up through the hierarchy from the
13116:        current category to the top level.
13117: 
13118: currcategories - reference to array of current categories assigned to the course
13119: 
13120: Returns: $output (markup to be displayed).
13121: 
13122: =cut
13123: 
13124: sub assign_category_rows {
13125:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13126:     my ($text,$name,$item,$chgstr);
13127:     if (ref($cats) eq 'ARRAY') {
13128:         my $maxdepth = scalar(@{$cats});
13129:         if (ref($cats->[$depth]) eq 'HASH') {
13130:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13131:                 my $numchildren = @{$cats->[$depth]{$parent}};
13132:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13133:                 $text .= '<td><table class="LC_datatable">';
13134:                 for (my $j=0; $j<$numchildren; $j++) {
13135:                     $name = $cats->[$depth]{$parent}[$j];
13136:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13137:                     my $deeper = $depth+1;
13138:                     my $checked = '';
13139:                     if (ref($currcategories) eq 'ARRAY') {
13140:                         if (@{$currcategories} > 0) {
13141:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13142:                                 $checked = ' checked="checked"';
13143:                             }
13144:                         }
13145:                     }
13146:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13147:                              '<input type="checkbox" name="usecategory" value="'.
13148:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13149:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13150:                              '</td><td>';
13151:                     if (ref($path) eq 'ARRAY') {
13152:                         push(@{$path},$name);
13153:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13154:                         pop(@{$path});
13155:                     }
13156:                     $text .= '</td></tr>';
13157:                 }
13158:                 $text .= '</table></td>';
13159:             }
13160:         }
13161:     }
13162:     return $text;
13163: }
13164: 
13165: ############################################################
13166: ############################################################
13167: 
13168: 
13169: sub commit_customrole {
13170:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13171:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13172:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13173:                          ($end?', ending '.localtime($end):'').': <b>'.
13174:               &Apache::lonnet::assigncustomrole(
13175:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13176:                  '</b><br />';
13177:     return $output;
13178: }
13179: 
13180: sub commit_standardrole {
13181:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13182:     my ($output,$logmsg,$linefeed);
13183:     if ($context eq 'auto') {
13184:         $linefeed = "\n";
13185:     } else {
13186:         $linefeed = "<br />\n";
13187:     }  
13188:     if ($three eq 'st') {
13189:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13190:                                          $one,$two,$sec,$context,$credits);
13191:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13192:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13193:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13194:         } else {
13195:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13196:                ($start?', '.&mt('starting').' '.localtime($start):'').
13197:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13198:             if ($context eq 'auto') {
13199:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13200:             } else {
13201:                $output .= '<b>'.$result.'</b>'.$linefeed.
13202:                &mt('Add to classlist').': <b>ok</b>';
13203:             }
13204:             $output .= $linefeed;
13205:         }
13206:     } else {
13207:         $output = &mt('Assigning').' '.$three.' in '.$url.
13208:                ($start?', '.&mt('starting').' '.localtime($start):'').
13209:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13210:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13211:         if ($context eq 'auto') {
13212:             $output .= $result.$linefeed;
13213:         } else {
13214:             $output .= '<b>'.$result.'</b>'.$linefeed;
13215:         }
13216:     }
13217:     return $output;
13218: }
13219: 
13220: sub commit_studentrole {
13221:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13222:         $credits) = @_;
13223:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13224:     if ($context eq 'auto') {
13225:         $linefeed = "\n";
13226:     } else {
13227:         $linefeed = '<br />'."\n";
13228:     }
13229:     if (defined($one) && defined($two)) {
13230:         my $cid=$one.'_'.$two;
13231:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13232:         my $secchange = 0;
13233:         my $expire_role_result;
13234:         my $modify_section_result;
13235:         if ($oldsec ne '-1') { 
13236:             if ($oldsec ne $sec) {
13237:                 $secchange = 1;
13238:                 my $now = time;
13239:                 my $uurl='/'.$cid;
13240:                 $uurl=~s/\_/\//g;
13241:                 if ($oldsec) {
13242:                     $uurl.='/'.$oldsec;
13243:                 }
13244:                 $oldsecurl = $uurl;
13245:                 $expire_role_result = 
13246:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13247:                 if ($env{'request.course.sec'} ne '') { 
13248:                     if ($expire_role_result eq 'refused') {
13249:                         my @roles = ('st');
13250:                         my @statuses = ('previous');
13251:                         my @roledoms = ($one);
13252:                         my $withsec = 1;
13253:                         my %roleshash = 
13254:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13255:                                               \@statuses,\@roles,\@roledoms,$withsec);
13256:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13257:                             my ($oldstart,$oldend) = 
13258:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13259:                             if ($oldend > 0 && $oldend <= $now) {
13260:                                 $expire_role_result = 'ok';
13261:                             }
13262:                         }
13263:                     }
13264:                 }
13265:                 $result = $expire_role_result;
13266:             }
13267:         }
13268:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13269:             $modify_section_result = 
13270:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13271:                                                            undef,undef,undef,$sec,
13272:                                                            $end,$start,'','',$cid,
13273:                                                            '',$context,$credits);
13274:             if ($modify_section_result =~ /^ok/) {
13275:                 if ($secchange == 1) {
13276:                     if ($sec eq '') {
13277:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13278:                     } else {
13279:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13280:                     }
13281:                 } elsif ($oldsec eq '-1') {
13282:                     if ($sec eq '') {
13283:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13284:                     } else {
13285:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13286:                     }
13287:                 } else {
13288:                     if ($sec eq '') {
13289:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13290:                     } else {
13291:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13292:                     }
13293:                 }
13294:             } else {
13295:                 if ($secchange) {       
13296:                     $$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;
13297:                 } else {
13298:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13299:                 }
13300:             }
13301:             $result = $modify_section_result;
13302:         } elsif ($secchange == 1) {
13303:             if ($oldsec eq '') {
13304:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13305:             } else {
13306:                 $$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;
13307:             }
13308:             if ($expire_role_result eq 'refused') {
13309:                 my $newsecurl = '/'.$cid;
13310:                 $newsecurl =~ s/\_/\//g;
13311:                 if ($sec ne '') {
13312:                     $newsecurl.='/'.$sec;
13313:                 }
13314:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13315:                     if ($sec eq '') {
13316:                         $$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;
13317:                     } else {
13318:                         $$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;
13319:                     }
13320:                 }
13321:             }
13322:         }
13323:     } else {
13324:         $$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;
13325:         $result = "error: incomplete course id\n";
13326:     }
13327:     return $result;
13328: }
13329: 
13330: sub show_role_extent {
13331:     my ($scope,$context,$role) = @_;
13332:     $scope =~ s{^/}{};
13333:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13334:     push(@courseroles,'co');
13335:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13336:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13337:         $scope =~ s{/}{_};
13338:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13339:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13340:         my ($audom,$auname) = split(/\//,$scope);
13341:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13342:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13343:     } else {
13344:         $scope =~ s{/$}{};
13345:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13346:                    &Apache::lonnet::domain($scope,'description').'</span>');
13347:     }
13348: }
13349: 
13350: ############################################################
13351: ############################################################
13352: 
13353: sub check_clone {
13354:     my ($args,$linefeed) = @_;
13355:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13356:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13357:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13358:     my $clonemsg;
13359:     my $can_clone = 0;
13360:     my $lctype = lc($args->{'crstype'});
13361:     if ($lctype ne 'community') {
13362:         $lctype = 'course';
13363:     }
13364:     if ($clonehome eq 'no_host') {
13365:         if ($args->{'crstype'} eq 'Community') {
13366:             $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'});
13367:         } else {
13368:             $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'});
13369:         }     
13370:     } else {
13371: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13372:         if ($args->{'crstype'} eq 'Community') {
13373:             if ($clonedesc{'type'} ne 'Community') {
13374:                  $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'});
13375:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13376:             }
13377:         }
13378: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13379:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13380: 	    $can_clone = 1;
13381: 	} else {
13382: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13383: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13384: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13385:             if (grep(/^\*$/,@cloners)) {
13386:                 $can_clone = 1;
13387:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13388:                 $can_clone = 1;
13389:             } else {
13390:                 my $ccrole = 'cc';
13391:                 if ($args->{'crstype'} eq 'Community') {
13392:                     $ccrole = 'co';
13393:                 }
13394: 	        my %roleshash =
13395: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13396: 					 $args->{'ccdomain'},
13397:                                          'userroles',['active'],[$ccrole],
13398: 					 [$args->{'clonedomain'}]);
13399: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13400:                     $can_clone = 1;
13401:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13402:                     $can_clone = 1;
13403:                 } else {
13404:                     if ($args->{'crstype'} eq 'Community') {
13405:                         $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'});
13406:                     } else {
13407:                         $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'});
13408:                     }
13409: 	        }
13410: 	    }
13411:         }
13412:     }
13413:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13414: }
13415: 
13416: sub construct_course {
13417:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13418:     my $outcome;
13419:     my $linefeed =  '<br />'."\n";
13420:     if ($context eq 'auto') {
13421:         $linefeed = "\n";
13422:     }
13423: 
13424: #
13425: # Are we cloning?
13426: #
13427:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13428:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13429: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13430: 	if ($context ne 'auto') {
13431:             if ($clonemsg ne '') {
13432: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13433:             }
13434: 	}
13435: 	$outcome .= $clonemsg.$linefeed;
13436: 
13437:         if (!$can_clone) {
13438: 	    return (0,$outcome);
13439: 	}
13440:     }
13441: 
13442: #
13443: # Open course
13444: #
13445:     my $crstype = lc($args->{'crstype'});
13446:     my %cenv=();
13447:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13448:                                              $args->{'cdescr'},
13449:                                              $args->{'curl'},
13450:                                              $args->{'course_home'},
13451:                                              $args->{'nonstandard'},
13452:                                              $args->{'crscode'},
13453:                                              $args->{'ccuname'}.':'.
13454:                                              $args->{'ccdomain'},
13455:                                              $args->{'crstype'},
13456:                                              $cnum,$context,$category);
13457: 
13458:     # Note: The testing routines depend on this being output; see 
13459:     # Utils::Course. This needs to at least be output as a comment
13460:     # if anyone ever decides to not show this, and Utils::Course::new
13461:     # will need to be suitably modified.
13462:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13463:     if ($$courseid =~ /^error:/) {
13464:         return (0,$outcome);
13465:     }
13466: 
13467: #
13468: # Check if created correctly
13469: #
13470:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13471:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13472:     if ($crsuhome eq 'no_host') {
13473:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13474:         return (0,$outcome);
13475:     }
13476:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13477: 
13478: #
13479: # Do the cloning
13480: #   
13481:     if ($can_clone && $cloneid) {
13482: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13483: 	if ($context ne 'auto') {
13484: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13485: 	}
13486: 	$outcome .= $clonemsg.$linefeed;
13487: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13488: # Copy all files
13489: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13490: # Restore URL
13491: 	$cenv{'url'}=$oldcenv{'url'};
13492: # Restore title
13493: 	$cenv{'description'}=$oldcenv{'description'};
13494: # Restore creation date, creator and creation context.
13495:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13496:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13497:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13498: # Mark as cloned
13499: 	$cenv{'clonedfrom'}=$cloneid;
13500: # Need to clone grading mode
13501:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13502:         $cenv{'grading'}=$newenv{'grading'};
13503: # Do not clone these environment entries
13504:         &Apache::lonnet::del('environment',
13505:                   ['default_enrollment_start_date',
13506:                    'default_enrollment_end_date',
13507:                    'question.email',
13508:                    'policy.email',
13509:                    'comment.email',
13510:                    'pch.users.denied',
13511:                    'plc.users.denied',
13512:                    'hidefromcat',
13513:                    'categories'],
13514:                    $$crsudom,$$crsunum);
13515:     }
13516: 
13517: #
13518: # Set environment (will override cloned, if existing)
13519: #
13520:     my @sections = ();
13521:     my @xlists = ();
13522:     if ($args->{'crstype'}) {
13523:         $cenv{'type'}=$args->{'crstype'};
13524:     }
13525:     if ($args->{'crsid'}) {
13526:         $cenv{'courseid'}=$args->{'crsid'};
13527:     }
13528:     if ($args->{'crscode'}) {
13529:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13530:     }
13531:     if ($args->{'crsquota'} ne '') {
13532:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13533:     } else {
13534:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13535:     }
13536:     if ($args->{'ccuname'}) {
13537:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13538:                                         ':'.$args->{'ccdomain'};
13539:     } else {
13540:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13541:     }
13542:     if ($args->{'defaultcredits'}) {
13543:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
13544:     }
13545:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13546:     if ($args->{'crssections'}) {
13547:         $cenv{'internal.sectionnums'} = '';
13548:         if ($args->{'crssections'} =~ m/,/) {
13549:             @sections = split/,/,$args->{'crssections'};
13550:         } else {
13551:             $sections[0] = $args->{'crssections'};
13552:         }
13553:         if (@sections > 0) {
13554:             foreach my $item (@sections) {
13555:                 my ($sec,$gp) = split/:/,$item;
13556:                 my $class = $args->{'crscode'}.$sec;
13557:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13558:                 $cenv{'internal.sectionnums'} .= $item.',';
13559:                 unless ($addcheck eq 'ok') {
13560:                     push @badclasses, $class;
13561:                 }
13562:             }
13563:             $cenv{'internal.sectionnums'} =~ s/,$//;
13564:         }
13565:     }
13566: # do not hide course coordinator from staff listing, 
13567: # even if privileged
13568:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13569: # add crosslistings
13570:     if ($args->{'crsxlist'}) {
13571:         $cenv{'internal.crosslistings'}='';
13572:         if ($args->{'crsxlist'} =~ m/,/) {
13573:             @xlists = split/,/,$args->{'crsxlist'};
13574:         } else {
13575:             $xlists[0] = $args->{'crsxlist'};
13576:         }
13577:         if (@xlists > 0) {
13578:             foreach my $item (@xlists) {
13579:                 my ($xl,$gp) = split/:/,$item;
13580:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13581:                 $cenv{'internal.crosslistings'} .= $item.',';
13582:                 unless ($addcheck eq 'ok') {
13583:                     push @badclasses, $xl;
13584:                 }
13585:             }
13586:             $cenv{'internal.crosslistings'} =~ s/,$//;
13587:         }
13588:     }
13589:     if ($args->{'autoadds'}) {
13590:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
13591:     }
13592:     if ($args->{'autodrops'}) {
13593:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
13594:     }
13595: # check for notification of enrollment changes
13596:     my @notified = ();
13597:     if ($args->{'notify_owner'}) {
13598:         if ($args->{'ccuname'} ne '') {
13599:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13600:         }
13601:     }
13602:     if ($args->{'notify_dc'}) {
13603:         if ($uname ne '') { 
13604:             push(@notified,$uname.':'.$udom);
13605:         }
13606:     }
13607:     if (@notified > 0) {
13608:         my $notifylist;
13609:         if (@notified > 1) {
13610:             $notifylist = join(',',@notified);
13611:         } else {
13612:             $notifylist = $notified[0];
13613:         }
13614:         $cenv{'internal.notifylist'} = $notifylist;
13615:     }
13616:     if (@badclasses > 0) {
13617:         my %lt=&Apache::lonlocal::texthash(
13618:                 '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',
13619:                 'dnhr' => 'does not have rights to access enrollment in these classes',
13620:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
13621:         );
13622:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13623:                            ' ('.$lt{'adby'}.')';
13624:         if ($context eq 'auto') {
13625:             $outcome .= $badclass_msg.$linefeed;
13626:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13627:             foreach my $item (@badclasses) {
13628:                 if ($context eq 'auto') {
13629:                     $outcome .= " - $item\n";
13630:                 } else {
13631:                     $outcome .= "<li>$item</li>\n";
13632:                 }
13633:             }
13634:             if ($context eq 'auto') {
13635:                 $outcome .= $linefeed;
13636:             } else {
13637:                 $outcome .= "</ul><br /><br /></div>\n";
13638:             }
13639:         } 
13640:     }
13641:     if ($args->{'no_end_date'}) {
13642:         $args->{'endaccess'} = 0;
13643:     }
13644:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
13645:     $cenv{'internal.autoend'}=$args->{'enrollend'};
13646:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13647:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13648:     if ($args->{'showphotos'}) {
13649:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
13650:     }
13651:     $cenv{'internal.authtype'} = $args->{'authtype'};
13652:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
13653:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13654:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
13655:             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'); 
13656:             if ($context eq 'auto') {
13657:                 $outcome .= $krb_msg;
13658:             } else {
13659:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13660:             }
13661:             $outcome .= $linefeed;
13662:         }
13663:     }
13664:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13665:        if ($args->{'setpolicy'}) {
13666:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13667:        }
13668:        if ($args->{'setcontent'}) {
13669:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13670:        }
13671:     }
13672:     if ($args->{'reshome'}) {
13673: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
13674: 	$cenv{'reshome'}=~s/\/+$/\//;
13675:     }
13676: #
13677: # course has keyed access
13678: #
13679:     if ($args->{'setkeys'}) {
13680:        $cenv{'keyaccess'}='yes';
13681:     }
13682: # if specified, key authority is not course, but user
13683: # only active if keyaccess is yes
13684:     if ($args->{'keyauth'}) {
13685: 	my ($user,$domain) = split(':',$args->{'keyauth'});
13686: 	$user = &LONCAPA::clean_username($user);
13687: 	$domain = &LONCAPA::clean_username($domain);
13688: 	if ($user ne '' && $domain ne '') {
13689: 	    $cenv{'keyauth'}=$user.':'.$domain;
13690: 	}
13691:     }
13692: 
13693:     if ($args->{'disresdis'}) {
13694:         $cenv{'pch.roles.denied'}='st';
13695:     }
13696:     if ($args->{'disablechat'}) {
13697:         $cenv{'plc.roles.denied'}='st';
13698:     }
13699: 
13700:     # Record we've not yet viewed the Course Initialization Helper for this 
13701:     # course
13702:     $cenv{'course.helper.not.run'} = 1;
13703:     #
13704:     # Use new Randomseed
13705:     #
13706:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13707:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13708:     #
13709:     # The encryption code and receipt prefix for this course
13710:     #
13711:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13712:     $cenv{'internal.encpref'}=100+int(9*rand(99));
13713:     #
13714:     # By default, use standard grading
13715:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13716: 
13717:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
13718:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13719: #
13720: # Open all assignments
13721: #
13722:     if ($args->{'openall'}) {
13723:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13724:        my %storecontent = ($storeunder         => time,
13725:                            $storeunder.'.type' => 'date_start');
13726:        
13727:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13728:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13729:    }
13730: #
13731: # Set first page
13732: #
13733:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13734: 	    || ($cloneid)) {
13735: 	use LONCAPA::map;
13736: 	$outcome .= &mt('Setting first resource').': ';
13737: 
13738: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13739:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13740: 
13741:         $outcome .= ($fatal?$errtext:'read ok').' - ';
13742:         my $title; my $url;
13743:         if ($args->{'firstres'} eq 'syl') {
13744: 	    $title=&mt('Syllabus');
13745:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13746:         } else {
13747:             $title=&mt('Table of Contents');
13748:             $url='/adm/navmaps';
13749:         }
13750: 
13751:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13752: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13753: 
13754: 	if ($errtext) { $fatal=2; }
13755:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13756:     }
13757: 
13758:     return (1,$outcome);
13759: }
13760: 
13761: ############################################################
13762: ############################################################
13763: 
13764: #SD
13765: # only Community and Course, or anything else?
13766: sub course_type {
13767:     my ($cid) = @_;
13768:     if (!defined($cid)) {
13769:         $cid = $env{'request.course.id'};
13770:     }
13771:     if (defined($env{'course.'.$cid.'.type'})) {
13772:         return $env{'course.'.$cid.'.type'};
13773:     } else {
13774:         return 'Course';
13775:     }
13776: }
13777: 
13778: sub group_term {
13779:     my $crstype = &course_type();
13780:     my %names = (
13781:                   'Course' => 'group',
13782:                   'Community' => 'group',
13783:                 );
13784:     return $names{$crstype};
13785: }
13786: 
13787: sub course_types {
13788:     my @types = ('official','unofficial','community');
13789:     my %typename = (
13790:                          official   => 'Official course',
13791:                          unofficial => 'Unofficial course',
13792:                          community  => 'Community',
13793:                    );
13794:     return (\@types,\%typename);
13795: }
13796: 
13797: sub icon {
13798:     my ($file)=@_;
13799:     my $curfext = lc((split(/\./,$file))[-1]);
13800:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13801:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13802:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13803: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13804: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13805: 	            $curfext.".gif") {
13806: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13807: 		$curfext.".gif";
13808: 	}
13809:     }
13810:     return &lonhttpdurl($iconname);
13811: } 
13812: 
13813: sub lonhttpdurl {
13814: #
13815: # Had been used for "small fry" static images on separate port 8080.
13816: # Modify here if lightweight http functionality desired again.
13817: # Currently eliminated due to increasing firewall issues.
13818: #
13819:     my ($url)=@_;
13820:     return $url;
13821: }
13822: 
13823: sub connection_aborted {
13824:     my ($r)=@_;
13825:     $r->print(" ");$r->rflush();
13826:     my $c = $r->connection;
13827:     return $c->aborted();
13828: }
13829: 
13830: #    Escapes strings that may have embedded 's that will be put into
13831: #    strings as 'strings'.
13832: sub escape_single {
13833:     my ($input) = @_;
13834:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
13835:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
13836:     return $input;
13837: }
13838: 
13839: #  Same as escape_single, but escape's "'s  This 
13840: #  can be used for  "strings"
13841: sub escape_double {
13842:     my ($input) = @_;
13843:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
13844:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
13845:     return $input;
13846: }
13847:  
13848: #   Escapes the last element of a full URL.
13849: sub escape_url {
13850:     my ($url)   = @_;
13851:     my @urlslices = split(/\//, $url,-1);
13852:     my $lastitem = &escape(pop(@urlslices));
13853:     return join('/',@urlslices).'/'.$lastitem;
13854: }
13855: 
13856: sub compare_arrays {
13857:     my ($arrayref1,$arrayref2) = @_;
13858:     my (@difference,%count);
13859:     @difference = ();
13860:     %count = ();
13861:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
13862:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
13863:         foreach my $element (keys(%count)) {
13864:             if ($count{$element} == 1) {
13865:                 push(@difference,$element);
13866:             }
13867:         }
13868:     }
13869:     return @difference;
13870: }
13871: 
13872: # -------------------------------------------------------- Initialize user login
13873: sub init_user_environment {
13874:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
13875:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13876: 
13877:     my $public=($username eq 'public' && $domain eq 'public');
13878: 
13879: # See if old ID present, if so, remove
13880: 
13881:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13882:     my $now=time;
13883: 
13884:     if ($public) {
13885: 	my $max_public=100;
13886: 	my $oldest;
13887: 	my $oldest_time=0;
13888: 	for(my $next=1;$next<=$max_public;$next++) {
13889: 	    if (-e $lonids."/publicuser_$next.id") {
13890: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13891: 		if ($mtime<$oldest_time || !$oldest_time) {
13892: 		    $oldest_time=$mtime;
13893: 		    $oldest=$next;
13894: 		}
13895: 	    } else {
13896: 		$cookie="publicuser_$next";
13897: 		last;
13898: 	    }
13899: 	}
13900: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
13901:     } else {
13902: 	# if this isn't a robot, kill any existing non-robot sessions
13903: 	if (!$args->{'robot'}) {
13904: 	    opendir(DIR,$lonids);
13905: 	    while ($filename=readdir(DIR)) {
13906: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13907: 		    unlink($lonids.'/'.$filename);
13908: 		}
13909: 	    }
13910: 	    closedir(DIR);
13911: 	}
13912: # Give them a new cookie
13913: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13914: 		                   : $now.$$.int(rand(10000)));
13915: 	$cookie="$username\_$id\_$domain\_$authhost";
13916:     
13917: # Initialize roles
13918: 
13919: 	($userroles,$firstaccenv,$timerintenv) = 
13920:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
13921:     }
13922: # ------------------------------------ Check browser type and MathML capability
13923: 
13924:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13925:         $clientunicode,$clientos) = &decode_user_agent($r);
13926: 
13927: # ------------------------------------------------------------- Get environment
13928: 
13929:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13930:     my ($tmp) = keys(%userenv);
13931:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13932:     } else {
13933: 	undef(%userenv);
13934:     }
13935:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
13936: 	$form->{'interface'}=$userenv{'interface'};
13937:     }
13938:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13939: 
13940: # --------------- Do not trust query string to be put directly into environment
13941:     foreach my $option ('interface','localpath','localres') {
13942:         $form->{$option}=~s/[\n\r\=]//gs;
13943:     }
13944: # --------------------------------------------------------- Write first profile
13945: 
13946:     {
13947: 	my %initial_env = 
13948: 	    ("user.name"          => $username,
13949: 	     "user.domain"        => $domain,
13950: 	     "user.home"          => $authhost,
13951: 	     "browser.type"       => $clientbrowser,
13952: 	     "browser.version"    => $clientversion,
13953: 	     "browser.mathml"     => $clientmathml,
13954: 	     "browser.unicode"    => $clientunicode,
13955: 	     "browser.os"         => $clientos,
13956: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
13957: 	     "request.course.fn"  => '',
13958: 	     "request.course.uri" => '',
13959: 	     "request.course.sec" => '',
13960: 	     "request.role"       => 'cm',
13961: 	     "request.role.adv"   => $env{'user.adv'},
13962: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
13963: 
13964:         if ($form->{'localpath'}) {
13965: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
13966: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
13967:         }
13968: 	
13969: 	if ($form->{'interface'}) {
13970: 	    $form->{'interface'}=~s/\W//gs;
13971: 	    $initial_env{"browser.interface"} = $form->{'interface'};
13972: 	    $env{'browser.interface'}=$form->{'interface'};
13973: 	}
13974: 
13975:         my %is_adv = ( is_adv => $env{'user.adv'} );
13976:         my %domdef;
13977:         unless ($domain eq 'public') {
13978:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
13979:         }
13980: 
13981:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
13982:             $userenv{'availabletools.'.$tool} = 
13983:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13984:                                                   undef,\%userenv,\%domdef,\%is_adv);
13985:         }
13986: 
13987:         foreach my $crstype ('official','unofficial','community') {
13988:             $userenv{'canrequest.'.$crstype} =
13989:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
13990:                                                   'reload','requestcourses',
13991:                                                   \%userenv,\%domdef,\%is_adv);
13992:         }
13993: 
13994:         $userenv{'canrequest.author'} =
13995:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
13996:                                         'reload','requestauthor',
13997:                                         \%userenv,\%domdef,\%is_adv);
13998:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
13999:                                              $domain,$username);
14000:         my $reqstatus = $reqauthor{'author_status'};
14001:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14002:             if (ref($reqauthor{'author'}) eq 'HASH') {
14003:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14004:                                                   $reqauthor{'author'}{'timestamp'};
14005:             }
14006:         }
14007: 
14008: 	$env{'user.environment'} = "$lonids/$cookie.id";
14009: 
14010: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14011: 		 &GDBM_WRCREAT(),0640)) {
14012: 	    &_add_to_env(\%disk_env,\%initial_env);
14013: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14014: 	    &_add_to_env(\%disk_env,$userroles);
14015:             if (ref($firstaccenv) eq 'HASH') {
14016:                 &_add_to_env(\%disk_env,$firstaccenv);
14017:             }
14018:             if (ref($timerintenv) eq 'HASH') {
14019:                 &_add_to_env(\%disk_env,$timerintenv);
14020:             }
14021: 	    if (ref($args->{'extra_env'})) {
14022: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14023: 	    }
14024: 	    untie(%disk_env);
14025: 	} else {
14026: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14027: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14028: 	    return 'error: '.$!;
14029: 	}
14030:     }
14031:     $env{'request.role'}='cm';
14032:     $env{'request.role.adv'}=$env{'user.adv'};
14033:     $env{'browser.type'}=$clientbrowser;
14034: 
14035:     return $cookie;
14036: 
14037: }
14038: 
14039: sub _add_to_env {
14040:     my ($idf,$env_data,$prefix) = @_;
14041:     if (ref($env_data) eq 'HASH') {
14042:         while (my ($key,$value) = each(%$env_data)) {
14043: 	    $idf->{$prefix.$key} = $value;
14044: 	    $env{$prefix.$key}   = $value;
14045:         }
14046:     }
14047: }
14048: 
14049: # --- Get the symbolic name of a problem and the url
14050: sub get_symb {
14051:     my ($request,$silent) = @_;
14052:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14053:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14054:     if ($symb eq '') {
14055:         if (!$silent) {
14056:             if (ref($request)) { 
14057:                 $request->print("Unable to handle ambiguous references:$url:.");
14058:             }
14059:             return ();
14060:         }
14061:     }
14062:     &Apache::lonenc::check_decrypt(\$symb);
14063:     return ($symb);
14064: }
14065: 
14066: # --------------------------------------------------------------Get annotation
14067: 
14068: sub get_annotation {
14069:     my ($symb,$enc) = @_;
14070: 
14071:     my $key = $symb;
14072:     if (!$enc) {
14073:         $key =
14074:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14075:     }
14076:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14077:     return $annotation{$key};
14078: }
14079: 
14080: sub clean_symb {
14081:     my ($symb,$delete_enc) = @_;
14082: 
14083:     &Apache::lonenc::check_decrypt(\$symb);
14084:     my $enc = $env{'request.enc'};
14085:     if ($delete_enc) {
14086:         delete($env{'request.enc'});
14087:     }
14088: 
14089:     return ($symb,$enc);
14090: }
14091: 
14092: sub build_release_hashes {
14093:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14094:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14095:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14096:                   (ref($randomizetry) eq 'HASH'));
14097:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14098:         my ($item,$name,$value) = split(/:/,$key);
14099:         if ($item eq 'parameter') {
14100:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14101:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14102:                     push(@{$checkparms->{$name}},$value);
14103:                 }
14104:             } else {
14105:                 push(@{$checkparms->{$name}},$value);
14106:             }
14107:         } elsif ($item eq 'resourcetag') {
14108:             if ($name eq 'responsetype') {
14109:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14110:             }
14111:         } elsif ($item eq 'course') {
14112:             if ($name eq 'crstype') {
14113:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14114:             }
14115:         }
14116:     }
14117:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14118:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14119:     return;
14120: }
14121: 
14122: sub update_content_constraints {
14123:     my ($cdom,$cnum,$chome,$cid) = @_;
14124:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14125:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14126:     my %checkresponsetypes;
14127:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14128:         my ($item,$name,$value) = split(/:/,$key);
14129:         if ($item eq 'resourcetag') {
14130:             if ($name eq 'responsetype') {
14131:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14132:             }
14133:         }
14134:     }
14135:     my $navmap = Apache::lonnavmaps::navmap->new();
14136:     if (defined($navmap)) {
14137:         my %allresponses;
14138:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14139:             my %responses = $res->responseTypes();
14140:             foreach my $key (keys(%responses)) {
14141:                 next unless(exists($checkresponsetypes{$key}));
14142:                 $allresponses{$key} += $responses{$key};
14143:             }
14144:         }
14145:         foreach my $key (keys(%allresponses)) {
14146:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14147:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14148:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14149:             }
14150:         }
14151:         undef($navmap);
14152:     }
14153:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14154:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14155:     }
14156:     return;
14157: }
14158: 
14159: sub allmaps_incourse {
14160:     my ($cdom,$cnum,$chome,$cid) = @_;
14161:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14162:         $cid = $env{'request.course.id'};
14163:         $cdom = $env{'course.'.$cid.'.domain'};
14164:         $cnum = $env{'course.'.$cid.'.num'};
14165:         $chome = $env{'course.'.$cid.'.home'};
14166:     }
14167:     my %allmaps = ();
14168:     my $lastchange =
14169:         &Apache::lonnet::get_coursechange($cdom,$cnum);
14170:     if ($lastchange > $env{'request.course.tied'}) {
14171:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14172:         unless ($ferr) {
14173:             &update_content_constraints($cdom,$cnum,$chome,$cid);
14174:         }
14175:     }
14176:     my $navmap = Apache::lonnavmaps::navmap->new();
14177:     if (defined($navmap)) {
14178:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14179:             $allmaps{$res->src()} = 1;
14180:         }
14181:     }
14182:     return \%allmaps;
14183: }
14184: 
14185: sub parse_supplemental_title {
14186:     my ($title) = @_;
14187: 
14188:     my ($foldertitle,$renametitle);
14189:     if ($title =~ /&amp;&amp;&amp;/) {
14190:         $title = &HTML::Entites::decode($title);
14191:     }
14192:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14193:         $renametitle=$4;
14194:         my ($time,$uname,$udom) = ($1,$2,$3);
14195:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14196:         my $name =  &plainname($uname,$udom);
14197:         $name = &HTML::Entities::encode($name,'"<>&\'');
14198:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14199:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14200:             $name.': <br />'.$foldertitle;
14201:     }
14202:     if (wantarray) {
14203:         return ($title,$foldertitle,$renametitle);
14204:     }
14205:     return $title;
14206: }
14207: 
14208: sub symb_to_docspath {
14209:     my ($symb) = @_;
14210:     return unless ($symb);
14211:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14212:     if ($resurl=~/\.(sequence|page)$/) {
14213:         $mapurl=$resurl;
14214:     } elsif ($resurl eq 'adm/navmaps') {
14215:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14216:     }
14217:     my $mapresobj;
14218:     my $navmap = Apache::lonnavmaps::navmap->new();
14219:     if (ref($navmap)) {
14220:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14221:     }
14222:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14223:     my $type=$2;
14224:     my $path;
14225:     if (ref($mapresobj)) {
14226:         my $pcslist = $mapresobj->map_hierarchy();
14227:         if ($pcslist ne '') {
14228:             foreach my $pc (split(/,/,$pcslist)) {
14229:                 next if ($pc <= 1);
14230:                 my $res = $navmap->getByMapPc($pc);
14231:                 if (ref($res)) {
14232:                     my $thisurl = $res->src();
14233:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14234:                     my $thistitle = $res->title();
14235:                     $path .= '&'.
14236:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14237:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
14238:                              ':'.$res->randompick().
14239:                              ':'.$res->randomout().
14240:                              ':'.$res->encrypted().
14241:                              ':'.$res->randomorder().
14242:                              ':'.$res->is_page();
14243:                 }
14244:             }
14245:         }
14246:         $path =~ s/^\&//;
14247:         my $maptitle = $mapresobj->title();
14248:         if ($mapurl eq 'default') {
14249:             $maptitle = 'Main Course Documents';
14250:         }
14251:         $path .= (($path ne '')? '&' : '').
14252:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14253:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
14254:                  ':'.$mapresobj->randompick().
14255:                  ':'.$mapresobj->randomout().
14256:                  ':'.$mapresobj->encrypted().
14257:                  ':'.$mapresobj->randomorder().
14258:                  ':'.$mapresobj->is_page();
14259:     } else {
14260:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14261:         my $ispage = (($type eq 'page')? 1 : '');
14262:         if ($mapurl eq 'default') {
14263:             $maptitle = 'Main Course Documents';
14264:         }
14265:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14266:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
14267:     }
14268:     unless ($mapurl eq 'default') {
14269:         $path = 'default&'.
14270:                 &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
14271:                 ':::::&'.$path;
14272:     }
14273:     return $path;
14274: }
14275: 
14276: sub captcha_display {
14277:     my ($context,$lonhost) = @_;
14278:     my ($output,$error);
14279:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14280:     if ($captcha eq 'original') {
14281:         $output = &create_captcha();
14282:         unless ($output) {
14283:             $error = 'captcha';
14284:         }
14285:     } elsif ($captcha eq 'recaptcha') {
14286:         $output = &create_recaptcha($pubkey);
14287:         unless ($output) {
14288:             $error = 'recaptcha';
14289:         }
14290:     }
14291:     return ($output,$error);
14292: }
14293: 
14294: sub captcha_response {
14295:     my ($context,$lonhost) = @_;
14296:     my ($captcha_chk,$captcha_error);
14297:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14298:     if ($captcha eq 'original') {
14299:         ($captcha_chk,$captcha_error) = &check_captcha();
14300:     } elsif ($captcha eq 'recaptcha') {
14301:         $captcha_chk = &check_recaptcha($privkey);
14302:     } else {
14303:         $captcha_chk = 1;
14304:     }
14305:     return ($captcha_chk,$captcha_error);
14306: }
14307: 
14308: sub get_captcha_config {
14309:     my ($context,$lonhost) = @_;
14310:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14311:     my $hostname = &Apache::lonnet::hostname($lonhost);
14312:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14313:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14314:     if ($context eq 'usercreation') {
14315:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14316:         if (ref($domconfig{$context}) eq 'HASH') {
14317:             $hashtocheck = $domconfig{$context}{'cancreate'};
14318:             if (ref($hashtocheck) eq 'HASH') {
14319:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14320:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14321:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14322:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14323:                     }
14324:                     if ($privkey && $pubkey) {
14325:                         $captcha = 'recaptcha';
14326:                     } else {
14327:                         $captcha = 'original';
14328:                     }
14329:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14330:                     $captcha = 'original';
14331:                 }
14332:             }
14333:         } else {
14334:             $captcha = 'captcha';
14335:         }
14336:     } elsif ($context eq 'login') {
14337:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14338:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14339:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14340:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14341:             if ($privkey && $pubkey) {
14342:                 $captcha = 'recaptcha';
14343:             } else {
14344:                 $captcha = 'original';
14345:             }
14346:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14347:             $captcha = 'original';
14348:         }
14349:     }
14350:     return ($captcha,$pubkey,$privkey);
14351: }
14352: 
14353: sub create_captcha {
14354:     my %captcha_params = &captcha_settings();
14355:     my ($output,$maxtries,$tries) = ('',10,0);
14356:     while ($tries < $maxtries) {
14357:         $tries ++;
14358:         my $captcha = Authen::Captcha->new (
14359:                                            output_folder => $captcha_params{'output_dir'},
14360:                                            data_folder   => $captcha_params{'db_dir'},
14361:                                           );
14362:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14363: 
14364:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14365:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14366:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14367:                      '<input type="text" size="5" name="code" value="" /><br />'.
14368:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14369:             last;
14370:         }
14371:     }
14372:     return $output;
14373: }
14374: 
14375: sub captcha_settings {
14376:     my %captcha_params = (
14377:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14378:                            www_output_dir => "/captchaspool",
14379:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14380:                            numchars       => '5',
14381:                          );
14382:     return %captcha_params;
14383: }
14384: 
14385: sub check_captcha {
14386:     my ($captcha_chk,$captcha_error);
14387:     my $code = $env{'form.code'};
14388:     my $md5sum = $env{'form.crypt'};
14389:     my %captcha_params = &captcha_settings();
14390:     my $captcha = Authen::Captcha->new(
14391:                       output_folder => $captcha_params{'output_dir'},
14392:                       data_folder   => $captcha_params{'db_dir'},
14393:                   );
14394:     $captcha_chk = $captcha->check_code($code,$md5sum);
14395:     my %captcha_hash = (
14396:                         0       => 'Code not checked (file error)',
14397:                        -1      => 'Failed: code expired',
14398:                        -2      => 'Failed: invalid code (not in database)',
14399:                        -3      => 'Failed: invalid code (code does not match crypt)',
14400:     );
14401:     if ($captcha_chk != 1) {
14402:         $captcha_error = $captcha_hash{$captcha_chk}
14403:     }
14404:     return ($captcha_chk,$captcha_error);
14405: }
14406: 
14407: sub create_recaptcha {
14408:     my ($pubkey) = @_;
14409:     my $captcha = Captcha::reCAPTCHA->new;
14410:     return $captcha->get_options_setter({theme => 'white'})."\n".
14411:            $captcha->get_html($pubkey).
14412:            &mt('If either word is hard to read, [_1] will replace them.',
14413:                '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14414:            '<br /><br />';
14415: }
14416: 
14417: sub check_recaptcha {
14418:     my ($privkey) = @_;
14419:     my $captcha_chk;
14420:     my $captcha = Captcha::reCAPTCHA->new;
14421:     my $captcha_result =
14422:         $captcha->check_answer(
14423:                                 $privkey,
14424:                                 $ENV{'REMOTE_ADDR'},
14425:                                 $env{'form.recaptcha_challenge_field'},
14426:                                 $env{'form.recaptcha_response_field'},
14427:                               );
14428:     if ($captcha_result->{is_valid}) {
14429:         $captcha_chk = 1;
14430:     }
14431:     return $captcha_chk;
14432: }
14433: 
14434: =pod
14435: 
14436: =back
14437: 
14438: =cut
14439: 
14440: 1;
14441: __END__;
14442: 

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