File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1109: download - view: text, annotated - select for diffs
Thu Jan 3 20:08:59 2013 UTC (11 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate duplicate declaration.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1109 2013/01/03 20:08:59 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 LONCAPA qw(:DEFAULT :match);
   72: use DateTime::TimeZone;
   73: use DateTime::Locale::Catalog;
   74: use Text::Aspell;
   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 %supported_codes;
  162: my %latex_language;		# For choosing hyphenation in <transl..>
  163: my %latex_language_bykey;	# for choosing hyphenation from metadata
  164: my %cprtag;
  165: my %scprtag;
  166: my %fe; my %fd; my %fm;
  167: my %category_extensions;
  168: 
  169: # ---------------------------------------------- Thesaurus variables
  170: #
  171: # %Keywords:
  172: #      A hash used by &keyword to determine if a word is considered a keyword.
  173: # $thesaurus_db_file 
  174: #      Scalar containing the full path to the thesaurus database.
  175: 
  176: my %Keywords;
  177: my $thesaurus_db_file;
  178: 
  179: #
  180: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  181: # thesaurus.tab, and filecategories.tab.
  182: #
  183: BEGIN {
  184:     # Variable initialization
  185:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  186:     #
  187:     unless ($readit) {
  188: # ------------------------------------------------------------------- languages
  189:     {
  190:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  191:                                    '/language.tab';
  192:         if ( open(my $fh,"<$langtabfile") ) {
  193:             while (my $line = <$fh>) {
  194:                 next if ($line=~/^\#/);
  195:                 chomp($line);
  196:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  197:                 $language{$key}=$val.' - '.$enc;
  198:                 if ($sup) {
  199:                     $supported_language{$key}=$sup;
  200: 		    $supported_codes{$key}   = $code;
  201:                 }
  202: 		if ($latex) {
  203: 		    $latex_language_bykey{$key} = $latex;
  204: 		    $latex_language{$code} = $latex;
  205: 		}
  206:             }
  207:             close($fh);
  208:         }
  209:     }
  210: # ------------------------------------------------------------------ copyrights
  211:     {
  212:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  213:                                   '/copyright.tab';
  214:         if ( open (my $fh,"<$copyrightfile") ) {
  215:             while (my $line = <$fh>) {
  216:                 next if ($line=~/^\#/);
  217:                 chomp($line);
  218:                 my ($key,$val)=(split(/\s+/,$line,2));
  219:                 $cprtag{$key}=$val;
  220:             }
  221:             close($fh);
  222:         }
  223:     }
  224: # ----------------------------------------------------------- source copyrights
  225:     {
  226:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  227:                                   '/source_copyright.tab';
  228:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  229:             while (my $line = <$fh>) {
  230:                 next if ($line =~ /^\#/);
  231:                 chomp($line);
  232:                 my ($key,$val)=(split(/\s+/,$line,2));
  233:                 $scprtag{$key}=$val;
  234:             }
  235:             close($fh);
  236:         }
  237:     }
  238: 
  239: # -------------------------------------------------------------- default domain designs
  240:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  241:     my $designfile = $designdir.'/default.tab';
  242:     if ( open (my $fh,"<$designfile") ) {
  243:         while (my $line = <$fh>) {
  244:             next if ($line =~ /^\#/);
  245:             chomp($line);
  246:             my ($key,$val)=(split(/\=/,$line));
  247:             if ($val) { $defaultdesign{$key}=$val; }
  248:         }
  249:         close($fh);
  250:     }
  251: 
  252: # ------------------------------------------------------------- file categories
  253:     {
  254:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  255:                                   '/filecategories.tab';
  256:         if ( open (my $fh,"<$categoryfile") ) {
  257: 	    while (my $line = <$fh>) {
  258: 		next if ($line =~ /^\#/);
  259: 		chomp($line);
  260:                 my ($extension,$category)=(split(/\s+/,$line,2));
  261:                 push @{$category_extensions{lc($category)}},$extension;
  262:             }
  263:             close($fh);
  264:         }
  265: 
  266:     }
  267: # ------------------------------------------------------------------ file types
  268:     {
  269:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  270:                '/filetypes.tab';
  271:         if ( open (my $fh,"<$typesfile") ) {
  272:             while (my $line = <$fh>) {
  273: 		next if ($line =~ /^\#/);
  274: 		chomp($line);
  275:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  276:                 if ($descr ne '') {
  277:                     $fe{$ending}=lc($emb);
  278:                     $fd{$ending}=$descr;
  279:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  280:                 }
  281:             }
  282:             close($fh);
  283:         }
  284:     }
  285:     &Apache::lonnet::logthis(
  286:              "<span style='color:yellow;'>INFO: Read file types</span>");
  287:     $readit=1;
  288:     }  # end of unless($readit) 
  289:     
  290: }
  291: 
  292: ###############################################################
  293: ##           HTML and Javascript Helper Functions            ##
  294: ###############################################################
  295: 
  296: =pod 
  297: 
  298: =head1 HTML and Javascript Functions
  299: 
  300: =over 4
  301: 
  302: =item * &browser_and_searcher_javascript()
  303: 
  304: X<browsing, javascript>X<searching, javascript>Returns a string
  305: containing javascript with two functions, C<openbrowser> and
  306: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  307: tags.
  308: 
  309: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  310: 
  311: inputs: formname, elementname, only, omit
  312: 
  313: formname and elementname indicate the name of the html form and name of
  314: the element that the results of the browsing selection are to be placed in. 
  315: 
  316: Specifying 'only' will restrict the browser to displaying only files
  317: with the given extension.  Can be a comma separated list.
  318: 
  319: Specifying 'omit' will restrict the browser to NOT displaying files
  320: with the given extension.  Can be a comma separated list.
  321: 
  322: =item * &opensearcher(formname,elementname) [javascript]
  323: 
  324: Inputs: formname, elementname
  325: 
  326: formname and elementname specify the name of the html form and the name
  327: of the element the selection from the search results will be placed in.
  328: 
  329: =cut
  330: 
  331: sub browser_and_searcher_javascript {
  332:     my ($mode)=@_;
  333:     if (!defined($mode)) { $mode='edit'; }
  334:     my $resurl=&escape_single(&lastresurl());
  335:     return <<END;
  336: // <!-- BEGIN LON-CAPA Internal
  337:     var editbrowser = null;
  338:     function openbrowser(formname,elementname,only,omit,titleelement) {
  339:         var url = '$resurl/?';
  340:         if (editbrowser == null) {
  341:             url += 'launch=1&';
  342:         }
  343:         url += 'catalogmode=interactive&';
  344:         url += 'mode=$mode&';
  345:         url += 'inhibitmenu=yes&';
  346:         url += 'form=' + formname + '&';
  347:         if (only != null) {
  348:             url += 'only=' + only + '&';
  349:         } else {
  350:             url += 'only=&';
  351: 	}
  352:         if (omit != null) {
  353:             url += 'omit=' + omit + '&';
  354:         } else {
  355:             url += 'omit=&';
  356: 	}
  357:         if (titleelement != null) {
  358:             url += 'titleelement=' + titleelement + '&';
  359:         } else {
  360: 	    url += 'titleelement=&';
  361: 	}
  362:         url += 'element=' + elementname + '';
  363:         var title = 'Browser';
  364:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  365:         options += ',width=700,height=600';
  366:         editbrowser = open(url,title,options,'1');
  367:         editbrowser.focus();
  368:     }
  369:     var editsearcher;
  370:     function opensearcher(formname,elementname,titleelement) {
  371:         var url = '/adm/searchcat?';
  372:         if (editsearcher == null) {
  373:             url += 'launch=1&';
  374:         }
  375:         url += 'catalogmode=interactive&';
  376:         url += 'mode=$mode&';
  377:         url += 'form=' + formname + '&';
  378:         if (titleelement != null) {
  379:             url += 'titleelement=' + titleelement + '&';
  380:         } else {
  381: 	    url += 'titleelement=&';
  382: 	}
  383:         url += 'element=' + elementname + '';
  384:         var title = 'Search';
  385:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  386:         options += ',width=700,height=600';
  387:         editsearcher = open(url,title,options,'1');
  388:         editsearcher.focus();
  389:     }
  390: // END LON-CAPA Internal -->
  391: END
  392: }
  393: 
  394: sub lastresurl {
  395:     if ($env{'environment.lastresurl'}) {
  396: 	return $env{'environment.lastresurl'}
  397:     } else {
  398: 	return '/res';
  399:     }
  400: }
  401: 
  402: sub storeresurl {
  403:     my $resurl=&Apache::lonnet::clutter(shift);
  404:     unless ($resurl=~/^\/res/) { return 0; }
  405:     $resurl=~s/\/$//;
  406:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  407:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  408:     return 1;
  409: }
  410: 
  411: sub studentbrowser_javascript {
  412:    unless (
  413:             (($env{'request.course.id'}) && 
  414:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  415: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  416: 					  '/'.$env{'request.course.sec'})
  417: 	      ))
  418:          || ($env{'request.role'}=~/^(au|dc|su)/)
  419:           ) { return ''; }  
  420:    return (<<'ENDSTDBRW');
  421: <script type="text/javascript" language="Javascript">
  422: // <![CDATA[
  423:     var stdeditbrowser;
  424:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  425:         var url = '/adm/pickstudent?';
  426:         var filter;
  427: 	if (!ignorefilter) {
  428: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  429: 	}
  430:         if (filter != null) {
  431:            if (filter != '') {
  432:                url += 'filter='+filter+'&';
  433: 	   }
  434:         }
  435:         url += 'form=' + formname + '&unameelement='+uname+
  436:                                     '&udomelement='+udom+
  437:                                     '&clicker='+clicker;
  438: 	if (roleflag) { url+="&roles=1"; }
  439:         if (courseadvonly) { url+="&courseadvonly=1"; }
  440:         var title = 'Student_Browser';
  441:         var options = 'scrollbars=1,resizable=1,menubar=0';
  442:         options += ',width=700,height=600';
  443:         stdeditbrowser = open(url,title,options,'1');
  444:         stdeditbrowser.focus();
  445:     }
  446: // ]]>
  447: </script>
  448: ENDSTDBRW
  449: }
  450: 
  451: sub resourcebrowser_javascript {
  452:    unless ($env{'request.course.id'}) { return ''; }
  453:    return (<<'ENDRESBRW');
  454: <script type="text/javascript" language="Javascript">
  455: // <![CDATA[
  456:     var reseditbrowser;
  457:     function openresbrowser(formname,reslink) {
  458:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  459:         var title = 'Resource_Browser';
  460:         var options = 'scrollbars=1,resizable=1,menubar=0';
  461:         options += ',width=700,height=500';
  462:         reseditbrowser = open(url,title,options,'1');
  463:         reseditbrowser.focus();
  464:     }
  465: // ]]>
  466: </script>
  467: ENDRESBRW
  468: }
  469: 
  470: sub selectstudent_link {
  471:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  472:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  473:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  474:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  475:    if ($env{'request.course.id'}) {  
  476:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  477: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  478: 					'/'.$env{'request.course.sec'})) {
  479: 	   return '';
  480:        }
  481:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  482:        if ($courseadvonly)  {
  483:            $callargs .= ",'',1,1";
  484:        }
  485:        return '<span class="LC_nobreak">'.
  486:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  487:               &mt('Select User').'</a></span>';
  488:    }
  489:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  490:        $callargs .= ",'',1"; 
  491:        return '<span class="LC_nobreak">'.
  492:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  493:               &mt('Select User').'</a></span>';
  494:    }
  495:    return '';
  496: }
  497: 
  498: sub selectresource_link {
  499:    my ($form,$reslink,$arg)=@_;
  500:    
  501:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  502:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  503:    unless ($env{'request.course.id'}) { return $arg; }
  504:    return '<span class="LC_nobreak">'.
  505:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  506:               $arg.'</a></span>';
  507: }
  508: 
  509: 
  510: 
  511: sub authorbrowser_javascript {
  512:     return <<"ENDAUTHORBRW";
  513: <script type="text/javascript" language="JavaScript">
  514: // <![CDATA[
  515: var stdeditbrowser;
  516: 
  517: function openauthorbrowser(formname,udom) {
  518:     var url = '/adm/pickauthor?';
  519:     url += 'form='+formname+'&roledom='+udom;
  520:     var title = 'Author_Browser';
  521:     var options = 'scrollbars=1,resizable=1,menubar=0';
  522:     options += ',width=700,height=600';
  523:     stdeditbrowser = open(url,title,options,'1');
  524:     stdeditbrowser.focus();
  525: }
  526: 
  527: // ]]>
  528: </script>
  529: ENDAUTHORBRW
  530: }
  531: 
  532: sub coursebrowser_javascript {
  533:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  534:     my $wintitle = 'Course_Browser';
  535:     if ($crstype eq 'Community') {
  536:         $wintitle = 'Community_Browser';
  537:     }
  538:     my $id_functions = &javascript_index_functions();
  539:     my $output = '
  540: <script type="text/javascript" language="JavaScript">
  541: // <![CDATA[
  542:     var stdeditbrowser;'."\n";
  543: 
  544:     $output .= <<"ENDSTDBRW";
  545:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  546:         var url = '/adm/pickcourse?';
  547:         var formid = getFormIdByName(formname);
  548:         var domainfilter = getDomainFromSelectbox(formname,udom);
  549:         if (domainfilter != null) {
  550:            if (domainfilter != '') {
  551:                url += 'domainfilter='+domainfilter+'&';
  552: 	   }
  553:         }
  554:         url += 'form=' + formname + '&cnumelement='+uname+
  555: 	                            '&cdomelement='+udom+
  556:                                     '&cnameelement='+desc;
  557:         if (extra_element !=null && extra_element != '') {
  558:             if (formname == 'rolechoice' || formname == 'studentform') {
  559:                 url += '&roleelement='+extra_element;
  560:                 if (domainfilter == null || domainfilter == '') {
  561:                     url += '&domainfilter='+extra_element;
  562:                 }
  563:             }
  564:             else {
  565:                 if (formname == 'portform') {
  566:                     url += '&setroles='+extra_element;
  567:                 } else {
  568:                     if (formname == 'rules') {
  569:                         url += '&fixeddom='+extra_element; 
  570:                     }
  571:                 }
  572:             }     
  573:         }
  574:         if (type != null && type != '') {
  575:             url += '&type='+type;
  576:         }
  577:         if (type_elem != null && type_elem != '') {
  578:             url += '&typeelement='+type_elem;
  579:         }
  580:         if (formname == 'ccrs') {
  581:             var ownername = document.forms[formid].ccuname.value;
  582:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  583:             url += '&cloner='+ownername+':'+ownerdom;
  584:         }
  585:         if (multflag !=null && multflag != '') {
  586:             url += '&multiple='+multflag;
  587:         }
  588:         var title = '$wintitle';
  589:         var options = 'scrollbars=1,resizable=1,menubar=0';
  590:         options += ',width=700,height=600';
  591:         stdeditbrowser = open(url,title,options,'1');
  592:         stdeditbrowser.focus();
  593:     }
  594: $id_functions
  595: ENDSTDBRW
  596:     if (($sec_element ne '') || ($role_element ne '')) {
  597:         $output .= &setsec_javascript($sec_element,$formname,$role_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 is 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) = @_;
  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:     return $setsections;
  850: }
  851: 
  852: sub selectcourse_link {
  853:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  854:        $typeelement) = @_;
  855:    my $type = $selecttype;
  856:    my $linktext = &mt('Select Course');
  857:    if ($selecttype eq 'Community') {
  858:        $linktext = &mt('Select Community');
  859:    } elsif ($selecttype eq 'Course/Community') {
  860:        $linktext = &mt('Select Course/Community');
  861:        $type = '';
  862:    } elsif ($selecttype eq 'Select') {
  863:        $linktext = &mt('Select');
  864:        $type = '';
  865:    }
  866:    return '<span class="LC_nobreak">'
  867:          ."<a href='"
  868:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  869:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  870:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  871:          ."'>".$linktext.'</a>'
  872:          .'</span>';
  873: }
  874: 
  875: sub selectauthor_link {
  876:    my ($form,$udom)=@_;
  877:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  878:           &mt('Select Author').'</a>';
  879: }
  880: 
  881: sub selectuser_link {
  882:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  883:         $coursedom,$linktext,$caller) = @_;
  884:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  885:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  886:            ');">'.$linktext.'</a>';
  887: }
  888: 
  889: sub check_uncheck_jscript {
  890:     my $jscript = <<"ENDSCRT";
  891: function checkAll(field) {
  892:     if (field.length > 0) {
  893:         for (i = 0; i < field.length; i++) {
  894:             if (!field[i].disabled) { 
  895:                 field[i].checked = true;
  896:             }
  897:         }
  898:     } else {
  899:         if (!field.disabled) { 
  900:             field.checked = true;
  901:         }
  902:     }
  903: }
  904:  
  905: function uncheckAll(field) {
  906:     if (field.length > 0) {
  907:         for (i = 0; i < field.length; i++) {
  908:             field[i].checked = false ;
  909:         }
  910:     } else {
  911:         field.checked = false ;
  912:     }
  913: }
  914: ENDSCRT
  915:     return $jscript;
  916: }
  917: 
  918: sub select_timezone {
  919:    my ($name,$selected,$onchange,$includeempty)=@_;
  920:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  921:    if ($includeempty) {
  922:        $output .= '<option value=""';
  923:        if (($selected eq '') || ($selected eq 'local')) {
  924:            $output .= ' selected="selected" ';
  925:        }
  926:        $output .= '> </option>';
  927:    }
  928:    my @timezones = DateTime::TimeZone->all_names;
  929:    foreach my $tzone (@timezones) {
  930:        $output.= '<option value="'.$tzone.'"';
  931:        if ($tzone eq $selected) {
  932:            $output.=' selected="selected"';
  933:        }
  934:        $output.=">$tzone</option>\n";
  935:    }
  936:    $output.="</select>";
  937:    return $output;
  938: }
  939: 
  940: sub select_datelocale {
  941:     my ($name,$selected,$onchange,$includeempty)=@_;
  942:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  943:     if ($includeempty) {
  944:         $output .= '<option value=""';
  945:         if ($selected eq '') {
  946:             $output .= ' selected="selected" ';
  947:         }
  948:         $output .= '> </option>';
  949:     }
  950:     my (@possibles,%locale_names);
  951:     my @locales = DateTime::Locale::Catalog::Locales;
  952:     foreach my $locale (@locales) {
  953:         if (ref($locale) eq 'HASH') {
  954:             my $id = $locale->{'id'};
  955:             if ($id ne '') {
  956:                 my $en_terr = $locale->{'en_territory'};
  957:                 my $native_terr = $locale->{'native_territory'};
  958:                 my @languages = &Apache::lonlocal::preferred_languages();
  959:                 if (grep(/^en$/,@languages) || !@languages) {
  960:                     if ($en_terr ne '') {
  961:                         $locale_names{$id} = '('.$en_terr.')';
  962:                     } elsif ($native_terr ne '') {
  963:                         $locale_names{$id} = $native_terr;
  964:                     }
  965:                 } else {
  966:                     if ($native_terr ne '') {
  967:                         $locale_names{$id} = $native_terr.' ';
  968:                     } elsif ($en_terr ne '') {
  969:                         $locale_names{$id} = '('.$en_terr.')';
  970:                     }
  971:                 }
  972:                 push (@possibles,$id);
  973:             }
  974:         }
  975:     }
  976:     foreach my $item (sort(@possibles)) {
  977:         $output.= '<option value="'.$item.'"';
  978:         if ($item eq $selected) {
  979:             $output.=' selected="selected"';
  980:         }
  981:         $output.=">$item";
  982:         if ($locale_names{$item} ne '') {
  983:             $output.="  $locale_names{$item}</option>\n";
  984:         }
  985:         $output.="</option>\n";
  986:     }
  987:     $output.="</select>";
  988:     return $output;
  989: }
  990: 
  991: sub select_language {
  992:     my ($name,$selected,$includeempty) = @_;
  993:     my %langchoices;
  994:     if ($includeempty) {
  995:         %langchoices = ('' => 'No language preference');
  996:     }
  997:     foreach my $id (&languageids()) {
  998:         my $code = &supportedlanguagecode($id);
  999:         if ($code) {
 1000:             $langchoices{$code} = &plainlanguagedescription($id);
 1001:         }
 1002:     }
 1003:     return &select_form($selected,$name,\%langchoices);
 1004: }
 1005: 
 1006: =pod
 1007: 
 1008: 
 1009: =item * &list_languages()
 1010: 
 1011: Returns an array reference that is suitable for use in language prompters.
 1012: Each array element is itself a two element array.  The first element
 1013: is the language code.  The second element a descsriptiuon of the 
 1014: language itself.  This is suitable for use in e.g.
 1015: &Apache::edit::select_arg (once dereferenced that is).
 1016: 
 1017: =cut 
 1018: 
 1019: sub list_languages {
 1020:     my @lang_choices;
 1021: 
 1022:     foreach my $id (&languageids()) {
 1023: 	my $code = &supportedlanguagecode($id);
 1024: 	if ($code) {
 1025: 	    my $selector    = $supported_codes{$id};
 1026: 	    my $description = &plainlanguagedescription($id);
 1027: 	    push (@lang_choices, [$selector, $description]);
 1028: 	}
 1029:     }
 1030:     return \@lang_choices;
 1031: }
 1032: 
 1033: =pod
 1034: 
 1035: =item * &linked_select_forms(...)
 1036: 
 1037: linked_select_forms returns a string containing a <script></script> block
 1038: and html for two <select> menus.  The select menus will be linked in that
 1039: changing the value of the first menu will result in new values being placed
 1040: in the second menu.  The values in the select menu will appear in alphabetical
 1041: order unless a defined order is provided.
 1042: 
 1043: linked_select_forms takes the following ordered inputs:
 1044: 
 1045: =over 4
 1046: 
 1047: =item * $formname, the name of the <form> tag
 1048: 
 1049: =item * $middletext, the text which appears between the <select> tags
 1050: 
 1051: =item * $firstdefault, the default value for the first menu
 1052: 
 1053: =item * $firstselectname, the name of the first <select> tag
 1054: 
 1055: =item * $secondselectname, the name of the second <select> tag
 1056: 
 1057: =item * $hashref, a reference to a hash containing the data for the menus.
 1058: 
 1059: =item * $menuorder, the order of values in the first menu
 1060: 
 1061: =back 
 1062: 
 1063: Below is an example of such a hash.  Only the 'text', 'default', and 
 1064: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1065: values for the first select menu.  The text that coincides with the 
 1066: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1067: and text for the second menu are given in the hash pointed to by 
 1068: $menu{$choice1}->{'select2'}.  
 1069: 
 1070:  my %menu = ( A1 => { text =>"Choice A1" ,
 1071:                        default => "B3",
 1072:                        select2 => { 
 1073:                            B1 => "Choice B1",
 1074:                            B2 => "Choice B2",
 1075:                            B3 => "Choice B3",
 1076:                            B4 => "Choice B4"
 1077:                            },
 1078:                        order => ['B4','B3','B1','B2'],
 1079:                    },
 1080:                A2 => { text =>"Choice A2" ,
 1081:                        default => "C2",
 1082:                        select2 => { 
 1083:                            C1 => "Choice C1",
 1084:                            C2 => "Choice C2",
 1085:                            C3 => "Choice C3"
 1086:                            },
 1087:                        order => ['C2','C1','C3'],
 1088:                    },
 1089:                A3 => { text =>"Choice A3" ,
 1090:                        default => "D6",
 1091:                        select2 => { 
 1092:                            D1 => "Choice D1",
 1093:                            D2 => "Choice D2",
 1094:                            D3 => "Choice D3",
 1095:                            D4 => "Choice D4",
 1096:                            D5 => "Choice D5",
 1097:                            D6 => "Choice D6",
 1098:                            D7 => "Choice D7"
 1099:                            },
 1100:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1101:                    }
 1102:                );
 1103: 
 1104: =cut
 1105: 
 1106: sub linked_select_forms {
 1107:     my ($formname,
 1108:         $middletext,
 1109:         $firstdefault,
 1110:         $firstselectname,
 1111:         $secondselectname, 
 1112:         $hashref,
 1113:         $menuorder,
 1114:         ) = @_;
 1115:     my $second = "document.$formname.$secondselectname";
 1116:     my $first = "document.$formname.$firstselectname";
 1117:     # output the javascript to do the changing
 1118:     my $result = '';
 1119:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1120:     $result.="// <![CDATA[\n";
 1121:     $result.="var select2data = new Object();\n";
 1122:     $" = '","';
 1123:     my $debug = '';
 1124:     foreach my $s1 (sort(keys(%$hashref))) {
 1125:         $result.="select2data.d_$s1 = new Object();\n";        
 1126:         $result.="select2data.d_$s1.def = new String('".
 1127:             $hashref->{$s1}->{'default'}."');\n";
 1128:         $result.="select2data.d_$s1.values = new Array(";
 1129:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1130:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1131:             @s2values = @{$hashref->{$s1}->{'order'}};
 1132:         }
 1133:         $result.="\"@s2values\");\n";
 1134:         $result.="select2data.d_$s1.texts = new Array(";        
 1135:         my @s2texts;
 1136:         foreach my $value (@s2values) {
 1137:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1138:         }
 1139:         $result.="\"@s2texts\");\n";
 1140:     }
 1141:     $"=' ';
 1142:     $result.= <<"END";
 1143: 
 1144: function select1_changed() {
 1145:     // Determine new choice
 1146:     var newvalue = "d_" + $first.value;
 1147:     // update select2
 1148:     var values     = select2data[newvalue].values;
 1149:     var texts      = select2data[newvalue].texts;
 1150:     var select2def = select2data[newvalue].def;
 1151:     var i;
 1152:     // out with the old
 1153:     for (i = 0; i < $second.options.length; i++) {
 1154:         $second.options[i] = null;
 1155:     }
 1156:     // in with the nuclear
 1157:     for (i=0;i<values.length; i++) {
 1158:         $second.options[i] = new Option(values[i]);
 1159:         $second.options[i].value = values[i];
 1160:         $second.options[i].text = texts[i];
 1161:         if (values[i] == select2def) {
 1162:             $second.options[i].selected = true;
 1163:         }
 1164:     }
 1165: }
 1166: // ]]>
 1167: </script>
 1168: END
 1169:     # output the initial values for the selection lists
 1170:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1171:     my @order = sort(keys(%{$hashref}));
 1172:     if (ref($menuorder) eq 'ARRAY') {
 1173:         @order = @{$menuorder};
 1174:     }
 1175:     foreach my $value (@order) {
 1176:         $result.="    <option value=\"$value\" ";
 1177:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1178:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1179:     }
 1180:     $result .= "</select>\n";
 1181:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1182:     $result .= $middletext;
 1183:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1184:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1185:     
 1186:     my @secondorder = sort(keys(%select2));
 1187:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1188:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1189:     }
 1190:     foreach my $value (@secondorder) {
 1191:         $result.="    <option value=\"$value\" ";        
 1192:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1193:         $result.=">".&mt($select2{$value})."</option>\n";
 1194:     }
 1195:     $result .= "</select>\n";
 1196:     #    return $debug;
 1197:     return $result;
 1198: }   #  end of sub linked_select_forms {
 1199: 
 1200: =pod
 1201: 
 1202: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1203: 
 1204: Returns a string corresponding to an HTML link to the given help
 1205: $topic, where $topic corresponds to the name of a .tex file in
 1206: /home/httpd/html/adm/help/tex, with underscores replaced by
 1207: spaces. 
 1208: 
 1209: $text will optionally be linked to the same topic, allowing you to
 1210: link text in addition to the graphic. If you do not want to link
 1211: text, but wish to specify one of the later parameters, pass an
 1212: empty string. 
 1213: 
 1214: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1215: the link will not open a new window. If false, the link will open
 1216: a new window using Javascript. (Default is false.) 
 1217: 
 1218: $width and $height are optional numerical parameters that will
 1219: override the width and height of the popped up window, which may
 1220: be useful for certain help topics with big pictures included.
 1221: 
 1222: $imgid is the id of the img tag used for the help icon. This may be
 1223: used in a javascript call to switch the image src.  See 
 1224: lonhtmlcommon::htmlareaselectactive() for an example.
 1225: 
 1226: =cut
 1227: 
 1228: sub help_open_topic {
 1229:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1230:     $text = "" if (not defined $text);
 1231:     $stayOnPage = 0 if (not defined $stayOnPage);
 1232:     $width = 500 if (not defined $width);
 1233:     $height = 400 if (not defined $height);
 1234:     my $filename = $topic;
 1235:     $filename =~ s/ /_/g;
 1236: 
 1237:     my $template = "";
 1238:     my $link;
 1239:     
 1240:     $topic=~s/\W/\_/g;
 1241: 
 1242:     if (!$stayOnPage) {
 1243: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1244:     } elsif ($stayOnPage eq 'popup') {
 1245:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1246:     } else {
 1247: 	$link = "/adm/help/${filename}.hlp";
 1248:     }
 1249: 
 1250:     # Add the text
 1251:     if ($text ne "") {	
 1252: 	$template.='<span class="LC_help_open_topic">'
 1253:                   .'<a target="_top" href="'.$link.'">'
 1254:                   .$text.'</a>';
 1255:     }
 1256: 
 1257:     # (Always) Add the graphic
 1258:     my $title = &mt('Online Help');
 1259:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1260:     if ($imgid ne '') {
 1261:         $imgid = ' id="'.$imgid.'"';
 1262:     }
 1263:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1264:               .'<img src="'.$helpicon.'" border="0"'
 1265:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1266:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1267:               .' /></a>';
 1268:     if ($text ne "") {	
 1269:         $template.='</span>';
 1270:     }
 1271:     return $template;
 1272: 
 1273: }
 1274: 
 1275: # This is a quicky function for Latex cheatsheet editing, since it 
 1276: # appears in at least four places
 1277: sub helpLatexCheatsheet {
 1278:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1279:     my $out;
 1280:     my $addOther = '';
 1281:     if ($topic) {
 1282: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1283:     }
 1284:     $out = '<span>' # Start cheatsheet
 1285: 	  .$addOther
 1286:           .'<span>'
 1287: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1288: 	  .'</span> <span>'
 1289: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1290: 	  .'</span>';
 1291:     unless ($not_author) {
 1292:         $out .= ' <span>'
 1293: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1294: 	       .'</span>';
 1295:     }
 1296:     $out .= '</span>'; # End cheatsheet
 1297:     return $out;
 1298: }
 1299: 
 1300: sub general_help {
 1301:     my $helptopic='Student_Intro';
 1302:     if ($env{'request.role'}=~/^(ca|au)/) {
 1303: 	$helptopic='Authoring_Intro';
 1304:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1305: 	$helptopic='Course_Coordination_Intro';
 1306:     } elsif ($env{'request.role'}=~/^dc/) {
 1307:         $helptopic='Domain_Coordination_Intro';
 1308:     }
 1309:     return $helptopic;
 1310: }
 1311: 
 1312: sub update_help_link {
 1313:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1314:     my $origurl = $ENV{'REQUEST_URI'};
 1315:     $origurl=~s|^/~|/priv/|;
 1316:     my $timestamp = time;
 1317:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1318:         $$datum = &escape($$datum);
 1319:     }
 1320: 
 1321:     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";
 1322:     my $output .= <<"ENDOUTPUT";
 1323: <script type="text/javascript">
 1324: // <![CDATA[
 1325: banner_link = '$banner_link';
 1326: // ]]>
 1327: </script>
 1328: ENDOUTPUT
 1329:     return $output;
 1330: }
 1331: 
 1332: # now just updates the help link and generates a blue icon
 1333: sub help_open_menu {
 1334:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1335: 	= @_;    
 1336:     $stayOnPage = 1;
 1337:     my $output;
 1338:     if ($component_help) {
 1339: 	if (!$text) {
 1340: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1341: 				       $width,$height);
 1342: 	} else {
 1343: 	    my $help_text;
 1344: 	    $help_text=&unescape($topic);
 1345: 	    $output='<table><tr><td>'.
 1346: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1347: 				 $width,$height).'</td></tr></table>';
 1348: 	}
 1349:     }
 1350:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1351:     return $output.$banner_link;
 1352: }
 1353: 
 1354: sub top_nav_help {
 1355:     my ($text) = @_;
 1356:     $text = &mt($text);
 1357:     my $stay_on_page = 1;
 1358: 
 1359:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1360: 	                     : "javascript:helpMenu('open')";
 1361:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1362: 
 1363:     my $title = &mt('Get help');
 1364: 
 1365:     return <<"END";
 1366: $banner_link
 1367:  <a href="$link" title="$title">$text</a>
 1368: END
 1369: }
 1370: 
 1371: sub help_menu_js {
 1372:     my ($text) = @_;
 1373:     my $stayOnPage = 1;
 1374:     my $width = 620;
 1375:     my $height = 600;
 1376:     my $helptopic=&general_help();
 1377:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1378:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1379:     my $start_page =
 1380:         &Apache::loncommon::start_page('Help Menu', undef,
 1381: 				       {'frameset'    => 1,
 1382: 					'js_ready'    => 1,
 1383: 					'add_entries' => {
 1384: 					    'border' => '0',
 1385: 					    'rows'   => "110,*",},});
 1386:     my $end_page =
 1387:         &Apache::loncommon::end_page({'frameset' => 1,
 1388: 				      'js_ready' => 1,});
 1389: 
 1390:     my $template .= <<"ENDTEMPLATE";
 1391: <script type="text/javascript">
 1392: // <![CDATA[
 1393: // <!-- BEGIN LON-CAPA Internal
 1394: var banner_link = '';
 1395: function helpMenu(target) {
 1396:     var caller = this;
 1397:     if (target == 'open') {
 1398:         var newWindow = null;
 1399:         try {
 1400:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1401:         }
 1402:         catch(error) {
 1403:             writeHelp(caller);
 1404:             return;
 1405:         }
 1406:         if (newWindow) {
 1407:             caller = newWindow;
 1408:         }
 1409:     }
 1410:     writeHelp(caller);
 1411:     return;
 1412: }
 1413: function writeHelp(caller) {
 1414:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1415:     caller.document.close()
 1416:     caller.focus()
 1417: }
 1418: // END LON-CAPA Internal -->
 1419: // ]]>
 1420: </script>
 1421: ENDTEMPLATE
 1422:     return $template;
 1423: }
 1424: 
 1425: sub help_open_bug {
 1426:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1427:     unless ($env{'user.adv'}) { return ''; }
 1428:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1429:     $text = "" if (not defined $text);
 1430: 	$stayOnPage=1;
 1431:     $width = 600 if (not defined $width);
 1432:     $height = 600 if (not defined $height);
 1433: 
 1434:     $topic=~s/\W+/\+/g;
 1435:     my $link='';
 1436:     my $template='';
 1437:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1438: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1439:     if (!$stayOnPage)
 1440:     {
 1441: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1442:     }
 1443:     else
 1444:     {
 1445: 	$link = $url;
 1446:     }
 1447:     # Add the text
 1448:     if ($text ne "")
 1449:     {
 1450: 	$template .= 
 1451:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1452:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1453:     }
 1454: 
 1455:     # Add the graphic
 1456:     my $title = &mt('Report a Bug');
 1457:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1458:     $template .= <<"ENDTEMPLATE";
 1459:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1460: ENDTEMPLATE
 1461:     if ($text ne '') { $template.='</td></tr></table>' };
 1462:     return $template;
 1463: 
 1464: }
 1465: 
 1466: sub help_open_faq {
 1467:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1468:     unless ($env{'user.adv'}) { return ''; }
 1469:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1470:     $text = "" if (not defined $text);
 1471: 	$stayOnPage=1;
 1472:     $width = 350 if (not defined $width);
 1473:     $height = 400 if (not defined $height);
 1474: 
 1475:     $topic=~s/\W+/\+/g;
 1476:     my $link='';
 1477:     my $template='';
 1478:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1479:     if (!$stayOnPage)
 1480:     {
 1481: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1482:     }
 1483:     else
 1484:     {
 1485: 	$link = $url;
 1486:     }
 1487: 
 1488:     # Add the text
 1489:     if ($text ne "")
 1490:     {
 1491: 	$template .= 
 1492:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1493:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1494:     }
 1495: 
 1496:     # Add the graphic
 1497:     my $title = &mt('View the FAQ');
 1498:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1499:     $template .= <<"ENDTEMPLATE";
 1500:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1501: ENDTEMPLATE
 1502:     if ($text ne '') { $template.='</td></tr></table>' };
 1503:     return $template;
 1504: 
 1505: }
 1506: 
 1507: ###############################################################
 1508: ###############################################################
 1509: 
 1510: =pod
 1511: 
 1512: =item * &change_content_javascript():
 1513: 
 1514: This and the next function allow you to create small sections of an
 1515: otherwise static HTML page that you can update on the fly with
 1516: Javascript, even in Netscape 4.
 1517: 
 1518: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1519: must be written to the HTML page once. It will prove the Javascript
 1520: function "change(name, content)". Calling the change function with the
 1521: name of the section 
 1522: you want to update, matching the name passed to C<changable_area>, and
 1523: the new content you want to put in there, will put the content into
 1524: that area.
 1525: 
 1526: B<Note>: Netscape 4 only reserves enough space for the changable area
 1527: to contain room for the original contents. You need to "make space"
 1528: for whatever changes you wish to make, and be B<sure> to check your
 1529: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1530: it's adequate for updating a one-line status display, but little more.
 1531: This script will set the space to 100% width, so you only need to
 1532: worry about height in Netscape 4.
 1533: 
 1534: Modern browsers are much less limiting, and if you can commit to the
 1535: user not using Netscape 4, this feature may be used freely with
 1536: pretty much any HTML.
 1537: 
 1538: =cut
 1539: 
 1540: sub change_content_javascript {
 1541:     # If we're on Netscape 4, we need to use Layer-based code
 1542:     if ($env{'browser.type'} eq 'netscape' &&
 1543: 	$env{'browser.version'} =~ /^4\./) {
 1544: 	return (<<NETSCAPE4);
 1545: 	function change(name, content) {
 1546: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1547: 	    doc.open();
 1548: 	    doc.write(content);
 1549: 	    doc.close();
 1550: 	}
 1551: NETSCAPE4
 1552:     } else {
 1553: 	# Otherwise, we need to use semi-standards-compliant code
 1554: 	# (technically, "innerHTML" isn't standard but the equivalent
 1555: 	# is really scary, and every useful browser supports it
 1556: 	return (<<DOMBASED);
 1557: 	function change(name, content) {
 1558: 	    element = document.getElementById(name);
 1559: 	    element.innerHTML = content;
 1560: 	}
 1561: DOMBASED
 1562:     }
 1563: }
 1564: 
 1565: =pod
 1566: 
 1567: =item * &changable_area($name,$origContent):
 1568: 
 1569: This provides a "changable area" that can be modified on the fly via
 1570: the Javascript code provided in C<change_content_javascript>. $name is
 1571: the name you will use to reference the area later; do not repeat the
 1572: same name on a given HTML page more then once. $origContent is what
 1573: the area will originally contain, which can be left blank.
 1574: 
 1575: =cut
 1576: 
 1577: sub changable_area {
 1578:     my ($name, $origContent) = @_;
 1579: 
 1580:     if ($env{'browser.type'} eq 'netscape' &&
 1581: 	$env{'browser.version'} =~ /^4\./) {
 1582: 	# If this is netscape 4, we need to use the Layer tag
 1583: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1584:     } else {
 1585: 	return "<span id='$name'>$origContent</span>";
 1586:     }
 1587: }
 1588: 
 1589: =pod
 1590: 
 1591: =item * &viewport_geometry_js 
 1592: 
 1593: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1594: 
 1595: =cut
 1596: 
 1597: 
 1598: sub viewport_geometry_js { 
 1599:     return <<"GEOMETRY";
 1600: var Geometry = {};
 1601: function init_geometry() {
 1602:     if (Geometry.init) { return };
 1603:     Geometry.init=1;
 1604:     if (window.innerHeight) {
 1605:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1606:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1607:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1608:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1609:     }
 1610:     else if (document.documentElement && document.documentElement.clientHeight) {
 1611:         Geometry.getViewportHeight =
 1612:             function() { return document.documentElement.clientHeight; };
 1613:         Geometry.getViewportWidth =
 1614:             function() { return document.documentElement.clientWidth; };
 1615: 
 1616:         Geometry.getHorizontalScroll =
 1617:             function() { return document.documentElement.scrollLeft; };
 1618:         Geometry.getVerticalScroll =
 1619:             function() { return document.documentElement.scrollTop; };
 1620:     }
 1621:     else if (document.body.clientHeight) {
 1622:         Geometry.getViewportHeight =
 1623:             function() { return document.body.clientHeight; };
 1624:         Geometry.getViewportWidth =
 1625:             function() { return document.body.clientWidth; };
 1626:         Geometry.getHorizontalScroll =
 1627:             function() { return document.body.scrollLeft; };
 1628:         Geometry.getVerticalScroll =
 1629:             function() { return document.body.scrollTop; };
 1630:     }
 1631: }
 1632: 
 1633: GEOMETRY
 1634: }
 1635: 
 1636: =pod
 1637: 
 1638: =item * &viewport_size_js()
 1639: 
 1640: 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. 
 1641: 
 1642: =cut
 1643: 
 1644: sub viewport_size_js {
 1645:     my $geometry = &viewport_geometry_js();
 1646:     return <<"DIMS";
 1647: 
 1648: $geometry
 1649: 
 1650: function getViewportDims(width,height) {
 1651:     init_geometry();
 1652:     width.value = Geometry.getViewportWidth();
 1653:     height.value = Geometry.getViewportHeight();
 1654:     return;
 1655: }
 1656: 
 1657: DIMS
 1658: }
 1659: 
 1660: =pod
 1661: 
 1662: =item * &resize_textarea_js()
 1663: 
 1664: emits the needed javascript to resize a textarea to be as big as possible
 1665: 
 1666: creates a function resize_textrea that takes two IDs first should be
 1667: the id of the element to resize, second should be the id of a div that
 1668: surrounds everything that comes after the textarea, this routine needs
 1669: to be attached to the <body> for the onload and onresize events.
 1670: 
 1671: =back
 1672: 
 1673: =cut
 1674: 
 1675: sub resize_textarea_js {
 1676:     my $geometry = &viewport_geometry_js();
 1677:     return <<"RESIZE";
 1678:     <script type="text/javascript">
 1679: // <![CDATA[
 1680: $geometry
 1681: 
 1682: function getX(element) {
 1683:     var x = 0;
 1684:     while (element) {
 1685: 	x += element.offsetLeft;
 1686: 	element = element.offsetParent;
 1687:     }
 1688:     return x;
 1689: }
 1690: function getY(element) {
 1691:     var y = 0;
 1692:     while (element) {
 1693: 	y += element.offsetTop;
 1694: 	element = element.offsetParent;
 1695:     }
 1696:     return y;
 1697: }
 1698: 
 1699: 
 1700: function resize_textarea(textarea_id,bottom_id) {
 1701:     init_geometry();
 1702:     var textarea        = document.getElementById(textarea_id);
 1703:     //alert(textarea);
 1704: 
 1705:     var textarea_top    = getY(textarea);
 1706:     var textarea_height = textarea.offsetHeight;
 1707:     var bottom          = document.getElementById(bottom_id);
 1708:     var bottom_top      = getY(bottom);
 1709:     var bottom_height   = bottom.offsetHeight;
 1710:     var window_height   = Geometry.getViewportHeight();
 1711:     var fudge           = 23;
 1712:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1713:     if (new_height < 300) {
 1714: 	new_height = 300;
 1715:     }
 1716:     textarea.style.height=new_height+'px';
 1717: }
 1718: // ]]>
 1719: </script>
 1720: RESIZE
 1721: 
 1722: }
 1723: 
 1724: =pod
 1725: 
 1726: =head1 Excel and CSV file utility routines
 1727: 
 1728: =over 4
 1729: 
 1730: =cut
 1731: 
 1732: ###############################################################
 1733: ###############################################################
 1734: 
 1735: =pod
 1736: 
 1737: =item * &csv_translate($text) 
 1738: 
 1739: Translate $text to allow it to be output as a 'comma separated values' 
 1740: format.
 1741: 
 1742: =cut
 1743: 
 1744: ###############################################################
 1745: ###############################################################
 1746: sub csv_translate {
 1747:     my $text = shift;
 1748:     $text =~ s/\"/\"\"/g;
 1749:     $text =~ s/\n/ /g;
 1750:     return $text;
 1751: }
 1752: 
 1753: ###############################################################
 1754: ###############################################################
 1755: 
 1756: =pod
 1757: 
 1758: =item * &define_excel_formats()
 1759: 
 1760: Define some commonly used Excel cell formats.
 1761: 
 1762: Currently supported formats:
 1763: 
 1764: =over 4
 1765: 
 1766: =item header
 1767: 
 1768: =item bold
 1769: 
 1770: =item h1
 1771: 
 1772: =item h2
 1773: 
 1774: =item h3
 1775: 
 1776: =item h4
 1777: 
 1778: =item i
 1779: 
 1780: =item date
 1781: 
 1782: =back
 1783: 
 1784: Inputs: $workbook
 1785: 
 1786: Returns: $format, a hash reference.
 1787: 
 1788: 
 1789: =cut
 1790: 
 1791: ###############################################################
 1792: ###############################################################
 1793: sub define_excel_formats {
 1794:     my ($workbook) = @_;
 1795:     my $format;
 1796:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1797:                                                 bottom    => 1,
 1798:                                                 align     => 'center');
 1799:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1800:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1801:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1802:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1803:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1804:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1805:     $format->{'date'} = $workbook->add_format(num_format=>
 1806:                                             'mm/dd/yyyy hh:mm:ss');
 1807:     return $format;
 1808: }
 1809: 
 1810: ###############################################################
 1811: ###############################################################
 1812: 
 1813: =pod
 1814: 
 1815: =item * &create_workbook()
 1816: 
 1817: Create an Excel worksheet.  If it fails, output message on the
 1818: request object and return undefs.
 1819: 
 1820: Inputs: Apache request object
 1821: 
 1822: Returns (undef) on failure, 
 1823:     Excel worksheet object, scalar with filename, and formats 
 1824:     from &Apache::loncommon::define_excel_formats on success
 1825: 
 1826: =cut
 1827: 
 1828: ###############################################################
 1829: ###############################################################
 1830: sub create_workbook {
 1831:     my ($r) = @_;
 1832:         #
 1833:     # Create the excel spreadsheet
 1834:     my $filename = '/prtspool/'.
 1835:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1836:         time.'_'.rand(1000000000).'.xls';
 1837:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1838:     if (! defined($workbook)) {
 1839:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1840:         $r->print(
 1841:             '<p class="LC_error">'
 1842:            .&mt('Problems occurred in creating the new Excel file.')
 1843:            .' '.&mt('This error has been logged.')
 1844:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1845:            .'</p>'
 1846:         );
 1847:         return (undef);
 1848:     }
 1849:     #
 1850:     $workbook->set_tempdir(LONCAPA::tempdir());
 1851:     #
 1852:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1853:     return ($workbook,$filename,$format);
 1854: }
 1855: 
 1856: ###############################################################
 1857: ###############################################################
 1858: 
 1859: =pod
 1860: 
 1861: =item * &create_text_file()
 1862: 
 1863: Create a file to write to and eventually make available to the user.
 1864: If file creation fails, outputs an error message on the request object and 
 1865: return undefs.
 1866: 
 1867: Inputs: Apache request object, and file suffix
 1868: 
 1869: Returns (undef) on failure, 
 1870:     Filehandle and filename on success.
 1871: 
 1872: =cut
 1873: 
 1874: ###############################################################
 1875: ###############################################################
 1876: sub create_text_file {
 1877:     my ($r,$suffix) = @_;
 1878:     if (! defined($suffix)) { $suffix = 'txt'; };
 1879:     my $fh;
 1880:     my $filename = '/prtspool/'.
 1881:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1882:         time.'_'.rand(1000000000).'.'.$suffix;
 1883:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1884:     if (! defined($fh)) {
 1885:         $r->log_error("Couldn't open $filename for output $!");
 1886:         $r->print(
 1887:             '<p class="LC_error">'
 1888:            .&mt('Problems occurred in creating the output file.')
 1889:            .' '.&mt('This error has been logged.')
 1890:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1891:            .'</p>'
 1892:         );
 1893:     }
 1894:     return ($fh,$filename)
 1895: }
 1896: 
 1897: 
 1898: =pod 
 1899: 
 1900: =back
 1901: 
 1902: =cut
 1903: 
 1904: ###############################################################
 1905: ##        Home server <option> list generating code          ##
 1906: ###############################################################
 1907: 
 1908: # ------------------------------------------
 1909: 
 1910: sub domain_select {
 1911:     my ($name,$value,$multiple)=@_;
 1912:     my %domains=map { 
 1913: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1914:     } &Apache::lonnet::all_domains();
 1915:     if ($multiple) {
 1916: 	$domains{''}=&mt('Any domain');
 1917: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1918: 	return &multiple_select_form($name,$value,4,\%domains);
 1919:     } else {
 1920: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1921: 	return &select_form($name,$value,\%domains);
 1922:     }
 1923: }
 1924: 
 1925: #-------------------------------------------
 1926: 
 1927: =pod
 1928: 
 1929: =head1 Routines for form select boxes
 1930: 
 1931: =over 4
 1932: 
 1933: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1934: 
 1935: Returns a string containing a <select> element int multiple mode
 1936: 
 1937: 
 1938: Args:
 1939:   $name - name of the <select> element
 1940:   $value - scalar or array ref of values that should already be selected
 1941:   $size - number of rows long the select element is
 1942:   $hash - the elements should be 'option' => 'shown text'
 1943:           (shown text should already have been &mt())
 1944:   $order - (optional) array ref of the order to show the elements in
 1945: 
 1946: =cut
 1947: 
 1948: #-------------------------------------------
 1949: sub multiple_select_form {
 1950:     my ($name,$value,$size,$hash,$order)=@_;
 1951:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1952:     my $output='';
 1953:     if (! defined($size)) {
 1954:         $size = 4;
 1955:         if (scalar(keys(%$hash))<4) {
 1956:             $size = scalar(keys(%$hash));
 1957:         }
 1958:     }
 1959:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1960:     my @order;
 1961:     if (ref($order) eq 'ARRAY')  {
 1962:         @order = @{$order};
 1963:     } else {
 1964:         @order = sort(keys(%$hash));
 1965:     }
 1966:     if (exists($$hash{'select_form_order'})) {
 1967:         @order = @{$$hash{'select_form_order'}};
 1968:     }
 1969:         
 1970:     foreach my $key (@order) {
 1971:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1972:         $output.='selected="selected" ' if ($selected{$key});
 1973:         $output.='>'.$hash->{$key}."</option>\n";
 1974:     }
 1975:     $output.="</select>\n";
 1976:     return $output;
 1977: }
 1978: 
 1979: #-------------------------------------------
 1980: 
 1981: =pod
 1982: 
 1983: =item * &select_form($defdom,$name,$hashref,$onchange)
 1984: 
 1985: Returns a string containing a <select name='$name' size='1'> form to 
 1986: allow a user to select options from a ref to a hash containing:
 1987: option_name => displayed text. An optional $onchange can include
 1988: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1989: 
 1990: See lonrights.pm for an example invocation and use.
 1991: 
 1992: =cut
 1993: 
 1994: #-------------------------------------------
 1995: sub select_form {
 1996:     my ($def,$name,$hashref,$onchange) = @_;
 1997:     return unless (ref($hashref) eq 'HASH');
 1998:     if ($onchange) {
 1999:         $onchange = ' onchange="'.$onchange.'"';
 2000:     }
 2001:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2002:     my @keys;
 2003:     if (exists($hashref->{'select_form_order'})) {
 2004: 	@keys=@{$hashref->{'select_form_order'}};
 2005:     } else {
 2006: 	@keys=sort(keys(%{$hashref}));
 2007:     }
 2008:     foreach my $key (@keys) {
 2009:         $selectform.=
 2010: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2011:             ($key eq $def ? 'selected="selected" ' : '').
 2012:                 ">".$hashref->{$key}."</option>\n";
 2013:     }
 2014:     $selectform.="</select>";
 2015:     return $selectform;
 2016: }
 2017: 
 2018: # For display filters
 2019: 
 2020: sub display_filter {
 2021:     my ($context) = @_;
 2022:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2023:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2024:     my $phraseinput = 'hidden';
 2025:     my $includeinput = 'hidden';
 2026:     my ($checked,$includetypestext);
 2027:     if ($env{'form.displayfilter'} eq 'containing') {
 2028:         $phraseinput = 'text'; 
 2029:         if ($context eq 'parmslog') {
 2030:             $includeinput = 'checkbox';
 2031:             if ($env{'form.includetypes'}) {
 2032:                 $checked = ' checked="checked"';
 2033:             }
 2034:             $includetypestext = &mt('Include parameter types');
 2035:         }
 2036:     } else {
 2037:         $includetypestext = '&nbsp;';
 2038:     }
 2039:     my ($additional,$secondid,$thirdid);
 2040:     if ($context eq 'parmslog') {
 2041:         $additional = 
 2042:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2043:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2044:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2045:             '</label>';
 2046:         $secondid = 'includetypes';
 2047:         $thirdid = 'includetypestext';
 2048:     }
 2049:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2050:                                                     '$secondid','$thirdid')";
 2051:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2052: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2053: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2054: 	   '</label></span> <span class="LC_nobreak">'.
 2055:            &mt('Filter: [_1]',
 2056: 	   &select_form($env{'form.displayfilter'},
 2057: 			'displayfilter',
 2058: 			{'currentfolder' => 'Current folder/page',
 2059: 			 'containing' => 'Containing phrase',
 2060: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2061: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2062:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2063:                          '" />'.$additional;
 2064: }
 2065: 
 2066: sub display_filter_js {
 2067:     my $includetext = &mt('Include parameter types');
 2068:     return <<"ENDJS";
 2069:   
 2070: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2071:     var firstType = 'hidden';
 2072:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2073:         firstType = 'text';
 2074:     }
 2075:     firstObject = document.getElementById(firstid);
 2076:     if (typeof(firstObject) == 'object') {
 2077:         if (firstObject.type != firstType) {
 2078:             changeInputType(firstObject,firstType);
 2079:         }
 2080:     }
 2081:     if (context == 'parmslog') {
 2082:         var secondType = 'hidden';
 2083:         if (firstType == 'text') {
 2084:             secondType = 'checkbox';
 2085:         }
 2086:         secondObject = document.getElementById(secondid);  
 2087:         if (typeof(secondObject) == 'object') {
 2088:             if (secondObject.type != secondType) {
 2089:                 changeInputType(secondObject,secondType);
 2090:             }
 2091:         }
 2092:         var textItem = document.getElementById(thirdid);
 2093:         var currtext = textItem.innerHTML;
 2094:         var newtext;
 2095:         if (firstType == 'text') {
 2096:             newtext = '$includetext';
 2097:         } else {
 2098:             newtext = '&nbsp;';
 2099:         }
 2100:         if (currtext != newtext) {
 2101:             textItem.innerHTML = newtext;
 2102:         }
 2103:     }
 2104:     return;
 2105: }
 2106: 
 2107: function changeInputType(oldObject,newType) {
 2108:     var newObject = document.createElement('input');
 2109:     newObject.type = newType;
 2110:     if (oldObject.size) {
 2111:         newObject.size = oldObject.size;
 2112:     }
 2113:     if (oldObject.value) {
 2114:         newObject.value = oldObject.value;
 2115:     }
 2116:     if (oldObject.name) {
 2117:         newObject.name = oldObject.name;
 2118:     }
 2119:     if (oldObject.id) {
 2120:         newObject.id = oldObject.id;
 2121:     }
 2122:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2123:     return;
 2124: }
 2125: 
 2126: ENDJS
 2127: }
 2128: 
 2129: sub gradeleveldescription {
 2130:     my $gradelevel=shift;
 2131:     my %gradelevels=(0 => 'Not specified',
 2132: 		     1 => 'Grade 1',
 2133: 		     2 => 'Grade 2',
 2134: 		     3 => 'Grade 3',
 2135: 		     4 => 'Grade 4',
 2136: 		     5 => 'Grade 5',
 2137: 		     6 => 'Grade 6',
 2138: 		     7 => 'Grade 7',
 2139: 		     8 => 'Grade 8',
 2140: 		     9 => 'Grade 9',
 2141: 		     10 => 'Grade 10',
 2142: 		     11 => 'Grade 11',
 2143: 		     12 => 'Grade 12',
 2144: 		     13 => 'Grade 13',
 2145: 		     14 => '100 Level',
 2146: 		     15 => '200 Level',
 2147: 		     16 => '300 Level',
 2148: 		     17 => '400 Level',
 2149: 		     18 => 'Graduate Level');
 2150:     return &mt($gradelevels{$gradelevel});
 2151: }
 2152: 
 2153: sub select_level_form {
 2154:     my ($deflevel,$name)=@_;
 2155:     unless ($deflevel) { $deflevel=0; }
 2156:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2157:     for (my $i=0; $i<=18; $i++) {
 2158:         $selectform.="<option value=\"$i\" ".
 2159:             ($i==$deflevel ? 'selected="selected" ' : '').
 2160:                 ">".&gradeleveldescription($i)."</option>\n";
 2161:     }
 2162:     $selectform.="</select>";
 2163:     return $selectform;
 2164: }
 2165: 
 2166: #-------------------------------------------
 2167: 
 2168: =pod
 2169: 
 2170: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2171: 
 2172: Returns a string containing a <select name='$name' size='1'> form to 
 2173: allow a user to select the domain to preform an operation in.  
 2174: See loncreateuser.pm for an example invocation and use.
 2175: 
 2176: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2177: selected");
 2178: 
 2179: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2180: 
 2181: 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.
 2182: 
 2183: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2184: 
 2185: =cut
 2186: 
 2187: #-------------------------------------------
 2188: sub select_dom_form {
 2189:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2190:     if ($onchange) {
 2191:         $onchange = ' onchange="'.$onchange.'"';
 2192:     }
 2193:     my @domains;
 2194:     if (ref($incdoms) eq 'ARRAY') {
 2195:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2196:     } else {
 2197:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2198:     }
 2199:     if ($includeempty) { @domains=('',@domains); }
 2200:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2201:     foreach my $dom (@domains) {
 2202:         $selectdomain.="<option value=\"$dom\" ".
 2203:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2204:         if ($showdomdesc) {
 2205:             if ($dom ne '') {
 2206:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2207:                 if ($domdesc ne '') {
 2208:                     $selectdomain .= ' ('.$domdesc.')';
 2209:                 }
 2210:             } 
 2211:         }
 2212:         $selectdomain .= "</option>\n";
 2213:     }
 2214:     $selectdomain.="</select>";
 2215:     return $selectdomain;
 2216: }
 2217: 
 2218: #-------------------------------------------
 2219: 
 2220: =pod
 2221: 
 2222: =item * &home_server_form_item($domain,$name,$defaultflag)
 2223: 
 2224: input: 4 arguments (two required, two optional) - 
 2225:     $domain - domain of new user
 2226:     $name - name of form element
 2227:     $default - Value of 'default' causes a default item to be first 
 2228:                             option, and selected by default. 
 2229:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2230:                             if 1 server found, or default, if 0 found.
 2231: output: returns 2 items: 
 2232: (a) form element which contains either:
 2233:    (i) <select name="$name">
 2234:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2235:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2236:        </select>
 2237:        form item if there are multiple library servers in $domain, or
 2238:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2239:        if there is only one library server in $domain.
 2240: 
 2241: (b) number of library servers found.
 2242: 
 2243: See loncreateuser.pm for example of use.
 2244: 
 2245: =cut
 2246: 
 2247: #-------------------------------------------
 2248: sub home_server_form_item {
 2249:     my ($domain,$name,$default,$hide) = @_;
 2250:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2251:     my $result;
 2252:     my $numlib = keys(%servers);
 2253:     if ($numlib > 1) {
 2254:         $result .= '<select name="'.$name.'" />'."\n";
 2255:         if ($default) {
 2256:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2257:                        '</option>'."\n";
 2258:         }
 2259:         foreach my $hostid (sort(keys(%servers))) {
 2260:             $result.= '<option value="'.$hostid.'">'.
 2261: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2262:         }
 2263:         $result .= '</select>'."\n";
 2264:     } elsif ($numlib == 1) {
 2265:         my $hostid;
 2266:         foreach my $item (keys(%servers)) {
 2267:             $hostid = $item;
 2268:         }
 2269:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2270:                    $hostid.'" />';
 2271:                    if (!$hide) {
 2272:                        $result .= $hostid.' '.$servers{$hostid};
 2273:                    }
 2274:                    $result .= "\n";
 2275:     } elsif ($default) {
 2276:         $result .= '<input type="hidden" name="'.$name.
 2277:                    '" value="default" />';
 2278:                    if (!$hide) {
 2279:                        $result .= &mt('default');
 2280:                    }
 2281:                    $result .= "\n";
 2282:     }
 2283:     return ($result,$numlib);
 2284: }
 2285: 
 2286: =pod
 2287: 
 2288: =back 
 2289: 
 2290: =cut
 2291: 
 2292: ###############################################################
 2293: ##                  Decoding User Agent                      ##
 2294: ###############################################################
 2295: 
 2296: =pod
 2297: 
 2298: =head1 Decoding the User Agent
 2299: 
 2300: =over 4
 2301: 
 2302: =item * &decode_user_agent()
 2303: 
 2304: Inputs: $r
 2305: 
 2306: Outputs:
 2307: 
 2308: =over 4
 2309: 
 2310: =item * $httpbrowser
 2311: 
 2312: =item * $clientbrowser
 2313: 
 2314: =item * $clientversion
 2315: 
 2316: =item * $clientmathml
 2317: 
 2318: =item * $clientunicode
 2319: 
 2320: =item * $clientos
 2321: 
 2322: =back
 2323: 
 2324: =back 
 2325: 
 2326: =cut
 2327: 
 2328: ###############################################################
 2329: ###############################################################
 2330: sub decode_user_agent {
 2331:     my ($r)=@_;
 2332:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2333:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2334:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2335:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2336:     my $clientbrowser='unknown';
 2337:     my $clientversion='0';
 2338:     my $clientmathml='';
 2339:     my $clientunicode='0';
 2340:     for (my $i=0;$i<=$#browsertype;$i++) {
 2341:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2342: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2343: 	    $clientbrowser=$bname;
 2344:             $httpbrowser=~/$vreg/i;
 2345: 	    $clientversion=$1;
 2346:             $clientmathml=($clientversion>=$minv);
 2347:             $clientunicode=($clientversion>=$univ);
 2348: 	}
 2349:     }
 2350:     my $clientos='unknown';
 2351:     if (($httpbrowser=~/linux/i) ||
 2352:         ($httpbrowser=~/unix/i) ||
 2353:         ($httpbrowser=~/ux/i) ||
 2354:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2355:     if (($httpbrowser=~/vax/i) ||
 2356:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2357:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2358:     if (($httpbrowser=~/mac/i) ||
 2359:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2360:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2361:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2362:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2363:             $clientunicode,$clientos,);
 2364: }
 2365: 
 2366: ###############################################################
 2367: ##    Authentication changing form generation subroutines    ##
 2368: ###############################################################
 2369: ##
 2370: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2371: ## hash, and have reasonable default values.
 2372: ##
 2373: ##    formname = the name given in the <form> tag.
 2374: #-------------------------------------------
 2375: 
 2376: =pod
 2377: 
 2378: =head1 Authentication Routines
 2379: 
 2380: =over 4
 2381: 
 2382: =item * &authform_xxxxxx()
 2383: 
 2384: The authform_xxxxxx subroutines provide javascript and html forms which 
 2385: handle some of the conveniences required for authentication forms.  
 2386: This is not an optimal method, but it works.  
 2387: 
 2388: =over 4
 2389: 
 2390: =item * authform_header
 2391: 
 2392: =item * authform_authorwarning
 2393: 
 2394: =item * authform_nochange
 2395: 
 2396: =item * authform_kerberos
 2397: 
 2398: =item * authform_internal
 2399: 
 2400: =item * authform_filesystem
 2401: 
 2402: =back
 2403: 
 2404: See loncreateuser.pm for invocation and use examples.
 2405: 
 2406: =cut
 2407: 
 2408: #-------------------------------------------
 2409: sub authform_header{  
 2410:     my %in = (
 2411:         formname => 'cu',
 2412:         kerb_def_dom => '',
 2413:         @_,
 2414:     );
 2415:     $in{'formname'} = 'document.' . $in{'formname'};
 2416:     my $result='';
 2417: 
 2418: #---------------------------------------------- Code for upper case translation
 2419:     my $Javascript_toUpperCase;
 2420:     unless ($in{kerb_def_dom}) {
 2421:         $Javascript_toUpperCase =<<"END";
 2422:         switch (choice) {
 2423:            case 'krb': currentform.elements[choicearg].value =
 2424:                currentform.elements[choicearg].value.toUpperCase();
 2425:                break;
 2426:            default:
 2427:         }
 2428: END
 2429:     } else {
 2430:         $Javascript_toUpperCase = "";
 2431:     }
 2432: 
 2433:     my $radioval = "'nochange'";
 2434:     if (defined($in{'curr_authtype'})) {
 2435:         if ($in{'curr_authtype'} ne '') {
 2436:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2437:         }
 2438:     }
 2439:     my $argfield = 'null';
 2440:     if (defined($in{'mode'})) {
 2441:         if ($in{'mode'} eq 'modifycourse')  {
 2442:             if (defined($in{'curr_autharg'})) {
 2443:                 if ($in{'curr_autharg'} ne '') {
 2444:                     $argfield = "'$in{'curr_autharg'}'";
 2445:                 }
 2446:             }
 2447:         }
 2448:     }
 2449: 
 2450:     $result.=<<"END";
 2451: var current = new Object();
 2452: current.radiovalue = $radioval;
 2453: current.argfield = $argfield;
 2454: 
 2455: function changed_radio(choice,currentform) {
 2456:     var choicearg = choice + 'arg';
 2457:     // If a radio button in changed, we need to change the argfield
 2458:     if (current.radiovalue != choice) {
 2459:         current.radiovalue = choice;
 2460:         if (current.argfield != null) {
 2461:             currentform.elements[current.argfield].value = '';
 2462:         }
 2463:         if (choice == 'nochange') {
 2464:             current.argfield = null;
 2465:         } else {
 2466:             current.argfield = choicearg;
 2467:             switch(choice) {
 2468:                 case 'krb': 
 2469:                     currentform.elements[current.argfield].value = 
 2470:                         "$in{'kerb_def_dom'}";
 2471:                 break;
 2472:               default:
 2473:                 break;
 2474:             }
 2475:         }
 2476:     }
 2477:     return;
 2478: }
 2479: 
 2480: function changed_text(choice,currentform) {
 2481:     var choicearg = choice + 'arg';
 2482:     if (currentform.elements[choicearg].value !='') {
 2483:         $Javascript_toUpperCase
 2484:         // clear old field
 2485:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2486:             currentform.elements[current.argfield].value = '';
 2487:         }
 2488:         current.argfield = choicearg;
 2489:     }
 2490:     set_auth_radio_buttons(choice,currentform);
 2491:     return;
 2492: }
 2493: 
 2494: function set_auth_radio_buttons(newvalue,currentform) {
 2495:     var numauthchoices = currentform.login.length;
 2496:     if (typeof numauthchoices  == "undefined") {
 2497:         return;
 2498:     } 
 2499:     var i=0;
 2500:     while (i < numauthchoices) {
 2501:         if (currentform.login[i].value == newvalue) { break; }
 2502:         i++;
 2503:     }
 2504:     if (i == numauthchoices) {
 2505:         return;
 2506:     }
 2507:     current.radiovalue = newvalue;
 2508:     currentform.login[i].checked = true;
 2509:     return;
 2510: }
 2511: END
 2512:     return $result;
 2513: }
 2514: 
 2515: sub authform_authorwarning {
 2516:     my $result='';
 2517:     $result='<i>'.
 2518:         &mt('As a general rule, only authors or co-authors should be '.
 2519:             'filesystem authenticated '.
 2520:             '(which allows access to the server filesystem).')."</i>\n";
 2521:     return $result;
 2522: }
 2523: 
 2524: sub authform_nochange {
 2525:     my %in = (
 2526:               formname => 'document.cu',
 2527:               kerb_def_dom => 'MSU.EDU',
 2528:               @_,
 2529:           );
 2530:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2531:     my $result;
 2532:     if (!$authnum) {
 2533:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2534:     } else {
 2535:         $result = '<label>'.&mt('[_1] Do not change login data',
 2536:                   '<input type="radio" name="login" value="nochange" '.
 2537:                   'checked="checked" onclick="'.
 2538:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2539: 	    '</label>';
 2540:     }
 2541:     return $result;
 2542: }
 2543: 
 2544: sub authform_kerberos {
 2545:     my %in = (
 2546:               formname => 'document.cu',
 2547:               kerb_def_dom => 'MSU.EDU',
 2548:               kerb_def_auth => 'krb4',
 2549:               @_,
 2550:               );
 2551:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2552:         $autharg,$jscall);
 2553:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2554:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2555:        $check5 = ' checked="checked"';
 2556:     } else {
 2557:        $check4 = ' checked="checked"';
 2558:     }
 2559:     $krbarg = $in{'kerb_def_dom'};
 2560:     if (defined($in{'curr_authtype'})) {
 2561:         if ($in{'curr_authtype'} eq 'krb') {
 2562:             $krbcheck = ' checked="checked"';
 2563:             if (defined($in{'mode'})) {
 2564:                 if ($in{'mode'} eq 'modifyuser') {
 2565:                     $krbcheck = '';
 2566:                 }
 2567:             }
 2568:             if (defined($in{'curr_kerb_ver'})) {
 2569:                 if ($in{'curr_krb_ver'} eq '5') {
 2570:                     $check5 = ' checked="checked"';
 2571:                     $check4 = '';
 2572:                 } else {
 2573:                     $check4 = ' checked="checked"';
 2574:                     $check5 = '';
 2575:                 }
 2576:             }
 2577:             if (defined($in{'curr_autharg'})) {
 2578:                 $krbarg = $in{'curr_autharg'};
 2579:             }
 2580:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2581:                 if (defined($in{'curr_autharg'})) {
 2582:                     $result = 
 2583:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2584:         $in{'curr_autharg'},$krbver);
 2585:                 } else {
 2586:                     $result =
 2587:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2588:                 }
 2589:                 return $result; 
 2590:             }
 2591:         }
 2592:     } else {
 2593:         if ($authnum == 1) {
 2594:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2595:         }
 2596:     }
 2597:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2598:         return;
 2599:     } elsif ($authtype eq '') {
 2600:         if (defined($in{'mode'})) {
 2601:             if ($in{'mode'} eq 'modifycourse') {
 2602:                 if ($authnum == 1) {
 2603:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2604:                 }
 2605:             }
 2606:         }
 2607:     }
 2608:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2609:     if ($authtype eq '') {
 2610:         $authtype = '<input type="radio" name="login" value="krb" '.
 2611:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2612:                     $krbcheck.' />';
 2613:     }
 2614:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2615:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2616:          $in{'curr_authtype'} eq 'krb5') ||
 2617:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2618:          $in{'curr_authtype'} eq 'krb4')) {
 2619:         $result .= &mt
 2620:         ('[_1] Kerberos authenticated with domain [_2] '.
 2621:          '[_3] Version 4 [_4] Version 5 [_5]',
 2622:          '<label>'.$authtype,
 2623:          '</label><input type="text" size="10" name="krbarg" '.
 2624:              'value="'.$krbarg.'" '.
 2625:              'onchange="'.$jscall.'" />',
 2626:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2627:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2628: 	 '</label>');
 2629:     } elsif ($can_assign{'krb4'}) {
 2630:         $result .= &mt
 2631:         ('[_1] Kerberos authenticated with domain [_2] '.
 2632:          '[_3] Version 4 [_4]',
 2633:          '<label>'.$authtype,
 2634:          '</label><input type="text" size="10" name="krbarg" '.
 2635:              'value="'.$krbarg.'" '.
 2636:              'onchange="'.$jscall.'" />',
 2637:          '<label><input type="hidden" name="krbver" value="4" />',
 2638:          '</label>');
 2639:     } elsif ($can_assign{'krb5'}) {
 2640:         $result .= &mt
 2641:         ('[_1] Kerberos authenticated with domain [_2] '.
 2642:          '[_3] Version 5 [_4]',
 2643:          '<label>'.$authtype,
 2644:          '</label><input type="text" size="10" name="krbarg" '.
 2645:              'value="'.$krbarg.'" '.
 2646:              'onchange="'.$jscall.'" />',
 2647:          '<label><input type="hidden" name="krbver" value="5" />',
 2648:          '</label>');
 2649:     }
 2650:     return $result;
 2651: }
 2652: 
 2653: sub authform_internal {
 2654:     my %in = (
 2655:                 formname => 'document.cu',
 2656:                 kerb_def_dom => 'MSU.EDU',
 2657:                 @_,
 2658:                 );
 2659:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2660:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2661:     if (defined($in{'curr_authtype'})) {
 2662:         if ($in{'curr_authtype'} eq 'int') {
 2663:             if ($can_assign{'int'}) {
 2664:                 $intcheck = 'checked="checked" ';
 2665:                 if (defined($in{'mode'})) {
 2666:                     if ($in{'mode'} eq 'modifyuser') {
 2667:                         $intcheck = '';
 2668:                     }
 2669:                 }
 2670:                 if (defined($in{'curr_autharg'})) {
 2671:                     $intarg = $in{'curr_autharg'};
 2672:                 }
 2673:             } else {
 2674:                 $result = &mt('Currently internally authenticated.');
 2675:                 return $result;
 2676:             }
 2677:         }
 2678:     } else {
 2679:         if ($authnum == 1) {
 2680:             $authtype = '<input type="hidden" name="login" value="int" />';
 2681:         }
 2682:     }
 2683:     if (!$can_assign{'int'}) {
 2684:         return;
 2685:     } elsif ($authtype eq '') {
 2686:         if (defined($in{'mode'})) {
 2687:             if ($in{'mode'} eq 'modifycourse') {
 2688:                 if ($authnum == 1) {
 2689:                     $authtype = '<input type="radio" name="login" value="int" />';
 2690:                 }
 2691:             }
 2692:         }
 2693:     }
 2694:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2695:     if ($authtype eq '') {
 2696:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2697:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2698:     }
 2699:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2700:                $intarg.'" onchange="'.$jscall.'" />';
 2701:     $result = &mt
 2702:         ('[_1] Internally authenticated (with initial password [_2])',
 2703:          '<label>'.$authtype,'</label>'.$autharg);
 2704:     $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>';
 2705:     return $result;
 2706: }
 2707: 
 2708: sub authform_local {
 2709:     my %in = (
 2710:               formname => 'document.cu',
 2711:               kerb_def_dom => 'MSU.EDU',
 2712:               @_,
 2713:               );
 2714:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2715:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2716:     if (defined($in{'curr_authtype'})) {
 2717:         if ($in{'curr_authtype'} eq 'loc') {
 2718:             if ($can_assign{'loc'}) {
 2719:                 $loccheck = 'checked="checked" ';
 2720:                 if (defined($in{'mode'})) {
 2721:                     if ($in{'mode'} eq 'modifyuser') {
 2722:                         $loccheck = '';
 2723:                     }
 2724:                 }
 2725:                 if (defined($in{'curr_autharg'})) {
 2726:                     $locarg = $in{'curr_autharg'};
 2727:                 }
 2728:             } else {
 2729:                 $result = &mt('Currently using local (institutional) authentication.');
 2730:                 return $result;
 2731:             }
 2732:         }
 2733:     } else {
 2734:         if ($authnum == 1) {
 2735:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2736:         }
 2737:     }
 2738:     if (!$can_assign{'loc'}) {
 2739:         return;
 2740:     } elsif ($authtype eq '') {
 2741:         if (defined($in{'mode'})) {
 2742:             if ($in{'mode'} eq 'modifycourse') {
 2743:                 if ($authnum == 1) {
 2744:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2745:                 }
 2746:             }
 2747:         }
 2748:     }
 2749:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2750:     if ($authtype eq '') {
 2751:         $authtype = '<input type="radio" name="login" value="loc" '.
 2752:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2753:                     $jscall.'" />';
 2754:     }
 2755:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2756:                $locarg.'" onchange="'.$jscall.'" />';
 2757:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2758:                   '<label>'.$authtype,'</label>'.$autharg);
 2759:     return $result;
 2760: }
 2761: 
 2762: sub authform_filesystem {
 2763:     my %in = (
 2764:               formname => 'document.cu',
 2765:               kerb_def_dom => 'MSU.EDU',
 2766:               @_,
 2767:               );
 2768:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2769:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2770:     if (defined($in{'curr_authtype'})) {
 2771:         if ($in{'curr_authtype'} eq 'fsys') {
 2772:             if ($can_assign{'fsys'}) {
 2773:                 $fsyscheck = 'checked="checked" ';
 2774:                 if (defined($in{'mode'})) {
 2775:                     if ($in{'mode'} eq 'modifyuser') {
 2776:                         $fsyscheck = '';
 2777:                     }
 2778:                 }
 2779:             } else {
 2780:                 $result = &mt('Currently Filesystem Authenticated.');
 2781:                 return $result;
 2782:             }           
 2783:         }
 2784:     } else {
 2785:         if ($authnum == 1) {
 2786:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2787:         }
 2788:     }
 2789:     if (!$can_assign{'fsys'}) {
 2790:         return;
 2791:     } elsif ($authtype eq '') {
 2792:         if (defined($in{'mode'})) {
 2793:             if ($in{'mode'} eq 'modifycourse') {
 2794:                 if ($authnum == 1) {
 2795:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2796:                 }
 2797:             }
 2798:         }
 2799:     }
 2800:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2801:     if ($authtype eq '') {
 2802:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2803:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2804:                     $jscall.'" />';
 2805:     }
 2806:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2807:                ' onchange="'.$jscall.'" />';
 2808:     $result = &mt
 2809:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2810:          '<label><input type="radio" name="login" value="fsys" '.
 2811:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2812:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2813:                   'onchange="'.$jscall.'" />');
 2814:     return $result;
 2815: }
 2816: 
 2817: sub get_assignable_auth {
 2818:     my ($dom) = @_;
 2819:     if ($dom eq '') {
 2820:         $dom = $env{'request.role.domain'};
 2821:     }
 2822:     my %can_assign = (
 2823:                           krb4 => 1,
 2824:                           krb5 => 1,
 2825:                           int  => 1,
 2826:                           loc  => 1,
 2827:                      );
 2828:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2829:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2830:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2831:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2832:             my $context;
 2833:             if ($env{'request.role'} =~ /^au/) {
 2834:                 $context = 'author';
 2835:             } elsif ($env{'request.role'} =~ /^dc/) {
 2836:                 $context = 'domain';
 2837:             } elsif ($env{'request.course.id'}) {
 2838:                 $context = 'course';
 2839:             }
 2840:             if ($context) {
 2841:                 if (ref($authhash->{$context}) eq 'HASH') {
 2842:                    %can_assign = %{$authhash->{$context}}; 
 2843:                 }
 2844:             }
 2845:         }
 2846:     }
 2847:     my $authnum = 0;
 2848:     foreach my $key (keys(%can_assign)) {
 2849:         if ($can_assign{$key}) {
 2850:             $authnum ++;
 2851:         }
 2852:     }
 2853:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2854:         $authnum --;
 2855:     }
 2856:     return ($authnum,%can_assign);
 2857: }
 2858: 
 2859: ###############################################################
 2860: ##    Get Kerberos Defaults for Domain                 ##
 2861: ###############################################################
 2862: ##
 2863: ## Returns default kerberos version and an associated argument
 2864: ## as listed in file domain.tab. If not listed, provides
 2865: ## appropriate default domain and kerberos version.
 2866: ##
 2867: #-------------------------------------------
 2868: 
 2869: =pod
 2870: 
 2871: =item * &get_kerberos_defaults()
 2872: 
 2873: get_kerberos_defaults($target_domain) returns the default kerberos
 2874: version and domain. If not found, it defaults to version 4 and the 
 2875: domain of the server.
 2876: 
 2877: =over 4
 2878: 
 2879: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2880: 
 2881: =back
 2882: 
 2883: =back
 2884: 
 2885: =cut
 2886: 
 2887: #-------------------------------------------
 2888: sub get_kerberos_defaults {
 2889:     my $domain=shift;
 2890:     my ($krbdef,$krbdefdom);
 2891:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2892:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2893:         $krbdef = $domdefaults{'auth_def'};
 2894:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2895:     } else {
 2896:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2897:         my $krbdefdom=$1;
 2898:         $krbdefdom=~tr/a-z/A-Z/;
 2899:         $krbdef = "krb4";
 2900:     }
 2901:     return ($krbdef,$krbdefdom);
 2902: }
 2903: 
 2904: 
 2905: ###############################################################
 2906: ##                Thesaurus Functions                        ##
 2907: ###############################################################
 2908: 
 2909: =pod
 2910: 
 2911: =head1 Thesaurus Functions
 2912: 
 2913: =over 4
 2914: 
 2915: =item * &initialize_keywords()
 2916: 
 2917: Initializes the package variable %Keywords if it is empty.  Uses the
 2918: package variable $thesaurus_db_file.
 2919: 
 2920: =cut
 2921: 
 2922: ###################################################
 2923: 
 2924: sub initialize_keywords {
 2925:     return 1 if (scalar keys(%Keywords));
 2926:     # If we are here, %Keywords is empty, so fill it up
 2927:     #   Make sure the file we need exists...
 2928:     if (! -e $thesaurus_db_file) {
 2929:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2930:                                  " failed because it does not exist");
 2931:         return 0;
 2932:     }
 2933:     #   Set up the hash as a database
 2934:     my %thesaurus_db;
 2935:     if (! tie(%thesaurus_db,'GDBM_File',
 2936:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2937:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2938:                                  $thesaurus_db_file);
 2939:         return 0;
 2940:     } 
 2941:     #  Get the average number of appearances of a word.
 2942:     my $avecount = $thesaurus_db{'average.count'};
 2943:     #  Put keywords (those that appear > average) into %Keywords
 2944:     while (my ($word,$data)=each (%thesaurus_db)) {
 2945:         my ($count,undef) = split /:/,$data;
 2946:         $Keywords{$word}++ if ($count > $avecount);
 2947:     }
 2948:     untie %thesaurus_db;
 2949:     # Remove special values from %Keywords.
 2950:     foreach my $value ('total.count','average.count') {
 2951:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2952:   }
 2953:     return 1;
 2954: }
 2955: 
 2956: ###################################################
 2957: 
 2958: =pod
 2959: 
 2960: =item * &keyword($word)
 2961: 
 2962: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2963: than the average number of times in the thesaurus database.  Calls 
 2964: &initialize_keywords
 2965: 
 2966: =cut
 2967: 
 2968: ###################################################
 2969: 
 2970: sub keyword {
 2971:     return if (!&initialize_keywords());
 2972:     my $word=lc(shift());
 2973:     $word=~s/\W//g;
 2974:     return exists($Keywords{$word});
 2975: }
 2976: 
 2977: ###############################################################
 2978: 
 2979: =pod 
 2980: 
 2981: =item * &get_related_words()
 2982: 
 2983: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2984: an array of words.  If the keyword is not in the thesaurus, an empty array
 2985: will be returned.  The order of the words returned is determined by the
 2986: database which holds them.
 2987: 
 2988: Uses global $thesaurus_db_file.
 2989: 
 2990: 
 2991: =cut
 2992: 
 2993: ###############################################################
 2994: sub get_related_words {
 2995:     my $keyword = shift;
 2996:     my %thesaurus_db;
 2997:     if (! -e $thesaurus_db_file) {
 2998:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2999:                                  "failed because the file does not exist");
 3000:         return ();
 3001:     }
 3002:     if (! tie(%thesaurus_db,'GDBM_File',
 3003:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3004:         return ();
 3005:     } 
 3006:     my @Words=();
 3007:     my $count=0;
 3008:     if (exists($thesaurus_db{$keyword})) {
 3009: 	# The first element is the number of times
 3010: 	# the word appears.  We do not need it now.
 3011: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3012: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3013: 	my $threshold=$mostfrequentcount/10;
 3014:         foreach my $possibleword (@RelatedWords) {
 3015:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3016:             if ($wordcount>$threshold) {
 3017: 		push(@Words,$word);
 3018:                 $count++;
 3019:                 if ($count>10) { last; }
 3020: 	    }
 3021:         }
 3022:     }
 3023:     untie %thesaurus_db;
 3024:     return @Words;
 3025: }
 3026: ###############################################################
 3027: #
 3028: #  Spell checking
 3029: #
 3030: 
 3031: =pod
 3032: 
 3033: =head1 Spell checking
 3034: 
 3035: =over 4
 3036: 
 3037: =item * &check_spelling($wordlist $language)
 3038: 
 3039: Takes a string containing words and feeds it to an external
 3040: spellcheck program via a pipeline. Returns a string containing
 3041: them mis-spelled words.
 3042: 
 3043: Parameters:
 3044: 
 3045: =over 4
 3046: 
 3047: =item - $wordlist
 3048: 
 3049: String that will be fed into the spellcheck program.
 3050: 
 3051: =item - $language
 3052: 
 3053: Language string that specifies the language for which the spell
 3054: check will be performed.
 3055: 
 3056: =back
 3057: 
 3058: =back
 3059: 
 3060: Note: This sub assumes that aspell is installed.
 3061: 
 3062: 
 3063: =cut
 3064: 
 3065: 
 3066: =pod
 3067: 
 3068: =back
 3069: 
 3070: =cut
 3071: 
 3072: sub check_spelling {
 3073:     my ($wordlist, $language) = @_;
 3074:     my @misspellings;
 3075:     
 3076:     # Generate the speller and set the langauge.
 3077:     # if explicitly selected:
 3078: 
 3079:     my $speller = Text::Aspell->new;
 3080:     if ($language) {
 3081: 	$speller->set_option('lang', $language);
 3082:     }
 3083: 
 3084:     # Turn the word list into an array of words by splittingon whitespace
 3085: 
 3086:     my @words = split(/\s+/, $wordlist);
 3087: 
 3088:     foreach my $word (@words) {
 3089: 	if(! $speller->check($word)) {
 3090: 	    push(@misspellings, $word);
 3091: 	}
 3092:     }
 3093:     return join(' ', @misspellings);
 3094:     
 3095: }
 3096: 
 3097: # -------------------------------------------------------------- Plaintext name
 3098: =pod
 3099: 
 3100: =head1 User Name Functions
 3101: 
 3102: =over 4
 3103: 
 3104: =item * &plainname($uname,$udom,$first)
 3105: 
 3106: Takes a users logon name and returns it as a string in
 3107: "first middle last generation" form 
 3108: if $first is set to 'lastname' then it returns it as
 3109: 'lastname generation, firstname middlename' if their is a lastname
 3110: 
 3111: =cut
 3112: 
 3113: 
 3114: ###############################################################
 3115: sub plainname {
 3116:     my ($uname,$udom,$first)=@_;
 3117:     return if (!defined($uname) || !defined($udom));
 3118:     my %names=&getnames($uname,$udom);
 3119:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3120: 					  $names{'middlename'},
 3121: 					  $names{'lastname'},
 3122: 					  $names{'generation'},$first);
 3123:     $name=~s/^\s+//;
 3124:     $name=~s/\s+$//;
 3125:     $name=~s/\s+/ /g;
 3126:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3127:     return $name;
 3128: }
 3129: 
 3130: # -------------------------------------------------------------------- Nickname
 3131: =pod
 3132: 
 3133: =item * &nickname($uname,$udom)
 3134: 
 3135: Gets a users name and returns it as a string as
 3136: 
 3137: "&quot;nickname&quot;"
 3138: 
 3139: if the user has a nickname or
 3140: 
 3141: "first middle last generation"
 3142: 
 3143: if the user does not
 3144: 
 3145: =cut
 3146: 
 3147: sub nickname {
 3148:     my ($uname,$udom)=@_;
 3149:     return if (!defined($uname) || !defined($udom));
 3150:     my %names=&getnames($uname,$udom);
 3151:     my $name=$names{'nickname'};
 3152:     if ($name) {
 3153:        $name='&quot;'.$name.'&quot;'; 
 3154:     } else {
 3155:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3156: 	     $names{'lastname'}.' '.$names{'generation'};
 3157:        $name=~s/\s+$//;
 3158:        $name=~s/\s+/ /g;
 3159:     }
 3160:     return $name;
 3161: }
 3162: 
 3163: sub getnames {
 3164:     my ($uname,$udom)=@_;
 3165:     return if (!defined($uname) || !defined($udom));
 3166:     if ($udom eq 'public' && $uname eq 'public') {
 3167: 	return ('lastname' => &mt('Public'));
 3168:     }
 3169:     my $id=$uname.':'.$udom;
 3170:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3171:     if ($cached) {
 3172: 	return %{$names};
 3173:     } else {
 3174: 	my %loadnames=&Apache::lonnet::get('environment',
 3175:                     ['firstname','middlename','lastname','generation','nickname'],
 3176: 					 $udom,$uname);
 3177: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3178: 	return %loadnames;
 3179:     }
 3180: }
 3181: 
 3182: # -------------------------------------------------------------------- getemails
 3183: 
 3184: =pod
 3185: 
 3186: =item * &getemails($uname,$udom)
 3187: 
 3188: Gets a user's email information and returns it as a hash with keys:
 3189: notification, critnotification, permanentemail
 3190: 
 3191: For notification and critnotification, values are comma-separated lists 
 3192: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3193:  
 3194: 
 3195: =cut
 3196: 
 3197: 
 3198: sub getemails {
 3199:     my ($uname,$udom)=@_;
 3200:     if ($udom eq 'public' && $uname eq 'public') {
 3201: 	return;
 3202:     }
 3203:     if (!$udom) { $udom=$env{'user.domain'}; }
 3204:     if (!$uname) { $uname=$env{'user.name'}; }
 3205:     my $id=$uname.':'.$udom;
 3206:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3207:     if ($cached) {
 3208: 	return %{$names};
 3209:     } else {
 3210: 	my %loadnames=&Apache::lonnet::get('environment',
 3211:                     			   ['notification','critnotification',
 3212: 					    'permanentemail'],
 3213: 					   $udom,$uname);
 3214: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3215: 	return %loadnames;
 3216:     }
 3217: }
 3218: 
 3219: sub flush_email_cache {
 3220:     my ($uname,$udom)=@_;
 3221:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3222:     if (!$uname) { $uname=$env{'user.name'};   }
 3223:     return if ($udom eq 'public' && $uname eq 'public');
 3224:     my $id=$uname.':'.$udom;
 3225:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3226: }
 3227: 
 3228: # -------------------------------------------------------------------- getlangs
 3229: 
 3230: =pod
 3231: 
 3232: =item * &getlangs($uname,$udom)
 3233: 
 3234: Gets a user's language preference and returns it as a hash with key:
 3235: language.
 3236: 
 3237: =cut
 3238: 
 3239: 
 3240: sub getlangs {
 3241:     my ($uname,$udom) = @_;
 3242:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3243:     if (!$uname) { $uname=$env{'user.name'};   }
 3244:     my $id=$uname.':'.$udom;
 3245:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3246:     if ($cached) {
 3247:         return %{$langs};
 3248:     } else {
 3249:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3250:                                            $udom,$uname);
 3251:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3252:         return %loadlangs;
 3253:     }
 3254: }
 3255: 
 3256: sub flush_langs_cache {
 3257:     my ($uname,$udom)=@_;
 3258:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3259:     if (!$uname) { $uname=$env{'user.name'};   }
 3260:     return if ($udom eq 'public' && $uname eq 'public');
 3261:     my $id=$uname.':'.$udom;
 3262:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3263: }
 3264: 
 3265: # ------------------------------------------------------------------ Screenname
 3266: 
 3267: =pod
 3268: 
 3269: =item * &screenname($uname,$udom)
 3270: 
 3271: Gets a users screenname and returns it as a string
 3272: 
 3273: =cut
 3274: 
 3275: sub screenname {
 3276:     my ($uname,$udom)=@_;
 3277:     if ($uname eq $env{'user.name'} &&
 3278: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3279:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3280:     return $names{'screenname'};
 3281: }
 3282: 
 3283: 
 3284: # ------------------------------------------------------------- Confirm Wrapper
 3285: =pod
 3286: 
 3287: =item confirmwrapper
 3288: 
 3289: Wrap messages about completion of operation in box
 3290: 
 3291: =cut
 3292: 
 3293: sub confirmwrapper {
 3294:     my ($message)=@_;
 3295:     if ($message) {
 3296:         return "\n".'<div class="LC_confirm_box">'."\n"
 3297:                .$message."\n"
 3298:                .'</div>'."\n";
 3299:     } else {
 3300:         return $message;
 3301:     }
 3302: }
 3303: 
 3304: # ------------------------------------------------------------- Message Wrapper
 3305: 
 3306: sub messagewrapper {
 3307:     my ($link,$username,$domain,$subject,$text)=@_;
 3308:     return 
 3309:         '<a href="/adm/email?compose=individual&amp;'.
 3310:         'recname='.$username.'&amp;recdom='.$domain.
 3311: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3312:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3313: }
 3314: 
 3315: # --------------------------------------------------------------- Notes Wrapper
 3316: 
 3317: sub noteswrapper {
 3318:     my ($link,$un,$do)=@_;
 3319:     return 
 3320: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3321: }
 3322: 
 3323: # ------------------------------------------------------------- Aboutme Wrapper
 3324: 
 3325: sub aboutmewrapper {
 3326:     my ($link,$username,$domain,$target,$class)=@_;
 3327:     if (!defined($username)  && !defined($domain)) {
 3328:         return;
 3329:     }
 3330:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3331: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3332: }
 3333: 
 3334: # ------------------------------------------------------------ Syllabus Wrapper
 3335: 
 3336: sub syllabuswrapper {
 3337:     my ($linktext,$coursedir,$domain)=@_;
 3338:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3339: }
 3340: 
 3341: # -----------------------------------------------------------------------------
 3342: 
 3343: sub track_student_link {
 3344:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3345:     my $link ="/adm/trackstudent?";
 3346:     my $title = 'View recent activity';
 3347:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3348:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3349:         $link .= "selected_student=$sname:$sdom";
 3350:         $title .= ' of this student';
 3351:     } 
 3352:     if (defined($target) && $target !~ /^\s*$/) {
 3353:         $target = qq{target="$target"};
 3354:     } else {
 3355:         $target = '';
 3356:     }
 3357:     if ($start) { $link.='&amp;start='.$start; }
 3358:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3359:     $title = &mt($title);
 3360:     $linktext = &mt($linktext);
 3361:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3362: 	&help_open_topic('View_recent_activity');
 3363: }
 3364: 
 3365: sub slot_reservations_link {
 3366:     my ($linktext,$sname,$sdom,$target) = @_;
 3367:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3368:     my $title = 'View slot reservation history';
 3369:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3370:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3371:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3372:         $title .= ' of this student';
 3373:     }
 3374:     if (defined($target) && $target !~ /^\s*$/) {
 3375:         $target = qq{target="$target"};
 3376:     } else {
 3377:         $target = '';
 3378:     }
 3379:     $title = &mt($title);
 3380:     $linktext = &mt($linktext);
 3381:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3382: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3383: 
 3384: }
 3385: 
 3386: # ===================================================== Display a student photo
 3387: 
 3388: 
 3389: sub student_image_tag {
 3390:     my ($domain,$user)=@_;
 3391:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3392:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3393: 	return '<img src="'.$imgsrc.'" align="right" />';
 3394:     } else {
 3395: 	return '';
 3396:     }
 3397: }
 3398: 
 3399: =pod
 3400: 
 3401: =back
 3402: 
 3403: =head1 Access .tab File Data
 3404: 
 3405: =over 4
 3406: 
 3407: =item * &languageids() 
 3408: 
 3409: returns list of all language ids
 3410: 
 3411: =cut
 3412: 
 3413: sub languageids {
 3414:     return sort(keys(%language));
 3415: }
 3416: 
 3417: =pod
 3418: 
 3419: =item * &languagedescription() 
 3420: 
 3421: returns description of a specified language id
 3422: 
 3423: =cut
 3424: 
 3425: sub languagedescription {
 3426:     my $code=shift;
 3427:     return  ($supported_language{$code}?'* ':'').
 3428:             $language{$code}.
 3429: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3430: }
 3431: 
 3432: =pod
 3433: 
 3434: =item * &plainlanguagedescription
 3435: 
 3436: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3437: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3438: 
 3439: =cut
 3440: 
 3441: sub plainlanguagedescription {
 3442:     my $code=shift;
 3443:     return $language{$code};
 3444: }
 3445: 
 3446: =pod
 3447: 
 3448: =item * &supportedlanguagecode
 3449: 
 3450: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3451: code.
 3452: 
 3453: =cut
 3454: 
 3455: sub supportedlanguagecode {
 3456:     my $code=shift;
 3457:     return $supported_language{$code};
 3458: }
 3459: 
 3460: =pod
 3461: 
 3462: =item * &latexlanguage()
 3463: 
 3464: Given a language key code returns the correspondnig language to use
 3465: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3466: is no supported hyphenation for the language code.
 3467: 
 3468: =cut
 3469: 
 3470: sub latexlanguage {
 3471:     my $code = shift;
 3472:     return $latex_language{$code};
 3473: }
 3474: 
 3475: =pod
 3476: 
 3477: =item * &latexhyphenation()
 3478: 
 3479: Same as above but what's supplied is the language as it might be stored
 3480: in the metadata.
 3481: 
 3482: =cut
 3483: 
 3484: sub latexhyphenation {
 3485:     my $key = shift;
 3486:     return $latex_language_bykey{$key};
 3487: }
 3488: 
 3489: =pod
 3490: 
 3491: =item * &copyrightids() 
 3492: 
 3493: returns list of all copyrights
 3494: 
 3495: =cut
 3496: 
 3497: sub copyrightids {
 3498:     return sort(keys(%cprtag));
 3499: }
 3500: 
 3501: =pod
 3502: 
 3503: =item * &copyrightdescription() 
 3504: 
 3505: returns description of a specified copyright id
 3506: 
 3507: =cut
 3508: 
 3509: sub copyrightdescription {
 3510:     return &mt($cprtag{shift(@_)});
 3511: }
 3512: 
 3513: =pod
 3514: 
 3515: =item * &source_copyrightids() 
 3516: 
 3517: returns list of all source copyrights
 3518: 
 3519: =cut
 3520: 
 3521: sub source_copyrightids {
 3522:     return sort(keys(%scprtag));
 3523: }
 3524: 
 3525: =pod
 3526: 
 3527: =item * &source_copyrightdescription() 
 3528: 
 3529: returns description of a specified source copyright id
 3530: 
 3531: =cut
 3532: 
 3533: sub source_copyrightdescription {
 3534:     return &mt($scprtag{shift(@_)});
 3535: }
 3536: 
 3537: =pod
 3538: 
 3539: =item * &filecategories() 
 3540: 
 3541: returns list of all file categories
 3542: 
 3543: =cut
 3544: 
 3545: sub filecategories {
 3546:     return sort(keys(%category_extensions));
 3547: }
 3548: 
 3549: =pod
 3550: 
 3551: =item * &filecategorytypes() 
 3552: 
 3553: returns list of file types belonging to a given file
 3554: category
 3555: 
 3556: =cut
 3557: 
 3558: sub filecategorytypes {
 3559:     my ($cat) = @_;
 3560:     return @{$category_extensions{lc($cat)}};
 3561: }
 3562: 
 3563: =pod
 3564: 
 3565: =item * &fileembstyle() 
 3566: 
 3567: returns embedding style for a specified file type
 3568: 
 3569: =cut
 3570: 
 3571: sub fileembstyle {
 3572:     return $fe{lc(shift(@_))};
 3573: }
 3574: 
 3575: sub filemimetype {
 3576:     return $fm{lc(shift(@_))};
 3577: }
 3578: 
 3579: 
 3580: sub filecategoryselect {
 3581:     my ($name,$value)=@_;
 3582:     return &select_form($value,$name,
 3583:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3584: }
 3585: 
 3586: =pod
 3587: 
 3588: =item * &filedescription() 
 3589: 
 3590: returns description for a specified file type
 3591: 
 3592: =cut
 3593: 
 3594: sub filedescription {
 3595:     my $file_description = $fd{lc(shift())};
 3596:     $file_description =~ s:([\[\]]):~$1:g;
 3597:     return &mt($file_description);
 3598: }
 3599: 
 3600: =pod
 3601: 
 3602: =item * &filedescriptionex() 
 3603: 
 3604: returns description for a specified file type with
 3605: extra formatting
 3606: 
 3607: =cut
 3608: 
 3609: sub filedescriptionex {
 3610:     my $ex=shift;
 3611:     my $file_description = $fd{lc($ex)};
 3612:     $file_description =~ s:([\[\]]):~$1:g;
 3613:     return '.'.$ex.' '.&mt($file_description);
 3614: }
 3615: 
 3616: # End of .tab access
 3617: =pod
 3618: 
 3619: =back
 3620: 
 3621: =cut
 3622: 
 3623: # ------------------------------------------------------------------ File Types
 3624: sub fileextensions {
 3625:     return sort(keys(%fe));
 3626: }
 3627: 
 3628: # ----------------------------------------------------------- Display Languages
 3629: # returns a hash with all desired display languages
 3630: #
 3631: 
 3632: sub display_languages {
 3633:     my %languages=();
 3634:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3635: 	$languages{$lang}=1;
 3636:     }
 3637:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3638:     if ($env{'form.displaylanguage'}) {
 3639: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3640: 	    $languages{$lang}=1;
 3641:         }
 3642:     }
 3643:     return %languages;
 3644: }
 3645: 
 3646: sub languages {
 3647:     my ($possible_langs) = @_;
 3648:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3649:     if (!ref($possible_langs)) {
 3650: 	if( wantarray ) {
 3651: 	    return @preferred_langs;
 3652: 	} else {
 3653: 	    return $preferred_langs[0];
 3654: 	}
 3655:     }
 3656:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3657:     my @preferred_possibilities;
 3658:     foreach my $preferred_lang (@preferred_langs) {
 3659: 	if (exists($possibilities{$preferred_lang})) {
 3660: 	    push(@preferred_possibilities, $preferred_lang);
 3661: 	}
 3662:     }
 3663:     if( wantarray ) {
 3664: 	return @preferred_possibilities;
 3665:     }
 3666:     return $preferred_possibilities[0];
 3667: }
 3668: 
 3669: sub user_lang {
 3670:     my ($touname,$toudom,$fromcid) = @_;
 3671:     my @userlangs;
 3672:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3673:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3674:                     $env{'course.'.$fromcid.'.languages'}));
 3675:     } else {
 3676:         my %langhash = &getlangs($touname,$toudom);
 3677:         if ($langhash{'languages'} ne '') {
 3678:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3679:         } else {
 3680:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3681:             if ($domdefs{'lang_def'} ne '') {
 3682:                 @userlangs = ($domdefs{'lang_def'});
 3683:             }
 3684:         }
 3685:     }
 3686:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3687:     my $user_lh = Apache::localize->get_handle(@languages);
 3688:     return $user_lh;
 3689: }
 3690: 
 3691: 
 3692: ###############################################################
 3693: ##               Student Answer Attempts                     ##
 3694: ###############################################################
 3695: 
 3696: =pod
 3697: 
 3698: =head1 Alternate Problem Views
 3699: 
 3700: =over 4
 3701: 
 3702: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3703:     $getattempt, $regexp, $gradesub)
 3704: 
 3705: Return string with previous attempt on problem. Arguments:
 3706: 
 3707: =over 4
 3708: 
 3709: =item * $symb: Problem, including path
 3710: 
 3711: =item * $username: username of the desired student
 3712: 
 3713: =item * $domain: domain of the desired student
 3714: 
 3715: =item * $course: Course ID
 3716: 
 3717: =item * $getattempt: Leave blank for all attempts, otherwise put
 3718:     something
 3719: 
 3720: =item * $regexp: if string matches this regexp, the string will be
 3721:     sent to $gradesub
 3722: 
 3723: =item * $gradesub: routine that processes the string if it matches $regexp
 3724: 
 3725: =back
 3726: 
 3727: The output string is a table containing all desired attempts, if any.
 3728: 
 3729: =cut
 3730: 
 3731: sub get_previous_attempt {
 3732:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3733:   my $prevattempts='';
 3734:   no strict 'refs';
 3735:   if ($symb) {
 3736:     my (%returnhash)=
 3737:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3738:     if ($returnhash{'version'}) {
 3739:       my %lasthash=();
 3740:       my $version;
 3741:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3742:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3743: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3744:         }
 3745:       }
 3746:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3747:       $prevattempts.='<th>'.&mt('History').'</th>';
 3748:       my (%typeparts,%lasthidden);
 3749:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3750:       foreach my $key (sort(keys(%lasthash))) {
 3751: 	my ($ign,@parts) = split(/\./,$key);
 3752: 	if ($#parts > 0) {
 3753: 	  my $data=$parts[-1];
 3754:           next if ($data eq 'foilorder');
 3755: 	  pop(@parts);
 3756:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3757:           if ($data eq 'type') {
 3758:               unless ($showsurv) {
 3759:                   my $id = join(',',@parts);
 3760:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3761:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3762:                       $lasthidden{$ign.'.'.$id} = 1;
 3763:                   }
 3764:               }
 3765:           } 
 3766: 	} else {
 3767: 	  if ($#parts == 0) {
 3768: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3769: 	  } else {
 3770: 	    $prevattempts.='<th>'.$ign.'</th>';
 3771: 	  }
 3772: 	}
 3773:       }
 3774:       $prevattempts.=&end_data_table_header_row();
 3775:       if ($getattempt eq '') {
 3776: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3777:             my @hidden;
 3778:             if (%typeparts) {
 3779:                 foreach my $id (keys(%typeparts)) {
 3780:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3781:                         push(@hidden,$id);
 3782:                     }
 3783:                 }
 3784:             }
 3785:             $prevattempts.=&start_data_table_row().
 3786:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3787:             if (@hidden) {
 3788:                 foreach my $key (sort(keys(%lasthash))) {
 3789:                     next if ($key =~ /\.foilorder$/);
 3790:                     my $hide;
 3791:                     foreach my $id (@hidden) {
 3792:                         if ($key =~ /^\Q$id\E/) {
 3793:                             $hide = 1;
 3794:                             last;
 3795:                         }
 3796:                     }
 3797:                     if ($hide) {
 3798:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3799:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3800:                             my $value = &format_previous_attempt_value($key,
 3801:                                              $returnhash{$version.':'.$key});
 3802:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3803:                         } else {
 3804:                             $prevattempts.='<td>&nbsp;</td>';
 3805:                         }
 3806:                     } else {
 3807:                         if ($key =~ /\./) {
 3808:                             my $value = &format_previous_attempt_value($key,
 3809:                                               $returnhash{$version.':'.$key});
 3810:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3811:                         } else {
 3812:                             $prevattempts.='<td>&nbsp;</td>';
 3813:                         }
 3814:                     }
 3815:                 }
 3816:             } else {
 3817: 	        foreach my $key (sort(keys(%lasthash))) {
 3818:                     next if ($key =~ /\.foilorder$/);
 3819: 		    my $value = &format_previous_attempt_value($key,
 3820: 			            $returnhash{$version.':'.$key});
 3821: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3822: 	        }
 3823:             }
 3824: 	    $prevattempts.=&end_data_table_row();
 3825: 	 }
 3826:       }
 3827:       my @currhidden = keys(%lasthidden);
 3828:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3829:       foreach my $key (sort(keys(%lasthash))) {
 3830:           next if ($key =~ /\.foilorder$/);
 3831:           if (%typeparts) {
 3832:               my $hidden;
 3833:               foreach my $id (@currhidden) {
 3834:                   if ($key =~ /^\Q$id\E/) {
 3835:                       $hidden = 1;
 3836:                       last;
 3837:                   }
 3838:               }
 3839:               if ($hidden) {
 3840:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3841:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3842:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3843:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3844:                           $value = &$gradesub($value);
 3845:                       }
 3846:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3847:                   } else {
 3848:                       $prevattempts.='<td>&nbsp;</td>';
 3849:                   }
 3850:               } else {
 3851:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3852:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3853:                       $value = &$gradesub($value);
 3854:                   }
 3855:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3856:               }
 3857:           } else {
 3858: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3859: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3860:                   $value = &$gradesub($value);
 3861:               }
 3862: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3863:           }
 3864:       }
 3865:       $prevattempts.= &end_data_table_row().&end_data_table();
 3866:     } else {
 3867:       $prevattempts=
 3868: 	  &start_data_table().&start_data_table_row().
 3869: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3870: 	  &end_data_table_row().&end_data_table();
 3871:     }
 3872:   } else {
 3873:     $prevattempts=
 3874: 	  &start_data_table().&start_data_table_row().
 3875: 	  '<td>'.&mt('No data.').'</td>'.
 3876: 	  &end_data_table_row().&end_data_table();
 3877:   }
 3878: }
 3879: 
 3880: sub format_previous_attempt_value {
 3881:     my ($key,$value) = @_;
 3882:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3883: 	$value = &Apache::lonlocal::locallocaltime($value);
 3884:     } elsif (ref($value) eq 'ARRAY') {
 3885: 	$value = '('.join(', ', @{ $value }).')';
 3886:     } elsif ($key =~ /answerstring$/) {
 3887:         my %answers = &Apache::lonnet::str2hash($value);
 3888:         my @anskeys = sort(keys(%answers));
 3889:         if (@anskeys == 1) {
 3890:             my $answer = $answers{$anskeys[0]};
 3891:             if ($answer =~ m{\0}) {
 3892:                 $answer =~ s{\0}{,}g;
 3893:             }
 3894:             my $tag_internal_answer_name = 'INTERNAL';
 3895:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3896:                 $value = $answer; 
 3897:             } else {
 3898:                 $value = $anskeys[0].'='.$answer;
 3899:             }
 3900:         } else {
 3901:             foreach my $ans (@anskeys) {
 3902:                 my $answer = $answers{$ans};
 3903:                 if ($answer =~ m{\0}) {
 3904:                     $answer =~ s{\0}{,}g;
 3905:                 }
 3906:                 $value .=  $ans.'='.$answer.'<br />';;
 3907:             } 
 3908:         }
 3909:     } else {
 3910: 	$value = &unescape($value);
 3911:     }
 3912:     return $value;
 3913: }
 3914: 
 3915: 
 3916: sub relative_to_absolute {
 3917:     my ($url,$output)=@_;
 3918:     my $parser=HTML::TokeParser->new(\$output);
 3919:     my $token;
 3920:     my $thisdir=$url;
 3921:     my @rlinks=();
 3922:     while ($token=$parser->get_token) {
 3923: 	if ($token->[0] eq 'S') {
 3924: 	    if ($token->[1] eq 'a') {
 3925: 		if ($token->[2]->{'href'}) {
 3926: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3927: 		}
 3928: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3929: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3930: 	    } elsif ($token->[1] eq 'base') {
 3931: 		$thisdir=$token->[2]->{'href'};
 3932: 	    }
 3933: 	}
 3934:     }
 3935:     $thisdir=~s-/[^/]*$--;
 3936:     foreach my $link (@rlinks) {
 3937: 	unless (($link=~/^https?\:\/\//i) ||
 3938: 		($link=~/^\//) ||
 3939: 		($link=~/^javascript:/i) ||
 3940: 		($link=~/^mailto:/i) ||
 3941: 		($link=~/^\#/)) {
 3942: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3943: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3944: 	}
 3945:     }
 3946: # -------------------------------------------------- Deal with Applet codebases
 3947:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3948:     return $output;
 3949: }
 3950: 
 3951: =pod
 3952: 
 3953: =item * &get_student_view()
 3954: 
 3955: show a snapshot of what student was looking at
 3956: 
 3957: =cut
 3958: 
 3959: sub get_student_view {
 3960:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3961:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3962:   my (%form);
 3963:   my @elements=('symb','courseid','domain','username');
 3964:   foreach my $element (@elements) {
 3965:       $form{'grade_'.$element}=eval '$'.$element #'
 3966:   }
 3967:   if (defined($moreenv)) {
 3968:       %form=(%form,%{$moreenv});
 3969:   }
 3970:   if (defined($target)) { $form{'grade_target'} = $target; }
 3971:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3972:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3973:   $userview=~s/\<body[^\>]*\>//gi;
 3974:   $userview=~s/\<\/body\>//gi;
 3975:   $userview=~s/\<html\>//gi;
 3976:   $userview=~s/\<\/html\>//gi;
 3977:   $userview=~s/\<head\>//gi;
 3978:   $userview=~s/\<\/head\>//gi;
 3979:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3980:   $userview=&relative_to_absolute($feedurl,$userview);
 3981:   if (wantarray) {
 3982:      return ($userview,$response);
 3983:   } else {
 3984:      return $userview;
 3985:   }
 3986: }
 3987: 
 3988: sub get_student_view_with_retries {
 3989:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3990: 
 3991:     my $ok = 0;                 # True if we got a good response.
 3992:     my $content;
 3993:     my $response;
 3994: 
 3995:     # Try to get the student_view done. within the retries count:
 3996:     
 3997:     do {
 3998:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3999:          $ok      = $response->is_success;
 4000:          if (!$ok) {
 4001:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4002:          }
 4003:          $retries--;
 4004:     } while (!$ok && ($retries > 0));
 4005:     
 4006:     if (!$ok) {
 4007:        $content = '';          # On error return an empty content.
 4008:     }
 4009:     if (wantarray) {
 4010:        return ($content, $response);
 4011:     } else {
 4012:        return $content;
 4013:     }
 4014: }
 4015: 
 4016: =pod
 4017: 
 4018: =item * &get_student_answers() 
 4019: 
 4020: show a snapshot of how student was answering problem
 4021: 
 4022: =cut
 4023: 
 4024: sub get_student_answers {
 4025:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4026:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4027:   my (%moreenv);
 4028:   my @elements=('symb','courseid','domain','username');
 4029:   foreach my $element (@elements) {
 4030:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4031:   }
 4032:   $moreenv{'grade_target'}='answer';
 4033:   %moreenv=(%form,%moreenv);
 4034:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4035:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4036:   return $userview;
 4037: }
 4038: 
 4039: =pod
 4040: 
 4041: =item * &submlink()
 4042: 
 4043: Inputs: $text $uname $udom $symb $target
 4044: 
 4045: Returns: A link to grades.pm such as to see the SUBM view of a student
 4046: 
 4047: =cut
 4048: 
 4049: ###############################################
 4050: sub submlink {
 4051:     my ($text,$uname,$udom,$symb,$target)=@_;
 4052:     if (!($uname && $udom)) {
 4053: 	(my $cursymb, my $courseid,$udom,$uname)=
 4054: 	    &Apache::lonnet::whichuser($symb);
 4055: 	if (!$symb) { $symb=$cursymb; }
 4056:     }
 4057:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4058:     $symb=&escape($symb);
 4059:     if ($target) { $target=" target=\"$target\""; }
 4060:     return
 4061:         '<a href="/adm/grades?command=submission'.
 4062:         '&amp;symb='.$symb.
 4063:         '&amp;student='.$uname.
 4064:         '&amp;userdom='.$udom.'"'.
 4065:         $target.'>'.$text.'</a>';
 4066: }
 4067: ##############################################
 4068: 
 4069: =pod
 4070: 
 4071: =item * &pgrdlink()
 4072: 
 4073: Inputs: $text $uname $udom $symb $target
 4074: 
 4075: Returns: A link to grades.pm such as to see the PGRD view of a student
 4076: 
 4077: =cut
 4078: 
 4079: ###############################################
 4080: sub pgrdlink {
 4081:     my $link=&submlink(@_);
 4082:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4083:     return $link;
 4084: }
 4085: ##############################################
 4086: 
 4087: =pod
 4088: 
 4089: =item * &pprmlink()
 4090: 
 4091: Inputs: $text $uname $udom $symb $target
 4092: 
 4093: Returns: A link to parmset.pm such as to see the PPRM view of a
 4094: student and a specific resource
 4095: 
 4096: =cut
 4097: 
 4098: ###############################################
 4099: sub pprmlink {
 4100:     my ($text,$uname,$udom,$symb,$target)=@_;
 4101:     if (!($uname && $udom)) {
 4102: 	(my $cursymb, my $courseid,$udom,$uname)=
 4103: 	    &Apache::lonnet::whichuser($symb);
 4104: 	if (!$symb) { $symb=$cursymb; }
 4105:     }
 4106:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4107:     $symb=&escape($symb);
 4108:     if ($target) { $target="target=\"$target\""; }
 4109:     return '<a href="/adm/parmset?command=set&amp;'.
 4110: 	'symb='.$symb.'&amp;uname='.$uname.
 4111: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4112: }
 4113: ##############################################
 4114: 
 4115: =pod
 4116: 
 4117: =back
 4118: 
 4119: =cut
 4120: 
 4121: ###############################################
 4122: 
 4123: 
 4124: sub timehash {
 4125:     my ($thistime) = @_;
 4126:     my $timezone = &Apache::lonlocal::gettimezone();
 4127:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4128:                      ->set_time_zone($timezone);
 4129:     my $wday = $dt->day_of_week();
 4130:     if ($wday == 7) { $wday = 0; }
 4131:     return ( 'second' => $dt->second(),
 4132:              'minute' => $dt->minute(),
 4133:              'hour'   => $dt->hour(),
 4134:              'day'     => $dt->day_of_month(),
 4135:              'month'   => $dt->month(),
 4136:              'year'    => $dt->year(),
 4137:              'weekday' => $wday,
 4138:              'dayyear' => $dt->day_of_year(),
 4139:              'dlsav'   => $dt->is_dst() );
 4140: }
 4141: 
 4142: sub utc_string {
 4143:     my ($date)=@_;
 4144:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4145: }
 4146: 
 4147: sub maketime {
 4148:     my %th=@_;
 4149:     my ($epoch_time,$timezone,$dt);
 4150:     $timezone = &Apache::lonlocal::gettimezone();
 4151:     eval {
 4152:         $dt = DateTime->new( year   => $th{'year'},
 4153:                              month  => $th{'month'},
 4154:                              day    => $th{'day'},
 4155:                              hour   => $th{'hour'},
 4156:                              minute => $th{'minute'},
 4157:                              second => $th{'second'},
 4158:                              time_zone => $timezone,
 4159:                          );
 4160:     };
 4161:     if (!$@) {
 4162:         $epoch_time = $dt->epoch;
 4163:         if ($epoch_time) {
 4164:             return $epoch_time;
 4165:         }
 4166:     }
 4167:     return POSIX::mktime(
 4168:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4169:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4170: }
 4171: 
 4172: #########################################
 4173: 
 4174: sub findallcourses {
 4175:     my ($roles,$uname,$udom) = @_;
 4176:     my %roles;
 4177:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4178:     my %courses;
 4179:     my $now=time;
 4180:     if (!defined($uname)) {
 4181:         $uname = $env{'user.name'};
 4182:     }
 4183:     if (!defined($udom)) {
 4184:         $udom = $env{'user.domain'};
 4185:     }
 4186:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4187:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4188:         if (!%roles) {
 4189:             %roles = (
 4190:                        cc => 1,
 4191:                        co => 1,
 4192:                        in => 1,
 4193:                        ep => 1,
 4194:                        ta => 1,
 4195:                        cr => 1,
 4196:                        st => 1,
 4197:              );
 4198:         }
 4199:         foreach my $entry (keys(%roleshash)) {
 4200:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4201:             if ($trole =~ /^cr/) { 
 4202:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4203:             } else {
 4204:                 next if (!exists($roles{$trole}));
 4205:             }
 4206:             if ($tend) {
 4207:                 next if ($tend < $now);
 4208:             }
 4209:             if ($tstart) {
 4210:                 next if ($tstart > $now);
 4211:             }
 4212:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4213:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4214:             my $value = $trole.'/'.$cdom.'/';
 4215:             if ($secpart eq '') {
 4216:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4217:                 $sec = 'none';
 4218:                 $value .= $cnum.'/';
 4219:             } else {
 4220:                 $cnum = $cnumpart;
 4221:                 ($sec,$role) = split(/_/,$secpart);
 4222:                 $value .= $cnum.'/'.$sec;
 4223:             }
 4224:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4225:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4226:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4227:                 }
 4228:             } else {
 4229:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4230:             }
 4231:         }
 4232:     } else {
 4233:         foreach my $key (keys(%env)) {
 4234: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4235:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4236: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4237: 	        next if ($role eq 'ca' || $role eq 'aa');
 4238: 	        next if (%roles && !exists($roles{$role}));
 4239: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4240:                 my $active=1;
 4241:                 if ($starttime) {
 4242: 		    if ($now<$starttime) { $active=0; }
 4243:                 }
 4244:                 if ($endtime) {
 4245:                     if ($now>$endtime) { $active=0; }
 4246:                 }
 4247:                 if ($active) {
 4248:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4249:                     if ($sec eq '') {
 4250:                         $sec = 'none';
 4251:                     } else {
 4252:                         $value .= $sec;
 4253:                     }
 4254:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4255:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4256:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4257:                         }
 4258:                     } else {
 4259:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4260:                     }
 4261:                 }
 4262:             }
 4263:         }
 4264:     }
 4265:     return %courses;
 4266: }
 4267: 
 4268: ###############################################
 4269: 
 4270: sub blockcheck {
 4271:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4272: 
 4273:     if (!defined($udom)) {
 4274:         $udom = $env{'user.domain'};
 4275:     }
 4276:     if (!defined($uname)) {
 4277:         $uname = $env{'user.name'};
 4278:     }
 4279: 
 4280:     # If uname and udom are for a course, check for blocks in the course.
 4281: 
 4282:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4283:         my ($startblock,$endblock,$triggerblock) = 
 4284:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4285:         return ($startblock,$endblock,$triggerblock);
 4286:     }
 4287: 
 4288:     my $startblock = 0;
 4289:     my $endblock = 0;
 4290:     my $triggerblock = '';
 4291:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4292: 
 4293:     # If uname is for a user, and activity is course-specific, i.e.,
 4294:     # boards, chat or groups, check for blocking in current course only.
 4295: 
 4296:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4297:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4298:         foreach my $key (keys(%live_courses)) {
 4299:             if ($key ne $env{'request.course.id'}) {
 4300:                 delete($live_courses{$key});
 4301:             }
 4302:         }
 4303:     }
 4304: 
 4305:     my $otheruser = 0;
 4306:     my %own_courses;
 4307:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4308:         # Resource belongs to user other than current user.
 4309:         $otheruser = 1;
 4310:         # Gather courses for current user
 4311:         %own_courses = 
 4312:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4313:     }
 4314: 
 4315:     # Gather active course roles - course coordinator, instructor, 
 4316:     # exam proctor, ta, student, or custom role.
 4317: 
 4318:     foreach my $course (keys(%live_courses)) {
 4319:         my ($cdom,$cnum);
 4320:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4321:             $cdom = $env{'course.'.$course.'.domain'};
 4322:             $cnum = $env{'course.'.$course.'.num'};
 4323:         } else {
 4324:             ($cdom,$cnum) = split(/_/,$course); 
 4325:         }
 4326:         my $no_ownblock = 0;
 4327:         my $no_userblock = 0;
 4328:         if ($otheruser && $activity ne 'com') {
 4329:             # Check if current user has 'evb' priv for this
 4330:             if (defined($own_courses{$course})) {
 4331:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4332:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4333:                     if ($sec ne 'none') {
 4334:                         $checkrole .= '/'.$sec;
 4335:                     }
 4336:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4337:                         $no_ownblock = 1;
 4338:                         last;
 4339:                     }
 4340:                 }
 4341:             }
 4342:             # if they have 'evb' priv and are currently not playing student
 4343:             next if (($no_ownblock) &&
 4344:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4345:         }
 4346:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4347:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4348:             if ($sec ne 'none') {
 4349:                 $checkrole .= '/'.$sec;
 4350:             }
 4351:             if ($otheruser) {
 4352:                 # Resource belongs to user other than current user.
 4353:                 # Assemble privs for that user, and check for 'evb' priv.
 4354:                 my (%allroles,%userroles);
 4355:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4356:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4357:                         my ($trole,$tdom,$tnum,$tsec);
 4358:                         if ($entry =~ /^cr/) {
 4359:                             ($trole,$tdom,$tnum,$tsec) = 
 4360:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4361:                         } else {
 4362:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4363:                         }
 4364:                         my ($spec,$area,$trest);
 4365:                         $area = '/'.$tdom.'/'.$tnum;
 4366:                         $trest = $tnum;
 4367:                         if ($tsec ne '') {
 4368:                             $area .= '/'.$tsec;
 4369:                             $trest .= '/'.$tsec;
 4370:                         }
 4371:                         $spec = $trole.'.'.$area;
 4372:                         if ($trole =~ /^cr/) {
 4373:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4374:                                                               $tdom,$spec,$trest,$area);
 4375:                         } else {
 4376:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4377:                                                                 $tdom,$spec,$trest,$area);
 4378:                         }
 4379:                     }
 4380:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4381:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4382:                         if ($1) {
 4383:                             $no_userblock = 1;
 4384:                             last;
 4385:                         }
 4386:                     }
 4387:                 }
 4388:             } else {
 4389:                 # Resource belongs to current user
 4390:                 # Check for 'evb' priv via lonnet::allowed().
 4391:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4392:                     $no_ownblock = 1;
 4393:                     last;
 4394:                 }
 4395:             }
 4396:         }
 4397:         # if they have the evb priv and are currently not playing student
 4398:         next if (($no_ownblock) &&
 4399:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4400:         next if ($no_userblock);
 4401: 
 4402:         # Retrieve blocking times and identity of locker for course
 4403:         # of specified user, unless user has 'evb' privilege.
 4404:         
 4405:         my ($start,$end,$trigger) = 
 4406:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4407:         if (($start != 0) && 
 4408:             (($startblock == 0) || ($startblock > $start))) {
 4409:             $startblock = $start;
 4410:             if ($trigger ne '') {
 4411:                 $triggerblock = $trigger;
 4412:             }
 4413:         }
 4414:         if (($end != 0)  &&
 4415:             (($endblock == 0) || ($endblock < $end))) {
 4416:             $endblock = $end;
 4417:             if ($trigger ne '') {
 4418:                 $triggerblock = $trigger;
 4419:             }
 4420:         }
 4421:     }
 4422:     return ($startblock,$endblock,$triggerblock);
 4423: }
 4424: 
 4425: sub get_blocks {
 4426:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4427:     my $startblock = 0;
 4428:     my $endblock = 0;
 4429:     my $triggerblock = '';
 4430:     my $course = $cdom.'_'.$cnum;
 4431:     $setters->{$course} = {};
 4432:     $setters->{$course}{'staff'} = [];
 4433:     $setters->{$course}{'times'} = [];
 4434:     $setters->{$course}{'triggers'} = [];
 4435:     my (@blockers,%triggered);
 4436:     my $now = time;
 4437:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4438:     if ($activity eq 'docs') {
 4439:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4440:         foreach my $block (@blockers) {
 4441:             if ($block =~ /^firstaccess____(.+)$/) {
 4442:                 my $item = $1;
 4443:                 my $type = 'map';
 4444:                 my $timersymb = $item;
 4445:                 if ($item eq 'course') {
 4446:                     $type = 'course';
 4447:                 } elsif ($item =~ /___\d+___/) {
 4448:                     $type = 'resource';
 4449:                 } else {
 4450:                     $timersymb = &Apache::lonnet::symbread($item);
 4451:                 }
 4452:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4453:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4454:                 $triggered{$block} = {
 4455:                                        start => $start,
 4456:                                        end   => $end,
 4457:                                        type  => $type,
 4458:                                      };
 4459:             }
 4460:         }
 4461:     } else {
 4462:         foreach my $block (keys(%commblocks)) {
 4463:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4464:                 my ($start,$end) = ($1,$2);
 4465:                 if ($start <= time && $end >= time) {
 4466:                     if (ref($commblocks{$block}) eq 'HASH') {
 4467:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4468:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4469:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4470:                                     push(@blockers,$block);
 4471:                                 }
 4472:                             }
 4473:                         }
 4474:                     }
 4475:                 }
 4476:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4477:                 my $item = $1;
 4478:                 my $timersymb = $item; 
 4479:                 my $type = 'map';
 4480:                 if ($item eq 'course') {
 4481:                     $type = 'course';
 4482:                 } elsif ($item =~ /___\d+___/) {
 4483:                     $type = 'resource';
 4484:                 } else {
 4485:                     $timersymb = &Apache::lonnet::symbread($item);
 4486:                 }
 4487:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4488:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4489:                 if ($start && $end) {
 4490:                     if (($start <= time) && ($end >= time)) {
 4491:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4492:                             push(@blockers,$block);
 4493:                             $triggered{$block} = {
 4494:                                                    start => $start,
 4495:                                                    end   => $end,
 4496:                                                    type  => $type,
 4497:                                                  };
 4498:                         }
 4499:                     }
 4500:                 }
 4501:             }
 4502:         }
 4503:     }
 4504:     foreach my $blocker (@blockers) {
 4505:         my ($staff_name,$staff_dom,$title,$blocks) =
 4506:             &parse_block_record($commblocks{$blocker});
 4507:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4508:         my ($start,$end,$triggertype);
 4509:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4510:             ($start,$end) = ($1,$2);
 4511:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4512:             $start = $triggered{$blocker}{'start'};
 4513:             $end = $triggered{$blocker}{'end'};
 4514:             $triggertype = $triggered{$blocker}{'type'};
 4515:         }
 4516:         if ($start) {
 4517:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4518:             if ($triggertype) {
 4519:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4520:             } else {
 4521:                 push(@{$$setters{$course}{'triggers'}},0);
 4522:             }
 4523:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4524:                 $startblock = $start;
 4525:                 if ($triggertype) {
 4526:                     $triggerblock = $blocker;
 4527:                 }
 4528:             }
 4529:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4530:                $endblock = $end;
 4531:                if ($triggertype) {
 4532:                    $triggerblock = $blocker;
 4533:                }
 4534:             }
 4535:         }
 4536:     }
 4537:     return ($startblock,$endblock,$triggerblock);
 4538: }
 4539: 
 4540: sub parse_block_record {
 4541:     my ($record) = @_;
 4542:     my ($setuname,$setudom,$title,$blocks);
 4543:     if (ref($record) eq 'HASH') {
 4544:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4545:         $title = &unescape($record->{'event'});
 4546:         $blocks = $record->{'blocks'};
 4547:     } else {
 4548:         my @data = split(/:/,$record,3);
 4549:         if (scalar(@data) eq 2) {
 4550:             $title = $data[1];
 4551:             ($setuname,$setudom) = split(/@/,$data[0]);
 4552:         } else {
 4553:             ($setuname,$setudom,$title) = @data;
 4554:         }
 4555:         $blocks = { 'com' => 'on' };
 4556:     }
 4557:     return ($setuname,$setudom,$title,$blocks);
 4558: }
 4559: 
 4560: sub blocking_status {
 4561:     my ($activity,$uname,$udom,$url) = @_;
 4562:     my %setters;
 4563: 
 4564: # check for active blocking
 4565:     my ($startblock,$endblock,$triggerblock) = 
 4566:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4567:     my $blocked = 0;
 4568:     if ($startblock && $endblock) {
 4569:         $blocked = 1;
 4570:     }
 4571: 
 4572: # caller just wants to know whether a block is active
 4573:     if (!wantarray) { return $blocked; }
 4574: 
 4575: # build a link to a popup window containing the details
 4576:     my $querystring  = "?activity=$activity";
 4577: # $uname and $udom decide whose portfolio the user is trying to look at
 4578:     if ($activity eq 'port') {
 4579:         $querystring .= "&amp;udom=$udom"      if $udom;
 4580:         $querystring .= "&amp;uname=$uname"    if $uname;
 4581:     } elsif ($activity eq 'docs') {
 4582:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4583:     }
 4584: 
 4585:     my $output .= <<'END_MYBLOCK';
 4586: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4587:     var options = "width=" + w + ",height=" + h + ",";
 4588:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4589:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4590:     var newWin = window.open(url, wdwName, options);
 4591:     newWin.focus();
 4592: }
 4593: END_MYBLOCK
 4594: 
 4595:     $output = Apache::lonhtmlcommon::scripttag($output);
 4596:   
 4597:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4598:     my $text = &mt('Communication Blocked');
 4599:     if ($activity eq 'docs') {
 4600:         $text = &mt('Content Access Blocked');
 4601:     } elsif ($activity eq 'printout') {
 4602:         $text = &mt('Printing Blocked');
 4603:     }
 4604:     $output .= <<"END_BLOCK";
 4605: <div class='LC_comblock'>
 4606:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4607:   title='$text'>
 4608:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4609:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4610:   title='$text'>$text</a>
 4611: </div>
 4612: 
 4613: END_BLOCK
 4614: 
 4615:     return ($blocked, $output);
 4616: }
 4617: 
 4618: ###############################################
 4619: 
 4620: sub check_ip_acc {
 4621:     my ($acc)=@_;
 4622:     &Apache::lonxml::debug("acc is $acc");
 4623:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4624:         return 1;
 4625:     }
 4626:     my $allowed=0;
 4627:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4628: 
 4629:     my $name;
 4630:     foreach my $pattern (split(',',$acc)) {
 4631:         $pattern =~ s/^\s*//;
 4632:         $pattern =~ s/\s*$//;
 4633:         if ($pattern =~ /\*$/) {
 4634:             #35.8.*
 4635:             $pattern=~s/\*//;
 4636:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4637:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4638:             #35.8.3.[34-56]
 4639:             my $low=$2;
 4640:             my $high=$3;
 4641:             $pattern=$1;
 4642:             if ($ip =~ /^\Q$pattern\E/) {
 4643:                 my $last=(split(/\./,$ip))[3];
 4644:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4645:             }
 4646:         } elsif ($pattern =~ /^\*/) {
 4647:             #*.msu.edu
 4648:             $pattern=~s/\*//;
 4649:             if (!defined($name)) {
 4650:                 use Socket;
 4651:                 my $netaddr=inet_aton($ip);
 4652:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4653:             }
 4654:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4655:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4656:             #127.0.0.1
 4657:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4658:         } else {
 4659:             #some.name.com
 4660:             if (!defined($name)) {
 4661:                 use Socket;
 4662:                 my $netaddr=inet_aton($ip);
 4663:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4664:             }
 4665:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4666:         }
 4667:         if ($allowed) { last; }
 4668:     }
 4669:     return $allowed;
 4670: }
 4671: 
 4672: ###############################################
 4673: 
 4674: =pod
 4675: 
 4676: =head1 Domain Template Functions
 4677: 
 4678: =over 4
 4679: 
 4680: =item * &determinedomain()
 4681: 
 4682: Inputs: $domain (usually will be undef)
 4683: 
 4684: Returns: Determines which domain should be used for designs
 4685: 
 4686: =cut
 4687: 
 4688: ###############################################
 4689: sub determinedomain {
 4690:     my $domain=shift;
 4691:     if (! $domain) {
 4692:         # Determine domain if we have not been given one
 4693:         $domain = &Apache::lonnet::default_login_domain();
 4694:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4695:         if ($env{'request.role.domain'}) { 
 4696:             $domain=$env{'request.role.domain'}; 
 4697:         }
 4698:     }
 4699:     return $domain;
 4700: }
 4701: ###############################################
 4702: 
 4703: sub devalidate_domconfig_cache {
 4704:     my ($udom)=@_;
 4705:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4706: }
 4707: 
 4708: # ---------------------- Get domain configuration for a domain
 4709: sub get_domainconf {
 4710:     my ($udom) = @_;
 4711:     my $cachetime=1800;
 4712:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4713:     if (defined($cached)) { return %{$result}; }
 4714: 
 4715:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4716: 					     ['login','rolecolors','autoenroll'],$udom);
 4717:     my (%designhash,%legacy);
 4718:     if (keys(%domconfig) > 0) {
 4719:         if (ref($domconfig{'login'}) eq 'HASH') {
 4720:             if (keys(%{$domconfig{'login'}})) {
 4721:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4722:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4723:                         if ($key eq 'loginvia') {
 4724:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4725:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4726:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4727:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4728:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4729:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4730:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4731: 
 4732:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4733:                                             } else {
 4734:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4735:                                             }
 4736:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4737:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4738:                                             }
 4739:                                         }
 4740:                                     }
 4741:                                 }
 4742:                             }
 4743:                         } else {
 4744:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4745:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4746:                                     $domconfig{'login'}{$key}{$img};
 4747:                             }
 4748:                         }
 4749:                     } else {
 4750:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4751:                     }
 4752:                 }
 4753:             } else {
 4754:                 $legacy{'login'} = 1;
 4755:             }
 4756:         } else {
 4757:             $legacy{'login'} = 1;
 4758:         }
 4759:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4760:             if (keys(%{$domconfig{'rolecolors'}})) {
 4761:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4762:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4763:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4764:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4765:                         }
 4766:                     }
 4767:                 }
 4768:             } else {
 4769:                 $legacy{'rolecolors'} = 1;
 4770:             }
 4771:         } else {
 4772:             $legacy{'rolecolors'} = 1;
 4773:         }
 4774:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4775:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4776:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4777:             }
 4778:         }
 4779:         if (keys(%legacy) > 0) {
 4780:             my %legacyhash = &get_legacy_domconf($udom);
 4781:             foreach my $item (keys(%legacyhash)) {
 4782:                 if ($item =~ /^\Q$udom\E\.login/) {
 4783:                     if ($legacy{'login'}) { 
 4784:                         $designhash{$item} = $legacyhash{$item};
 4785:                     }
 4786:                 } else {
 4787:                     if ($legacy{'rolecolors'}) {
 4788:                         $designhash{$item} = $legacyhash{$item};
 4789:                     }
 4790:                 }
 4791:             }
 4792:         }
 4793:     } else {
 4794:         %designhash = &get_legacy_domconf($udom); 
 4795:     }
 4796:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4797: 				  $cachetime);
 4798:     return %designhash;
 4799: }
 4800: 
 4801: sub get_legacy_domconf {
 4802:     my ($udom) = @_;
 4803:     my %legacyhash;
 4804:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4805:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4806:     if (-e $designfile) {
 4807:         if ( open (my $fh,"<$designfile") ) {
 4808:             while (my $line = <$fh>) {
 4809:                 next if ($line =~ /^\#/);
 4810:                 chomp($line);
 4811:                 my ($key,$val)=(split(/\=/,$line));
 4812:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4813:             }
 4814:             close($fh);
 4815:         }
 4816:     }
 4817:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4818:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4819:     }
 4820:     return %legacyhash;
 4821: }
 4822: 
 4823: =pod
 4824: 
 4825: =item * &domainlogo()
 4826: 
 4827: Inputs: $domain (usually will be undef)
 4828: 
 4829: Returns: A link to a domain logo, if the domain logo exists.
 4830: If the domain logo does not exist, a description of the domain.
 4831: 
 4832: =cut
 4833: 
 4834: ###############################################
 4835: sub domainlogo {
 4836:     my $domain = &determinedomain(shift);
 4837:     my %designhash = &get_domainconf($domain);    
 4838:     # See if there is a logo
 4839:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4840:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4841:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4842: 	    if ($imgsrc =~ m{^/res/}) {
 4843: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4844: 		&Apache::lonnet::repcopy($local_name);
 4845: 	    }
 4846: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4847:         } 
 4848:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4849:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4850:         return &Apache::lonnet::domain($domain,'description');
 4851:     } else {
 4852:         return '';
 4853:     }
 4854: }
 4855: ##############################################
 4856: 
 4857: =pod
 4858: 
 4859: =item * &designparm()
 4860: 
 4861: Inputs: $which parameter; $domain (usually will be undef)
 4862: 
 4863: Returns: value of designparamter $which
 4864: 
 4865: =cut
 4866: 
 4867: 
 4868: ##############################################
 4869: sub designparm {
 4870:     my ($which,$domain)=@_;
 4871:     if (exists($env{'environment.color.'.$which})) {
 4872:         return $env{'environment.color.'.$which};
 4873:     }
 4874:     $domain=&determinedomain($domain);
 4875:     my %domdesign;
 4876:     unless ($domain eq 'public') {
 4877:         %domdesign = &get_domainconf($domain);
 4878:     }
 4879:     my $output;
 4880:     if ($domdesign{$domain.'.'.$which} ne '') {
 4881:         $output = $domdesign{$domain.'.'.$which};
 4882:     } else {
 4883:         $output = $defaultdesign{$which};
 4884:     }
 4885:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4886:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4887:         if ($output =~ m{^/(adm|res)/}) {
 4888:             if ($output =~ m{^/res/}) {
 4889:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4890:                 &Apache::lonnet::repcopy($local_name);
 4891:             }
 4892:             $output = &lonhttpdurl($output);
 4893:         }
 4894:     }
 4895:     return $output;
 4896: }
 4897: 
 4898: ##############################################
 4899: =pod
 4900: 
 4901: =item * &authorspace()
 4902: 
 4903: Inputs: $url (usually will be undef).
 4904: 
 4905: Returns: Path to Construction Space containing the resource or 
 4906:          directory being viewed (or for which action is being taken). 
 4907:          If $url is provided, and begins /priv/<domain>/<uname>
 4908:          the path will be that portion of the $context argument.
 4909:          Otherwise the path will be for the author space of the current
 4910:          user when the current role is author, or for that of the 
 4911:          co-author/assistant co-author space when the current role 
 4912:          is co-author or assistant co-author.
 4913: 
 4914: =cut
 4915: 
 4916: sub authorspace {
 4917:     my ($url) = @_;
 4918:     if ($url ne '') {
 4919:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4920:            return $1;
 4921:         }
 4922:     }
 4923:     my $caname = '';
 4924:     my $cadom = '';
 4925:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4926:         ($cadom,$caname) =
 4927:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4928:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4929:         $caname = $env{'user.name'};
 4930:         $cadom = $env{'user.domain'};
 4931:     }
 4932:     if (($caname ne '') && ($cadom ne '')) {
 4933:         return "/priv/$cadom/$caname/";
 4934:     }
 4935:     return;
 4936: }
 4937: 
 4938: ##############################################
 4939: =pod
 4940: 
 4941: =item * &head_subbox()
 4942: 
 4943: Inputs: $content (contains HTML code with page functions, etc.)
 4944: 
 4945: Returns: HTML div with $content
 4946:          To be included in page header
 4947: 
 4948: =cut
 4949: 
 4950: sub head_subbox {
 4951:     my ($content)=@_;
 4952:     my $output =
 4953:         '<div class="LC_head_subbox">'
 4954:        .$content
 4955:        .'</div>'
 4956: }
 4957: 
 4958: ##############################################
 4959: =pod
 4960: 
 4961: =item * &CSTR_pageheader()
 4962: 
 4963: Input: (optional) filename from which breadcrumb trail is built.
 4964:        In most cases no input as needed, as $env{'request.filename'}
 4965:        is appropriate for use in building the breadcrumb trail.
 4966: 
 4967: Returns: HTML div with CSTR path and recent box
 4968:          To be included on Construction Space pages
 4969: 
 4970: =cut
 4971: 
 4972: sub CSTR_pageheader {
 4973:     my ($trailfile) = @_;
 4974:     if ($trailfile eq '') {
 4975:         $trailfile = $env{'request.filename'};
 4976:     }
 4977: 
 4978: # this is for resources; directories have customtitle, and crumbs
 4979: # and select recent are created in lonpubdir.pm
 4980: 
 4981:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4982:     my ($udom,$uname,$thisdisfn)=
 4983:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
 4984:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4985:     $formaction =~ s{/+}{/}g;
 4986: 
 4987:     my $parentpath = '';
 4988:     my $lastitem = '';
 4989:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4990:         $parentpath = $1;
 4991:         $lastitem = $2;
 4992:     } else {
 4993:         $lastitem = $thisdisfn;
 4994:     }
 4995: 
 4996:     my $output =
 4997:          '<div>'
 4998:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4999:         .'<b>'.&mt('Construction Space:').'</b> '
 5000:         .'<form name="dirs" method="post" action="'.$formaction
 5001:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5002:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5003: 
 5004:     if ($lastitem) {
 5005:         $output .=
 5006:              '<span class="LC_filename">'
 5007:             .$lastitem
 5008:             .'</span>';
 5009:     }
 5010:     $output .=
 5011:          '<br />'
 5012:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5013:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5014:         .'</form>'
 5015:         .&Apache::lonmenu::constspaceform()
 5016:         .'</div>';
 5017: 
 5018:     return $output;
 5019: }
 5020: 
 5021: ###############################################
 5022: ###############################################
 5023: 
 5024: =pod
 5025: 
 5026: =back
 5027: 
 5028: =head1 HTML Helpers
 5029: 
 5030: =over 4
 5031: 
 5032: =item * &bodytag()
 5033: 
 5034: Returns a uniform header for LON-CAPA web pages.
 5035: 
 5036: Inputs: 
 5037: 
 5038: =over 4
 5039: 
 5040: =item * $title, A title to be displayed on the page.
 5041: 
 5042: =item * $function, the current role (can be undef).
 5043: 
 5044: =item * $addentries, extra parameters for the <body> tag.
 5045: 
 5046: =item * $bodyonly, if defined, only return the <body> tag.
 5047: 
 5048: =item * $domain, if defined, force a given domain.
 5049: 
 5050: =item * $forcereg, if page should register as content page (relevant for 
 5051:             text interface only)
 5052: 
 5053: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5054:                      navigational links
 5055: 
 5056: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5057: 
 5058: =item * $args, optional argument valid values are
 5059:             no_auto_mt_title -> prevents &mt()ing the title arg
 5060:             inherit_jsmath -> when creating popup window in a page,
 5061:                               should it have jsmath forced on by the
 5062:                               current page
 5063: 
 5064: =item * $advtoolsref, optional argument, ref to an array containing
 5065:             inlineremote items to be added in "Functions" menu below
 5066:             breadcrumbs.
 5067: 
 5068: =back
 5069: 
 5070: Returns: A uniform header for LON-CAPA web pages.  
 5071: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5072: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5073: other decorations will be returned.
 5074: 
 5075: =cut
 5076: 
 5077: sub bodytag {
 5078:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5079:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5080: 
 5081:     my $public;
 5082:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5083:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5084:         $public = 1;
 5085:     }
 5086:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5087: 
 5088:     $function = &get_users_function() if (!$function);
 5089:     my $img =    &designparm($function.'.img',$domain);
 5090:     my $font =   &designparm($function.'.font',$domain);
 5091:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5092: 
 5093:     my %design = ( 'style'   => 'margin-top: 0',
 5094: 		   'bgcolor' => $pgbg,
 5095: 		   'text'    => $font,
 5096:                    'alink'   => &designparm($function.'.alink',$domain),
 5097: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5098: 		   'link'    => &designparm($function.'.link',$domain),);
 5099:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5100: 
 5101:  # role and realm
 5102:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5103:     if ($role  eq 'ca') {
 5104:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5105:         $realm = &plainname($rname,$rdom);
 5106:     } 
 5107: # realm
 5108:     if ($env{'request.course.id'}) {
 5109:         if ($env{'request.role'} !~ /^cr/) {
 5110:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5111:         }
 5112:         if ($env{'request.course.sec'}) {
 5113:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5114:         }   
 5115: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5116:     } else {
 5117:         $role = &Apache::lonnet::plaintext($role);
 5118:     }
 5119: 
 5120:     if (!$realm) { $realm='&nbsp;'; }
 5121: 
 5122:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5123: 
 5124: # construct main body tag
 5125:     my $bodytag = "<body $extra_body_attr>".
 5126: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5127: 
 5128:     if ($bodyonly) {
 5129:         return $bodytag;
 5130:     } 
 5131: 
 5132:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5133:     if ($public) {
 5134: 	undef($role);
 5135:     } else {
 5136: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5137:                                 undef,'LC_menubuttons_link');
 5138:     }
 5139:     
 5140:     my $titleinfo = '<h1>'.$title.'</h1>';
 5141:     #
 5142:     # Extra info if you are the DC
 5143:     my $dc_info = '';
 5144:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5145:                         $env{'course.'.$env{'request.course.id'}.
 5146:                                  '.domain'}.'/'})) {
 5147:         my $cid = $env{'request.course.id'};
 5148:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5149:         $dc_info =~ s/\s+$//;
 5150:     }
 5151: 
 5152:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5153:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5154: 
 5155:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 5156:             return $bodytag; 
 5157:         } 
 5158: 
 5159:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5160: 
 5161:         #    if ($env{'request.state'} eq 'construct') {
 5162:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5163:         #    }
 5164: 
 5165: 
 5166: 
 5167:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5168:              if ($dc_info) {
 5169:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5170:              }
 5171:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 5172:                 <em>$realm</em> $dc_info</div>|;
 5173:             return $bodytag;
 5174:         }
 5175: 
 5176:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5177:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 5178:         }
 5179: 
 5180:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5181:             Apache::lonmenu::utilityfunctions(), 'start');
 5182: 
 5183:         $bodytag .= Apache::lonmenu::primary_menu();
 5184: 
 5185:         if ($dc_info) {
 5186:             $dc_info = &dc_courseid_toggle($dc_info);
 5187:         }
 5188:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5189: 
 5190:         #don't show menus for public users
 5191:         if (!$public){
 5192:             $bodytag .= Apache::lonmenu::secondary_menu();
 5193:             $bodytag .= Apache::lonmenu::serverform();
 5194:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5195:             if ($env{'request.state'} eq 'construct') {
 5196:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5197:                                 $args->{'bread_crumbs'});
 5198:             } elsif ($forcereg) {
 5199:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5200:                                                             $args->{'group'});
 5201:             } else {
 5202:                 $bodytag .= 
 5203:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5204:                                                         $forcereg,$args->{'group'},
 5205:                                                         $args->{'bread_crumbs'},
 5206:                                                         $advtoolsref);
 5207:             }
 5208:         }else{
 5209:             # this is to seperate menu from content when there's no secondary
 5210:             # menu. Especially needed for public accessible ressources.
 5211:             $bodytag .= '<hr style="clear:both" />';
 5212:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5213:         }
 5214: 
 5215:         return $bodytag;
 5216: }
 5217: 
 5218: sub dc_courseid_toggle {
 5219:     my ($dc_info) = @_;
 5220:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5221:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5222:            &mt('(More ...)').'</a></span>'.
 5223:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5224: }
 5225: 
 5226: sub make_attr_string {
 5227:     my ($register,$attr_ref) = @_;
 5228: 
 5229:     if ($attr_ref && !ref($attr_ref)) {
 5230: 	die("addentries Must be a hash ref ".
 5231: 	    join(':',caller(1))." ".
 5232: 	    join(':',caller(0))." ");
 5233:     }
 5234: 
 5235:     if ($register) {
 5236: 	my ($on_load,$on_unload);
 5237: 	foreach my $key (keys(%{$attr_ref})) {
 5238: 	    if      (lc($key) eq 'onload') {
 5239: 		$on_load.=$attr_ref->{$key}.';';
 5240: 		delete($attr_ref->{$key});
 5241: 
 5242: 	    } elsif (lc($key) eq 'onunload') {
 5243: 		$on_unload.=$attr_ref->{$key}.';';
 5244: 		delete($attr_ref->{$key});
 5245: 	    }
 5246: 	}
 5247: 	$attr_ref->{'onload'}  = $on_load;
 5248: 	$attr_ref->{'onunload'}= $on_unload;
 5249:     }
 5250: 
 5251:     my $attr_string;
 5252:     foreach my $attr (keys(%$attr_ref)) {
 5253: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5254:     }
 5255:     return $attr_string;
 5256: }
 5257: 
 5258: 
 5259: ###############################################
 5260: ###############################################
 5261: 
 5262: =pod
 5263: 
 5264: =item * &endbodytag()
 5265: 
 5266: Returns a uniform footer for LON-CAPA web pages.
 5267: 
 5268: Inputs: 1 - optional reference to an args hash
 5269: If in the hash, key for noredirectlink has a value which evaluates to true,
 5270: a 'Continue' link is not displayed if the page contains an
 5271: internal redirect in the <head></head> section,
 5272: i.e., $env{'internal.head.redirect'} exists   
 5273: 
 5274: =cut
 5275: 
 5276: sub endbodytag {
 5277:     my ($args) = @_;
 5278:     my $endbodytag;
 5279:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5280:         $endbodytag='</body>';
 5281:     }
 5282:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5283:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5284:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5285: 	    $endbodytag=
 5286: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5287: 	        &mt('Continue').'</a>'.
 5288: 	        $endbodytag;
 5289:         }
 5290:     }
 5291:     return $endbodytag;
 5292: }
 5293: 
 5294: =pod
 5295: 
 5296: =item * &standard_css()
 5297: 
 5298: Returns a style sheet
 5299: 
 5300: Inputs: (all optional)
 5301:             domain         -> force to color decorate a page for a specific
 5302:                                domain
 5303:             function       -> force usage of a specific rolish color scheme
 5304:             bgcolor        -> override the default page bgcolor
 5305: 
 5306: =cut
 5307: 
 5308: sub standard_css {
 5309:     my ($function,$domain,$bgcolor) = @_;
 5310:     $function  = &get_users_function() if (!$function);
 5311:     my $img    = &designparm($function.'.img',   $domain);
 5312:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5313:     my $font   = &designparm($function.'.font',  $domain);
 5314:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5315: #second colour for later usage
 5316:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5317:     my $pgbg_or_bgcolor =
 5318: 	         $bgcolor ||
 5319: 	         &designparm($function.'.pgbg',  $domain);
 5320:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5321:     my $alink  = &designparm($function.'.alink', $domain);
 5322:     my $vlink  = &designparm($function.'.vlink', $domain);
 5323:     my $link   = &designparm($function.'.link',  $domain);
 5324: 
 5325:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5326:     my $mono                 = 'monospace';
 5327:     my $data_table_head      = $sidebg;
 5328:     my $data_table_light     = '#FAFAFA';
 5329:     my $data_table_dark      = '#E0E0E0';
 5330:     my $data_table_darker    = '#CCCCCC';
 5331:     my $data_table_highlight = '#FFFF00';
 5332:     my $mail_new             = '#FFBB77';
 5333:     my $mail_new_hover       = '#DD9955';
 5334:     my $mail_read            = '#BBBB77';
 5335:     my $mail_read_hover      = '#999944';
 5336:     my $mail_replied         = '#AAAA88';
 5337:     my $mail_replied_hover   = '#888855';
 5338:     my $mail_other           = '#99BBBB';
 5339:     my $mail_other_hover     = '#669999';
 5340:     my $table_header         = '#DDDDDD';
 5341:     my $feedback_link_bg     = '#BBBBBB';
 5342:     my $lg_border_color      = '#C8C8C8';
 5343:     my $button_hover         = '#BF2317';
 5344: 
 5345:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5346:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5347:                                              : '0 3px 0 4px';
 5348: 
 5349: 
 5350:     return <<END;
 5351: 
 5352: /* needed for iframe to allow 100% height in FF */
 5353: body, html { 
 5354:     margin: 0;
 5355:     padding: 0 0.5%;
 5356:     height: 99%; /* to avoid scrollbars */
 5357: }
 5358: 
 5359: body {
 5360:   font-family: $sans;
 5361:   line-height:130%;
 5362:   font-size:0.83em;
 5363:   color:$font;
 5364: }
 5365: 
 5366: a:focus,
 5367: a:focus img {
 5368:   color: red;
 5369: }
 5370: 
 5371: form, .inline {
 5372:   display: inline;
 5373: }
 5374: 
 5375: .LC_right {
 5376:   text-align:right;
 5377: }
 5378: 
 5379: .LC_middle {
 5380:   vertical-align:middle;
 5381: }
 5382: 
 5383: .LC_400Box {
 5384:   width:400px;
 5385: }
 5386: 
 5387: .LC_iframecontainer {
 5388:     width: 98%;
 5389:     margin: 0;
 5390:     position: fixed;
 5391:     top: 8.5em;
 5392:     bottom: 0;
 5393: }
 5394: 
 5395: .LC_iframecontainer iframe{
 5396:     border: none;
 5397:     width: 100%;
 5398:     height: 100%;
 5399: }
 5400: 
 5401: .LC_filename {
 5402:   font-family: $mono;
 5403:   white-space:pre;
 5404:   font-size: 120%;
 5405: }
 5406: 
 5407: .LC_fileicon {
 5408:   border: none;
 5409:   height: 1.3em;
 5410:   vertical-align: text-bottom;
 5411:   margin-right: 0.3em;
 5412:   text-decoration:none;
 5413: }
 5414: 
 5415: .LC_setting {
 5416:   text-decoration:underline;
 5417: }
 5418: 
 5419: .LC_error {
 5420:   color: red;
 5421: }
 5422: 
 5423: .LC_warning {
 5424:   color: darkorange;
 5425: }
 5426: 
 5427: .LC_diff_removed {
 5428:   color: red;
 5429: }
 5430: 
 5431: .LC_info,
 5432: .LC_success,
 5433: .LC_diff_added {
 5434:   color: green;
 5435: }
 5436: 
 5437: div.LC_confirm_box {
 5438:   background-color: #FAFAFA;
 5439:   border: 1px solid $lg_border_color;
 5440:   margin-right: 0;
 5441:   padding: 5px;
 5442: }
 5443: 
 5444: div.LC_confirm_box .LC_error img,
 5445: div.LC_confirm_box .LC_success img {
 5446:   vertical-align: middle;
 5447: }
 5448: 
 5449: .LC_icon {
 5450:   border: none;
 5451:   vertical-align: middle;
 5452: }
 5453: 
 5454: .LC_docs_spacer {
 5455:   width: 25px;
 5456:   height: 1px;
 5457:   border: none;
 5458: }
 5459: 
 5460: .LC_internal_info {
 5461:   color: #999999;
 5462: }
 5463: 
 5464: .LC_discussion {
 5465:   background: $data_table_dark;
 5466:   border: 1px solid black;
 5467:   margin: 2px;
 5468: }
 5469: 
 5470: .LC_disc_action_left {
 5471:   background: $sidebg;
 5472:   text-align: left;
 5473:   padding: 4px;
 5474:   margin: 2px;
 5475: }
 5476: 
 5477: .LC_disc_action_right {
 5478:   background: $sidebg;
 5479:   text-align: right;
 5480:   padding: 4px;
 5481:   margin: 2px;
 5482: }
 5483: 
 5484: .LC_disc_new_item {
 5485:   background: white;
 5486:   border: 2px solid red;
 5487:   margin: 4px;
 5488:   padding: 4px;
 5489: }
 5490: 
 5491: .LC_disc_old_item {
 5492:   background: white;
 5493:   margin: 4px;
 5494:   padding: 4px;
 5495: }
 5496: 
 5497: table.LC_pastsubmission {
 5498:   border: 1px solid black;
 5499:   margin: 2px;
 5500: }
 5501: 
 5502: table#LC_menubuttons {
 5503:   width: 100%;
 5504:   background: $pgbg;
 5505:   border: 2px;
 5506:   border-collapse: separate;
 5507:   padding: 0;
 5508: }
 5509: 
 5510: table#LC_title_bar a {
 5511:   color: $fontmenu;
 5512: }
 5513: 
 5514: table#LC_title_bar {
 5515:   clear: both;
 5516:   display: none;
 5517: }
 5518: 
 5519: table#LC_title_bar,
 5520: table.LC_breadcrumbs, /* obsolete? */
 5521: table#LC_title_bar.LC_with_remote {
 5522:   width: 100%;
 5523:   border-color: $pgbg;
 5524:   border-style: solid;
 5525:   border-width: $border;
 5526:   background: $pgbg;
 5527:   color: $fontmenu;
 5528:   border-collapse: collapse;
 5529:   padding: 0;
 5530:   margin: 0;
 5531: }
 5532: 
 5533: ul.LC_breadcrumb_tools_outerlist {
 5534:     margin: 0;
 5535:     padding: 0;
 5536:     position: relative;
 5537:     list-style: none;
 5538: }
 5539: ul.LC_breadcrumb_tools_outerlist li {
 5540:     display: inline;
 5541: }
 5542: 
 5543: .LC_breadcrumb_tools_navigation {
 5544:     padding: 0;
 5545:     margin: 0;
 5546:     float: left;
 5547: }
 5548: .LC_breadcrumb_tools_tools {
 5549:     padding: 0;
 5550:     margin: 0;
 5551:     float: right;
 5552: }
 5553: 
 5554: table#LC_title_bar td {
 5555:   background: $tabbg;
 5556: }
 5557: 
 5558: table#LC_menubuttons img {
 5559:   border: none;
 5560: }
 5561: 
 5562: .LC_breadcrumbs_component {
 5563:   float: right;
 5564:   margin: 0 1em;
 5565: }
 5566: .LC_breadcrumbs_component img {
 5567:   vertical-align: middle;
 5568: }
 5569: 
 5570: td.LC_table_cell_checkbox {
 5571:   text-align: center;
 5572: }
 5573: 
 5574: .LC_fontsize_small {
 5575:   font-size: 70%;
 5576: }
 5577: 
 5578: #LC_breadcrumbs {
 5579:   clear:both;
 5580:   background: $sidebg;
 5581:   border-bottom: 1px solid $lg_border_color;
 5582:   line-height: 2.5em;
 5583:   overflow: hidden;
 5584:   margin: 0;
 5585:   padding: 0;
 5586:   text-align: left;
 5587: }
 5588: 
 5589: .LC_head_subbox, .LC_actionbox {
 5590:   clear:both;
 5591:   background: #F8F8F8; /* $sidebg; */
 5592:   border: 1px solid $sidebg;
 5593:   margin: 0 0 10px 0;
 5594:   padding: 3px;
 5595:   text-align: left;
 5596: }
 5597: 
 5598: .LC_fontsize_medium {
 5599:   font-size: 85%;
 5600: }
 5601: 
 5602: .LC_fontsize_large {
 5603:   font-size: 120%;
 5604: }
 5605: 
 5606: .LC_menubuttons_inline_text {
 5607:   color: $font;
 5608:   font-size: 90%;
 5609:   padding-left:3px;
 5610: }
 5611: 
 5612: .LC_menubuttons_inline_text img{
 5613:   vertical-align: middle;
 5614: }
 5615: 
 5616: li.LC_menubuttons_inline_text img {
 5617:   cursor:pointer;
 5618:   text-decoration: none;
 5619: }
 5620: 
 5621: .LC_menubuttons_link {
 5622:   text-decoration: none;
 5623: }
 5624: 
 5625: .LC_menubuttons_category {
 5626:   color: $font;
 5627:   background: $pgbg;
 5628:   font-size: larger;
 5629:   font-weight: bold;
 5630: }
 5631: 
 5632: td.LC_menubuttons_text {
 5633:   color: $font;
 5634: }
 5635: 
 5636: .LC_current_location {
 5637:   background: $tabbg;
 5638: }
 5639: 
 5640: table.LC_data_table {
 5641:   border: 1px solid #000000;
 5642:   border-collapse: separate;
 5643:   border-spacing: 1px;
 5644:   background: $pgbg;
 5645: }
 5646: 
 5647: .LC_data_table_dense {
 5648:   font-size: small;
 5649: }
 5650: 
 5651: table.LC_nested_outer {
 5652:   border: 1px solid #000000;
 5653:   border-collapse: collapse;
 5654:   border-spacing: 0;
 5655:   width: 100%;
 5656: }
 5657: 
 5658: table.LC_innerpickbox,
 5659: table.LC_nested {
 5660:   border: none;
 5661:   border-collapse: collapse;
 5662:   border-spacing: 0;
 5663:   width: 100%;
 5664: }
 5665: 
 5666: table.LC_data_table tr th,
 5667: table.LC_calendar tr th,
 5668: table.LC_prior_tries tr th,
 5669: table.LC_innerpickbox tr th {
 5670:   font-weight: bold;
 5671:   background-color: $data_table_head;
 5672:   color:$fontmenu;
 5673:   font-size:90%;
 5674: }
 5675: 
 5676: table.LC_innerpickbox tr th,
 5677: table.LC_innerpickbox tr td {
 5678:   vertical-align: top;
 5679: }
 5680: 
 5681: table.LC_data_table tr.LC_info_row > td {
 5682:   background-color: #CCCCCC;
 5683:   font-weight: bold;
 5684:   text-align: left;
 5685: }
 5686: 
 5687: table.LC_data_table tr.LC_odd_row > td {
 5688:   background-color: $data_table_light;
 5689:   padding: 2px;
 5690:   vertical-align: top;
 5691: }
 5692: 
 5693: table.LC_pick_box tr > td.LC_odd_row {
 5694:   background-color: $data_table_light;
 5695:   vertical-align: top;
 5696: }
 5697: 
 5698: table.LC_data_table tr.LC_even_row > td {
 5699:   background-color: $data_table_dark;
 5700:   padding: 2px;
 5701:   vertical-align: top;
 5702: }
 5703: 
 5704: table.LC_pick_box tr > td.LC_even_row {
 5705:   background-color: $data_table_dark;
 5706:   vertical-align: top;
 5707: }
 5708: 
 5709: table.LC_data_table tr.LC_data_table_highlight td {
 5710:   background-color: $data_table_darker;
 5711: }
 5712: 
 5713: table.LC_data_table tr td.LC_leftcol_header {
 5714:   background-color: $data_table_head;
 5715:   font-weight: bold;
 5716: }
 5717: 
 5718: table.LC_data_table tr.LC_empty_row td,
 5719: table.LC_nested tr.LC_empty_row td {
 5720:   font-weight: bold;
 5721:   font-style: italic;
 5722:   text-align: center;
 5723:   padding: 8px;
 5724: }
 5725: 
 5726: table.LC_data_table tr.LC_empty_row td {
 5727:   background-color: $sidebg;
 5728: }
 5729: 
 5730: table.LC_nested tr.LC_empty_row td {
 5731:   background-color: #FFFFFF;
 5732: }
 5733: 
 5734: table.LC_caption {
 5735: }
 5736: 
 5737: table.LC_nested tr.LC_empty_row td {
 5738:   padding: 4ex
 5739: }
 5740: 
 5741: table.LC_nested_outer tr th {
 5742:   font-weight: bold;
 5743:   color:$fontmenu;
 5744:   background-color: $data_table_head;
 5745:   font-size: small;
 5746:   border-bottom: 1px solid #000000;
 5747: }
 5748: 
 5749: table.LC_nested_outer tr td.LC_subheader {
 5750:   background-color: $data_table_head;
 5751:   font-weight: bold;
 5752:   font-size: small;
 5753:   border-bottom: 1px solid #000000;
 5754:   text-align: right;
 5755: }
 5756: 
 5757: table.LC_nested tr.LC_info_row td {
 5758:   background-color: #CCCCCC;
 5759:   font-weight: bold;
 5760:   font-size: small;
 5761:   text-align: center;
 5762: }
 5763: 
 5764: table.LC_nested tr.LC_info_row td.LC_left_item,
 5765: table.LC_nested_outer tr th.LC_left_item {
 5766:   text-align: left;
 5767: }
 5768: 
 5769: table.LC_nested td {
 5770:   background-color: #FFFFFF;
 5771:   font-size: small;
 5772: }
 5773: 
 5774: table.LC_nested_outer tr th.LC_right_item,
 5775: table.LC_nested tr.LC_info_row td.LC_right_item,
 5776: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5777: table.LC_nested tr td.LC_right_item {
 5778:   text-align: right;
 5779: }
 5780: 
 5781: table.LC_nested tr.LC_odd_row td {
 5782:   background-color: #EEEEEE;
 5783: }
 5784: 
 5785: table.LC_createuser {
 5786: }
 5787: 
 5788: table.LC_createuser tr.LC_section_row td {
 5789:   font-size: small;
 5790: }
 5791: 
 5792: table.LC_createuser tr.LC_info_row td  {
 5793:   background-color: #CCCCCC;
 5794:   font-weight: bold;
 5795:   text-align: center;
 5796: }
 5797: 
 5798: table.LC_calendar {
 5799:   border: 1px solid #000000;
 5800:   border-collapse: collapse;
 5801:   width: 98%;
 5802: }
 5803: 
 5804: table.LC_calendar_pickdate {
 5805:   font-size: xx-small;
 5806: }
 5807: 
 5808: table.LC_calendar tr td {
 5809:   border: 1px solid #000000;
 5810:   vertical-align: top;
 5811:   width: 14%;
 5812: }
 5813: 
 5814: table.LC_calendar tr td.LC_calendar_day_empty {
 5815:   background-color: $data_table_dark;
 5816: }
 5817: 
 5818: table.LC_calendar tr td.LC_calendar_day_current {
 5819:   background-color: $data_table_highlight;
 5820: }
 5821: 
 5822: table.LC_data_table tr td.LC_mail_new {
 5823:   background-color: $mail_new;
 5824: }
 5825: 
 5826: table.LC_data_table tr.LC_mail_new:hover {
 5827:   background-color: $mail_new_hover;
 5828: }
 5829: 
 5830: table.LC_data_table tr td.LC_mail_read {
 5831:   background-color: $mail_read;
 5832: }
 5833: 
 5834: /*
 5835: table.LC_data_table tr.LC_mail_read:hover {
 5836:   background-color: $mail_read_hover;
 5837: }
 5838: */
 5839: 
 5840: table.LC_data_table tr td.LC_mail_replied {
 5841:   background-color: $mail_replied;
 5842: }
 5843: 
 5844: /*
 5845: table.LC_data_table tr.LC_mail_replied:hover {
 5846:   background-color: $mail_replied_hover;
 5847: }
 5848: */
 5849: 
 5850: table.LC_data_table tr td.LC_mail_other {
 5851:   background-color: $mail_other;
 5852: }
 5853: 
 5854: /*
 5855: table.LC_data_table tr.LC_mail_other:hover {
 5856:   background-color: $mail_other_hover;
 5857: }
 5858: */
 5859: 
 5860: table.LC_data_table tr > td.LC_browser_file,
 5861: table.LC_data_table tr > td.LC_browser_file_published {
 5862:   background: #AAEE77;
 5863: }
 5864: 
 5865: table.LC_data_table tr > td.LC_browser_file_locked,
 5866: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5867:   background: #FFAA99;
 5868: }
 5869: 
 5870: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5871:   background: #888888;
 5872: }
 5873: 
 5874: table.LC_data_table tr > td.LC_browser_file_modified,
 5875: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5876:   background: #F8F866;
 5877: }
 5878: 
 5879: table.LC_data_table tr.LC_browser_folder > td {
 5880:   background: #E0E8FF;
 5881: }
 5882: 
 5883: table.LC_data_table tr > td.LC_roles_is {
 5884:   /* background: #77FF77; */
 5885: }
 5886: 
 5887: table.LC_data_table tr > td.LC_roles_future {
 5888:   border-right: 8px solid #FFFF77;
 5889: }
 5890: 
 5891: table.LC_data_table tr > td.LC_roles_will {
 5892:   border-right: 8px solid #FFAA77;
 5893: }
 5894: 
 5895: table.LC_data_table tr > td.LC_roles_expired {
 5896:   border-right: 8px solid #FF7777;
 5897: }
 5898: 
 5899: table.LC_data_table tr > td.LC_roles_will_not {
 5900:   border-right: 8px solid #AAFF77;
 5901: }
 5902: 
 5903: table.LC_data_table tr > td.LC_roles_selected {
 5904:   border-right: 8px solid #11CC55;
 5905: }
 5906: 
 5907: span.LC_current_location {
 5908:   font-size:larger;
 5909:   background: $pgbg;
 5910: }
 5911: 
 5912: span.LC_current_nav_location {
 5913:   font-weight:bold;
 5914:   background: $sidebg;
 5915: }
 5916: 
 5917: span.LC_parm_menu_item {
 5918:   font-size: larger;
 5919: }
 5920: 
 5921: span.LC_parm_scope_all {
 5922:   color: red;
 5923: }
 5924: 
 5925: span.LC_parm_scope_folder {
 5926:   color: green;
 5927: }
 5928: 
 5929: span.LC_parm_scope_resource {
 5930:   color: orange;
 5931: }
 5932: 
 5933: span.LC_parm_part {
 5934:   color: blue;
 5935: }
 5936: 
 5937: span.LC_parm_folder,
 5938: span.LC_parm_symb {
 5939:   font-size: x-small;
 5940:   font-family: $mono;
 5941:   color: #AAAAAA;
 5942: }
 5943: 
 5944: ul.LC_parm_parmlist li {
 5945:   display: inline-block;
 5946:   padding: 0.3em 0.8em;
 5947:   vertical-align: top;
 5948:   width: 150px;
 5949:   border-top:1px solid $lg_border_color;
 5950: }
 5951: 
 5952: td.LC_parm_overview_level_menu,
 5953: td.LC_parm_overview_map_menu,
 5954: td.LC_parm_overview_parm_selectors,
 5955: td.LC_parm_overview_restrictions  {
 5956:   border: 1px solid black;
 5957:   border-collapse: collapse;
 5958: }
 5959: 
 5960: table.LC_parm_overview_restrictions td {
 5961:   border-width: 1px 4px 1px 4px;
 5962:   border-style: solid;
 5963:   border-color: $pgbg;
 5964:   text-align: center;
 5965: }
 5966: 
 5967: table.LC_parm_overview_restrictions th {
 5968:   background: $tabbg;
 5969:   border-width: 1px 4px 1px 4px;
 5970:   border-style: solid;
 5971:   border-color: $pgbg;
 5972: }
 5973: 
 5974: table#LC_helpmenu {
 5975:   border: none;
 5976:   height: 55px;
 5977:   border-spacing: 0;
 5978: }
 5979: 
 5980: table#LC_helpmenu fieldset legend {
 5981:   font-size: larger;
 5982: }
 5983: 
 5984: table#LC_helpmenu_links {
 5985:   width: 100%;
 5986:   border: 1px solid black;
 5987:   background: $pgbg;
 5988:   padding: 0;
 5989:   border-spacing: 1px;
 5990: }
 5991: 
 5992: table#LC_helpmenu_links tr td {
 5993:   padding: 1px;
 5994:   background: $tabbg;
 5995:   text-align: center;
 5996:   font-weight: bold;
 5997: }
 5998: 
 5999: table#LC_helpmenu_links a:link,
 6000: table#LC_helpmenu_links a:visited,
 6001: table#LC_helpmenu_links a:active {
 6002:   text-decoration: none;
 6003:   color: $font;
 6004: }
 6005: 
 6006: table#LC_helpmenu_links a:hover {
 6007:   text-decoration: underline;
 6008:   color: $vlink;
 6009: }
 6010: 
 6011: .LC_chrt_popup_exists {
 6012:   border: 1px solid #339933;
 6013:   margin: -1px;
 6014: }
 6015: 
 6016: .LC_chrt_popup_up {
 6017:   border: 1px solid yellow;
 6018:   margin: -1px;
 6019: }
 6020: 
 6021: .LC_chrt_popup {
 6022:   border: 1px solid #8888FF;
 6023:   background: #CCCCFF;
 6024: }
 6025: 
 6026: table.LC_pick_box {
 6027:   border-collapse: separate;
 6028:   background: white;
 6029:   border: 1px solid black;
 6030:   border-spacing: 1px;
 6031: }
 6032: 
 6033: table.LC_pick_box td.LC_pick_box_title {
 6034:   background: $sidebg;
 6035:   font-weight: bold;
 6036:   text-align: left;
 6037:   vertical-align: top;
 6038:   width: 184px;
 6039:   padding: 8px;
 6040: }
 6041: 
 6042: table.LC_pick_box td.LC_pick_box_value {
 6043:   text-align: left;
 6044:   padding: 8px;
 6045: }
 6046: 
 6047: table.LC_pick_box td.LC_pick_box_select {
 6048:   text-align: left;
 6049:   padding: 8px;
 6050: }
 6051: 
 6052: table.LC_pick_box td.LC_pick_box_separator {
 6053:   padding: 0;
 6054:   height: 1px;
 6055:   background: black;
 6056: }
 6057: 
 6058: table.LC_pick_box td.LC_pick_box_submit {
 6059:   text-align: right;
 6060: }
 6061: 
 6062: table.LC_pick_box td.LC_evenrow_value {
 6063:   text-align: left;
 6064:   padding: 8px;
 6065:   background-color: $data_table_light;
 6066: }
 6067: 
 6068: table.LC_pick_box td.LC_oddrow_value {
 6069:   text-align: left;
 6070:   padding: 8px;
 6071:   background-color: $data_table_light;
 6072: }
 6073: 
 6074: span.LC_helpform_receipt_cat {
 6075:   font-weight: bold;
 6076: }
 6077: 
 6078: table.LC_group_priv_box {
 6079:   background: white;
 6080:   border: 1px solid black;
 6081:   border-spacing: 1px;
 6082: }
 6083: 
 6084: table.LC_group_priv_box td.LC_pick_box_title {
 6085:   background: $tabbg;
 6086:   font-weight: bold;
 6087:   text-align: right;
 6088:   width: 184px;
 6089: }
 6090: 
 6091: table.LC_group_priv_box td.LC_groups_fixed {
 6092:   background: $data_table_light;
 6093:   text-align: center;
 6094: }
 6095: 
 6096: table.LC_group_priv_box td.LC_groups_optional {
 6097:   background: $data_table_dark;
 6098:   text-align: center;
 6099: }
 6100: 
 6101: table.LC_group_priv_box td.LC_groups_functionality {
 6102:   background: $data_table_darker;
 6103:   text-align: center;
 6104:   font-weight: bold;
 6105: }
 6106: 
 6107: table.LC_group_priv td {
 6108:   text-align: left;
 6109:   padding: 0;
 6110: }
 6111: 
 6112: .LC_navbuttons {
 6113:   margin: 2ex 0ex 2ex 0ex;
 6114: }
 6115: 
 6116: .LC_topic_bar {
 6117:   font-weight: bold;
 6118:   background: $tabbg;
 6119:   margin: 1em 0em 1em 2em;
 6120:   padding: 3px;
 6121:   font-size: 1.2em;
 6122: }
 6123: 
 6124: .LC_topic_bar span {
 6125:   left: 0.5em;
 6126:   position: absolute;
 6127:   vertical-align: middle;
 6128:   font-size: 1.2em;
 6129: }
 6130: 
 6131: table.LC_course_group_status {
 6132:   margin: 20px;
 6133: }
 6134: 
 6135: table.LC_status_selector td {
 6136:   vertical-align: top;
 6137:   text-align: center;
 6138:   padding: 4px;
 6139: }
 6140: 
 6141: div.LC_feedback_link {
 6142:   clear: both;
 6143:   background: $sidebg;
 6144:   width: 100%;
 6145:   padding-bottom: 10px;
 6146:   border: 1px $tabbg solid;
 6147:   height: 22px;
 6148:   line-height: 22px;
 6149:   padding-top: 5px;
 6150: }
 6151: 
 6152: div.LC_feedback_link img {
 6153:   height: 22px;
 6154:   vertical-align:middle;
 6155: }
 6156: 
 6157: div.LC_feedback_link a {
 6158:   text-decoration: none;
 6159: }
 6160: 
 6161: div.LC_comblock {
 6162:   display:inline;
 6163:   color:$font;
 6164:   font-size:90%;
 6165: }
 6166: 
 6167: div.LC_feedback_link div.LC_comblock {
 6168:   padding-left:5px;
 6169: }
 6170: 
 6171: div.LC_feedback_link div.LC_comblock a {
 6172:   color:$font;
 6173: }
 6174: 
 6175: span.LC_feedback_link {
 6176:   /* background: $feedback_link_bg; */
 6177:   font-size: larger;
 6178: }
 6179: 
 6180: span.LC_message_link {
 6181:   /* background: $feedback_link_bg; */
 6182:   font-size: larger;
 6183:   position: absolute;
 6184:   right: 1em;
 6185: }
 6186: 
 6187: table.LC_prior_tries {
 6188:   border: 1px solid #000000;
 6189:   border-collapse: separate;
 6190:   border-spacing: 1px;
 6191: }
 6192: 
 6193: table.LC_prior_tries td {
 6194:   padding: 2px;
 6195: }
 6196: 
 6197: .LC_answer_correct {
 6198:   background: lightgreen;
 6199:   color: darkgreen;
 6200:   padding: 6px;
 6201: }
 6202: 
 6203: .LC_answer_charged_try {
 6204:   background: #FFAAAA;
 6205:   color: darkred;
 6206:   padding: 6px;
 6207: }
 6208: 
 6209: .LC_answer_not_charged_try,
 6210: .LC_answer_no_grade,
 6211: .LC_answer_late {
 6212:   background: lightyellow;
 6213:   color: black;
 6214:   padding: 6px;
 6215: }
 6216: 
 6217: .LC_answer_previous {
 6218:   background: lightblue;
 6219:   color: darkblue;
 6220:   padding: 6px;
 6221: }
 6222: 
 6223: .LC_answer_no_message {
 6224:   background: #FFFFFF;
 6225:   color: black;
 6226:   padding: 6px;
 6227: }
 6228: 
 6229: .LC_answer_unknown {
 6230:   background: orange;
 6231:   color: black;
 6232:   padding: 6px;
 6233: }
 6234: 
 6235: span.LC_prior_numerical,
 6236: span.LC_prior_string,
 6237: span.LC_prior_custom,
 6238: span.LC_prior_reaction,
 6239: span.LC_prior_math {
 6240:   font-family: $mono;
 6241:   white-space: pre;
 6242: }
 6243: 
 6244: span.LC_prior_string {
 6245:   font-family: $mono;
 6246:   white-space: pre;
 6247: }
 6248: 
 6249: table.LC_prior_option {
 6250:   width: 100%;
 6251:   border-collapse: collapse;
 6252: }
 6253: 
 6254: table.LC_prior_rank,
 6255: table.LC_prior_match {
 6256:   border-collapse: collapse;
 6257: }
 6258: 
 6259: table.LC_prior_option tr td,
 6260: table.LC_prior_rank tr td,
 6261: table.LC_prior_match tr td {
 6262:   border: 1px solid #000000;
 6263: }
 6264: 
 6265: .LC_nobreak {
 6266:   white-space: nowrap;
 6267: }
 6268: 
 6269: span.LC_cusr_emph {
 6270:   font-style: italic;
 6271: }
 6272: 
 6273: span.LC_cusr_subheading {
 6274:   font-weight: normal;
 6275:   font-size: 85%;
 6276: }
 6277: 
 6278: div.LC_docs_entry_move {
 6279:   border: 1px solid #BBBBBB;
 6280:   background: #DDDDDD;
 6281:   width: 22px;
 6282:   padding: 1px;
 6283:   margin: 0;
 6284: }
 6285: 
 6286: table.LC_data_table tr > td.LC_docs_entry_commands,
 6287: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6288:   font-size: x-small;
 6289: }
 6290: 
 6291: .LC_docs_entry_parameter {
 6292:   white-space: nowrap;
 6293: }
 6294: 
 6295: .LC_docs_copy {
 6296:   color: #000099;
 6297: }
 6298: 
 6299: .LC_docs_cut {
 6300:   color: #550044;
 6301: }
 6302: 
 6303: .LC_docs_rename {
 6304:   color: #009900;
 6305: }
 6306: 
 6307: .LC_docs_remove {
 6308:   color: #990000;
 6309: }
 6310: 
 6311: .LC_docs_reinit_warn,
 6312: .LC_docs_ext_edit {
 6313:   font-size: x-small;
 6314: }
 6315: 
 6316: table.LC_docs_adddocs td,
 6317: table.LC_docs_adddocs th {
 6318:   border: 1px solid #BBBBBB;
 6319:   padding: 4px;
 6320:   background: #DDDDDD;
 6321: }
 6322: 
 6323: table.LC_sty_begin {
 6324:   background: #BBFFBB;
 6325: }
 6326: 
 6327: table.LC_sty_end {
 6328:   background: #FFBBBB;
 6329: }
 6330: 
 6331: table.LC_double_column {
 6332:   border-width: 0;
 6333:   border-collapse: collapse;
 6334:   width: 100%;
 6335:   padding: 2px;
 6336: }
 6337: 
 6338: table.LC_double_column tr td.LC_left_col {
 6339:   top: 2px;
 6340:   left: 2px;
 6341:   width: 47%;
 6342:   vertical-align: top;
 6343: }
 6344: 
 6345: table.LC_double_column tr td.LC_right_col {
 6346:   top: 2px;
 6347:   right: 2px;
 6348:   width: 47%;
 6349:   vertical-align: top;
 6350: }
 6351: 
 6352: div.LC_left_float {
 6353:   float: left;
 6354:   padding-right: 5%;
 6355:   padding-bottom: 4px;
 6356: }
 6357: 
 6358: div.LC_clear_float_header {
 6359:   padding-bottom: 2px;
 6360: }
 6361: 
 6362: div.LC_clear_float_footer {
 6363:   padding-top: 10px;
 6364:   clear: both;
 6365: }
 6366: 
 6367: div.LC_grade_show_user {
 6368: /*  border-left: 5px solid $sidebg; */
 6369:   border-top: 5px solid #000000;
 6370:   margin: 50px 0 0 0;
 6371:   padding: 15px 0 5px 10px;
 6372: }
 6373: 
 6374: div.LC_grade_show_user_odd_row {
 6375: /*  border-left: 5px solid #000000; */
 6376: }
 6377: 
 6378: div.LC_grade_show_user div.LC_Box {
 6379:   margin-right: 50px;
 6380: }
 6381: 
 6382: div.LC_grade_submissions,
 6383: div.LC_grade_message_center,
 6384: div.LC_grade_info_links {
 6385:   margin: 5px;
 6386:   width: 99%;
 6387:   background: #FFFFFF;
 6388: }
 6389: 
 6390: div.LC_grade_submissions_header,
 6391: div.LC_grade_message_center_header {
 6392:   font-weight: bold;
 6393:   font-size: large;
 6394: }
 6395: 
 6396: div.LC_grade_submissions_body,
 6397: div.LC_grade_message_center_body {
 6398:   border: 1px solid black;
 6399:   width: 99%;
 6400:   background: #FFFFFF;
 6401: }
 6402: 
 6403: table.LC_scantron_action {
 6404:   width: 100%;
 6405: }
 6406: 
 6407: table.LC_scantron_action tr th {
 6408:   font-weight:bold;
 6409:   font-style:normal;
 6410: }
 6411: 
 6412: .LC_edit_problem_header,
 6413: div.LC_edit_problem_footer {
 6414:   font-weight: normal;
 6415:   font-size:  medium;
 6416:   margin: 2px;
 6417:   background-color: $sidebg;
 6418: }
 6419: 
 6420: div.LC_edit_problem_header,
 6421: div.LC_edit_problem_header div,
 6422: div.LC_edit_problem_footer,
 6423: div.LC_edit_problem_footer div,
 6424: div.LC_edit_problem_editxml_header,
 6425: div.LC_edit_problem_editxml_header div {
 6426:   margin-top: 5px;
 6427: }
 6428: 
 6429: div.LC_edit_problem_header_title {
 6430:   font-weight: bold;
 6431:   font-size: larger;
 6432:   background: $tabbg;
 6433:   padding: 3px;
 6434:   margin: 0 0 5px 0;
 6435: }
 6436: 
 6437: table.LC_edit_problem_header_title {
 6438:   width: 100%;
 6439:   background: $tabbg;
 6440: }
 6441: 
 6442: div.LC_edit_problem_discards {
 6443:   float: left;
 6444:   padding-bottom: 5px;
 6445: }
 6446: 
 6447: div.LC_edit_problem_saves {
 6448:   float: right;
 6449:   padding-bottom: 5px;
 6450: }
 6451: 
 6452: img.stift {
 6453:   border-width: 0;
 6454:   vertical-align: middle;
 6455: }
 6456: 
 6457: table td.LC_mainmenu_col_fieldset {
 6458:   vertical-align: top;
 6459: }
 6460: 
 6461: div.LC_createcourse {
 6462:   margin: 10px 10px 10px 10px;
 6463: }
 6464: 
 6465: .LC_dccid {
 6466:   margin: 0.2em 0 0 0;
 6467:   padding: 0;
 6468:   font-size: 90%;
 6469:   display:none;
 6470: }
 6471: 
 6472: ol.LC_primary_menu a:hover,
 6473: ol#LC_MenuBreadcrumbs a:hover,
 6474: ol#LC_PathBreadcrumbs a:hover,
 6475: ul#LC_secondary_menu a:hover,
 6476: .LC_FormSectionClearButton input:hover
 6477: ul.LC_TabContent   li:hover a {
 6478:   color:$button_hover;
 6479:   text-decoration:none;
 6480: }
 6481: 
 6482: h1 {
 6483:   padding: 0;
 6484:   line-height:130%;
 6485: }
 6486: 
 6487: h2,
 6488: h3,
 6489: h4,
 6490: h5,
 6491: h6 {
 6492:   margin: 5px 0 5px 0;
 6493:   padding: 0;
 6494:   line-height:130%;
 6495: }
 6496: 
 6497: .LC_hcell {
 6498:   padding:3px 15px 3px 15px;
 6499:   margin: 0;
 6500:   background-color:$tabbg;
 6501:   color:$fontmenu;
 6502:   border-bottom:solid 1px $lg_border_color;
 6503: }
 6504: 
 6505: .LC_Box > .LC_hcell {
 6506:   margin: 0 -10px 10px -10px;
 6507: }
 6508: 
 6509: .LC_noBorder {
 6510:   border: 0;
 6511: }
 6512: 
 6513: .LC_FormSectionClearButton input {
 6514:   background-color:transparent;
 6515:   border: none;
 6516:   cursor:pointer;
 6517:   text-decoration:underline;
 6518: }
 6519: 
 6520: .LC_help_open_topic {
 6521:   color: #FFFFFF;
 6522:   background-color: #EEEEFF;
 6523:   margin: 1px;
 6524:   padding: 4px;
 6525:   border: 1px solid #000033;
 6526:   white-space: nowrap;
 6527:   /* vertical-align: middle; */
 6528: }
 6529: 
 6530: dl,
 6531: ul,
 6532: div,
 6533: fieldset {
 6534:   margin: 10px 10px 10px 0;
 6535:   /* overflow: hidden; */
 6536: }
 6537: 
 6538: fieldset > legend {
 6539:   font-weight: bold;
 6540:   padding: 0 5px 0 5px;
 6541: }
 6542: 
 6543: #LC_nav_bar {
 6544:   float: left;
 6545:   background-color: $pgbg_or_bgcolor;
 6546:   margin: 0 0 2px 0;
 6547: }
 6548: 
 6549: #LC_realm {
 6550:   margin: 0.2em 0 0 0;
 6551:   padding: 0;
 6552:   font-weight: bold;
 6553:   text-align: center;
 6554:   background-color: $pgbg_or_bgcolor;
 6555: }
 6556: 
 6557: #LC_nav_bar em {
 6558:   font-weight: bold;
 6559:   font-style: normal;
 6560: }
 6561: 
 6562: ol.LC_primary_menu {
 6563:   float: right;
 6564:   margin: 0;
 6565:   padding: 0;
 6566:   background-color: $pgbg_or_bgcolor;
 6567: }
 6568: 
 6569: ol#LC_PathBreadcrumbs {
 6570:   margin: 0;
 6571: }
 6572: 
 6573: ol.LC_primary_menu li {
 6574:   color: RGB(80, 80, 80);
 6575:   vertical-align: middle;
 6576:   text-align: left;
 6577:   list-style: none;
 6578:   float: left;
 6579: }
 6580: 
 6581: ol.LC_primary_menu li a {
 6582:   display: block;
 6583:   margin: 0;
 6584:   padding: 0 5px 0 10px;
 6585:   text-decoration: none;
 6586: }
 6587: 
 6588: ol.LC_primary_menu li ul {
 6589:   display: none;
 6590:   width: 10em;
 6591:   background-color: $data_table_light;
 6592: }
 6593: 
 6594: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6595:   display: block;
 6596:   position: absolute;
 6597:   margin: 0;
 6598:   padding: 0;
 6599:   z-index: 2;
 6600: }
 6601: 
 6602: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6603:   font-size: 90%;
 6604:   vertical-align: top;
 6605:   float: none;
 6606:   border-left: 1px solid black;
 6607:   border-right: 1px solid black;
 6608: }
 6609: 
 6610: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6611:   background-color:$data_table_light;
 6612: }
 6613: 
 6614: ol.LC_primary_menu li li a:hover {
 6615:    color:$button_hover;
 6616:    background-color:$data_table_dark;
 6617: }
 6618: 
 6619: ol.LC_primary_menu li img {
 6620:   vertical-align: bottom;
 6621:   height: 1.1em;
 6622:   margin: 0.2em 0 0 0;
 6623: }
 6624: 
 6625: ol.LC_primary_menu a {
 6626:   color: RGB(80, 80, 80);
 6627:   text-decoration: none;
 6628: }
 6629: 
 6630: ol.LC_primary_menu a.LC_new_message {
 6631:   font-weight:bold;
 6632:   color: darkred;
 6633: }
 6634: 
 6635: ol.LC_docs_parameters {
 6636:   margin-left: 0;
 6637:   padding: 0;
 6638:   list-style: none;
 6639: }
 6640: 
 6641: ol.LC_docs_parameters li {
 6642:   margin: 0;
 6643:   padding-right: 20px;
 6644:   display: inline;
 6645: }
 6646: 
 6647: ol.LC_docs_parameters li:before {
 6648:   content: "\\002022 \\0020";
 6649: }
 6650: 
 6651: li.LC_docs_parameters_title {
 6652:   font-weight: bold;
 6653: }
 6654: 
 6655: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6656:   content: "";
 6657: }
 6658: 
 6659: ul#LC_secondary_menu {
 6660:   clear: right;
 6661:   color: $fontmenu;
 6662:   background: $tabbg;
 6663:   list-style: none;
 6664:   padding: 0;
 6665:   margin: 0;
 6666:   width: 100%;
 6667:   text-align: left;
 6668:   float: left;
 6669: }
 6670: 
 6671: ul#LC_secondary_menu li {
 6672:   font-weight: bold;
 6673:   line-height: 1.8em;
 6674:   border-right: 1px solid black;
 6675:   float: left;
 6676: }
 6677: 
 6678: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6679:   background-color: $data_table_light;
 6680: }
 6681: 
 6682: ul#LC_secondary_menu li a {
 6683:   padding: 0 0.8em;
 6684: }
 6685: 
 6686: ul#LC_secondary_menu li ul {
 6687:   display: none;
 6688: }
 6689: 
 6690: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6691:   display: block;
 6692:   position: absolute;
 6693:   margin: 0;
 6694:   padding: 0;
 6695:   list-style:none;
 6696:   float: none;
 6697:   background-color: $data_table_light;
 6698:   z-index: 2;
 6699:   margin-left: -1px;
 6700: }
 6701: 
 6702: ul#LC_secondary_menu li ul li {
 6703:   font-size: 90%;
 6704:   vertical-align: top;
 6705:   border-left: 1px solid black;
 6706:   border-right: 1px solid black;
 6707:   background-color: $data_table_light
 6708:   list-style:none;
 6709:   float: none;
 6710: }
 6711: 
 6712: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6713:   background-color: $data_table_dark;
 6714: }
 6715: 
 6716: ul.LC_TabContent {
 6717:   display:block;
 6718:   background: $sidebg;
 6719:   border-bottom: solid 1px $lg_border_color;
 6720:   list-style:none;
 6721:   margin: -1px -10px 0 -10px;
 6722:   padding: 0;
 6723: }
 6724: 
 6725: ul.LC_TabContent li,
 6726: ul.LC_TabContentBigger li {
 6727:   float:left;
 6728: }
 6729: 
 6730: ul#LC_secondary_menu li a {
 6731:   color: $fontmenu;
 6732:   text-decoration: none;
 6733: }
 6734: 
 6735: ul.LC_TabContent {
 6736:   min-height:20px;
 6737: }
 6738: 
 6739: ul.LC_TabContent li {
 6740:   vertical-align:middle;
 6741:   padding: 0 16px 0 10px;
 6742:   background-color:$tabbg;
 6743:   border-bottom:solid 1px $lg_border_color;
 6744:   border-left: solid 1px $font;
 6745: }
 6746: 
 6747: ul.LC_TabContent .right {
 6748:   float:right;
 6749: }
 6750: 
 6751: ul.LC_TabContent li a,
 6752: ul.LC_TabContent li {
 6753:   color:rgb(47,47,47);
 6754:   text-decoration:none;
 6755:   font-size:95%;
 6756:   font-weight:bold;
 6757:   min-height:20px;
 6758: }
 6759: 
 6760: ul.LC_TabContent li a:hover,
 6761: ul.LC_TabContent li a:focus {
 6762:   color: $button_hover;
 6763:   background:none;
 6764:   outline:none;
 6765: }
 6766: 
 6767: ul.LC_TabContent li:hover {
 6768:   color: $button_hover;
 6769:   cursor:pointer;
 6770: }
 6771: 
 6772: ul.LC_TabContent li.active {
 6773:   color: $font;
 6774:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6775:   border-bottom:solid 1px #FFFFFF;
 6776:   cursor: default;
 6777: }
 6778: 
 6779: ul.LC_TabContent li.active a {
 6780:   color:$font;
 6781:   background:#FFFFFF;
 6782:   outline: none;
 6783: }
 6784: 
 6785: ul.LC_TabContent li.goback {
 6786:   float: left;
 6787:   border-left: none;
 6788: }
 6789: 
 6790: #maincoursedoc {
 6791:   clear:both;
 6792: }
 6793: 
 6794: ul.LC_TabContentBigger {
 6795:   display:block;
 6796:   list-style:none;
 6797:   padding: 0;
 6798: }
 6799: 
 6800: ul.LC_TabContentBigger li {
 6801:   vertical-align:bottom;
 6802:   height: 30px;
 6803:   font-size:110%;
 6804:   font-weight:bold;
 6805:   color: #737373;
 6806: }
 6807: 
 6808: ul.LC_TabContentBigger li.active {
 6809:   position: relative;
 6810:   top: 1px;
 6811: }
 6812: 
 6813: ul.LC_TabContentBigger li a {
 6814:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6815:   height: 30px;
 6816:   line-height: 30px;
 6817:   text-align: center;
 6818:   display: block;
 6819:   text-decoration: none;
 6820:   outline: none;  
 6821: }
 6822: 
 6823: ul.LC_TabContentBigger li.active a {
 6824:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6825:   color:$font;
 6826: }
 6827: 
 6828: ul.LC_TabContentBigger li b {
 6829:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6830:   display: block;
 6831:   float: left;
 6832:   padding: 0 30px;
 6833:   border-bottom: 1px solid $lg_border_color;
 6834: }
 6835: 
 6836: ul.LC_TabContentBigger li:hover b {
 6837:   color:$button_hover;
 6838: }
 6839: 
 6840: ul.LC_TabContentBigger li.active b {
 6841:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6842:   color:$font;
 6843:   border: 0;
 6844: }
 6845: 
 6846: 
 6847: ul.LC_CourseBreadcrumbs {
 6848:   background: $sidebg;
 6849:   height: 2em;
 6850:   padding-left: 10px;
 6851:   margin: 0;
 6852:   list-style-position: inside;
 6853: }
 6854: 
 6855: ol#LC_MenuBreadcrumbs,
 6856: ol#LC_PathBreadcrumbs {
 6857:   padding-left: 10px;
 6858:   margin: 0;
 6859:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6860: }
 6861: 
 6862: ol#LC_MenuBreadcrumbs li,
 6863: ol#LC_PathBreadcrumbs li,
 6864: ul.LC_CourseBreadcrumbs li {
 6865:   display: inline;
 6866:   white-space: normal;  
 6867: }
 6868: 
 6869: ol#LC_MenuBreadcrumbs li a,
 6870: ul.LC_CourseBreadcrumbs li a {
 6871:   text-decoration: none;
 6872:   font-size:90%;
 6873: }
 6874: 
 6875: ol#LC_MenuBreadcrumbs h1 {
 6876:   display: inline;
 6877:   font-size: 90%;
 6878:   line-height: 2.5em;
 6879:   margin: 0;
 6880:   padding: 0;
 6881: }
 6882: 
 6883: ol#LC_PathBreadcrumbs li a {
 6884:   text-decoration:none;
 6885:   font-size:100%;
 6886:   font-weight:bold;
 6887: }
 6888: 
 6889: .LC_Box {
 6890:   border: solid 1px $lg_border_color;
 6891:   padding: 0 10px 10px 10px;
 6892: }
 6893: 
 6894: .LC_DocsBox {
 6895:   border: solid 1px $lg_border_color;
 6896:   padding: 0 0 10px 10px;
 6897: }
 6898: 
 6899: .LC_AboutMe_Image {
 6900:   float:left;
 6901:   margin-right:10px;
 6902: }
 6903: 
 6904: .LC_Clear_AboutMe_Image {
 6905:   clear:left;
 6906: }
 6907: 
 6908: dl.LC_ListStyleClean dt {
 6909:   padding-right: 5px;
 6910:   display: table-header-group;
 6911: }
 6912: 
 6913: dl.LC_ListStyleClean dd {
 6914:   display: table-row;
 6915: }
 6916: 
 6917: .LC_ListStyleClean,
 6918: .LC_ListStyleSimple,
 6919: .LC_ListStyleNormal,
 6920: .LC_ListStyleSpecial {
 6921:   /* display:block; */
 6922:   list-style-position: inside;
 6923:   list-style-type: none;
 6924:   overflow: hidden;
 6925:   padding: 0;
 6926: }
 6927: 
 6928: .LC_ListStyleSimple li,
 6929: .LC_ListStyleSimple dd,
 6930: .LC_ListStyleNormal li,
 6931: .LC_ListStyleNormal dd,
 6932: .LC_ListStyleSpecial li,
 6933: .LC_ListStyleSpecial dd {
 6934:   margin: 0;
 6935:   padding: 5px 5px 5px 10px;
 6936:   clear: both;
 6937: }
 6938: 
 6939: .LC_ListStyleClean li,
 6940: .LC_ListStyleClean dd {
 6941:   padding-top: 0;
 6942:   padding-bottom: 0;
 6943: }
 6944: 
 6945: .LC_ListStyleSimple dd,
 6946: .LC_ListStyleSimple li {
 6947:   border-bottom: solid 1px $lg_border_color;
 6948: }
 6949: 
 6950: .LC_ListStyleSpecial li,
 6951: .LC_ListStyleSpecial dd {
 6952:   list-style-type: none;
 6953:   background-color: RGB(220, 220, 220);
 6954:   margin-bottom: 4px;
 6955: }
 6956: 
 6957: table.LC_SimpleTable {
 6958:   margin:5px;
 6959:   border:solid 1px $lg_border_color;
 6960: }
 6961: 
 6962: table.LC_SimpleTable tr {
 6963:   padding: 0;
 6964:   border:solid 1px $lg_border_color;
 6965: }
 6966: 
 6967: table.LC_SimpleTable thead {
 6968:   background:rgb(220,220,220);
 6969: }
 6970: 
 6971: div.LC_columnSection {
 6972:   display: block;
 6973:   clear: both;
 6974:   overflow: hidden;
 6975:   margin: 0;
 6976: }
 6977: 
 6978: div.LC_columnSection>* {
 6979:   float: left;
 6980:   margin: 10px 20px 10px 0;
 6981:   overflow:hidden;
 6982: }
 6983: 
 6984: table em {
 6985:   font-weight: bold;
 6986:   font-style: normal;
 6987: }
 6988: 
 6989: table.LC_tableBrowseRes,
 6990: table.LC_tableOfContent {
 6991:   border:none;
 6992:   border-spacing: 1px;
 6993:   padding: 3px;
 6994:   background-color: #FFFFFF;
 6995:   font-size: 90%;
 6996: }
 6997: 
 6998: table.LC_tableOfContent {
 6999:   border-collapse: collapse;
 7000: }
 7001: 
 7002: table.LC_tableBrowseRes a,
 7003: table.LC_tableOfContent a {
 7004:   background-color: transparent;
 7005:   text-decoration: none;
 7006: }
 7007: 
 7008: table.LC_tableOfContent img {
 7009:   border: none;
 7010:   height: 1.3em;
 7011:   vertical-align: text-bottom;
 7012:   margin-right: 0.3em;
 7013: }
 7014: 
 7015: a#LC_content_toolbar_firsthomework {
 7016:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7017: }
 7018: 
 7019: a#LC_content_toolbar_everything {
 7020:   background-image:url(/res/adm/pages/show-all.gif);
 7021: }
 7022: 
 7023: a#LC_content_toolbar_uncompleted {
 7024:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7025: }
 7026: 
 7027: #LC_content_toolbar_clearbubbles {
 7028:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7029: }
 7030: 
 7031: a#LC_content_toolbar_changefolder {
 7032:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7033: }
 7034: 
 7035: a#LC_content_toolbar_changefolder_toggled {
 7036:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7037: }
 7038: 
 7039: a#LC_content_toolbar_edittoplevel {
 7040:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7041: }
 7042: 
 7043: ul#LC_toolbar li a:hover {
 7044:   background-position: bottom center;
 7045: }
 7046: 
 7047: ul#LC_toolbar {
 7048:   padding: 0;
 7049:   margin: 2px;
 7050:   list-style:none;
 7051:   position:relative;
 7052:   background-color:white;
 7053:   overflow: auto;
 7054: }
 7055: 
 7056: ul#LC_toolbar li {
 7057:   border:1px solid white;
 7058:   padding: 0;
 7059:   margin: 0;
 7060:   float: left;
 7061:   display:inline;
 7062:   vertical-align:middle;
 7063:   white-space: nowrap;
 7064: }
 7065: 
 7066: 
 7067: a.LC_toolbarItem {
 7068:   display:block;
 7069:   padding: 0;
 7070:   margin: 0;
 7071:   height: 32px;
 7072:   width: 32px;
 7073:   color:white;
 7074:   border: none;
 7075:   background-repeat:no-repeat;
 7076:   background-color:transparent;
 7077: }
 7078: 
 7079: ul.LC_funclist {
 7080:     margin: 0;
 7081:     padding: 0.5em 1em 0.5em 0;
 7082: }
 7083: 
 7084: ul.LC_funclist > li:first-child {
 7085:     font-weight:bold; 
 7086:     margin-left:0.8em;
 7087: }
 7088: 
 7089: ul.LC_funclist + ul.LC_funclist {
 7090:     /* 
 7091:        left border as a seperator if we have more than
 7092:        one list 
 7093:     */
 7094:     border-left: 1px solid $sidebg;
 7095:     /* 
 7096:        this hides the left border behind the border of the 
 7097:        outer box if element is wrapped to the next 'line' 
 7098:     */
 7099:     margin-left: -1px;
 7100: }
 7101: 
 7102: ul.LC_funclist li {
 7103:   display: inline;
 7104:   white-space: nowrap;
 7105:   margin: 0 0 0 25px;
 7106:   line-height: 150%;
 7107: }
 7108: 
 7109: .LC_hidden {
 7110:   display: none;
 7111: }
 7112: 
 7113: .LCmodal-overlay {
 7114: 		position:fixed;
 7115: 		top:0;
 7116: 		right:0;
 7117: 		bottom:0;
 7118: 		left:0;
 7119: 		height:100%;
 7120: 		width:100%;
 7121: 		margin:0;
 7122: 		padding:0;
 7123: 		background:#999;
 7124: 		opacity:.75;
 7125: 		filter: alpha(opacity=75);
 7126: 		-moz-opacity: 0.75;
 7127: 		z-index:101;
 7128: }
 7129: 
 7130: * html .LCmodal-overlay {   
 7131: 		position: absolute;
 7132: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7133: }
 7134: 
 7135: .LCmodal-window {
 7136: 		position:fixed;
 7137: 		top:50%;
 7138: 		left:50%;
 7139: 		margin:0;
 7140: 		padding:0;
 7141: 		z-index:102;
 7142: 	}
 7143: 
 7144: * html .LCmodal-window {
 7145: 		position:absolute;
 7146: }
 7147: 
 7148: .LCclose-window {
 7149: 		position:absolute;
 7150: 		width:32px;
 7151: 		height:32px;
 7152: 		right:8px;
 7153: 		top:8px;
 7154: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7155: 		text-indent:-99999px;
 7156: 		overflow:hidden;
 7157: 		cursor:pointer;
 7158: }
 7159: 
 7160: /*
 7161:   styles used by TTH when "Default set of options to pass to tth/m
 7162:   when converting TeX" in course settings has been set
 7163: 
 7164:   option passed: -t
 7165: 
 7166: */
 7167: 
 7168: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7169: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7170: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7171: td div.norm {line-height:normal;}
 7172: 
 7173: /*
 7174:   option passed -y3
 7175: */
 7176: 
 7177: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7178: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7179: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7180: 
 7181: END
 7182: }
 7183: 
 7184: =pod
 7185: 
 7186: =item * &headtag()
 7187: 
 7188: Returns a uniform footer for LON-CAPA web pages.
 7189: 
 7190: Inputs: $title - optional title for the head
 7191:         $head_extra - optional extra HTML to put inside the <head>
 7192:         $args - optional arguments
 7193:             force_register - if is true call registerurl so the remote is 
 7194:                              informed
 7195:             redirect       -> array ref of
 7196:                                    1- seconds before redirect occurs
 7197:                                    2- url to redirect to
 7198:                                    3- whether the side effect should occur
 7199:                            (side effect of setting 
 7200:                                $env{'internal.head.redirect'} to the url 
 7201:                                redirected too)
 7202:             domain         -> force to color decorate a page for a specific
 7203:                                domain
 7204:             function       -> force usage of a specific rolish color scheme
 7205:             bgcolor        -> override the default page bgcolor
 7206:             no_auto_mt_title
 7207:                            -> prevent &mt()ing the title arg
 7208: 
 7209: =cut
 7210: 
 7211: sub headtag {
 7212:     my ($title,$head_extra,$args) = @_;
 7213:     
 7214:     my $function = $args->{'function'} || &get_users_function();
 7215:     my $domain   = $args->{'domain'}   || &determinedomain();
 7216:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7217:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7218: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7219: 		   #time(),
 7220: 		   $env{'environment.color.timestamp'},
 7221: 		   $function,$domain,$bgcolor);
 7222: 
 7223:     $url = '/adm/css/'.&escape($url).'.css';
 7224: 
 7225:     my $result =
 7226: 	'<head>'.
 7227: 	&font_settings();
 7228: 
 7229:     my $inhibitprint = &print_suppression();
 7230: 
 7231:     if (!$args->{'frameset'}) {
 7232: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7233:     }
 7234:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7235:         $result .= Apache::lonxml::display_title();
 7236:     }
 7237:     if (!$args->{'no_nav_bar'} 
 7238: 	&& !$args->{'only_body'}
 7239: 	&& !$args->{'frameset'}) {
 7240: 	$result .= &help_menu_js();
 7241:         $result.=&modal_window();
 7242:         $result.=&togglebox_script();
 7243:         $result.=&wishlist_window();
 7244:         $result.=&LCprogressbarUpdate_script();
 7245:     } else {
 7246:         if ($args->{'add_modal'}) {
 7247:            $result.=&modal_window();
 7248:         }
 7249:         if ($args->{'add_wishlist'}) {
 7250:            $result.=&wishlist_window();
 7251:         }
 7252:         if ($args->{'add_togglebox'}) {
 7253:            $result.=&togglebox_script();
 7254:         }
 7255:         if ($args->{'add_progressbar'}) {
 7256:            $result.=&LCprogressbarUpdate_script();
 7257:         }
 7258:     }
 7259:     if (ref($args->{'redirect'})) {
 7260: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7261: 	$url = &Apache::lonenc::check_encrypt($url);
 7262: 	if (!$inhibit_continue) {
 7263: 	    $env{'internal.head.redirect'} = $url;
 7264: 	}
 7265: 	$result.=<<ADDMETA
 7266: <meta http-equiv="pragma" content="no-cache" />
 7267: <meta http-equiv="Refresh" content="$time; url=$url" />
 7268: ADDMETA
 7269:     }
 7270:     if (!defined($title)) {
 7271: 	$title = 'The LearningOnline Network with CAPA';
 7272:     }
 7273:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7274:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7275: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7276:         .$inhibitprint
 7277: 	.$head_extra;
 7278:     return $result.'</head>';
 7279: }
 7280: 
 7281: =pod
 7282: 
 7283: =item * &font_settings()
 7284: 
 7285: Returns neccessary <meta> to set the proper encoding
 7286: 
 7287: Inputs: none
 7288: 
 7289: =cut
 7290: 
 7291: sub font_settings {
 7292:     my $headerstring='';
 7293:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 7294: 	$headerstring.=
 7295: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 7296:     }
 7297:     return $headerstring;
 7298: }
 7299: 
 7300: =pod
 7301: 
 7302: =item * &print_suppression()
 7303: 
 7304: In course context returns css which causes the body to be blank when media="print",
 7305: if printout generation is unavailable for the current resource.
 7306: 
 7307: This could be because:
 7308: 
 7309: (a) printstartdate is in the future
 7310: 
 7311: (b) printenddate is in the past
 7312: 
 7313: (c) there is an active exam block with "printout"
 7314: functionality blocked
 7315: 
 7316: Users with pav, pfo or evb privileges are exempt.
 7317: 
 7318: Inputs: none
 7319: 
 7320: =cut
 7321: 
 7322: 
 7323: sub print_suppression {
 7324:     my $noprint;
 7325:     if ($env{'request.course.id'}) {
 7326:         my $scope = $env{'request.course.id'};
 7327:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7328:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7329:             return;
 7330:         }
 7331:         if ($env{'request.course.sec'} ne '') {
 7332:             $scope .= "/$env{'request.course.sec'}";
 7333:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7334:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7335:                 return;
 7336:             }
 7337:         }
 7338:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7339:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7340:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7341:         if ($blocked) {
 7342:             my $checkrole = "cm./$cdom/$cnum";
 7343:             if ($env{'request.course.sec'} ne '') {
 7344:                 $checkrole .= "/$env{'request.course.sec'}";
 7345:             }
 7346:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7347:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7348:                 $noprint = 1;
 7349:             }
 7350:         }
 7351:         unless ($noprint) {
 7352:             my $symb = &Apache::lonnet::symbread();
 7353:             if ($symb ne '') {
 7354:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7355:                 if (ref($navmap)) {
 7356:                     my $res = $navmap->getBySymb($symb);
 7357:                     if (ref($res)) {
 7358:                         if (!$res->resprintable()) {
 7359:                             $noprint = 1;
 7360:                         }
 7361:                     }
 7362:                 }
 7363:             }
 7364:         }
 7365:         if ($noprint) {
 7366:             return <<"ENDSTYLE";
 7367: <style type="text/css" media="print">
 7368:     body { display:none }
 7369: </style>
 7370: ENDSTYLE
 7371:         }
 7372:     }
 7373:     return;
 7374: }
 7375: 
 7376: =pod
 7377: 
 7378: =item * &xml_begin()
 7379: 
 7380: Returns the needed doctype and <html>
 7381: 
 7382: Inputs: none
 7383: 
 7384: =cut
 7385: 
 7386: sub xml_begin {
 7387:     my $output='';
 7388: 
 7389:     if ($env{'browser.mathml'}) {
 7390: 	$output='<?xml version="1.0"?>'
 7391:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7392: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7393:             
 7394: #	    .'<!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">] >'
 7395: 	    .'<!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">'
 7396:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7397: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7398:     } else {
 7399: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7400:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7401:     }
 7402:     return $output;
 7403: }
 7404: 
 7405: =pod
 7406: 
 7407: =item * &start_page()
 7408: 
 7409: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7410: 
 7411: Inputs:
 7412: 
 7413: =over 4
 7414: 
 7415: $title - optional title for the page
 7416: 
 7417: $head_extra - optional extra HTML to incude inside the <head>
 7418: 
 7419: $args - additional optional args supported are:
 7420: 
 7421: =over 8
 7422: 
 7423:              only_body      -> is true will set &bodytag() onlybodytag
 7424:                                     arg on
 7425:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7426:              add_entries    -> additional attributes to add to the  <body>
 7427:              domain         -> force to color decorate a page for a 
 7428:                                     specific domain
 7429:              function       -> force usage of a specific rolish color
 7430:                                     scheme
 7431:              redirect       -> see &headtag()
 7432:              bgcolor        -> override the default page bg color
 7433:              js_ready       -> return a string ready for being used in 
 7434:                                     a javascript writeln
 7435:              html_encode    -> return a string ready for being used in 
 7436:                                     a html attribute
 7437:              force_register -> if is true will turn on the &bodytag()
 7438:                                     $forcereg arg
 7439:              frameset       -> if true will start with a <frameset>
 7440:                                     rather than <body>
 7441:              skip_phases    -> hash ref of 
 7442:                                     head -> skip the <html><head> generation
 7443:                                     body -> skip all <body> generation
 7444:              no_auto_mt_title -> prevent &mt()ing the title arg
 7445:              inherit_jsmath -> when creating popup window in a page,
 7446:                                     should it have jsmath forced on by the
 7447:                                     current page
 7448:              bread_crumbs ->             Array containing breadcrumbs
 7449:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7450:              group          -> includes the current group, if page is for a 
 7451:                                specific group  
 7452: 
 7453: =back
 7454: 
 7455: =back
 7456: 
 7457: =cut
 7458: 
 7459: sub start_page {
 7460:     my ($title,$head_extra,$args) = @_;
 7461:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7462: 
 7463:     $env{'internal.start_page'}++;
 7464:     my ($result,@advtools);
 7465: 
 7466:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7467:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7468:     }
 7469:     
 7470:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7471: 	if ($args->{'frameset'}) {
 7472: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7473: 						$args->{'add_entries'});
 7474: 	    $result .= "\n<frameset $attr_string>\n";
 7475:         } else {
 7476:             $result .=
 7477:                 &bodytag($title, 
 7478:                          $args->{'function'},       $args->{'add_entries'},
 7479:                          $args->{'only_body'},      $args->{'domain'},
 7480:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7481:                          $args->{'bgcolor'},        $args,
 7482:                          \@advtools);
 7483:         }
 7484:     }
 7485: 
 7486:     if ($args->{'js_ready'}) {
 7487: 		$result = &js_ready($result);
 7488:     }
 7489:     if ($args->{'html_encode'}) {
 7490: 		$result = &html_encode($result);
 7491:     }
 7492: 
 7493:     # Preparation for new and consistent functionlist at top of screen
 7494:     # if ($args->{'functionlist'}) {
 7495:     #            $result .= &build_functionlist();
 7496:     #}
 7497: 
 7498:     # Don't add anything more if only_body wanted or in const space
 7499:     return $result if    $args->{'only_body'} 
 7500:                       || $env{'request.state'} eq 'construct';
 7501: 
 7502:     #Breadcrumbs
 7503:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7504: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7505: 		#if any br links exists, add them to the breadcrumbs
 7506: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7507: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7508: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7509: 			}
 7510: 		}
 7511:                 # if @advtools array contains items add then to the breadcrumbs
 7512:                 if (@advtools > 0) {
 7513:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7514:                 }
 7515: 
 7516: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7517: 		if(exists($args->{'bread_crumbs_component'})){
 7518: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7519: 		}else{
 7520: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7521: 		}
 7522:     }
 7523:     return $result;
 7524: }
 7525: 
 7526: sub end_page {
 7527:     my ($args) = @_;
 7528:     $env{'internal.end_page'}++;
 7529:     my $result;
 7530:     if ($args->{'discussion'}) {
 7531: 	my ($target,$parser);
 7532: 	if (ref($args->{'discussion'})) {
 7533: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7534: 				$args->{'discussion'}{'parser'});
 7535: 	}
 7536: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7537:     }
 7538:     if ($args->{'frameset'}) {
 7539: 	$result .= '</frameset>';
 7540:     } else {
 7541: 	$result .= &endbodytag($args);
 7542:     }
 7543:     unless ($args->{'notbody'}) {
 7544:         $result .= "\n</html>";
 7545:     }
 7546: 
 7547:     if ($args->{'js_ready'}) {
 7548: 	$result = &js_ready($result);
 7549:     }
 7550: 
 7551:     if ($args->{'html_encode'}) {
 7552: 	$result = &html_encode($result);
 7553:     }
 7554: 
 7555:     return $result;
 7556: }
 7557: 
 7558: sub wishlist_window {
 7559:     return(<<'ENDWISHLIST');
 7560: <script type="text/javascript">
 7561: // <![CDATA[
 7562: // <!-- BEGIN LON-CAPA Internal
 7563: function set_wishlistlink(title, path) {
 7564:     if (!title) {
 7565:         title = document.title;
 7566:         title = title.replace(/^LON-CAPA /,'');
 7567:     }
 7568:     if (!path) {
 7569:         path = location.pathname;
 7570:     }
 7571:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7572:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7573: }
 7574: // END LON-CAPA Internal -->
 7575: // ]]>
 7576: </script>
 7577: ENDWISHLIST
 7578: }
 7579: 
 7580: sub modal_window {
 7581:     return(<<'ENDMODAL');
 7582: <script type="text/javascript">
 7583: // <![CDATA[
 7584: // <!-- BEGIN LON-CAPA Internal
 7585: var modalWindow = {
 7586: 	parent:"body",
 7587: 	windowId:null,
 7588: 	content:null,
 7589: 	width:null,
 7590: 	height:null,
 7591: 	close:function()
 7592: 	{
 7593: 	        $(".LCmodal-window").remove();
 7594: 	        $(".LCmodal-overlay").remove();
 7595: 	},
 7596: 	open:function()
 7597: 	{
 7598: 		var modal = "";
 7599: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7600: 		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;\">";
 7601: 		modal += this.content;
 7602: 		modal += "</div>";	
 7603: 
 7604: 		$(this.parent).append(modal);
 7605: 
 7606: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7607: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7608: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7609: 	}
 7610: };
 7611: 	var openMyModal = function(source,width,height,scrolling)
 7612: 	{
 7613: 		modalWindow.windowId = "myModal";
 7614: 		modalWindow.width = width;
 7615: 		modalWindow.height = height;
 7616: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
 7617: 		modalWindow.open();
 7618: 	};	
 7619: // END LON-CAPA Internal -->
 7620: // ]]>
 7621: </script>
 7622: ENDMODAL
 7623: }
 7624: 
 7625: sub modal_link {
 7626:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
 7627:     unless ($width) { $width=480; }
 7628:     unless ($height) { $height=400; }
 7629:     unless ($scrolling) { $scrolling='yes'; }
 7630:     my $target_attr;
 7631:     if (defined($target)) {
 7632:         $target_attr = 'target="'.$target.'"';
 7633:     }
 7634:     return <<"ENDLINK";
 7635: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
 7636:            $linktext</a>
 7637: ENDLINK
 7638: }
 7639: 
 7640: sub modal_adhoc_script {
 7641:     my ($funcname,$width,$height,$content)=@_;
 7642:     return (<<ENDADHOC);
 7643: <script type="text/javascript">
 7644: // <![CDATA[
 7645:         var $funcname = function()
 7646:         {
 7647:                 modalWindow.windowId = "myModal";
 7648:                 modalWindow.width = $width;
 7649:                 modalWindow.height = $height;
 7650:                 modalWindow.content = '$content';
 7651:                 modalWindow.open();
 7652:         };  
 7653: // ]]>
 7654: </script>
 7655: ENDADHOC
 7656: }
 7657: 
 7658: sub modal_adhoc_inner {
 7659:     my ($funcname,$width,$height,$content)=@_;
 7660:     my $innerwidth=$width-20;
 7661:     $content=&js_ready(
 7662:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7663:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
 7664:                     $content.
 7665:                  &end_scrollbox().
 7666:                &end_page()
 7667:              );
 7668:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7669: }
 7670: 
 7671: sub modal_adhoc_window {
 7672:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7673:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7674:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7675: }
 7676: 
 7677: sub modal_adhoc_launch {
 7678:     my ($funcname,$width,$height,$content)=@_;
 7679:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7680: <script type="text/javascript">
 7681: // <![CDATA[
 7682: $funcname();
 7683: // ]]>
 7684: </script>
 7685: ENDLAUNCH
 7686: }
 7687: 
 7688: sub modal_adhoc_close {
 7689:     return (<<ENDCLOSE);
 7690: <script type="text/javascript">
 7691: // <![CDATA[
 7692: modalWindow.close();
 7693: // ]]>
 7694: </script>
 7695: ENDCLOSE
 7696: }
 7697: 
 7698: sub togglebox_script {
 7699:    return(<<ENDTOGGLE);
 7700: <script type="text/javascript"> 
 7701: // <![CDATA[
 7702: function LCtoggleDisplay(id,hidetext,showtext) {
 7703:    link = document.getElementById(id + "link").childNodes[0];
 7704:    with (document.getElementById(id).style) {
 7705:       if (display == "none" ) {
 7706:           display = "inline";
 7707:           link.nodeValue = hidetext;
 7708:         } else {
 7709:           display = "none";
 7710:           link.nodeValue = showtext;
 7711:        }
 7712:    }
 7713: }
 7714: // ]]>
 7715: </script>
 7716: ENDTOGGLE
 7717: }
 7718: 
 7719: sub start_togglebox {
 7720:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7721:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7722:     unless ($showtext) { $showtext=&mt('show'); }
 7723:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7724:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7725:     return &start_data_table().
 7726:            &start_data_table_header_row().
 7727:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7728:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7729:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7730:            &end_data_table_header_row().
 7731:            '<tr id="'.$id.'" style="display:none""><td>';
 7732: }
 7733: 
 7734: sub end_togglebox {
 7735:     return '</td></tr>'.&end_data_table();
 7736: }
 7737: 
 7738: sub LCprogressbar_script {
 7739:    my ($id)=@_;
 7740:    return(<<ENDPROGRESS);
 7741: <script type="text/javascript">
 7742: // <![CDATA[
 7743: \$('#progressbar$id').progressbar({
 7744:   value: 0,
 7745:   change: function(event, ui) {
 7746:     var newVal = \$(this).progressbar('option', 'value');
 7747:     \$('.pblabel', this).text(LCprogressTxt);
 7748:   }
 7749: });
 7750: // ]]>
 7751: </script>
 7752: ENDPROGRESS
 7753: }
 7754: 
 7755: sub LCprogressbarUpdate_script {
 7756:    return(<<ENDPROGRESSUPDATE);
 7757: <style type="text/css">
 7758: .ui-progressbar { position:relative; }
 7759: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7760: </style>
 7761: <script type="text/javascript">
 7762: // <![CDATA[
 7763: var LCprogressTxt='---';
 7764: 
 7765: function LCupdateProgress(percent,progresstext,id) {
 7766:    LCprogressTxt=progresstext;
 7767:    \$('#progressbar'+id).progressbar('value',percent);
 7768: }
 7769: // ]]>
 7770: </script>
 7771: ENDPROGRESSUPDATE
 7772: }
 7773: 
 7774: my $LClastpercent;
 7775: my $LCidcnt;
 7776: my $LCcurrentid;
 7777: 
 7778: sub LCprogressbar {
 7779:     my ($r)=(@_);
 7780:     $LClastpercent=0;
 7781:     $LCidcnt++;
 7782:     $LCcurrentid=$$.'_'.$LCidcnt;
 7783:     my $starting=&mt('Starting');
 7784:     my $content=(<<ENDPROGBAR);
 7785: <p>
 7786:   <div id="progressbar$LCcurrentid">
 7787:     <span class="pblabel">$starting</span>
 7788:   </div>
 7789: </p>
 7790: ENDPROGBAR
 7791:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7792: }
 7793: 
 7794: sub LCprogressbarUpdate {
 7795:     my ($r,$val,$text)=@_;
 7796:     unless ($val) { 
 7797:        if ($LClastpercent) {
 7798:            $val=$LClastpercent;
 7799:        } else {
 7800:            $val=0;
 7801:        }
 7802:     }
 7803:     if ($val<0) { $val=0; }
 7804:     if ($val>100) { $val=0; }
 7805:     $LClastpercent=$val;
 7806:     unless ($text) { $text=$val.'%'; }
 7807:     $text=&js_ready($text);
 7808:     &r_print($r,<<ENDUPDATE);
 7809: <script type="text/javascript">
 7810: // <![CDATA[
 7811: LCupdateProgress($val,'$text','$LCcurrentid');
 7812: // ]]>
 7813: </script>
 7814: ENDUPDATE
 7815: }
 7816: 
 7817: sub LCprogressbarClose {
 7818:     my ($r)=@_;
 7819:     $LClastpercent=0;
 7820:     &r_print($r,<<ENDCLOSE);
 7821: <script type="text/javascript">
 7822: // <![CDATA[
 7823: \$("#progressbar$LCcurrentid").hide('slow'); 
 7824: // ]]>
 7825: </script>
 7826: ENDCLOSE
 7827: }
 7828: 
 7829: sub r_print {
 7830:     my ($r,$to_print)=@_;
 7831:     if ($r) {
 7832:       $r->print($to_print);
 7833:       $r->rflush();
 7834:     } else {
 7835:       print($to_print);
 7836:     }
 7837: }
 7838: 
 7839: sub html_encode {
 7840:     my ($result) = @_;
 7841: 
 7842:     $result = &HTML::Entities::encode($result,'<>&"');
 7843:     
 7844:     return $result;
 7845: }
 7846: 
 7847: sub js_ready {
 7848:     my ($result) = @_;
 7849: 
 7850:     $result =~ s/[\n\r]/ /xmsg;
 7851:     $result =~ s/\\/\\\\/xmsg;
 7852:     $result =~ s/'/\\'/xmsg;
 7853:     $result =~ s{</}{<\\/}xmsg;
 7854:     
 7855:     return $result;
 7856: }
 7857: 
 7858: sub validate_page {
 7859:     if (  exists($env{'internal.start_page'})
 7860: 	  &&     $env{'internal.start_page'} > 1) {
 7861: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7862: 				 $env{'internal.start_page'}.' '.
 7863: 				 $ENV{'request.filename'});
 7864:     }
 7865:     if (  exists($env{'internal.end_page'})
 7866: 	  &&     $env{'internal.end_page'} > 1) {
 7867: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7868: 				 $env{'internal.end_page'}.' '.
 7869: 				 $env{'request.filename'});
 7870:     }
 7871:     if (     exists($env{'internal.start_page'})
 7872: 	&& ! exists($env{'internal.end_page'})) {
 7873: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7874: 				 $env{'request.filename'});
 7875:     }
 7876:     if (   ! exists($env{'internal.start_page'})
 7877: 	&&   exists($env{'internal.end_page'})) {
 7878: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7879: 				 $env{'request.filename'});
 7880:     }
 7881: }
 7882: 
 7883: 
 7884: sub start_scrollbox {
 7885:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
 7886:     unless ($outerwidth) { $outerwidth='520px'; }
 7887:     unless ($width) { $width='500px'; }
 7888:     unless ($height) { $height='200px'; }
 7889:     my ($table_id,$div_id,$tdcol);
 7890:     if ($id ne '') {
 7891:         $table_id = " id='table_$id'";
 7892:         $div_id = " id='div_$id'";
 7893:     }
 7894:     if ($bgcolor ne '') {
 7895:         $tdcol = "background-color: $bgcolor;";
 7896:     }
 7897:     return <<"END";
 7898: <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>
 7899: END
 7900: }
 7901: 
 7902: sub end_scrollbox {
 7903:     return '</div></td></tr></table>';
 7904: }
 7905: 
 7906: sub simple_error_page {
 7907:     my ($r,$title,$msg) = @_;
 7908:     my $page =
 7909: 	&Apache::loncommon::start_page($title).
 7910: 	'<p class="LC_error">'.&mt($msg).'</p>'.
 7911: 	&Apache::loncommon::end_page();
 7912:     if (ref($r)) {
 7913: 	$r->print($page);
 7914: 	return;
 7915:     }
 7916:     return $page;
 7917: }
 7918: 
 7919: {
 7920:     my @row_count;
 7921: 
 7922:     sub start_data_table_count {
 7923:         unshift(@row_count, 0);
 7924:         return;
 7925:     }
 7926: 
 7927:     sub end_data_table_count {
 7928:         shift(@row_count);
 7929:         return;
 7930:     }
 7931: 
 7932:     sub start_data_table {
 7933: 	my ($add_class,$id) = @_;
 7934: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7935:         my $table_id;
 7936:         if (defined($id)) {
 7937:             $table_id = ' id="'.$id.'"';
 7938:         }
 7939: 	&start_data_table_count();
 7940: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 7941:     }
 7942: 
 7943:     sub end_data_table {
 7944: 	&end_data_table_count();
 7945: 	return '</table>'."\n";;
 7946:     }
 7947: 
 7948:     sub start_data_table_row {
 7949: 	my ($add_class, $id) = @_;
 7950: 	$row_count[0]++;
 7951: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7952: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7953:         $id = (' id="'.$id.'"') unless ($id eq '');
 7954:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7955:     }
 7956:     
 7957:     sub continue_data_table_row {
 7958: 	my ($add_class, $id) = @_;
 7959: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7960: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7961:         $id = (' id="'.$id.'"') unless ($id eq '');
 7962:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7963:     }
 7964: 
 7965:     sub end_data_table_row {
 7966: 	return '</tr>'."\n";;
 7967:     }
 7968: 
 7969:     sub start_data_table_empty_row {
 7970: #	$row_count[0]++;
 7971: 	return  '<tr class="LC_empty_row" >'."\n";;
 7972:     }
 7973: 
 7974:     sub end_data_table_empty_row {
 7975: 	return '</tr>'."\n";;
 7976:     }
 7977: 
 7978:     sub start_data_table_header_row {
 7979: 	return  '<tr class="LC_header_row">'."\n";;
 7980:     }
 7981: 
 7982:     sub end_data_table_header_row {
 7983: 	return '</tr>'."\n";;
 7984:     }
 7985: 
 7986:     sub data_table_caption {
 7987:         my $caption = shift;
 7988:         return "<caption class=\"LC_caption\">$caption</caption>";
 7989:     }
 7990: }
 7991: 
 7992: =pod
 7993: 
 7994: =item * &inhibit_menu_check($arg)
 7995: 
 7996: Checks for a inhibitmenu state and generates output to preserve it
 7997: 
 7998: Inputs:         $arg - can be any of
 7999:                      - undef - in which case the return value is a string 
 8000:                                to add  into arguments list of a uri
 8001:                      - 'input' - in which case the return value is a HTML
 8002:                                  <form> <input> field of type hidden to
 8003:                                  preserve the value
 8004:                      - a url - in which case the return value is the url with
 8005:                                the neccesary cgi args added to preserve the
 8006:                                inhibitmenu state
 8007:                      - a ref to a url - no return value, but the string is
 8008:                                         updated to include the neccessary cgi
 8009:                                         args to preserve the inhibitmenu state
 8010: 
 8011: =cut
 8012: 
 8013: sub inhibit_menu_check {
 8014:     my ($arg) = @_;
 8015:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8016:     if ($arg eq 'input') {
 8017: 	if ($env{'form.inhibitmenu'}) {
 8018: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8019: 	} else {
 8020: 	    return
 8021: 	}
 8022:     }
 8023:     if ($env{'form.inhibitmenu'}) {
 8024: 	if (ref($arg)) {
 8025: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8026: 	} elsif ($arg eq '') {
 8027: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8028: 	} else {
 8029: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8030: 	}
 8031:     }
 8032:     if (!ref($arg)) {
 8033: 	return $arg;
 8034:     }
 8035: }
 8036: 
 8037: ###############################################
 8038: 
 8039: =pod
 8040: 
 8041: =back
 8042: 
 8043: =head1 User Information Routines
 8044: 
 8045: =over 4
 8046: 
 8047: =item * &get_users_function()
 8048: 
 8049: Used by &bodytag to determine the current users primary role.
 8050: Returns either 'student','coordinator','admin', or 'author'.
 8051: 
 8052: =cut
 8053: 
 8054: ###############################################
 8055: sub get_users_function {
 8056:     my $function = 'norole';
 8057:     if ($env{'request.role'}=~/^(st)/) {
 8058:         $function='student';
 8059:     }
 8060:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8061:         $function='coordinator';
 8062:     }
 8063:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8064:         $function='admin';
 8065:     }
 8066:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8067:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8068:         $function='author';
 8069:     }
 8070:     return $function;
 8071: }
 8072: 
 8073: ###############################################
 8074: 
 8075: =pod
 8076: 
 8077: =item * &show_course()
 8078: 
 8079: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8080: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8081: 
 8082: Inputs:
 8083: None
 8084: 
 8085: Outputs:
 8086: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8087: 
 8088: =cut
 8089: 
 8090: ###############################################
 8091: sub show_course {
 8092:     my $course = !$env{'user.adv'};
 8093:     if (!$env{'user.adv'}) {
 8094:         foreach my $env (keys(%env)) {
 8095:             next if ($env !~ m/^user\.priv\./);
 8096:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8097:                 $course = 0;
 8098:                 last;
 8099:             }
 8100:         }
 8101:     }
 8102:     return $course;
 8103: }
 8104: 
 8105: ###############################################
 8106: 
 8107: =pod
 8108: 
 8109: =item * &check_user_status()
 8110: 
 8111: Determines current status of supplied role for a
 8112: specific user. Roles can be active, previous or future.
 8113: 
 8114: Inputs: 
 8115: user's domain, user's username, course's domain,
 8116: course's number, optional section ID.
 8117: 
 8118: Outputs:
 8119: role status: active, previous or future. 
 8120: 
 8121: =cut
 8122: 
 8123: sub check_user_status {
 8124:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8125:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8126:     my @uroles = keys %userinfo;
 8127:     my $srchstr;
 8128:     my $active_chk = 'none';
 8129:     my $now = time;
 8130:     if (@uroles > 0) {
 8131:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8132:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8133:         } else {
 8134:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8135:         }
 8136:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8137:             my $role_end = 0;
 8138:             my $role_start = 0;
 8139:             $active_chk = 'active';
 8140:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8141:                 $role_end = $1;
 8142:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8143:                     $role_start = $1;
 8144:                 }
 8145:             }
 8146:             if ($role_start > 0) {
 8147:                 if ($now < $role_start) {
 8148:                     $active_chk = 'future';
 8149:                 }
 8150:             }
 8151:             if ($role_end > 0) {
 8152:                 if ($now > $role_end) {
 8153:                     $active_chk = 'previous';
 8154:                 }
 8155:             }
 8156:         }
 8157:     }
 8158:     return $active_chk;
 8159: }
 8160: 
 8161: ###############################################
 8162: 
 8163: =pod
 8164: 
 8165: =item * &get_sections()
 8166: 
 8167: Determines all the sections for a course including
 8168: sections with students and sections containing other roles.
 8169: Incoming parameters: 
 8170: 
 8171: 1. domain
 8172: 2. course number 
 8173: 3. reference to array containing roles for which sections should 
 8174: be gathered (optional).
 8175: 4. reference to array containing status types for which sections 
 8176: should be gathered (optional).
 8177: 
 8178: If the third argument is undefined, sections are gathered for any role. 
 8179: If the fourth argument is undefined, sections are gathered for any status.
 8180: Permissible values are 'active' or 'future' or 'previous'.
 8181:  
 8182: Returns section hash (keys are section IDs, values are
 8183: number of users in each section), subject to the
 8184: optional roles filter, optional status filter 
 8185: 
 8186: =cut
 8187: 
 8188: ###############################################
 8189: sub get_sections {
 8190:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8191:     if (!defined($cdom) || !defined($cnum)) {
 8192:         my $cid =  $env{'request.course.id'};
 8193: 
 8194: 	return if (!defined($cid));
 8195: 
 8196:         $cdom = $env{'course.'.$cid.'.domain'};
 8197:         $cnum = $env{'course.'.$cid.'.num'};
 8198:     }
 8199: 
 8200:     my %sectioncount;
 8201:     my $now = time;
 8202: 
 8203:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 8204: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8205: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8206: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8207:         my $start_index = &Apache::loncoursedata::CL_START();
 8208:         my $end_index = &Apache::loncoursedata::CL_END();
 8209:         my $status;
 8210: 	while (my ($student,$data) = each(%$classlist)) {
 8211: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8212: 				                     $data->[$status_index],
 8213:                                                      $data->[$start_index],
 8214:                                                      $data->[$end_index]);
 8215:             if ($stu_status eq 'Active') {
 8216:                 $status = 'active';
 8217:             } elsif ($end < $now) {
 8218:                 $status = 'previous';
 8219:             } elsif ($start > $now) {
 8220:                 $status = 'future';
 8221:             } 
 8222: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8223:                 if ((!defined($possible_status)) || (($status ne '') && 
 8224:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8225: 		    $sectioncount{$section}++;
 8226:                 }
 8227: 	    }
 8228: 	}
 8229:     }
 8230:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8231:     foreach my $user (sort(keys(%courseroles))) {
 8232: 	if ($user !~ /^(\w{2})/) { next; }
 8233: 	my ($role) = ($user =~ /^(\w{2})/);
 8234: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8235: 	my ($section,$status);
 8236: 	if ($role eq 'cr' &&
 8237: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8238: 	    $section=$1;
 8239: 	}
 8240: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8241: 	if (!defined($section) || $section eq '-1') { next; }
 8242:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8243:         if ($end == -1 && $start == -1) {
 8244:             next; #deleted role
 8245:         }
 8246:         if (!defined($possible_status)) { 
 8247:             $sectioncount{$section}++;
 8248:         } else {
 8249:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8250:                 $status = 'active';
 8251:             } elsif ($end < $now) {
 8252:                 $status = 'future';
 8253:             } elsif ($start > $now) {
 8254:                 $status = 'previous';
 8255:             }
 8256:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8257:                 $sectioncount{$section}++;
 8258:             }
 8259:         }
 8260:     }
 8261:     return %sectioncount;
 8262: }
 8263: 
 8264: ###############################################
 8265: 
 8266: =pod
 8267: 
 8268: =item * &get_course_users()
 8269: 
 8270: Retrieves usernames:domains for users in the specified course
 8271: with specific role(s), and access status. 
 8272: 
 8273: Incoming parameters:
 8274: 1. course domain
 8275: 2. course number
 8276: 3. access status: users must have - either active, 
 8277: previous, future, or all.
 8278: 4. reference to array of permissible roles
 8279: 5. reference to array of section restrictions (optional)
 8280: 6. reference to results object (hash of hashes).
 8281: 7. reference to optional userdata hash
 8282: 8. reference to optional statushash
 8283: 9. flag if privileged users (except those set to unhide in
 8284:    course settings) should be excluded    
 8285: Keys of top level results hash are roles.
 8286: Keys of inner hashes are username:domain, with 
 8287: values set to access type.
 8288: Optional userdata hash returns an array with arguments in the 
 8289: same order as loncoursedata::get_classlist() for student data.
 8290: 
 8291: Optional statushash returns
 8292: 
 8293: Entries for end, start, section and status are blank because
 8294: of the possibility of multiple values for non-student roles.
 8295: 
 8296: =cut
 8297: 
 8298: ###############################################
 8299: 
 8300: sub get_course_users {
 8301:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8302:     my %idx = ();
 8303:     my %seclists;
 8304: 
 8305:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8306:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8307:     $idx{end} = &Apache::loncoursedata::CL_END();
 8308:     $idx{start} = &Apache::loncoursedata::CL_START();
 8309:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8310:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8311:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8312:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8313: 
 8314:     if (grep(/^st$/,@{$roles})) {
 8315:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8316:         my $now = time;
 8317:         foreach my $student (keys(%{$classlist})) {
 8318:             my $match = 0;
 8319:             my $secmatch = 0;
 8320:             my $section = $$classlist{$student}[$idx{section}];
 8321:             my $status = $$classlist{$student}[$idx{status}];
 8322:             if ($section eq '') {
 8323:                 $section = 'none';
 8324:             }
 8325:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8326:                 if (grep(/^all$/,@{$sections})) {
 8327:                     $secmatch = 1;
 8328:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8329:                     if (grep(/^none$/,@{$sections})) {
 8330:                         $secmatch = 1;
 8331:                     }
 8332:                 } else {  
 8333: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8334: 		        $secmatch = 1;
 8335:                     }
 8336: 		}
 8337:                 if (!$secmatch) {
 8338:                     next;
 8339:                 }
 8340:             }
 8341:             if (defined($$types{'active'})) {
 8342:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8343:                     push(@{$$users{st}{$student}},'active');
 8344:                     $match = 1;
 8345:                 }
 8346:             }
 8347:             if (defined($$types{'previous'})) {
 8348:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8349:                     push(@{$$users{st}{$student}},'previous');
 8350:                     $match = 1;
 8351:                 }
 8352:             }
 8353:             if (defined($$types{'future'})) {
 8354:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8355:                     push(@{$$users{st}{$student}},'future');
 8356:                     $match = 1;
 8357:                 }
 8358:             }
 8359:             if ($match) {
 8360:                 push(@{$seclists{$student}},$section);
 8361:                 if (ref($userdata) eq 'HASH') {
 8362:                     $$userdata{$student} = $$classlist{$student};
 8363:                 }
 8364:                 if (ref($statushash) eq 'HASH') {
 8365:                     $statushash->{$student}{'st'}{$section} = $status;
 8366:                 }
 8367:             }
 8368:         }
 8369:     }
 8370:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8371:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8372:         my $now = time;
 8373:         my %displaystatus = ( previous => 'Expired',
 8374:                               active   => 'Active',
 8375:                               future   => 'Future',
 8376:                             );
 8377:         my %nothide;
 8378:         if ($hidepriv) {
 8379:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8380:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8381:                 if ($user !~ /:/) {
 8382:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8383:                 } else {
 8384:                     $nothide{$user} = 1;
 8385:                 }
 8386:             }
 8387:         }
 8388:         foreach my $person (sort(keys(%coursepersonnel))) {
 8389:             my $match = 0;
 8390:             my $secmatch = 0;
 8391:             my $status;
 8392:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8393:             $user =~ s/:$//;
 8394:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8395:             if ($end == -1 || $start == -1) {
 8396:                 next;
 8397:             }
 8398:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8399:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8400:                 my ($uname,$udom) = split(/:/,$user);
 8401:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8402:                     if (grep(/^all$/,@{$sections})) {
 8403:                         $secmatch = 1;
 8404:                     } elsif ($usec eq '') {
 8405:                         if (grep(/^none$/,@{$sections})) {
 8406:                             $secmatch = 1;
 8407:                         }
 8408:                     } else {
 8409:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8410:                             $secmatch = 1;
 8411:                         }
 8412:                     }
 8413:                     if (!$secmatch) {
 8414:                         next;
 8415:                     }
 8416:                 }
 8417:                 if ($usec eq '') {
 8418:                     $usec = 'none';
 8419:                 }
 8420:                 if ($uname ne '' && $udom ne '') {
 8421:                     if ($hidepriv) {
 8422:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 8423:                             (!$nothide{$uname.':'.$udom})) {
 8424:                             next;
 8425:                         }
 8426:                     }
 8427:                     if ($end > 0 && $end < $now) {
 8428:                         $status = 'previous';
 8429:                     } elsif ($start > $now) {
 8430:                         $status = 'future';
 8431:                     } else {
 8432:                         $status = 'active';
 8433:                     }
 8434:                     foreach my $type (keys(%{$types})) { 
 8435:                         if ($status eq $type) {
 8436:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8437:                                 push(@{$$users{$role}{$user}},$type);
 8438:                             }
 8439:                             $match = 1;
 8440:                         }
 8441:                     }
 8442:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8443:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8444: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8445:                         }
 8446:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8447:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8448:                         }
 8449:                         if (ref($statushash) eq 'HASH') {
 8450:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8451:                         }
 8452:                     }
 8453:                 }
 8454:             }
 8455:         }
 8456:         if (grep(/^ow$/,@{$roles})) {
 8457:             if ((defined($cdom)) && (defined($cnum))) {
 8458:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8459:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8460:                     my $owner = $csettings{'internal.courseowner'};
 8461:                     next if ($owner eq '');
 8462:                     my ($ownername,$ownerdom);
 8463:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8464:                         $ownername = $1;
 8465:                         $ownerdom = $2;
 8466:                     } else {
 8467:                         $ownername = $owner;
 8468:                         $ownerdom = $cdom;
 8469:                         $owner = $ownername.':'.$ownerdom;
 8470:                     }
 8471:                     @{$$users{'ow'}{$owner}} = 'any';
 8472:                     if (defined($userdata) && 
 8473: 			!exists($$userdata{$owner})) {
 8474: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8475:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8476:                             push(@{$seclists{$owner}},'none');
 8477:                         }
 8478:                         if (ref($statushash) eq 'HASH') {
 8479:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8480:                         }
 8481: 		    }
 8482:                 }
 8483:             }
 8484:         }
 8485:         foreach my $user (keys(%seclists)) {
 8486:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8487:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8488:         }
 8489:     }
 8490:     return;
 8491: }
 8492: 
 8493: sub get_user_info {
 8494:     my ($udom,$uname,$idx,$userdata) = @_;
 8495:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8496: 	&plainname($uname,$udom,'lastname');
 8497:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8498:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8499:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8500:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8501:     return;
 8502: }
 8503: 
 8504: ###############################################
 8505: 
 8506: =pod
 8507: 
 8508: =item * &get_user_quota()
 8509: 
 8510: Retrieves quota assigned for storage of portfolio files for a user  
 8511: 
 8512: Incoming parameters:
 8513: 1. user's username
 8514: 2. user's domain
 8515: 
 8516: Returns:
 8517: 1. Disk quota (in Mb) assigned to student.
 8518: 2. (Optional) Type of setting: custom or default
 8519:    (individually assigned or default for user's 
 8520:    institutional status).
 8521: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8522:    or student - types as defined in localenroll::inst_usertypes 
 8523:    for user's domain, which determines default quota for user.
 8524: 4. (Optional) - Default quota which would apply to the user.
 8525: 
 8526: If a value has been stored in the user's environment, 
 8527: it will return that, otherwise it returns the maximal default
 8528: defined for the user's instituional status(es) in the domain.
 8529: 
 8530: =cut
 8531: 
 8532: ###############################################
 8533: 
 8534: 
 8535: sub get_user_quota {
 8536:     my ($uname,$udom) = @_;
 8537:     my ($quota,$quotatype,$settingstatus,$defquota);
 8538:     if (!defined($udom)) {
 8539:         $udom = $env{'user.domain'};
 8540:     }
 8541:     if (!defined($uname)) {
 8542:         $uname = $env{'user.name'};
 8543:     }
 8544:     if (($udom eq '' || $uname eq '') ||
 8545:         ($udom eq 'public') && ($uname eq 'public')) {
 8546:         $quota = 0;
 8547:         $quotatype = 'default';
 8548:         $defquota = 0; 
 8549:     } else {
 8550:         my $inststatus;
 8551:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8552:             $quota = $env{'environment.portfolioquota'};
 8553:             $inststatus = $env{'environment.inststatus'};
 8554:         } else {
 8555:             my %userenv = 
 8556:                 &Apache::lonnet::get('environment',['portfolioquota',
 8557:                                      'inststatus'],$udom,$uname);
 8558:             my ($tmp) = keys(%userenv);
 8559:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8560:                 $quota = $userenv{'portfolioquota'};
 8561:                 $inststatus = $userenv{'inststatus'};
 8562:             } else {
 8563:                 undef(%userenv);
 8564:             }
 8565:         }
 8566:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 8567:         if ($quota eq '') {
 8568:             $quota = $defquota;
 8569:             $quotatype = 'default';
 8570:         } else {
 8571:             $quotatype = 'custom';
 8572:         }
 8573:     }
 8574:     if (wantarray) {
 8575:         return ($quota,$quotatype,$settingstatus,$defquota);
 8576:     } else {
 8577:         return $quota;
 8578:     }
 8579: }
 8580: 
 8581: ###############################################
 8582: 
 8583: =pod
 8584: 
 8585: =item * &default_quota()
 8586: 
 8587: Retrieves default quota assigned for storage of user portfolio files,
 8588: given an (optional) user's institutional status.
 8589: 
 8590: Incoming parameters:
 8591: 1. domain
 8592: 2. (Optional) institutional status(es).  This is a : separated list of 
 8593:    status types (e.g., faculty, staff, student etc.)
 8594:    which apply to the user for whom the default is being retrieved.
 8595:    If the institutional status string in undefined, the domain
 8596:    default quota will be returned. 
 8597: 
 8598: Returns:
 8599: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8600: 2. (Optional) institutional type which determined the value of the
 8601:    default quota.
 8602: 
 8603: If a value has been stored in the domain's configuration db,
 8604: it will return that, otherwise it returns 20 (for backwards 
 8605: compatibility with domains which have not set up a configuration
 8606: db file; the original statically defined portfolio quota was 20 Mb). 
 8607: 
 8608: If the user's status includes multiple types (e.g., staff and student),
 8609: the largest default quota which applies to the user determines the
 8610: default quota returned.
 8611: 
 8612: =back
 8613: 
 8614: =cut
 8615: 
 8616: ###############################################
 8617: 
 8618: 
 8619: sub default_quota {
 8620:     my ($udom,$inststatus) = @_;
 8621:     my ($defquota,$settingstatus);
 8622:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8623:                                             ['quotas'],$udom);
 8624:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8625:         if ($inststatus ne '') {
 8626:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8627:             foreach my $item (@statuses) {
 8628:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8629:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 8630:                         if ($defquota eq '') {
 8631:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8632:                             $settingstatus = $item;
 8633:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 8634:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8635:                             $settingstatus = $item;
 8636:                         }
 8637:                     }
 8638:                 } else {
 8639:                     if ($quotahash{'quotas'}{$item} ne '') {
 8640:                         if ($defquota eq '') {
 8641:                             $defquota = $quotahash{'quotas'}{$item};
 8642:                             $settingstatus = $item;
 8643:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8644:                             $defquota = $quotahash{'quotas'}{$item};
 8645:                             $settingstatus = $item;
 8646:                         }
 8647:                     }
 8648:                 }
 8649:             }
 8650:         }
 8651:         if ($defquota eq '') {
 8652:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8653:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 8654:             } else {
 8655:                 $defquota = $quotahash{'quotas'}{'default'};
 8656:             }
 8657:             $settingstatus = 'default';
 8658:         }
 8659:     } else {
 8660:         $settingstatus = 'default';
 8661:         $defquota = 20;
 8662:     }
 8663:     if (wantarray) {
 8664:         return ($defquota,$settingstatus);
 8665:     } else {
 8666:         return $defquota;
 8667:     }
 8668: }
 8669: 
 8670: sub get_secgrprole_info {
 8671:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8672:     my %sections_count = &get_sections($cdom,$cnum);
 8673:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8674:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8675:     my @groups = sort(keys(%curr_groups));
 8676:     my $allroles = [];
 8677:     my $rolehash;
 8678:     my $accesshash = {
 8679:                      active => 'Currently has access',
 8680:                      future => 'Will have future access',
 8681:                      previous => 'Previously had access',
 8682:                   };
 8683:     if ($needroles) {
 8684:         $rolehash = {'all' => 'all'};
 8685:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8686: 	if (&Apache::lonnet::error(%user_roles)) {
 8687: 	    undef(%user_roles);
 8688: 	}
 8689:         foreach my $item (keys(%user_roles)) {
 8690:             my ($role)=split(/\:/,$item,2);
 8691:             if ($role eq 'cr') { next; }
 8692:             if ($role =~ /^cr/) {
 8693:                 $$rolehash{$role} = (split('/',$role))[3];
 8694:             } else {
 8695:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8696:             }
 8697:         }
 8698:         foreach my $key (sort(keys(%{$rolehash}))) {
 8699:             push(@{$allroles},$key);
 8700:         }
 8701:         push (@{$allroles},'st');
 8702:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8703:     }
 8704:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8705: }
 8706: 
 8707: sub user_picker {
 8708:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8709:     my $currdom = $dom;
 8710:     my %curr_selected = (
 8711:                         srchin => 'dom',
 8712:                         srchby => 'lastname',
 8713:                       );
 8714:     my $srchterm;
 8715:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8716:         if ($srch->{'srchby'} ne '') {
 8717:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8718:         }
 8719:         if ($srch->{'srchin'} ne '') {
 8720:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8721:         }
 8722:         if ($srch->{'srchtype'} ne '') {
 8723:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8724:         }
 8725:         if ($srch->{'srchdomain'} ne '') {
 8726:             $currdom = $srch->{'srchdomain'};
 8727:         }
 8728:         $srchterm = $srch->{'srchterm'};
 8729:     }
 8730:     my %lt=&Apache::lonlocal::texthash(
 8731:                     'usr'       => 'Search criteria',
 8732:                     'doma'      => 'Domain/institution to search',
 8733:                     'uname'     => 'username',
 8734:                     'lastname'  => 'last name',
 8735:                     'lastfirst' => 'last name, first name',
 8736:                     'crs'       => 'in this course',
 8737:                     'dom'       => 'in selected LON-CAPA domain', 
 8738:                     'alc'       => 'all LON-CAPA',
 8739:                     'instd'     => 'in institutional directory for selected domain',
 8740:                     'exact'     => 'is',
 8741:                     'contains'  => 'contains',
 8742:                     'begins'    => 'begins with',
 8743:                     'youm'      => "You must include some text to search for.",
 8744:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 8745:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 8746:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 8747:                     'ymcd'      => "You must choose a domain when using a domain search.",
 8748:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 8749:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 8750:                      'thfo'     => "The following need to be corrected before the search can be run:",
 8751:                                        );
 8752:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 8753:     my $srchinsel = ' <select name="srchin">';
 8754: 
 8755:     my @srchins = ('crs','dom','alc','instd');
 8756: 
 8757:     foreach my $option (@srchins) {
 8758:         # FIXME 'alc' option unavailable until 
 8759:         #       loncreateuser::print_user_query_page()
 8760:         #       has been completed.
 8761:         next if ($option eq 'alc');
 8762:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 8763:         next if ($option eq 'crs' && !$env{'request.course.id'});
 8764:         if ($curr_selected{'srchin'} eq $option) {
 8765:             $srchinsel .= ' 
 8766:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8767:         } else {
 8768:             $srchinsel .= '
 8769:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8770:         }
 8771:     }
 8772:     $srchinsel .= "\n  </select>\n";
 8773: 
 8774:     my $srchbysel =  ' <select name="srchby">';
 8775:     foreach my $option ('lastname','lastfirst','uname') {
 8776:         if ($curr_selected{'srchby'} eq $option) {
 8777:             $srchbysel .= '
 8778:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8779:         } else {
 8780:             $srchbysel .= '
 8781:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8782:          }
 8783:     }
 8784:     $srchbysel .= "\n  </select>\n";
 8785: 
 8786:     my $srchtypesel = ' <select name="srchtype">';
 8787:     foreach my $option ('begins','contains','exact') {
 8788:         if ($curr_selected{'srchtype'} eq $option) {
 8789:             $srchtypesel .= '
 8790:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8791:         } else {
 8792:             $srchtypesel .= '
 8793:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8794:         }
 8795:     }
 8796:     $srchtypesel .= "\n  </select>\n";
 8797: 
 8798:     my ($newuserscript,$new_user_create);
 8799:     my $context_dom = $env{'request.role.domain'};
 8800:     if ($context eq 'requestcrs') {
 8801:         if ($env{'form.coursedom'} ne '') { 
 8802:             $context_dom = $env{'form.coursedom'};
 8803:         }
 8804:     }
 8805:     if ($forcenewuser) {
 8806:         if (ref($srch) eq 'HASH') {
 8807:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 8808:                 if ($cancreate) {
 8809:                     $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>';
 8810:                 } else {
 8811:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 8812:                     my %usertypetext = (
 8813:                         official   => 'institutional',
 8814:                         unofficial => 'non-institutional',
 8815:                     );
 8816:                     $new_user_create = '<p class="LC_warning">'
 8817:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8818:                                       .' '
 8819:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8820:                                           ,'<a href="'.$helplink.'">','</a>')
 8821:                                       .'</p><br />';
 8822:                 }
 8823:             }
 8824:         }
 8825: 
 8826:         $newuserscript = <<"ENDSCRIPT";
 8827: 
 8828: function setSearch(createnew,callingForm) {
 8829:     if (createnew == 1) {
 8830:         for (var i=0; i<callingForm.srchby.length; i++) {
 8831:             if (callingForm.srchby.options[i].value == 'uname') {
 8832:                 callingForm.srchby.selectedIndex = i;
 8833:             }
 8834:         }
 8835:         for (var i=0; i<callingForm.srchin.length; i++) {
 8836:             if ( callingForm.srchin.options[i].value == 'dom') {
 8837: 		callingForm.srchin.selectedIndex = i;
 8838:             }
 8839:         }
 8840:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8841:             if (callingForm.srchtype.options[i].value == 'exact') {
 8842:                 callingForm.srchtype.selectedIndex = i;
 8843:             }
 8844:         }
 8845:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8846:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8847:                 callingForm.srchdomain.selectedIndex = i;
 8848:             }
 8849:         }
 8850:     }
 8851: }
 8852: ENDSCRIPT
 8853: 
 8854:     }
 8855: 
 8856:     my $output = <<"END_BLOCK";
 8857: <script type="text/javascript">
 8858: // <![CDATA[
 8859: function validateEntry(callingForm) {
 8860: 
 8861:     var checkok = 1;
 8862:     var srchin;
 8863:     for (var i=0; i<callingForm.srchin.length; i++) {
 8864: 	if ( callingForm.srchin[i].checked ) {
 8865: 	    srchin = callingForm.srchin[i].value;
 8866: 	}
 8867:     }
 8868: 
 8869:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8870:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8871:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8872:     var srchterm =  callingForm.srchterm.value;
 8873:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8874:     var msg = "";
 8875: 
 8876:     if (srchterm == "") {
 8877:         checkok = 0;
 8878:         msg += "$lt{'youm'}\\n";
 8879:     }
 8880: 
 8881:     if (srchtype== 'begins') {
 8882:         if (srchterm.length < 2) {
 8883:             checkok = 0;
 8884:             msg += "$lt{'thte'}\\n";
 8885:         }
 8886:     }
 8887: 
 8888:     if (srchtype== 'contains') {
 8889:         if (srchterm.length < 3) {
 8890:             checkok = 0;
 8891:             msg += "$lt{'thet'}\\n";
 8892:         }
 8893:     }
 8894:     if (srchin == 'instd') {
 8895:         if (srchdomain == '') {
 8896:             checkok = 0;
 8897:             msg += "$lt{'yomc'}\\n";
 8898:         }
 8899:     }
 8900:     if (srchin == 'dom') {
 8901:         if (srchdomain == '') {
 8902:             checkok = 0;
 8903:             msg += "$lt{'ymcd'}\\n";
 8904:         }
 8905:     }
 8906:     if (srchby == 'lastfirst') {
 8907:         if (srchterm.indexOf(",") == -1) {
 8908:             checkok = 0;
 8909:             msg += "$lt{'whus'}\\n";
 8910:         }
 8911:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8912:             checkok = 0;
 8913:             msg += "$lt{'whse'}\\n";
 8914:         }
 8915:     }
 8916:     if (checkok == 0) {
 8917:         alert("$lt{'thfo'}\\n"+msg);
 8918:         return;
 8919:     }
 8920:     if (checkok == 1) {
 8921:         callingForm.submit();
 8922:     }
 8923: }
 8924: 
 8925: $newuserscript
 8926: 
 8927: // ]]>
 8928: </script>
 8929: 
 8930: $new_user_create
 8931: 
 8932: END_BLOCK
 8933: 
 8934:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8935:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8936:                $domform.
 8937:                &Apache::lonhtmlcommon::row_closure().
 8938:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8939:                $srchbysel.
 8940:                $srchtypesel. 
 8941:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8942:                $srchinsel.
 8943:                &Apache::lonhtmlcommon::row_closure(1). 
 8944:                &Apache::lonhtmlcommon::end_pick_box().
 8945:                '<br />';
 8946:     return $output;
 8947: }
 8948: 
 8949: sub user_rule_check {
 8950:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8951:     my $response;
 8952:     if (ref($usershash) eq 'HASH') {
 8953:         foreach my $user (keys(%{$usershash})) {
 8954:             my ($uname,$udom) = split(/:/,$user);
 8955:             next if ($udom eq '' || $uname eq '');
 8956:             my ($id,$newuser);
 8957:             if (ref($usershash->{$user}) eq 'HASH') {
 8958:                 $newuser = $usershash->{$user}->{'newuser'};
 8959:                 $id = $usershash->{$user}->{'id'};
 8960:             }
 8961:             my $inst_response;
 8962:             if (ref($checks) eq 'HASH') {
 8963:                 if (defined($checks->{'username'})) {
 8964:                     ($inst_response,%{$inst_results->{$user}}) = 
 8965:                         &Apache::lonnet::get_instuser($udom,$uname);
 8966:                 } elsif (defined($checks->{'id'})) {
 8967:                     ($inst_response,%{$inst_results->{$user}}) =
 8968:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8969:                 }
 8970:             } else {
 8971:                 ($inst_response,%{$inst_results->{$user}}) =
 8972:                     &Apache::lonnet::get_instuser($udom,$uname);
 8973:                 return;
 8974:             }
 8975:             if (!$got_rules->{$udom}) {
 8976:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8977:                                                   ['usercreation'],$udom);
 8978:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8979:                     foreach my $item ('username','id') {
 8980:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8981:                             $$curr_rules{$udom}{$item} = 
 8982:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8983:                         }
 8984:                     }
 8985:                 }
 8986:                 $got_rules->{$udom} = 1;  
 8987:             }
 8988:             foreach my $item (keys(%{$checks})) {
 8989:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8990:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8991:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8992:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8993:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8994:                                 if ($rule_check{$rule}) {
 8995:                                     $$rulematch{$user}{$item} = $rule;
 8996:                                     if ($inst_response eq 'ok') {
 8997:                                         if (ref($inst_results) eq 'HASH') {
 8998:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8999:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9000:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9001:                                                 }
 9002:                                             }
 9003:                                         }
 9004:                                     }
 9005:                                     last;
 9006:                                 }
 9007:                             }
 9008:                         }
 9009:                     }
 9010:                 }
 9011:             }
 9012:         }
 9013:     }
 9014:     return;
 9015: }
 9016: 
 9017: sub user_rule_formats {
 9018:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9019:     my %text = ( 
 9020:                  'username' => 'Usernames',
 9021:                  'id'       => 'IDs',
 9022:                );
 9023:     my $output;
 9024:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9025:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9026:         if (@{$ruleorder} > 0) {
 9027:             $output = '<br />'.
 9028:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9029:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9030:                       ' <ul>';
 9031:             foreach my $rule (@{$ruleorder}) {
 9032:                 if (ref($curr_rules) eq 'ARRAY') {
 9033:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9034:                         if (ref($rules->{$rule}) eq 'HASH') {
 9035:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9036:                                         $rules->{$rule}{'desc'}.'</li>';
 9037:                         }
 9038:                     }
 9039:                 }
 9040:             }
 9041:             $output .= '</ul>';
 9042:         }
 9043:     }
 9044:     return $output;
 9045: }
 9046: 
 9047: sub instrule_disallow_msg {
 9048:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9049:     my $response;
 9050:     my %text = (
 9051:                   item   => 'username',
 9052:                   items  => 'usernames',
 9053:                   match  => 'matches',
 9054:                   do     => 'does',
 9055:                   action => 'a username',
 9056:                   one    => 'one',
 9057:                );
 9058:     if ($count > 1) {
 9059:         $text{'item'} = 'usernames';
 9060:         $text{'match'} ='match';
 9061:         $text{'do'} = 'do';
 9062:         $text{'action'} = 'usernames',
 9063:         $text{'one'} = 'ones';
 9064:     }
 9065:     if ($checkitem eq 'id') {
 9066:         $text{'items'} = 'IDs';
 9067:         $text{'item'} = 'ID';
 9068:         $text{'action'} = 'an ID';
 9069:         if ($count > 1) {
 9070:             $text{'item'} = 'IDs';
 9071:             $text{'action'} = 'IDs';
 9072:         }
 9073:     }
 9074:     $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 />';
 9075:     if ($mode eq 'upload') {
 9076:         if ($checkitem eq 'username') {
 9077:             $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'}.");
 9078:         } elsif ($checkitem eq 'id') {
 9079:             $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.");
 9080:         }
 9081:     } elsif ($mode eq 'selfcreate') {
 9082:         if ($checkitem eq 'id') {
 9083:             $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.");
 9084:         }
 9085:     } else {
 9086:         if ($checkitem eq 'username') {
 9087:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9088:         } elsif ($checkitem eq 'id') {
 9089:             $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.");
 9090:         }
 9091:     }
 9092:     return $response;
 9093: }
 9094: 
 9095: sub personal_data_fieldtitles {
 9096:     my %fieldtitles = &Apache::lonlocal::texthash (
 9097:                         id => 'Student/Employee ID',
 9098:                         permanentemail => 'E-mail address',
 9099:                         lastname => 'Last Name',
 9100:                         firstname => 'First Name',
 9101:                         middlename => 'Middle Name',
 9102:                         generation => 'Generation',
 9103:                         gen => 'Generation',
 9104:                         inststatus => 'Affiliation',
 9105:                    );
 9106:     return %fieldtitles;
 9107: }
 9108: 
 9109: sub sorted_inst_types {
 9110:     my ($dom) = @_;
 9111:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9112:     my $othertitle = &mt('All users');
 9113:     if ($env{'request.course.id'}) {
 9114:         $othertitle  = &mt('Any users');
 9115:     }
 9116:     my @types;
 9117:     if (ref($order) eq 'ARRAY') {
 9118:         @types = @{$order};
 9119:     }
 9120:     if (@types == 0) {
 9121:         if (ref($usertypes) eq 'HASH') {
 9122:             @types = sort(keys(%{$usertypes}));
 9123:         }
 9124:     }
 9125:     if (keys(%{$usertypes}) > 0) {
 9126:         $othertitle = &mt('Other users');
 9127:     }
 9128:     return ($othertitle,$usertypes,\@types);
 9129: }
 9130: 
 9131: sub get_institutional_codes {
 9132:     my ($settings,$allcourses,$LC_code) = @_;
 9133: # Get complete list of course sections to update
 9134:     my @currsections = ();
 9135:     my @currxlists = ();
 9136:     my $coursecode = $$settings{'internal.coursecode'};
 9137: 
 9138:     if ($$settings{'internal.sectionnums'} ne '') {
 9139:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9140:     }
 9141: 
 9142:     if ($$settings{'internal.crosslistings'} ne '') {
 9143:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9144:     }
 9145: 
 9146:     if (@currxlists > 0) {
 9147:         foreach (@currxlists) {
 9148:             if (m/^([^:]+):(\w*)$/) {
 9149:                 unless (grep/^$1$/,@{$allcourses}) {
 9150:                     push @{$allcourses},$1;
 9151:                     $$LC_code{$1} = $2;
 9152:                 }
 9153:             }
 9154:         }
 9155:     }
 9156:  
 9157:     if (@currsections > 0) {
 9158:         foreach (@currsections) {
 9159:             if (m/^(\w+):(\w*)$/) {
 9160:                 my $sec = $coursecode.$1;
 9161:                 my $lc_sec = $2;
 9162:                 unless (grep/^$sec$/,@{$allcourses}) {
 9163:                     push @{$allcourses},$sec;
 9164:                     $$LC_code{$sec} = $lc_sec;
 9165:                 }
 9166:             }
 9167:         }
 9168:     }
 9169:     return;
 9170: }
 9171: 
 9172: sub get_standard_codeitems {
 9173:     return ('Year','Semester','Department','Number','Section');
 9174: }
 9175: 
 9176: =pod
 9177: 
 9178: =head1 Slot Helpers
 9179: 
 9180: =over 4
 9181: 
 9182: =item * sorted_slots()
 9183: 
 9184: Sorts an array of slot names in order of an optional sort key,
 9185: default sort is by slot start time (earliest first). 
 9186: 
 9187: Inputs:
 9188: 
 9189: =over 4
 9190: 
 9191: slotsarr  - Reference to array of unsorted slot names.
 9192: 
 9193: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9194: 
 9195: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9196: 
 9197: =back
 9198: 
 9199: Returns:
 9200: 
 9201: =over 4
 9202: 
 9203: sorted   - An array of slot names sorted by a specified sort key 
 9204:            (default sort key is start time of the slot).
 9205: 
 9206: =back
 9207: 
 9208: =cut
 9209: 
 9210: 
 9211: sub sorted_slots {
 9212:     my ($slotsarr,$slots,$sortkey) = @_;
 9213:     if ($sortkey eq '') {
 9214:         $sortkey = 'starttime';
 9215:     }
 9216:     my @sorted;
 9217:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9218:         @sorted =
 9219:             sort {
 9220:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9221:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9222:                      }
 9223:                      if (ref($slots->{$a})) { return -1;}
 9224:                      if (ref($slots->{$b})) { return 1;}
 9225:                      return 0;
 9226:                  } @{$slotsarr};
 9227:     }
 9228:     return @sorted;
 9229: }
 9230: 
 9231: =pod
 9232: 
 9233: =item * get_future_slots()
 9234: 
 9235: Inputs:
 9236: 
 9237: =over 4
 9238: 
 9239: cnum - course number
 9240: 
 9241: cdom - course domain
 9242: 
 9243: now - current UNIX time
 9244: 
 9245: symb - optional symb
 9246: 
 9247: =back
 9248: 
 9249: Returns:
 9250: 
 9251: =over 4
 9252: 
 9253: sorted_reservable - ref to array of student_schedulable slots currently 
 9254:                     reservable, ordered by end date of reservation period.
 9255: 
 9256: reservable_now - ref to hash of student_schedulable slots currently
 9257:                  reservable.
 9258: 
 9259:     Keys in inner hash are:
 9260:     (a) symb: either blank or symb to which slot use is restricted.
 9261:     (b) endreserve: end date of reservation period. 
 9262: 
 9263: sorted_future - ref to array of student_schedulable slots reservable in
 9264:                 the future, ordered by start date of reservation period.
 9265: 
 9266: future_reservable - ref to hash of student_schedulable slots reservable
 9267:                     in the future.
 9268: 
 9269:     Keys in inner hash are:
 9270:     (a) symb: either blank or symb to which slot use is restricted.
 9271:     (b) startreserve:  start date of reservation period.
 9272: 
 9273: =back
 9274: 
 9275: =cut
 9276: 
 9277: sub get_future_slots {
 9278:     my ($cnum,$cdom,$now,$symb) = @_;
 9279:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9280:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9281:     foreach my $slot (keys(%slots)) {
 9282:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9283:         if ($symb) {
 9284:             next if (($slots{$slot}->{'symb'} ne '') && 
 9285:                      ($slots{$slot}->{'symb'} ne $symb));
 9286:         }
 9287:         if (($slots{$slot}->{'starttime'} > $now) &&
 9288:             ($slots{$slot}->{'endtime'} > $now)) {
 9289:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9290:                 my $userallowed = 0;
 9291:                 if ($slots{$slot}->{'allowedsections'}) {
 9292:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9293:                     if (!defined($env{'request.role.sec'})
 9294:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9295:                         $userallowed=1;
 9296:                     } else {
 9297:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9298:                             $userallowed=1;
 9299:                         }
 9300:                     }
 9301:                     unless ($userallowed) {
 9302:                         if (defined($env{'request.course.groups'})) {
 9303:                             my @groups = split(/:/,$env{'request.course.groups'});
 9304:                             foreach my $group (@groups) {
 9305:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9306:                                     $userallowed=1;
 9307:                                     last;
 9308:                                 }
 9309:                             }
 9310:                         }
 9311:                     }
 9312:                 }
 9313:                 if ($slots{$slot}->{'allowedusers'}) {
 9314:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9315:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9316:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9317:                         $userallowed = 1;
 9318:                     }
 9319:                 }
 9320:                 next unless($userallowed);
 9321:             }
 9322:             my $startreserve = $slots{$slot}->{'startreserve'};
 9323:             my $endreserve = $slots{$slot}->{'endreserve'};
 9324:             my $symb = $slots{$slot}->{'symb'};
 9325:             if (($startreserve < $now) &&
 9326:                 (!$endreserve || $endreserve > $now)) {
 9327:                 my $lastres = $endreserve;
 9328:                 if (!$lastres) {
 9329:                     $lastres = $slots{$slot}->{'starttime'};
 9330:                 }
 9331:                 $reservable_now{$slot} = {
 9332:                                            symb       => $symb,
 9333:                                            endreserve => $lastres
 9334:                                          };
 9335:             } elsif (($startreserve > $now) &&
 9336:                      (!$endreserve || $endreserve > $startreserve)) {
 9337:                 $future_reservable{$slot} = {
 9338:                                               symb         => $symb,
 9339:                                               startreserve => $startreserve
 9340:                                             };
 9341:             }
 9342:         }
 9343:     }
 9344:     my @unsorted_reservable = keys(%reservable_now);
 9345:     if (@unsorted_reservable > 0) {
 9346:         @sorted_reservable = 
 9347:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9348:     }
 9349:     my @unsorted_future = keys(%future_reservable);
 9350:     if (@unsorted_future > 0) {
 9351:         @sorted_future =
 9352:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9353:     }
 9354:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9355: }
 9356: 
 9357: =pod
 9358: 
 9359: =back
 9360: 
 9361: =head1 HTTP Helpers
 9362: 
 9363: =over 4
 9364: 
 9365: =item * &get_unprocessed_cgi($query,$possible_names)
 9366: 
 9367: Modify the %env hash to contain unprocessed CGI form parameters held in
 9368: $query.  The parameters listed in $possible_names (an array reference),
 9369: will be set in $env{'form.name'} if they do not already exist.
 9370: 
 9371: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9372: $possible_names is an ref to an array of form element names.  As an example:
 9373: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9374: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9375: 
 9376: =cut
 9377: 
 9378: sub get_unprocessed_cgi {
 9379:   my ($query,$possible_names)= @_;
 9380:   # $Apache::lonxml::debug=1;
 9381:   foreach my $pair (split(/&/,$query)) {
 9382:     my ($name, $value) = split(/=/,$pair);
 9383:     $name = &unescape($name);
 9384:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9385:       $value =~ tr/+/ /;
 9386:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9387:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9388:     }
 9389:   }
 9390: }
 9391: 
 9392: =pod
 9393: 
 9394: =item * &cacheheader() 
 9395: 
 9396: returns cache-controlling header code
 9397: 
 9398: =cut
 9399: 
 9400: sub cacheheader {
 9401:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9402:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9403:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9404:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9405:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9406:     return $output;
 9407: }
 9408: 
 9409: =pod
 9410: 
 9411: =item * &no_cache($r) 
 9412: 
 9413: specifies header code to not have cache
 9414: 
 9415: =cut
 9416: 
 9417: sub no_cache {
 9418:     my ($r) = @_;
 9419:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9420: 	$env{'request.method'} ne 'GET') { return ''; }
 9421:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9422:     $r->no_cache(1);
 9423:     $r->header_out("Expires" => $date);
 9424:     $r->header_out("Pragma" => "no-cache");
 9425: }
 9426: 
 9427: sub content_type {
 9428:     my ($r,$type,$charset) = @_;
 9429:     if ($r) {
 9430: 	#  Note that printout.pl calls this with undef for $r.
 9431: 	&no_cache($r);
 9432:     }
 9433:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9434:     unless ($charset) {
 9435: 	$charset=&Apache::lonlocal::current_encoding;
 9436:     }
 9437:     if ($charset) { $type.='; charset='.$charset; }
 9438:     if ($r) {
 9439: 	$r->content_type($type);
 9440:     } else {
 9441: 	print("Content-type: $type\n\n");
 9442:     }
 9443: }
 9444: 
 9445: =pod
 9446: 
 9447: =item * &add_to_env($name,$value) 
 9448: 
 9449: adds $name to the %env hash with value
 9450: $value, if $name already exists, the entry is converted to an array
 9451: reference and $value is added to the array.
 9452: 
 9453: =cut
 9454: 
 9455: sub add_to_env {
 9456:   my ($name,$value)=@_;
 9457:   if (defined($env{$name})) {
 9458:     if (ref($env{$name})) {
 9459:       #already have multiple values
 9460:       push(@{ $env{$name} },$value);
 9461:     } else {
 9462:       #first time seeing multiple values, convert hash entry to an arrayref
 9463:       my $first=$env{$name};
 9464:       undef($env{$name});
 9465:       push(@{ $env{$name} },$first,$value);
 9466:     }
 9467:   } else {
 9468:     $env{$name}=$value;
 9469:   }
 9470: }
 9471: 
 9472: =pod
 9473: 
 9474: =item * &get_env_multiple($name) 
 9475: 
 9476: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9477: values may be defined and end up as an array ref.
 9478: 
 9479: returns an array of values
 9480: 
 9481: =cut
 9482: 
 9483: sub get_env_multiple {
 9484:     my ($name) = @_;
 9485:     my @values;
 9486:     if (defined($env{$name})) {
 9487:         # exists is it an array
 9488:         if (ref($env{$name})) {
 9489:             @values=@{ $env{$name} };
 9490:         } else {
 9491:             $values[0]=$env{$name};
 9492:         }
 9493:     }
 9494:     return(@values);
 9495: }
 9496: 
 9497: sub ask_for_embedded_content {
 9498:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9499:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9500:         %currsubfile,%unused,$rem);
 9501:     my $counter = 0;
 9502:     my $numnew = 0;
 9503:     my $numremref = 0;
 9504:     my $numinvalid = 0;
 9505:     my $numpathchg = 0;
 9506:     my $numexisting = 0;
 9507:     my $numunused = 0;
 9508:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9509:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9510:     my $heading = &mt('Upload embedded files');
 9511:     my $buttontext = &mt('Upload');
 9512: 
 9513:     my $navmap;
 9514:     if ($env{'request.course.id'}) {
 9515:         $navmap = Apache::lonnavmaps::navmap->new();
 9516:     }
 9517:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9518:         my $current_path='/';
 9519:         if ($env{'form.currentpath'}) {
 9520:             $current_path = $env{'form.currentpath'};
 9521:         }
 9522:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9523:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9524:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 9525:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9526:         } else {
 9527:             $udom = $env{'user.domain'};
 9528:             $uname = $env{'user.name'};
 9529:             $url = '/userfiles/portfolio';
 9530:         }
 9531:         $toplevel = $url.'/';
 9532:         $url .= $current_path;
 9533:         $getpropath = 1;
 9534:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9535:              ($actionurl eq '/adm/imsimport')) { 
 9536:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9537:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9538:         $toplevel = $url;
 9539:         if ($rest ne '') {
 9540:             $url .= $rest;
 9541:         }
 9542:     } elsif ($actionurl eq '/adm/coursedocs') {
 9543:         if (ref($args) eq 'HASH') {
 9544:             $url = $args->{'docs_url'};
 9545:             $toplevel = $url;
 9546:             if ($args->{'context'} eq 'paste') {
 9547:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9548:                 ($path) = 
 9549:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9550:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9551:                 $fileloc =~ s{^/}{};
 9552:             }
 9553:         }
 9554:     } elsif ($actionurl eq '/adm/dependencies')  {
 9555:         if ($env{'request.course.id'} ne '') {
 9556:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9557:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
 9558:             if (ref($args) eq 'HASH') {
 9559:                 $url = $args->{'docs_url'};
 9560:                 $title = $args->{'docs_title'};
 9561:                 $toplevel = "/$url";
 9562:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9563:                 ($path) =  
 9564:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9565:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9566:                 $fileloc =~ s{^/}{};
 9567:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9568:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9569:             }
 9570:         }
 9571:     }
 9572:     my $now = time();
 9573:     foreach my $embed_file (keys(%{$allfiles})) {
 9574:         my $absolutepath;
 9575:         if ($embed_file =~ m{^\w+://}) {
 9576:             $newfiles{$embed_file} = 1;
 9577:             $mapping{$embed_file} = $embed_file;
 9578:         } else {
 9579:             if ($embed_file =~ m{^/}) {
 9580:                 $absolutepath = $embed_file;
 9581:                 $embed_file =~ s{^(/+)}{};
 9582:             }
 9583:             if ($embed_file =~ m{/}) {
 9584:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 9585:                 $path = &check_for_traversal($path,$url,$toplevel);
 9586:                 my $item = $fname;
 9587:                 if ($path ne '') {
 9588:                     $item = $path.'/'.$fname;
 9589:                     $subdependencies{$path}{$fname} = 1;
 9590:                 } else {
 9591:                     $dependencies{$item} = 1;
 9592:                 }
 9593:                 if ($absolutepath) {
 9594:                     $mapping{$item} = $absolutepath;
 9595:                 } else {
 9596:                     $mapping{$item} = $embed_file;
 9597:                 }
 9598:             } else {
 9599:                 $dependencies{$embed_file} = 1;
 9600:                 if ($absolutepath) {
 9601:                     $mapping{$embed_file} = $absolutepath;
 9602:                 } else {
 9603:                     $mapping{$embed_file} = $embed_file;
 9604:                 }
 9605:             }
 9606:         }
 9607:     }
 9608:     my $dirptr = 16384;
 9609:     foreach my $path (keys(%subdependencies)) {
 9610:         $currsubfile{$path} = {};
 9611:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9612:             my ($sublistref,$listerror) =
 9613:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9614:             if (ref($sublistref) eq 'ARRAY') {
 9615:                 foreach my $line (@{$sublistref}) {
 9616:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9617:                     $currsubfile{$path}{$file_name} = 1;
 9618:                 }
 9619:             }
 9620:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9621:             if (opendir(my $dir,$url.'/'.$path)) {
 9622:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9623:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9624:             }
 9625:         } elsif (($actionurl eq '/adm/dependencies') ||
 9626:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9627:                   ($args->{'context'} eq 'paste'))) {
 9628:             if ($env{'request.course.id'} ne '') {
 9629:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9630:                 if ($dir ne '') {
 9631:                     my ($sublistref,$listerror) =
 9632:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9633:                     if (ref($sublistref) eq 'ARRAY') {
 9634:                         foreach my $line (@{$sublistref}) {
 9635:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9636:                                 undef,$mtime)=split(/\&/,$line,12);
 9637:                             unless (($testdir&$dirptr) ||
 9638:                                     ($file_name =~ /^\.\.?$/)) {
 9639:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9640:                             }
 9641:                         }
 9642:                     }
 9643:                 }
 9644:             }
 9645:         }
 9646:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9647:             if (exists($currsubfile{$path}{$file})) {
 9648:                 my $item = $path.'/'.$file;
 9649:                 unless ($mapping{$item} eq $item) {
 9650:                     $pathchanges{$item} = 1;
 9651:                 }
 9652:                 $existing{$item} = 1;
 9653:                 $numexisting ++;
 9654:             } else {
 9655:                 $newfiles{$path.'/'.$file} = 1;
 9656:             }
 9657:         }
 9658:         if ($actionurl eq '/adm/dependencies') {
 9659:             foreach my $path (keys(%currsubfile)) {
 9660:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9661:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9662:                          unless ($subdependencies{$path}{$file}) {
 9663:                              next if (($rem ne '') &&
 9664:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9665:                                        (ref($navmap) &&
 9666:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9667:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9668:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9669:                              $unused{$path.'/'.$file} = 1; 
 9670:                          }
 9671:                     }
 9672:                 }
 9673:             }
 9674:         }
 9675:     }
 9676:     my %currfile;
 9677:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9678:         my ($dirlistref,$listerror) =
 9679:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9680:         if (ref($dirlistref) eq 'ARRAY') {
 9681:             foreach my $line (@{$dirlistref}) {
 9682:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9683:                 $currfile{$file_name} = 1;
 9684:             }
 9685:         }
 9686:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9687:         if (opendir(my $dir,$url)) {
 9688:             my @dir_list = grep(!/^\./,readdir($dir));
 9689:             map {$currfile{$_} = 1;} @dir_list;
 9690:         }
 9691:     } elsif (($actionurl eq '/adm/dependencies') ||
 9692:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9693:               ($args->{'context'} eq 'paste'))) {
 9694:         if ($env{'request.course.id'} ne '') {
 9695:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9696:             if ($dir ne '') {
 9697:                 my ($dirlistref,$listerror) =
 9698:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9699:                 if (ref($dirlistref) eq 'ARRAY') {
 9700:                     foreach my $line (@{$dirlistref}) {
 9701:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9702:                             $size,undef,$mtime)=split(/\&/,$line,12);
 9703:                         unless (($testdir&$dirptr) ||
 9704:                                 ($file_name =~ /^\.\.?$/)) {
 9705:                             $currfile{$file_name} = [$size,$mtime];
 9706:                         }
 9707:                     }
 9708:                 }
 9709:             }
 9710:         }
 9711:     }
 9712:     foreach my $file (keys(%dependencies)) {
 9713:         if (exists($currfile{$file})) {
 9714:             unless ($mapping{$file} eq $file) {
 9715:                 $pathchanges{$file} = 1;
 9716:             }
 9717:             $existing{$file} = 1;
 9718:             $numexisting ++;
 9719:         } else {
 9720:             $newfiles{$file} = 1;
 9721:         }
 9722:     }
 9723:     foreach my $file (keys(%currfile)) {
 9724:         unless (($file eq $filename) ||
 9725:                 ($file eq $filename.'.bak') ||
 9726:                 ($dependencies{$file})) {
 9727:             if ($actionurl eq '/adm/dependencies') {
 9728:                 next if (($rem ne '') &&
 9729:                          (($env{"httpref.$rem".$file} ne '') ||
 9730:                           (ref($navmap) &&
 9731:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
 9732:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9733:                             ($navmap->getResourceByUrl($rem.$1)))))));
 9734:             }
 9735:             $unused{$file} = 1;
 9736:         }
 9737:     }
 9738:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9739:         ($args->{'context'} eq 'paste')) {
 9740:         $counter = scalar(keys(%existing));
 9741:         $numpathchg = scalar(keys(%pathchanges));
 9742:         return ($output,$counter,$numpathchg,\%existing); 
 9743:     }
 9744:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 9745:         if ($actionurl eq '/adm/dependencies') {
 9746:             next if ($embed_file =~ m{^\w+://});
 9747:         }
 9748:         $upload_output .= &start_data_table_row().
 9749:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
 9750:                           '<span class="LC_filename">'.$embed_file.'</span>';
 9751:         unless ($mapping{$embed_file} eq $embed_file) {
 9752:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 9753:         }
 9754:         $upload_output .= '</td><td>';
 9755:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
 9756:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 9757:             $numremref++;
 9758:         } elsif ($args->{'error_on_invalid_names'}
 9759:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 9760:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 9761:             $numinvalid++;
 9762:         } else {
 9763:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
 9764:                                                      $embed_file,\%mapping,
 9765:                                                      $allfiles,$codebase,'upload');
 9766:             $counter ++;
 9767:             $numnew ++;
 9768:         }
 9769:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 9770:     }
 9771:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 9772:         if ($actionurl eq '/adm/dependencies') {
 9773:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
 9774:             $modify_output .= &start_data_table_row().
 9775:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
 9776:                               '<img src="'.&icon($embed_file).'" border="0" />'.
 9777:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
 9778:                               '<td>'.$size.'</td>'.
 9779:                               '<td>'.$mtime.'</td>'.
 9780:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
 9781:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
 9782:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
 9783:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
 9784:                               &embedded_file_element('upload_embedded',$counter,
 9785:                                                      $embed_file,\%mapping,
 9786:                                                      $allfiles,$codebase,'modify').
 9787:                               '</div></td>'.
 9788:                               &end_data_table_row()."\n";
 9789:             $counter ++;
 9790:         } else {
 9791:             $upload_output .= &start_data_table_row().
 9792:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
 9793:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 9794:                               &Apache::loncommon::end_data_table_row()."\n";
 9795:         }
 9796:     }
 9797:     my $delidx = $counter;
 9798:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
 9799:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
 9800:         $delete_output .= &start_data_table_row().
 9801:                           '<td><img src="'.&icon($oldfile).'" />'.
 9802:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
 9803:                           '<td>'.$size.'</td>'.
 9804:                           '<td>'.$mtime.'</td>'.
 9805:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
 9806:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
 9807:                           &embedded_file_element('upload_embedded',$delidx,
 9808:                                                  $oldfile,\%mapping,$allfiles,
 9809:                                                  $codebase,'delete').'</td>'.
 9810:                           &end_data_table_row()."\n"; 
 9811:         $numunused ++;
 9812:         $delidx ++;
 9813:     }
 9814:     if ($upload_output) {
 9815:         $upload_output = &start_data_table().
 9816:                          $upload_output.
 9817:                          &end_data_table()."\n";
 9818:     }
 9819:     if ($modify_output) {
 9820:         $modify_output = &start_data_table().
 9821:                          &start_data_table_header_row().
 9822:                          '<th>'.&mt('File').'</th>'.
 9823:                          '<th>'.&mt('Size (KB)').'</th>'.
 9824:                          '<th>'.&mt('Modified').'</th>'.
 9825:                          '<th>'.&mt('Upload replacement?').'</th>'.
 9826:                          &end_data_table_header_row().
 9827:                          $modify_output.
 9828:                          &end_data_table()."\n";
 9829:     }
 9830:     if ($delete_output) {
 9831:         $delete_output = &start_data_table().
 9832:                          &start_data_table_header_row().
 9833:                          '<th>'.&mt('File').'</th>'.
 9834:                          '<th>'.&mt('Size (KB)').'</th>'.
 9835:                          '<th>'.&mt('Modified').'</th>'.
 9836:                          '<th>'.&mt('Delete?').'</th>'.
 9837:                          &end_data_table_header_row().
 9838:                          $delete_output.
 9839:                          &end_data_table()."\n";
 9840:     }
 9841:     my $applies = 0;
 9842:     if ($numremref) {
 9843:         $applies ++;
 9844:     }
 9845:     if ($numinvalid) {
 9846:         $applies ++;
 9847:     }
 9848:     if ($numexisting) {
 9849:         $applies ++;
 9850:     }
 9851:     if ($counter || $numunused) {
 9852:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 9853:                   ' method="post" enctype="multipart/form-data">'."\n".
 9854:                   $state.'<h3>'.$heading.'</h3>'; 
 9855:         if ($actionurl eq '/adm/dependencies') {
 9856:             if ($numnew) {
 9857:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
 9858:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
 9859:                            $upload_output.'<br />'."\n";
 9860:             }
 9861:             if ($numexisting) {
 9862:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
 9863:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
 9864:                            $modify_output.'<br />'."\n";
 9865:                            $buttontext = &mt('Save changes');
 9866:             }
 9867:             if ($numunused) {
 9868:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
 9869:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
 9870:                            $delete_output.'<br />'."\n";
 9871:                            $buttontext = &mt('Save changes');
 9872:             }
 9873:         } else {
 9874:             $output .= $upload_output.'<br />'."\n";
 9875:         }
 9876:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
 9877:                    $counter.'" />'."\n";
 9878:         if ($actionurl eq '/adm/dependencies') { 
 9879:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
 9880:                        $numnew.'" />'."\n";
 9881:         } elsif ($actionurl eq '') {
 9882:             $output .=  '<input type="hidden" name="phase" value="three" />';
 9883:         }
 9884:     } elsif ($applies) {
 9885:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 9886:         if ($applies > 1) {
 9887:             $output .=  
 9888:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 9889:             if ($numremref) {
 9890:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 9891:             }
 9892:             if ($numinvalid) {
 9893:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 9894:             }
 9895:             if ($numexisting) {
 9896:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 9897:             }
 9898:             $output .= '</ul><br />';
 9899:         } elsif ($numremref) {
 9900:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 9901:         } elsif ($numinvalid) {
 9902:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 9903:         } elsif ($numexisting) {
 9904:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 9905:         }
 9906:         $output .= $upload_output.'<br />';
 9907:     }
 9908:     my ($pathchange_output,$chgcount);
 9909:     $chgcount = $counter;
 9910:     if (keys(%pathchanges) > 0) {
 9911:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 9912:             if ($counter) {
 9913:                 $output .= &embedded_file_element('pathchange',$chgcount,
 9914:                                                   $embed_file,\%mapping,
 9915:                                                   $allfiles,$codebase,'change');
 9916:             } else {
 9917:                 $pathchange_output .= 
 9918:                     &start_data_table_row().
 9919:                     '<td><input type ="checkbox" name="namechange" value="'.
 9920:                     $chgcount.'" checked="checked" /></td>'.
 9921:                     '<td>'.$mapping{$embed_file}.'</td>'.
 9922:                     '<td>'.$embed_file.
 9923:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 9924:                                            \%mapping,$allfiles,$codebase,'change').
 9925:                     '</td>'.&end_data_table_row();
 9926:             }
 9927:             $numpathchg ++;
 9928:             $chgcount ++;
 9929:         }
 9930:     }
 9931:     if ($counter) {
 9932:         if ($numpathchg) {
 9933:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 9934:                        $numpathchg.'" />'."\n";
 9935:         }
 9936:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 9937:             ($actionurl eq '/adm/imsimport')) {
 9938:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 9939:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 9940:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 9941:         } elsif ($actionurl eq '/adm/dependencies') {
 9942:             $output .= '<input type="hidden" name="action" value="process_changes" />';
 9943:         }
 9944:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
 9945:     } elsif ($numpathchg) {
 9946:         my %pathchange = ();
 9947:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 9948:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9949:             $output .= '<p>'.&mt('or').'</p>'; 
 9950:         } 
 9951:     }
 9952:     return ($output,$counter,$numpathchg);
 9953: }
 9954: 
 9955: sub embedded_file_element {
 9956:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
 9957:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 9958:                    (ref($codebase) eq 'HASH'));
 9959:     my $output;
 9960:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
 9961:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 9962:     }
 9963:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 9964:                &escape($embed_file).'" />';
 9965:     unless (($context eq 'upload_embedded') && 
 9966:             ($mapping->{$embed_file} eq $embed_file)) {
 9967:         $output .='
 9968:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 9969:     }
 9970:     my $attrib;
 9971:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 9972:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 9973:     }
 9974:     $output .=
 9975:         "\n\t\t".
 9976:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 9977:         $attrib.'" />';
 9978:     if (exists($codebase->{$mapping->{$embed_file}})) {
 9979:         $output .=
 9980:             "\n\t\t".
 9981:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 9982:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 9983:     }
 9984:     return $output;
 9985: }
 9986: 
 9987: sub get_dependency_details {
 9988:     my ($currfile,$currsubfile,$embed_file) = @_;
 9989:     my ($size,$mtime,$showsize,$showmtime);
 9990:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
 9991:         if ($embed_file =~ m{/}) {
 9992:             my ($path,$fname) = split(/\//,$embed_file);
 9993:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
 9994:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
 9995:             }
 9996:         } else {
 9997:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
 9998:                 ($size,$mtime) = @{$currfile->{$embed_file}};
 9999:             }
10000:         }
10001:         $showsize = $size/1024.0;
10002:         $showsize = sprintf("%.1f",$showsize);
10003:         if ($mtime > 0) {
10004:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10005:         }
10006:     }
10007:     return ($showsize,$showmtime);
10008: }
10009: 
10010: sub ask_embedded_js {
10011:     return <<"END";
10012: <script type="text/javascript"">
10013: // <![CDATA[
10014: function toggleBrowse(counter) {
10015:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10016:     var fileid = document.getElementById('embedded_item_'+counter);
10017:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10018:     if (chkboxid.checked == true) {
10019:         uploaddivid.style.display='block';
10020:     } else {
10021:         uploaddivid.style.display='none';
10022:         fileid.value = '';
10023:     }
10024: }
10025: // ]]>
10026: </script>
10027: 
10028: END
10029: }
10030: 
10031: sub upload_embedded {
10032:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10033:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10034:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10035:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10036:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10037:         my $orig_uploaded_filename =
10038:             $env{'form.embedded_item_'.$i.'.filename'};
10039:         foreach my $type ('orig','ref','attrib','codebase') {
10040:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10041:                 $env{'form.embedded_'.$type.'_'.$i} =
10042:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10043:             }
10044:         }
10045:         my ($path,$fname) =
10046:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10047:         # no path, whole string is fname
10048:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10049:         $fname = &Apache::lonnet::clean_filename($fname);
10050:         # See if there is anything left
10051:         next if ($fname eq '');
10052: 
10053:         # Check if file already exists as a file or directory.
10054:         my ($state,$msg);
10055:         if ($context eq 'portfolio') {
10056:             my $port_path = $dirpath;
10057:             if ($group ne '') {
10058:                 $port_path = "groups/$group/$port_path";
10059:             }
10060:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10061:                                               $fname,$group,'embedded_item_'.$i,
10062:                                               $dir_root,$port_path,$disk_quota,
10063:                                               $current_disk_usage,$uname,$udom);
10064:             if ($state eq 'will_exceed_quota'
10065:                 || $state eq 'file_locked') {
10066:                 $output .= $msg;
10067:                 next;
10068:             }
10069:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10070:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10071:             if ($state eq 'exists') {
10072:                 $output .= $msg;
10073:                 next;
10074:             }
10075:         }
10076:         # Check if extension is valid
10077:         if (($fname =~ /\.(\w+)$/) &&
10078:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10079:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
10080:             next;
10081:         } elsif (($fname =~ /\.(\w+)$/) &&
10082:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10083:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10084:             next;
10085:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10086:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10087:             next;
10088:         }
10089:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10090:         if ($context eq 'portfolio') {
10091:             my $result;
10092:             if ($state eq 'existingfile') {
10093:                 $result=
10094:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10095:                                                     $dirpath.$env{'form.currentpath'}.$path);
10096:             } else {
10097:                 $result=
10098:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10099:                                                     $dirpath.
10100:                                                     $env{'form.currentpath'}.$path);
10101:                 if ($result !~ m|^/uploaded/|) {
10102:                     $output .= '<span class="LC_error">'
10103:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10104:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10105:                                .'</span><br />';
10106:                     next;
10107:                 } else {
10108:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10109:                                $path.$fname.'</span>').'<br />';     
10110:                 }
10111:             }
10112:         } elsif ($context eq 'coursedoc') {
10113:             my $result =
10114:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
10115:                                                 $dirpath.'/'.$path);
10116:             if ($result !~ m|^/uploaded/|) {
10117:                 $output .= '<span class="LC_error">'
10118:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10119:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10120:                            .'</span><br />';
10121:                     next;
10122:             } else {
10123:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10124:                            $path.$fname.'</span>').'<br />';
10125:             }
10126:         } else {
10127: # Save the file
10128:             my $target = $env{'form.embedded_item_'.$i};
10129:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10130:             my $dest = $fullpath.$fname;
10131:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10132:             my @parts=split(/\//,"$dirpath/$path");
10133:             my $count;
10134:             my $filepath = $dir_root;
10135:             foreach my $subdir (@parts) {
10136:                 $filepath .= "/$subdir";
10137:                 if (!-e $filepath) {
10138:                     mkdir($filepath,0770);
10139:                 }
10140:             }
10141:             my $fh;
10142:             if (!open($fh,'>'.$dest)) {
10143:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10144:                 $output .= '<span class="LC_error">'.
10145:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10146:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10147:                            '</span><br />';
10148:             } else {
10149:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10150:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10151:                     $output .= '<span class="LC_error">'.
10152:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10153:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10154:                               '</span><br />';
10155:                 } else {
10156:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10157:                                $url.'</span>').'<br />';
10158:                     unless ($context eq 'testbank') {
10159:                         $footer .= &mt('View embedded file: [_1]',
10160:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10161:                     }
10162:                 }
10163:                 close($fh);
10164:             }
10165:         }
10166:         if ($env{'form.embedded_ref_'.$i}) {
10167:             $pathchange{$i} = 1;
10168:         }
10169:     }
10170:     if ($output) {
10171:         $output = '<p>'.$output.'</p>';
10172:     }
10173:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10174:     $returnflag = 'ok';
10175:     my $numpathchgs = scalar(keys(%pathchange));
10176:     if ($numpathchgs > 0) {
10177:         if ($context eq 'portfolio') {
10178:             $output .= '<p>'.&mt('or').'</p>';
10179:         } elsif ($context eq 'testbank') {
10180:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10181:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10182:             $returnflag = 'modify_orightml';
10183:         }
10184:     }
10185:     return ($output.$footer,$returnflag,$numpathchgs);
10186: }
10187: 
10188: sub modify_html_form {
10189:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10190:     my $end = 0;
10191:     my $modifyform;
10192:     if ($context eq 'upload_embedded') {
10193:         return unless (ref($pathchange) eq 'HASH');
10194:         if ($env{'form.number_embedded_items'}) {
10195:             $end += $env{'form.number_embedded_items'};
10196:         }
10197:         if ($env{'form.number_pathchange_items'}) {
10198:             $end += $env{'form.number_pathchange_items'};
10199:         }
10200:         if ($end) {
10201:             for (my $i=0; $i<$end; $i++) {
10202:                 if ($i < $env{'form.number_embedded_items'}) {
10203:                     next unless($pathchange->{$i});
10204:                 }
10205:                 $modifyform .=
10206:                     &start_data_table_row().
10207:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10208:                     'checked="checked" /></td>'.
10209:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10210:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10211:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10212:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10213:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10214:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10215:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10216:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10217:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10218:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10219:                     &end_data_table_row();
10220:             }
10221:         }
10222:     } else {
10223:         $modifyform = $pathchgtable;
10224:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10225:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10226:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10227:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10228:         }
10229:     }
10230:     if ($modifyform) {
10231:         if ($actionurl eq '/adm/dependencies') {
10232:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10233:         }
10234:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10235:                '<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".
10236:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10237:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10238:                '</ol></p>'."\n".'<p>'.
10239:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10240:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10241:                &start_data_table()."\n".
10242:                &start_data_table_header_row().
10243:                '<th>'.&mt('Change?').'</th>'.
10244:                '<th>'.&mt('Current reference').'</th>'.
10245:                '<th>'.&mt('Required reference').'</th>'.
10246:                &end_data_table_header_row()."\n".
10247:                $modifyform.
10248:                &end_data_table().'<br />'."\n".$hiddenstate.
10249:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10250:                '</form>'."\n";
10251:     }
10252:     return;
10253: }
10254: 
10255: sub modify_html_refs {
10256:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
10257:     my $container;
10258:     if ($context eq 'portfolio') {
10259:         $container = $env{'form.container'};
10260:     } elsif ($context eq 'coursedoc') {
10261:         $container = $env{'form.primaryurl'};
10262:     } elsif ($context eq 'manage_dependencies') {
10263:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10264:         $container = "/$container";
10265:     } else {
10266:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10267:     }
10268:     my (%allfiles,%codebase,$output,$content);
10269:     my @changes = &get_env_multiple('form.namechange');
10270:     unless (@changes > 0) {
10271:         if (wantarray) {
10272:             return ('',0,0); 
10273:         } else {
10274:             return;
10275:         }
10276:     }
10277:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10278:         ($context eq 'manage_dependencies')) {
10279:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10280:             if (wantarray) {
10281:                 return ('',0,0);
10282:             } else {
10283:                 return;
10284:             }
10285:         } 
10286:         $content = &Apache::lonnet::getfile($container);
10287:         if ($content eq '-1') {
10288:             if (wantarray) {
10289:                 return ('',0,0);
10290:             } else {
10291:                 return;
10292:             }
10293:         }
10294:     } else {
10295:         unless ($container =~ /^\Q$dir_root\E/) {
10296:             if (wantarray) {
10297:                 return ('',0,0);
10298:             } else {
10299:                 return;
10300:             }
10301:         } 
10302:         if (open(my $fh,"<$container")) {
10303:             $content = join('', <$fh>);
10304:             close($fh);
10305:         } else {
10306:             if (wantarray) {
10307:                 return ('',0,0);
10308:             } else {
10309:                 return;
10310:             }
10311:         }
10312:     }
10313:     my ($count,$codebasecount) = (0,0);
10314:     my $mm = new File::MMagic;
10315:     my $mime_type = $mm->checktype_contents($content);
10316:     if ($mime_type eq 'text/html') {
10317:         my $parse_result = 
10318:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10319:                                                     \%codebase,\$content);
10320:         if ($parse_result eq 'ok') {
10321:             foreach my $i (@changes) {
10322:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10323:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10324:                 if ($allfiles{$ref}) {
10325:                     my $newname =  $orig;
10326:                     my ($attrib_regexp,$codebase);
10327:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10328:                     if ($attrib_regexp =~ /:/) {
10329:                         $attrib_regexp =~ s/\:/|/g;
10330:                     }
10331:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10332:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10333:                         $count += $numchg;
10334:                     }
10335:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10336:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10337:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10338:                         $codebasecount ++;
10339:                     }
10340:                 }
10341:             }
10342:             if ($count || $codebasecount) {
10343:                 my $saveresult;
10344:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10345:                     ($context eq 'manage_dependencies')) {
10346:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10347:                     if ($url eq $container) {
10348:                         my ($fname) = ($container =~ m{/([^/]+)$});
10349:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10350:                                             $count,'<span class="LC_filename">'.
10351:                                             $fname.'</span>').'</p>';
10352:                     } else {
10353:                          $output = '<p class="LC_error">'.
10354:                                    &mt('Error: update failed for: [_1].',
10355:                                    '<span class="LC_filename">'.
10356:                                    $container.'</span>').'</p>';
10357:                     }
10358:                 } else {
10359:                     if (open(my $fh,">$container")) {
10360:                         print $fh $content;
10361:                         close($fh);
10362:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10363:                                   $count,'<span class="LC_filename">'.
10364:                                   $container.'</span>').'</p>';
10365:                     } else {
10366:                          $output = '<p class="LC_error">'.
10367:                                    &mt('Error: could not update [_1].',
10368:                                    '<span class="LC_filename">'.
10369:                                    $container.'</span>').'</p>';
10370:                     }
10371:                 }
10372:             }
10373:         } else {
10374:             &logthis('Failed to parse '.$container.
10375:                      ' to modify references: '.$parse_result);
10376:         }
10377:     }
10378:     if (wantarray) {
10379:         return ($output,$count,$codebasecount);
10380:     } else {
10381:         return $output;
10382:     }
10383: }
10384: 
10385: sub check_for_existing {
10386:     my ($path,$fname,$element) = @_;
10387:     my ($state,$msg);
10388:     if (-d $path.'/'.$fname) {
10389:         $state = 'exists';
10390:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10391:     } elsif (-e $path.'/'.$fname) {
10392:         $state = 'exists';
10393:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10394:     }
10395:     if ($state eq 'exists') {
10396:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10397:     }
10398:     return ($state,$msg);
10399: }
10400: 
10401: sub check_for_upload {
10402:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10403:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10404:     my $filesize = length($env{'form.'.$element});
10405:     if (!$filesize) {
10406:         my $msg = '<span class="LC_error">'.
10407:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10408:                       '<span class="LC_filename">'.$fname.'</span>',
10409:                       $filesize).'<br />'.
10410:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10411:                   '</span>';
10412:         return ('zero_bytes',$msg);
10413:     }
10414:     $filesize =  $filesize/1000; #express in k (1024?)
10415:     my $getpropath = 1;
10416:     my ($dirlistref,$listerror) =
10417:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10418:     my $found_file = 0;
10419:     my $locked_file = 0;
10420:     my @lockers;
10421:     my $navmap;
10422:     if ($env{'request.course.id'}) {
10423:         $navmap = Apache::lonnavmaps::navmap->new();
10424:     }
10425:     if (ref($dirlistref) eq 'ARRAY') {
10426:         foreach my $line (@{$dirlistref}) {
10427:             my ($file_name,$rest)=split(/\&/,$line,2);
10428:             if ($file_name eq $fname){
10429:                 $file_name = $path.$file_name;
10430:                 if ($group ne '') {
10431:                     $file_name = $group.$file_name;
10432:                 }
10433:                 $found_file = 1;
10434:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10435:                     foreach my $lock (@lockers) {
10436:                         if (ref($lock) eq 'ARRAY') {
10437:                             my ($symb,$crsid) = @{$lock};
10438:                             if ($crsid eq $env{'request.course.id'}) {
10439:                                 if (ref($navmap)) {
10440:                                     my $res = $navmap->getBySymb($symb);
10441:                                     foreach my $part (@{$res->parts()}) { 
10442:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10443:                                         unless (($slot_status == $res->RESERVED) ||
10444:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10445:                                             $locked_file = 1;
10446:                                         }
10447:                                     }
10448:                                 } else {
10449:                                     $locked_file = 1;
10450:                                 }
10451:                             } else {
10452:                                 $locked_file = 1;
10453:                             }
10454:                         }
10455:                    }
10456:                 } else {
10457:                     my @info = split(/\&/,$rest);
10458:                     my $currsize = $info[6]/1000;
10459:                     if ($currsize < $filesize) {
10460:                         my $extra = $filesize - $currsize;
10461:                         if (($current_disk_usage + $extra) > $disk_quota) {
10462:                             my $msg = '<span class="LC_error">'.
10463:                                       &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.',
10464:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10465:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10466:                                                    $disk_quota,$current_disk_usage);
10467:                             return ('will_exceed_quota',$msg);
10468:                         }
10469:                     }
10470:                 }
10471:             }
10472:         }
10473:     }
10474:     if (($current_disk_usage + $filesize) > $disk_quota){
10475:         my $msg = '<span class="LC_error">'.
10476:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10477:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10478:         return ('will_exceed_quota',$msg);
10479:     } elsif ($found_file) {
10480:         if ($locked_file) {
10481:             my $msg = '<span class="LC_error">';
10482:             $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>');
10483:             $msg .= '</span><br />';
10484:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10485:             return ('file_locked',$msg);
10486:         } else {
10487:             my $msg = '<span class="LC_error">';
10488:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10489:             $msg .= '</span>';
10490:             return ('existingfile',$msg);
10491:         }
10492:     }
10493: }
10494: 
10495: sub check_for_traversal {
10496:     my ($path,$url,$toplevel) = @_;
10497:     my @parts=split(/\//,$path);
10498:     my $cleanpath;
10499:     my $fullpath = $url;
10500:     for (my $i=0;$i<@parts;$i++) {
10501:         next if ($parts[$i] eq '.');
10502:         if ($parts[$i] eq '..') {
10503:             $fullpath =~ s{([^/]+/)$}{};
10504:         } else {
10505:             $fullpath .= $parts[$i].'/';
10506:         }
10507:     }
10508:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10509:         $cleanpath = $1;
10510:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10511:         my $curr_toprel = $1;
10512:         my @parts = split(/\//,$curr_toprel);
10513:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10514:         my @urlparts = split(/\//,$url_toprel);
10515:         my $doubledots;
10516:         my $startdiff = -1;
10517:         for (my $i=0; $i<@urlparts; $i++) {
10518:             if ($startdiff == -1) {
10519:                 unless ($urlparts[$i] eq $parts[$i]) {
10520:                     $startdiff = $i;
10521:                     $doubledots .= '../';
10522:                 }
10523:             } else {
10524:                 $doubledots .= '../';
10525:             }
10526:         }
10527:         if ($startdiff > -1) {
10528:             $cleanpath = $doubledots;
10529:             for (my $i=$startdiff; $i<@parts; $i++) {
10530:                 $cleanpath .= $parts[$i].'/';
10531:             }
10532:         }
10533:     }
10534:     $cleanpath =~ s{(/)$}{};
10535:     return $cleanpath;
10536: }
10537: 
10538: sub is_archive_file {
10539:     my ($mimetype) = @_;
10540:     if (($mimetype eq 'application/octet-stream') ||
10541:         ($mimetype eq 'application/x-stuffit') ||
10542:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10543:         return 1;
10544:     }
10545:     return;
10546: }
10547: 
10548: sub decompress_form {
10549:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10550:     my %lt = &Apache::lonlocal::texthash (
10551:         this => 'This file is an archive file.',
10552:         camt => 'This file is a Camtasia archive file.',
10553:         itsc => 'Its contents are as follows:',
10554:         youm => 'You may wish to extract its contents.',
10555:         extr => 'Extract contents',
10556:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10557:         proa => 'Process automatically?',
10558:         yes  => 'Yes',
10559:         no   => 'No',
10560:         fold => 'Title for folder containing movie',
10561:         movi => 'Title for page containing embedded movie', 
10562:     );
10563:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10564:     my ($is_camtasia,$topdir,%toplevel,@paths);
10565:     my $info = &list_archive_contents($fileloc,\@paths);
10566:     if (@paths) {
10567:         foreach my $path (@paths) {
10568:             $path =~ s{^/}{};
10569:             if ($path =~ m{^([^/]+)/$}) {
10570:                 $topdir = $1;
10571:             }
10572:             if ($path =~ m{^([^/]+)/}) {
10573:                 $toplevel{$1} = $path;
10574:             } else {
10575:                 $toplevel{$path} = $path;
10576:             }
10577:         }
10578:     }
10579:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10580:         my @camtasia = ("$topdir/","$topdir/index.html",
10581:                         "$topdir/media/",
10582:                         "$topdir/media/$topdir.mp4",
10583:                         "$topdir/media/FirstFrame.png",
10584:                         "$topdir/media/player.swf",
10585:                         "$topdir/media/swfobject.js",
10586:                         "$topdir/media/expressInstall.swf");
10587:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10588:         if (@diffs == 0) {
10589:             $is_camtasia = 1;
10590:         }
10591:     }
10592:     my $output;
10593:     if ($is_camtasia) {
10594:         $output = <<"ENDCAM";
10595: <script type="text/javascript" language="Javascript">
10596: // <![CDATA[
10597: 
10598: function camtasiaToggle() {
10599:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10600:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10601:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10602: 
10603:                 document.getElementById('camtasia_titles').style.display='block';
10604:             } else {
10605:                 document.getElementById('camtasia_titles').style.display='none';
10606:             }
10607:         }
10608:     }
10609:     return;
10610: }
10611: 
10612: // ]]>
10613: </script>
10614: <p>$lt{'camt'}</p>
10615: ENDCAM
10616:     } else {
10617:         $output = '<p>'.$lt{'this'};
10618:         if ($info eq '') {
10619:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
10620:         } else {
10621:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10622:                        '<div><pre>'.$info.'</pre></div>';
10623:         }
10624:     }
10625:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10626:     my $duplicates;
10627:     my $num = 0;
10628:     if (ref($dirlist) eq 'ARRAY') {
10629:         foreach my $item (@{$dirlist}) {
10630:             if (ref($item) eq 'ARRAY') {
10631:                 if (exists($toplevel{$item->[0]})) {
10632:                     $duplicates .= 
10633:                         &start_data_table_row().
10634:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10635:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
10636:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
10637:                         'value="1" />'.&mt('Yes').'</label>'.
10638:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10639:                         '<td>'.$item->[0].'</td>';
10640:                     if ($item->[2]) {
10641:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
10642:                     } else {
10643:                         $duplicates .= '<td>'.&mt('File').'</td>';
10644:                     }
10645:                     $duplicates .= '<td>'.$item->[3].'</td>'.
10646:                                    '<td>'.
10647:                                    &Apache::lonlocal::locallocaltime($item->[4]).
10648:                                    '</td>'.
10649:                                    &end_data_table_row();
10650:                     $num ++;
10651:                 }
10652:             }
10653:         }
10654:     }
10655:     my $itemcount;
10656:     if (@paths > 0) {
10657:         $itemcount = scalar(@paths);
10658:     } else {
10659:         $itemcount = 1;
10660:     }
10661:     if ($is_camtasia) {
10662:         $output .= $lt{'auto'}.'<br />'.
10663:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10664:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10665:                    $lt{'yes'}.'</label>&nbsp;<label>'.
10666:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10667:                    $lt{'no'}.'</label></span><br />'.
10668:                    '<div id="camtasia_titles" style="display:block">'.
10669:                    &Apache::lonhtmlcommon::start_pick_box().
10670:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10671:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10672:                    &Apache::lonhtmlcommon::row_closure().
10673:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10674:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10675:                    &Apache::lonhtmlcommon::row_closure(1).
10676:                    &Apache::lonhtmlcommon::end_pick_box().
10677:                    '</div>';
10678:     }
10679:     $output .= 
10680:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10681:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10682:         "\n";
10683:     if ($duplicates ne '') {
10684:         $output .= '<p><span class="LC_warning">'.
10685:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
10686:                    &start_data_table().
10687:                    &start_data_table_header_row().
10688:                    '<th>'.&mt('Overwrite?').'</th>'.
10689:                    '<th>'.&mt('Name').'</th>'.
10690:                    '<th>'.&mt('Type').'</th>'.
10691:                    '<th>'.&mt('Size').'</th>'.
10692:                    '<th>'.&mt('Last modified').'</th>'.
10693:                    &end_data_table_header_row().
10694:                    $duplicates.
10695:                    &end_data_table().
10696:                    '</p>';
10697:     }
10698:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10699:     if (ref($hiddenelements) eq 'HASH') {
10700:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10701:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10702:         }
10703:     }
10704:     $output .= <<"END";
10705: <br />
10706: <input type="submit" name="decompress" value="$lt{'extr'}" />
10707: </form>
10708: $noextract
10709: END
10710:     return $output;
10711: }
10712: 
10713: sub decompression_utility {
10714:     my ($program) = @_;
10715:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
10716:     my $location;
10717:     if (grep(/^\Q$program\E$/,@utilities)) { 
10718:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10719:                          '/usr/sbin/') {
10720:             if (-x $dir.$program) {
10721:                 $location = $dir.$program;
10722:                 last;
10723:             }
10724:         }
10725:     }
10726:     return $location;
10727: }
10728: 
10729: sub list_archive_contents {
10730:     my ($file,$pathsref) = @_;
10731:     my (@cmd,$output);
10732:     my $needsregexp;
10733:     if ($file =~ /\.zip$/) {
10734:         @cmd = (&decompression_utility('unzip'),"-l");
10735:         $needsregexp = 1;
10736:     } elsif (($file =~ m/\.tar\.gz$/) ||
10737:              ($file =~ /\.tgz$/)) {
10738:         @cmd = (&decompression_utility('tar'),"-ztf");
10739:     } elsif ($file =~ /\.tar\.bz2$/) {
10740:         @cmd = (&decompression_utility('tar'),"-jtf");
10741:     } elsif ($file =~ m|\.tar$|) {
10742:         @cmd = (&decompression_utility('tar'),"-tf");
10743:     }
10744:     if (@cmd) {
10745:         undef($!);
10746:         undef($@);
10747:         if (open(my $fh,"-|", @cmd, $file)) {
10748:             while (my $line = <$fh>) {
10749:                 $output .= $line;
10750:                 chomp($line);
10751:                 my $item;
10752:                 if ($needsregexp) {
10753:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
10754:                 } else {
10755:                     $item = $line;
10756:                 }
10757:                 if ($item ne '') {
10758:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10759:                         push(@{$pathsref},$item);
10760:                     } 
10761:                 }
10762:             }
10763:             close($fh);
10764:         }
10765:     }
10766:     return $output;
10767: }
10768: 
10769: sub decompress_uploaded_file {
10770:     my ($file,$dir) = @_;
10771:     &Apache::lonnet::appenv({'cgi.file' => $file});
10772:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
10773:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10774:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10775:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10776:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10777:     my $decompressed = $env{'cgi.decompressed'};
10778:     &Apache::lonnet::delenv('cgi.file');
10779:     &Apache::lonnet::delenv('cgi.dir');
10780:     &Apache::lonnet::delenv('cgi.decompressed');
10781:     return ($decompressed,$result);
10782: }
10783: 
10784: sub process_decompression {
10785:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10786:     my ($dir,$error,$warning,$output);
10787:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10788:         $error = &mt('File name not a supported archive file type.').
10789:                  '<br />'.&mt('File name should end with one of: [_1].',
10790:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10791:     } else {
10792:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10793:         if ($docuhome eq 'no_host') {
10794:             $error = &mt('Could not determine home server for course.');
10795:         } else {
10796:             my @ids=&Apache::lonnet::current_machine_ids();
10797:             my $currdir = "$dir_root/$destination";
10798:             if (grep(/^\Q$docuhome\E$/,@ids)) {
10799:                 $dir = &LONCAPA::propath($docudom,$docuname).
10800:                        "$dir_root/$destination";
10801:             } else {
10802:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10803:                        "$dir_root/$docudom/$docuname/$destination";
10804:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10805:                     $error = &mt('Archive file not found.');
10806:                 }
10807:             }
10808:             my (@to_overwrite,@to_skip);
10809:             if ($env{'form.archive_overwrite_total'} > 0) {
10810:                 my $total = $env{'form.archive_overwrite_total'};
10811:                 for (my $i=0; $i<$total; $i++) {
10812:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
10813:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10814:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10815:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10816:                     }
10817:                 }
10818:             }
10819:             my $numskip = scalar(@to_skip);
10820:             if (($numskip > 0) && 
10821:                 ($numskip == $env{'form.archive_itemcount'})) {
10822:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
10823:             } elsif ($dir eq '') {
10824:                 $error = &mt('Directory containing archive file unavailable.');
10825:             } elsif (!$error) {
10826:                 my ($decompressed,$display);
10827:                 if ($numskip > 0) {
10828:                     my $tempdir = time.'_'.$$.int(rand(10000));
10829:                     mkdir("$dir/$tempdir",0755);
10830:                     system("mv $dir/$file $dir/$tempdir/$file");
10831:                     ($decompressed,$display) = 
10832:                         &decompress_uploaded_file($file,"$dir/$tempdir");
10833:                     foreach my $item (@to_skip) {
10834:                         if (($item ne '') && ($item !~ /\.\./)) {
10835:                             if (-f "$dir/$tempdir/$item") { 
10836:                                 unlink("$dir/$tempdir/$item");
10837:                             } elsif (-d "$dir/$tempdir/$item") {
10838:                                 system("rm -rf $dir/$tempdir/$item");
10839:                             }
10840:                         }
10841:                     }
10842:                     system("mv $dir/$tempdir/* $dir");
10843:                     rmdir("$dir/$tempdir");   
10844:                 } else {
10845:                     ($decompressed,$display) = 
10846:                         &decompress_uploaded_file($file,$dir);
10847:                 }
10848:                 if ($decompressed eq 'ok') {
10849:                     $output = '<p class="LC_info">'.
10850:                               &mt('Files extracted successfully from archive.').
10851:                               '</p>'."\n";
10852:                     my ($warning,$result,@contents);
10853:                     my ($newdirlistref,$newlisterror) =
10854:                         &Apache::lonnet::dirlist($currdir,$docudom,
10855:                                                  $docuname,1);
10856:                     my (%is_dir,%changes,@newitems);
10857:                     my $dirptr = 16384;
10858:                     if (ref($newdirlistref) eq 'ARRAY') {
10859:                         foreach my $dir_line (@{$newdirlistref}) {
10860:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10861:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
10862:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10863:                                 push(@newitems,$item);
10864:                                 if ($dirptr&$testdir) {
10865:                                     $is_dir{$item} = 1;
10866:                                 }
10867:                                 $changes{$item} = 1;
10868:                             }
10869:                         }
10870:                     }
10871:                     if (keys(%changes) > 0) {
10872:                         foreach my $item (sort(@newitems)) {
10873:                             if ($changes{$item}) {
10874:                                 push(@contents,$item);
10875:                             }
10876:                         }
10877:                     }
10878:                     if (@contents > 0) {
10879:                         my $wantform;
10880:                         unless ($env{'form.autoextract_camtasia'}) {
10881:                             $wantform = 1;
10882:                         }
10883:                         my (%children,%parent,%dirorder,%titles);
10884:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
10885:                                                                 $currdir,\%is_dir,
10886:                                                                 \%children,\%parent,
10887:                                                                 \@contents,\%dirorder,
10888:                                                                 \%titles,$wantform);
10889:                         if ($datatable ne '') {
10890:                             $output .= &archive_options_form('decompressed',$datatable,
10891:                                                              $count,$hiddenelem);
10892:                             my $startcount = 6;
10893:                             $output .= &archive_javascript($startcount,$count,
10894:                                                            \%titles,\%children);
10895:                         }
10896:                         if ($env{'form.autoextract_camtasia'}) {
10897:                             my %displayed;
10898:                             my $total = 1;
10899:                             $env{'form.archive_directory'} = [];
10900:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
10901:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
10902:                                 $path =~ s{/$}{};
10903:                                 my $item;
10904:                                 if ($path ne '') {
10905:                                     $item = "$path/$titles{$i}";
10906:                                 } else {
10907:                                     $item = $titles{$i};
10908:                                 }
10909:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
10910:                                 if ($item eq $contents[0]) {
10911:                                     push(@{$env{'form.archive_directory'}},$i);
10912:                                     $env{'form.archive_'.$i} = 'display';
10913:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
10914:                                     $displayed{'folder'} = $i;
10915:                                 } elsif ($item eq "$contents[0]/index.html") {
10916:                                     $env{'form.archive_'.$i} = 'display';
10917:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
10918:                                     $displayed{'web'} = $i;
10919:                                 } else {
10920:                                     if ($item eq "$contents[0]/media") {
10921:                                         push(@{$env{'form.archive_directory'}},$i);
10922:                                     }
10923:                                     $env{'form.archive_'.$i} = 'dependency';
10924:                                 }
10925:                                 $total ++;
10926:                             }
10927:                             for (my $i=1; $i<$total; $i++) {
10928:                                 next if ($i == $displayed{'web'});
10929:                                 next if ($i == $displayed{'folder'});
10930:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
10931:                             }
10932:                             $env{'form.phase'} = 'decompress_cleanup';
10933:                             $env{'form.archivedelete'} = 1;
10934:                             $env{'form.archive_count'} = $total-1;
10935:                             $output .=
10936:                                 &process_extracted_files('coursedocs',$docudom,
10937:                                                          $docuname,$destination,
10938:                                                          $dir_root,$hiddenelem);
10939:                         }
10940:                     } else {
10941:                         $warning = &mt('No new items extracted from archive file.');
10942:                     }
10943:                 } else {
10944:                     $output = $display;
10945:                     $error = &mt('An error occurred during extraction from the archive file.');
10946:                 }
10947:             }
10948:         }
10949:     }
10950:     if ($error) {
10951:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10952:                    $error.'</p>'."\n";
10953:     }
10954:     if ($warning) {
10955:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10956:     }
10957:     return $output;
10958: }
10959: 
10960: sub get_extracted {
10961:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10962:         $titles,$wantform) = @_;
10963:     my $count = 0;
10964:     my $depth = 0;
10965:     my $datatable;
10966:     my @hierarchy;
10967:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10968:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10969:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10970:     foreach my $item (@{$contents}) {
10971:         $count ++;
10972:         @{$dirorder->{$count}} = @hierarchy;
10973:         $titles->{$count} = $item;
10974:         &archive_hierarchy($depth,$count,$parent,$children);
10975:         if ($wantform) {
10976:             $datatable .= &archive_row($is_dir->{$item},$item,
10977:                                        $currdir,$depth,$count);
10978:         }
10979:         if ($is_dir->{$item}) {
10980:             $depth ++;
10981:             push(@hierarchy,$count);
10982:             $parent->{$depth} = $count;
10983:             $datatable .=
10984:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10985:                                            \$depth,\$count,\@hierarchy,$dirorder,
10986:                                            $children,$parent,$titles,$wantform);
10987:             $depth --;
10988:             pop(@hierarchy);
10989:         }
10990:     }
10991:     return ($count,$datatable);
10992: }
10993: 
10994: sub recurse_extracted_archive {
10995:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
10996:         $children,$parent,$titles,$wantform) = @_;
10997:     my $result='';
10998:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
10999:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11000:             (ref($dirorder) eq 'HASH')) {
11001:         return $result;
11002:     }
11003:     my $dirptr = 16384;
11004:     my ($newdirlistref,$newlisterror) =
11005:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11006:     if (ref($newdirlistref) eq 'ARRAY') {
11007:         foreach my $dir_line (@{$newdirlistref}) {
11008:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11009:             unless ($item =~ /^\.+$/) {
11010:                 $$count ++;
11011:                 @{$dirorder->{$$count}} = @{$hierarchy};
11012:                 $titles->{$$count} = $item;
11013:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11014: 
11015:                 my $is_dir;
11016:                 if ($dirptr&$testdir) {
11017:                     $is_dir = 1;
11018:                 }
11019:                 if ($wantform) {
11020:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11021:                 }
11022:                 if ($is_dir) {
11023:                     $$depth ++;
11024:                     push(@{$hierarchy},$$count);
11025:                     $parent->{$$depth} = $$count;
11026:                     $result .=
11027:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11028:                                                    $docuname,$depth,$count,
11029:                                                    $hierarchy,$dirorder,$children,
11030:                                                    $parent,$titles,$wantform);
11031:                     $$depth --;
11032:                     pop(@{$hierarchy});
11033:                 }
11034:             }
11035:         }
11036:     }
11037:     return $result;
11038: }
11039: 
11040: sub archive_hierarchy {
11041:     my ($depth,$count,$parent,$children) =@_;
11042:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11043:         if (exists($parent->{$depth})) {
11044:              $children->{$parent->{$depth}} .= $count.':';
11045:         }
11046:     }
11047:     return;
11048: }
11049: 
11050: sub archive_row {
11051:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11052:     my ($name) = ($item =~ m{([^/]+)$});
11053:     my %choices = &Apache::lonlocal::texthash (
11054:                                        'display'    => 'Add as file',
11055:                                        'dependency' => 'Include as dependency',
11056:                                        'discard'    => 'Discard',
11057:                                       );
11058:     if ($is_dir) {
11059:         $choices{'display'} = &mt('Add as folder'); 
11060:     }
11061:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11062:     my $offset = 0;
11063:     foreach my $action ('display','dependency','discard') {
11064:         $offset ++;
11065:         if ($action ne 'display') {
11066:             $offset ++;
11067:         }  
11068:         $output .= '<td><span class="LC_nobreak">'.
11069:                    '<label><input type="radio" name="archive_'.$count.
11070:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11071:         my $text = $choices{$action};
11072:         if ($is_dir) {
11073:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11074:             if ($action eq 'display') {
11075:                 $text = &mt('Add as folder');
11076:             }
11077:         } else {
11078:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11079: 
11080:         }
11081:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11082:         if ($action eq 'dependency') {
11083:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11084:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11085:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11086:                        '<option value=""></option>'."\n".
11087:                        '</select>'."\n".
11088:                        '</div>';
11089:         } elsif ($action eq 'display') {
11090:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11091:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11092:                        '</div>';
11093:         }
11094:         $output .= '</td>';
11095:     }
11096:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11097:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11098:     for (my $i=0; $i<$depth; $i++) {
11099:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11100:     }
11101:     if ($is_dir) {
11102:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11103:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11104:     } else {
11105:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11106:     }
11107:     $output .= '&nbsp;'.$name.'</td>'."\n".
11108:                &end_data_table_row();
11109:     return $output;
11110: }
11111: 
11112: sub archive_options_form {
11113:     my ($form,$display,$count,$hiddenelem) = @_;
11114:     my %lt = &Apache::lonlocal::texthash(
11115:                perm => 'Permanently remove archive file?',
11116:                hows => 'How should each extracted item be incorporated in the course?',
11117:                cont => 'Content actions for all',
11118:                addf => 'Add as folder/file',
11119:                incd => 'Include as dependency for a displayed file',
11120:                disc => 'Discard',
11121:                no   => 'No',
11122:                yes  => 'Yes',
11123:                save => 'Save',
11124:     );
11125:     my $output = <<"END";
11126: <form name="$form" method="post" action="">
11127: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11128: <label>
11129:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11130: </label>
11131: &nbsp;
11132: <label>
11133:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11134: </span>
11135: </p>
11136: <input type="hidden" name="phase" value="decompress_cleanup" />
11137: <br />$lt{'hows'}
11138: <div class="LC_columnSection">
11139:   <fieldset>
11140:     <legend>$lt{'cont'}</legend>
11141:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11142:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11143:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11144:   </fieldset>
11145: </div>
11146: END
11147:     return $output.
11148:            &start_data_table()."\n".
11149:            $display."\n".
11150:            &end_data_table()."\n".
11151:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11152:            $hiddenelem.
11153:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11154:            '</form>';
11155: }
11156: 
11157: sub archive_javascript {
11158:     my ($startcount,$numitems,$titles,$children) = @_;
11159:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11160:     my $maintitle = $env{'form.comment'};
11161:     my $scripttag = <<START;
11162: <script type="text/javascript">
11163: // <![CDATA[
11164: 
11165: function checkAll(form,prefix) {
11166:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11167:     for (var i=0; i < form.elements.length; i++) {
11168:         var id = form.elements[i].id;
11169:         if ((id != '') && (id != undefined)) {
11170:             if (idstr.test(id)) {
11171:                 if (form.elements[i].type == 'radio') {
11172:                     form.elements[i].checked = true;
11173:                     var nostart = i-$startcount;
11174:                     var offset = nostart%7;
11175:                     var count = (nostart-offset)/7;    
11176:                     dependencyCheck(form,count,offset);
11177:                 }
11178:             }
11179:         }
11180:     }
11181: }
11182: 
11183: function propagateCheck(form,count) {
11184:     if (count > 0) {
11185:         var startelement = $startcount + ((count-1) * 7);
11186:         for (var j=1; j<6; j++) {
11187:             if ((j != 2) && (j != 4)) {
11188:                 var item = startelement + j; 
11189:                 if (form.elements[item].type == 'radio') {
11190:                     if (form.elements[item].checked) {
11191:                         containerCheck(form,count,j);
11192:                         break;
11193:                     }
11194:                 }
11195:             }
11196:         }
11197:     }
11198: }
11199: 
11200: numitems = $numitems
11201: var titles = new Array(numitems);
11202: var parents = new Array(numitems);
11203: for (var i=0; i<numitems; i++) {
11204:     parents[i] = new Array;
11205: }
11206: var maintitle = '$maintitle';
11207: 
11208: START
11209: 
11210:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11211:         my @contents = split(/:/,$children->{$container});
11212:         for (my $i=0; $i<@contents; $i ++) {
11213:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11214:         }
11215:     }
11216: 
11217:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11218:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11219:     }
11220: 
11221:     $scripttag .= <<END;
11222: 
11223: function containerCheck(form,count,offset) {
11224:     if (count > 0) {
11225:         dependencyCheck(form,count,offset);
11226:         var item = (offset+$startcount)+7*(count-1);
11227:         form.elements[item].checked = true;
11228:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11229:             if (parents[count].length > 0) {
11230:                 for (var j=0; j<parents[count].length; j++) {
11231:                     containerCheck(form,parents[count][j],offset);
11232:                 }
11233:             }
11234:         }
11235:     }
11236: }
11237: 
11238: function dependencyCheck(form,count,offset) {
11239:     if (count > 0) {
11240:         var chosen = (offset+$startcount)+7*(count-1);
11241:         var depitem = $startcount + ((count-1) * 7) + 4;
11242:         var currtype = form.elements[depitem].type;
11243:         if (form.elements[chosen].value == 'dependency') {
11244:             document.getElementById('arc_depon_'+count).style.display='block'; 
11245:             form.elements[depitem].options.length = 0;
11246:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11247:             for (var i=1; i<=numitems; i++) {
11248:                 if (i == count) {
11249:                     continue;
11250:                 }
11251:                 var startelement = $startcount + (i-1) * 7;
11252:                 for (var j=1; j<6; j++) {
11253:                     if ((j != 2) && (j!= 4)) {
11254:                         var item = startelement + j;
11255:                         if (form.elements[item].type == 'radio') {
11256:                             if (form.elements[item].checked) {
11257:                                 if (form.elements[item].value == 'display') {
11258:                                     var n = form.elements[depitem].options.length;
11259:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11260:                                 }
11261:                             }
11262:                         }
11263:                     }
11264:                 }
11265:             }
11266:         } else {
11267:             document.getElementById('arc_depon_'+count).style.display='none';
11268:             form.elements[depitem].options.length = 0;
11269:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11270:         }
11271:         titleCheck(form,count,offset);
11272:     }
11273: }
11274: 
11275: function propagateSelect(form,count,offset) {
11276:     if (count > 0) {
11277:         var item = (1+offset+$startcount)+7*(count-1);
11278:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11279:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11280:             if (parents[count].length > 0) {
11281:                 for (var j=0; j<parents[count].length; j++) {
11282:                     containerSelect(form,parents[count][j],offset,picked);
11283:                 }
11284:             }
11285:         }
11286:     }
11287: }
11288: 
11289: function containerSelect(form,count,offset,picked) {
11290:     if (count > 0) {
11291:         var item = (offset+$startcount)+7*(count-1);
11292:         if (form.elements[item].type == 'radio') {
11293:             if (form.elements[item].value == 'dependency') {
11294:                 if (form.elements[item+1].type == 'select-one') {
11295:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11296:                         if (form.elements[item+1].options[i].value == picked) {
11297:                             form.elements[item+1].selectedIndex = i;
11298:                             break;
11299:                         }
11300:                     }
11301:                 }
11302:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11303:                     if (parents[count].length > 0) {
11304:                         for (var j=0; j<parents[count].length; j++) {
11305:                             containerSelect(form,parents[count][j],offset,picked);
11306:                         }
11307:                     }
11308:                 }
11309:             }
11310:         }
11311:     }
11312: }
11313: 
11314: function titleCheck(form,count,offset) {
11315:     if (count > 0) {
11316:         var chosen = (offset+$startcount)+7*(count-1);
11317:         var depitem = $startcount + ((count-1) * 7) + 2;
11318:         var currtype = form.elements[depitem].type;
11319:         if (form.elements[chosen].value == 'display') {
11320:             document.getElementById('arc_title_'+count).style.display='block';
11321:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11322:                 document.getElementById('archive_title_'+count).value=maintitle;
11323:             }
11324:         } else {
11325:             document.getElementById('arc_title_'+count).style.display='none';
11326:             if (currtype == 'text') { 
11327:                 document.getElementById('archive_title_'+count).value='';
11328:             }
11329:         }
11330:     }
11331:     return;
11332: }
11333: 
11334: // ]]>
11335: </script>
11336: END
11337:     return $scripttag;
11338: }
11339: 
11340: sub process_extracted_files {
11341:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11342:     my $numitems = $env{'form.archive_count'};
11343:     return unless ($numitems);
11344:     my @ids=&Apache::lonnet::current_machine_ids();
11345:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11346:         %folders,%containers,%mapinner,%prompttofetch);
11347:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11348:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11349:         $prefix = &LONCAPA::propath($docudom,$docuname);
11350:         $pathtocheck = "$dir_root/$destination";
11351:         $dir = $dir_root;
11352:         $ishome = 1;
11353:     } else {
11354:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11355:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11356:         $dir = "$dir_root/$docudom/$docuname";    
11357:     }
11358:     my $currdir = "$dir_root/$destination";
11359:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11360:     if ($env{'form.folderpath'}) {
11361:         my @items = split('&',$env{'form.folderpath'});
11362:         $folders{'0'} = $items[-2];
11363:         if ($env{'form.folderpath'} =~ /\:1$/) {
11364:             $containers{'0'}='page';
11365:         } else {  
11366:             $containers{'0'}='sequence';
11367:         }
11368:     }
11369:     my @archdirs = &get_env_multiple('form.archive_directory');
11370:     if ($numitems) {
11371:         for (my $i=1; $i<=$numitems; $i++) {
11372:             my $path = $env{'form.archive_content_'.$i};
11373:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11374:                 my $item = $1;
11375:                 $toplevelitems{$item} = $i;
11376:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11377:                     $is_dir{$item} = 1;
11378:                 }
11379:             }
11380:         }
11381:     }
11382:     my ($output,%children,%parent,%titles,%dirorder,$result);
11383:     if (keys(%toplevelitems) > 0) {
11384:         my @contents = sort(keys(%toplevelitems));
11385:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11386:                                            \%parent,\@contents,\%dirorder,\%titles);
11387:     }
11388:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11389:     if ($numitems) {
11390:         for (my $i=1; $i<=$numitems; $i++) {
11391:             next if ($env{'form.archive_'.$i} eq 'dependency');
11392:             my $path = $env{'form.archive_content_'.$i};
11393:             if ($path =~ /^\Q$pathtocheck\E/) {
11394:                 if ($env{'form.archive_'.$i} eq 'discard') {
11395:                     if ($prefix ne '' && $path ne '') {
11396:                         if (-e $prefix.$path) {
11397:                             if ((@archdirs > 0) && 
11398:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11399:                                 $todeletedir{$prefix.$path} = 1;
11400:                             } else {
11401:                                 $todelete{$prefix.$path} = 1;
11402:                             }
11403:                         }
11404:                     }
11405:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11406:                     my ($docstitle,$title,$url,$outer);
11407:                     ($title) = ($path =~ m{/([^/]+)$});
11408:                     $docstitle = $env{'form.archive_title_'.$i};
11409:                     if ($docstitle eq '') {
11410:                         $docstitle = $title;
11411:                     }
11412:                     $outer = 0;
11413:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11414:                         if (@{$dirorder{$i}} > 0) {
11415:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11416:                                 if ($env{'form.archive_'.$item} eq 'display') {
11417:                                     $outer = $item;
11418:                                     last;
11419:                                 }
11420:                             }
11421:                         }
11422:                     }
11423:                     my ($errtext,$fatal) = 
11424:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11425:                                                '/'.$folders{$outer}.'.'.
11426:                                                $containers{$outer});
11427:                     next if ($fatal);
11428:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11429:                         if ($context eq 'coursedocs') {
11430:                             $mapinner{$i} = time;
11431:                             $folders{$i} = 'default_'.$mapinner{$i};
11432:                             $containers{$i} = 'sequence';
11433:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11434:                                       $folders{$i}.'.'.$containers{$i};
11435:                             my $newidx = &LONCAPA::map::getresidx();
11436:                             $LONCAPA::map::resources[$newidx]=
11437:                                 $docstitle.':'.$url.':false:normal:res';
11438:                             push(@LONCAPA::map::order,$newidx);
11439:                             my ($outtext,$errtext) =
11440:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11441:                                                         $docuname.'/'.$folders{$outer}.
11442:                                                         '.'.$containers{$outer},1,1);
11443:                             $newseqid{$i} = $newidx;
11444:                             unless ($errtext) {
11445:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11446:                             }
11447:                         }
11448:                     } else {
11449:                         if ($context eq 'coursedocs') {
11450:                             my $newidx=&LONCAPA::map::getresidx();
11451:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11452:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11453:                                       $title;
11454:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11455:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11456:                             }
11457:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11458:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11459:                             }
11460:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11461:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11462:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11463:                                 unless ($ishome) {
11464:                                     my $fetch = "$newdest{$i}/$title";
11465:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11466:                                     $prompttofetch{$fetch} = 1;
11467:                                 }
11468:                             }
11469:                             $LONCAPA::map::resources[$newidx]=
11470:                                 $docstitle.':'.$url.':false:normal:res';
11471:                             push(@LONCAPA::map::order, $newidx);
11472:                             my ($outtext,$errtext)=
11473:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11474:                                                         $docuname.'/'.$folders{$outer}.
11475:                                                         '.'.$containers{$outer},1,1);
11476:                             unless ($errtext) {
11477:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11478:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11479:                                 }
11480:                             }
11481:                         }
11482:                     }
11483:                 }
11484:             } else {
11485:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11486:             }
11487:         }
11488:         for (my $i=1; $i<=$numitems; $i++) {
11489:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11490:             my $path = $env{'form.archive_content_'.$i};
11491:             if ($path =~ /^\Q$pathtocheck\E/) {
11492:                 my ($title) = ($path =~ m{/([^/]+)$});
11493:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11494:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11495:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11496:                         my ($itemidx,$fullpath,$relpath);
11497:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11498:                             my $container = $dirorder{$referrer{$i}}->[-1];
11499:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11500:                                 if ($dirorder{$i}->[$j] eq $container) {
11501:                                     $itemidx = $j;
11502:                                 }
11503:                             }
11504:                         }
11505:                         if ($itemidx eq '') {
11506:                             $itemidx =  0;
11507:                         } 
11508:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11509:                             if ($mapinner{$referrer{$i}}) {
11510:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11511:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11512:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11513:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11514:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11515:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11516:                                             if (!-e $fullpath) {
11517:                                                 mkdir($fullpath,0755);
11518:                                             }
11519:                                         }
11520:                                     } else {
11521:                                         last;
11522:                                     }
11523:                                 }
11524:                             }
11525:                         } elsif ($newdest{$referrer{$i}}) {
11526:                             $fullpath = $newdest{$referrer{$i}};
11527:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11528:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11529:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11530:                                     last;
11531:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11532:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11533:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11534:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11535:                                         if (!-e $fullpath) {
11536:                                             mkdir($fullpath,0755);
11537:                                         }
11538:                                     }
11539:                                 } else {
11540:                                     last;
11541:                                 }
11542:                             }
11543:                         }
11544:                         if ($fullpath ne '') {
11545:                             if (-e "$prefix$path") {
11546:                                 system("mv $prefix$path $fullpath/$title");
11547:                             }
11548:                             if (-e "$fullpath/$title") {
11549:                                 my $showpath;
11550:                                 if ($relpath ne '') {
11551:                                     $showpath = "$relpath/$title";
11552:                                 } else {
11553:                                     $showpath = "/$title";
11554:                                 } 
11555:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11556:                             } 
11557:                             unless ($ishome) {
11558:                                 my $fetch = "$fullpath/$title";
11559:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
11560:                                 $prompttofetch{$fetch} = 1;
11561:                             }
11562:                         }
11563:                     }
11564:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11565:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11566:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11567:                 }
11568:             } else {
11569:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11570:             }
11571:         }
11572:         if (keys(%todelete)) {
11573:             foreach my $key (keys(%todelete)) {
11574:                 unlink($key);
11575:             }
11576:         }
11577:         if (keys(%todeletedir)) {
11578:             foreach my $key (keys(%todeletedir)) {
11579:                 rmdir($key);
11580:             }
11581:         }
11582:         foreach my $dir (sort(keys(%is_dir))) {
11583:             if (($pathtocheck ne '') && ($dir ne ''))  {
11584:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11585:             }
11586:         }
11587:         if ($result ne '') {
11588:             $output .= '<ul>'."\n".
11589:                        $result."\n".
11590:                        '</ul>';
11591:         }
11592:         unless ($ishome) {
11593:             my $replicationfail;
11594:             foreach my $item (keys(%prompttofetch)) {
11595:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11596:                 unless ($fetchresult eq 'ok') {
11597:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
11598:                 }
11599:             }
11600:             if ($replicationfail) {
11601:                 $output .= '<p class="LC_error">'.
11602:                            &mt('Course home server failed to retrieve:').'<ul>'.
11603:                            $replicationfail.
11604:                            '</ul></p>';
11605:             }
11606:         }
11607:     } else {
11608:         $warning = &mt('No items found in archive.');
11609:     }
11610:     if ($error) {
11611:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11612:                    $error.'</p>'."\n";
11613:     }
11614:     if ($warning) {
11615:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11616:     }
11617:     return $output;
11618: }
11619: 
11620: sub cleanup_empty_dirs {
11621:     my ($path) = @_;
11622:     if (($path ne '') && (-d $path)) {
11623:         if (opendir(my $dirh,$path)) {
11624:             my @dircontents = grep(!/^\./,readdir($dirh));
11625:             my $numitems = 0;
11626:             foreach my $item (@dircontents) {
11627:                 if (-d "$path/$item") {
11628:                     &recurse_dirs("$path/$item");
11629:                     if (-e "$path/$item") {
11630:                         $numitems ++;
11631:                     }
11632:                 } else {
11633:                     $numitems ++;
11634:                 }
11635:             }
11636:             if ($numitems == 0) {
11637:                 rmdir($path);
11638:             }
11639:             closedir($dirh);
11640:         }
11641:     }
11642:     return;
11643: }
11644: 
11645: =pod
11646: 
11647: =item &get_folder_hierarchy()
11648: 
11649: Provides hierarchy of names of folders/sub-folders containing the current
11650: item,
11651: 
11652: Inputs: 3
11653:      - $navmap - navmaps object
11654: 
11655:      - $map - url for map (either the trigger itself, or map containing
11656:                            the resource, which is the trigger).
11657: 
11658:      - $showitem - 1 => show title for map itself; 0 => do not show.
11659: 
11660: Outputs: 1 @pathitems - array of folder/subfolder names.
11661: 
11662: =cut
11663: 
11664: sub get_folder_hierarchy {
11665:     my ($navmap,$map,$showitem) = @_;
11666:     my @pathitems;
11667:     if (ref($navmap)) {
11668:         my $mapres = $navmap->getResourceByUrl($map);
11669:         if (ref($mapres)) {
11670:             my $pcslist = $mapres->map_hierarchy();
11671:             if ($pcslist ne '') {
11672:                 my @pcs = split(/,/,$pcslist);
11673:                 foreach my $pc (@pcs) {
11674:                     if ($pc == 1) {
11675:                         push(@pathitems,&mt('Main Course Documents'));
11676:                     } else {
11677:                         my $res = $navmap->getByMapPc($pc);
11678:                         if (ref($res)) {
11679:                             my $title = $res->compTitle();
11680:                             $title =~ s/\W+/_/g;
11681:                             if ($title ne '') {
11682:                                 push(@pathitems,$title);
11683:                             }
11684:                         }
11685:                     }
11686:                 }
11687:             }
11688:             if ($showitem) {
11689:                 if ($mapres->{ID} eq '0.0') {
11690:                     push(@pathitems,&mt('Main Course Documents'));
11691:                 } else {
11692:                     my $maptitle = $mapres->compTitle();
11693:                     $maptitle =~ s/\W+/_/g;
11694:                     if ($maptitle ne '') {
11695:                         push(@pathitems,$maptitle);
11696:                     }
11697:                 }
11698:             }
11699:         }
11700:     }
11701:     return @pathitems;
11702: }
11703: 
11704: =pod
11705: 
11706: =item * &get_turnedin_filepath()
11707: 
11708: Determines path in a user's portfolio file for storage of files uploaded
11709: to a specific essayresponse or dropbox item.
11710: 
11711: Inputs: 3 required + 1 optional.
11712: $symb is symb for resource, $uname and $udom are for current user (required).
11713: $caller is optional (can be "submission", if routine is called when storing
11714: an upoaded file when "Submit Answer" button was pressed).
11715: 
11716: Returns array containing $path and $multiresp. 
11717: $path is path in portfolio.  $multiresp is 1 if this resource contains more
11718: than one file upload item.  Callers of routine should append partid as a 
11719: subdirectory to $path in cases where $multiresp is 1.
11720: 
11721: Called by: homework/essayresponse.pm and homework/structuretags.pm
11722: 
11723: =cut
11724: 
11725: sub get_turnedin_filepath {
11726:     my ($symb,$uname,$udom,$caller) = @_;
11727:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11728:     my $turnindir;
11729:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11730:     $turnindir = $userhash{'turnindir'};
11731:     my ($path,$multiresp);
11732:     if ($turnindir eq '') {
11733:         if ($caller eq 'submission') {
11734:             $turnindir = &mt('turned in');
11735:             $turnindir =~ s/\W+/_/g;
11736:             my %newhash = (
11737:                             'turnindir' => $turnindir,
11738:                           );
11739:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11740:         }
11741:     }
11742:     if ($turnindir ne '') {
11743:         $path = '/'.$turnindir.'/';
11744:         my ($multipart,$turnin,@pathitems);
11745:         my $navmap = Apache::lonnavmaps::navmap->new();
11746:         if (defined($navmap)) {
11747:             my $mapres = $navmap->getResourceByUrl($map);
11748:             if (ref($mapres)) {
11749:                 my $pcslist = $mapres->map_hierarchy();
11750:                 if ($pcslist ne '') {
11751:                     foreach my $pc (split(/,/,$pcslist)) {
11752:                         my $res = $navmap->getByMapPc($pc);
11753:                         if (ref($res)) {
11754:                             my $title = $res->compTitle();
11755:                             $title =~ s/\W+/_/g;
11756:                             if ($title ne '') {
11757:                                 push(@pathitems,$title);
11758:                             }
11759:                         }
11760:                     }
11761:                 }
11762:                 my $maptitle = $mapres->compTitle();
11763:                 $maptitle =~ s/\W+/_/g;
11764:                 if ($maptitle ne '') {
11765:                     push(@pathitems,$maptitle);
11766:                 }
11767:                 unless ($env{'request.state'} eq 'construct') {
11768:                     my $res = $navmap->getBySymb($symb);
11769:                     if (ref($res)) {
11770:                         my $partlist = $res->parts();
11771:                         my $totaluploads = 0;
11772:                         if (ref($partlist) eq 'ARRAY') {
11773:                             foreach my $part (@{$partlist}) {
11774:                                 my @types = $res->responseType($part);
11775:                                 my @ids = $res->responseIds($part);
11776:                                 for (my $i=0; $i < scalar(@ids); $i++) {
11777:                                     if ($types[$i] eq 'essay') {
11778:                                         my $partid = $part.'_'.$ids[$i];
11779:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11780:                                             $totaluploads ++;
11781:                                         }
11782:                                     }
11783:                                 }
11784:                             }
11785:                             if ($totaluploads > 1) {
11786:                                 $multiresp = 1;
11787:                             }
11788:                         }
11789:                     }
11790:                 }
11791:             } else {
11792:                 return;
11793:             }
11794:         } else {
11795:             return;
11796:         }
11797:         my $restitle=&Apache::lonnet::gettitle($symb);
11798:         $restitle =~ s/\W+/_/g;
11799:         if ($restitle eq '') {
11800:             $restitle = ($resurl =~ m{/[^/]+$});
11801:             if ($restitle eq '') {
11802:                 $restitle = time;
11803:             }
11804:         }
11805:         push(@pathitems,$restitle);
11806:         $path .= join('/',@pathitems);
11807:     }
11808:     return ($path,$multiresp);
11809: }
11810: 
11811: =pod
11812: 
11813: =back
11814: 
11815: =head1 CSV Upload/Handling functions
11816: 
11817: =over 4
11818: 
11819: =item * &upfile_store($r)
11820: 
11821: Store uploaded file, $r should be the HTTP Request object,
11822: needs $env{'form.upfile'}
11823: returns $datatoken to be put into hidden field
11824: 
11825: =cut
11826: 
11827: sub upfile_store {
11828:     my $r=shift;
11829:     $env{'form.upfile'}=~s/\r/\n/gs;
11830:     $env{'form.upfile'}=~s/\f/\n/gs;
11831:     $env{'form.upfile'}=~s/\n+/\n/gs;
11832:     $env{'form.upfile'}=~s/\n+$//gs;
11833: 
11834:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11835: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11836:     {
11837:         my $datafile = $r->dir_config('lonDaemons').
11838:                            '/tmp/'.$datatoken.'.tmp';
11839:         if ( open(my $fh,">$datafile") ) {
11840:             print $fh $env{'form.upfile'};
11841:             close($fh);
11842:         }
11843:     }
11844:     return $datatoken;
11845: }
11846: 
11847: =pod
11848: 
11849: =item * &load_tmp_file($r)
11850: 
11851: Load uploaded file from tmp, $r should be the HTTP Request object,
11852: needs $env{'form.datatoken'},
11853: sets $env{'form.upfile'} to the contents of the file
11854: 
11855: =cut
11856: 
11857: sub load_tmp_file {
11858:     my $r=shift;
11859:     my @studentdata=();
11860:     {
11861:         my $studentfile = $r->dir_config('lonDaemons').
11862:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
11863:         if ( open(my $fh,"<$studentfile") ) {
11864:             @studentdata=<$fh>;
11865:             close($fh);
11866:         }
11867:     }
11868:     $env{'form.upfile'}=join('',@studentdata);
11869: }
11870: 
11871: =pod
11872: 
11873: =item * &upfile_record_sep()
11874: 
11875: Separate uploaded file into records
11876: returns array of records,
11877: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11878: 
11879: =cut
11880: 
11881: sub upfile_record_sep {
11882:     if ($env{'form.upfiletype'} eq 'xml') {
11883:     } else {
11884: 	my @records;
11885: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
11886: 	    if ($line=~/^\s*$/) { next; }
11887: 	    push(@records,$line);
11888: 	}
11889: 	return @records;
11890:     }
11891: }
11892: 
11893: =pod
11894: 
11895: =item * &record_sep($record)
11896: 
11897: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11898: 
11899: =cut
11900: 
11901: sub takeleft {
11902:     my $index=shift;
11903:     return substr('0000'.$index,-4,4);
11904: }
11905: 
11906: sub record_sep {
11907:     my $record=shift;
11908:     my %components=();
11909:     if ($env{'form.upfiletype'} eq 'xml') {
11910:     } elsif ($env{'form.upfiletype'} eq 'space') {
11911:         my $i=0;
11912:         foreach my $field (split(/\s+/,$record)) {
11913:             $field=~s/^(\"|\')//;
11914:             $field=~s/(\"|\')$//;
11915:             $components{&takeleft($i)}=$field;
11916:             $i++;
11917:         }
11918:     } elsif ($env{'form.upfiletype'} eq 'tab') {
11919:         my $i=0;
11920:         foreach my $field (split(/\t/,$record)) {
11921:             $field=~s/^(\"|\')//;
11922:             $field=~s/(\"|\')$//;
11923:             $components{&takeleft($i)}=$field;
11924:             $i++;
11925:         }
11926:     } else {
11927:         my $separator=',';
11928:         if ($env{'form.upfiletype'} eq 'semisv') {
11929:             $separator=';';
11930:         }
11931:         my $i=0;
11932: # the character we are looking for to indicate the end of a quote or a record 
11933:         my $looking_for=$separator;
11934: # do not add the characters to the fields
11935:         my $ignore=0;
11936: # we just encountered a separator (or the beginning of the record)
11937:         my $just_found_separator=1;
11938: # store the field we are working on here
11939:         my $field='';
11940: # work our way through all characters in record
11941:         foreach my $character ($record=~/(.)/g) {
11942:             if ($character eq $looking_for) {
11943:                if ($character ne $separator) {
11944: # Found the end of a quote, again looking for separator
11945:                   $looking_for=$separator;
11946:                   $ignore=1;
11947:                } else {
11948: # Found a separator, store away what we got
11949:                   $components{&takeleft($i)}=$field;
11950: 	          $i++;
11951:                   $just_found_separator=1;
11952:                   $ignore=0;
11953:                   $field='';
11954:                }
11955:                next;
11956:             }
11957: # single or double quotation marks after a separator indicate beginning of a quote
11958: # we are now looking for the end of the quote and need to ignore separators
11959:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
11960:                $looking_for=$character;
11961:                next;
11962:             }
11963: # ignore would be true after we reached the end of a quote
11964:             if ($ignore) { next; }
11965:             if (($just_found_separator) && ($character=~/\s/)) { next; }
11966:             $field.=$character;
11967:             $just_found_separator=0; 
11968:         }
11969: # catch the very last entry, since we never encountered the separator
11970:         $components{&takeleft($i)}=$field;
11971:     }
11972:     return %components;
11973: }
11974: 
11975: ######################################################
11976: ######################################################
11977: 
11978: =pod
11979: 
11980: =item * &upfile_select_html()
11981: 
11982: Return HTML code to select a file from the users machine and specify 
11983: the file type.
11984: 
11985: =cut
11986: 
11987: ######################################################
11988: ######################################################
11989: sub upfile_select_html {
11990:     my %Types = (
11991:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
11992:                  semisv => &mt('Semicolon separated values'),
11993:                  space => &mt('Space separated'),
11994:                  tab   => &mt('Tabulator separated'),
11995: #                 xml   => &mt('HTML/XML'),
11996:                  );
11997:     my $Str = '<input type="file" name="upfile" size="50" />'.
11998:         '<br />'.&mt('Type').': <select name="upfiletype">';
11999:     foreach my $type (sort(keys(%Types))) {
12000:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12001:     }
12002:     $Str .= "</select>\n";
12003:     return $Str;
12004: }
12005: 
12006: sub get_samples {
12007:     my ($records,$toget) = @_;
12008:     my @samples=({});
12009:     my $got=0;
12010:     foreach my $rec (@$records) {
12011: 	my %temp = &record_sep($rec);
12012: 	if (! grep(/\S/, values(%temp))) { next; }
12013: 	if (%temp) {
12014: 	    $samples[$got]=\%temp;
12015: 	    $got++;
12016: 	    if ($got == $toget) { last; }
12017: 	}
12018:     }
12019:     return \@samples;
12020: }
12021: 
12022: ######################################################
12023: ######################################################
12024: 
12025: =pod
12026: 
12027: =item * &csv_print_samples($r,$records)
12028: 
12029: Prints a table of sample values from each column uploaded $r is an
12030: Apache Request ref, $records is an arrayref from
12031: &Apache::loncommon::upfile_record_sep
12032: 
12033: =cut
12034: 
12035: ######################################################
12036: ######################################################
12037: sub csv_print_samples {
12038:     my ($r,$records) = @_;
12039:     my $samples = &get_samples($records,5);
12040: 
12041:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12042:               &start_data_table_header_row());
12043:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12044:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12045:     $r->print(&end_data_table_header_row());
12046:     foreach my $hash (@$samples) {
12047: 	$r->print(&start_data_table_row());
12048: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12049: 	    $r->print('<td>');
12050: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12051: 	    $r->print('</td>');
12052: 	}
12053: 	$r->print(&end_data_table_row());
12054:     }
12055:     $r->print(&end_data_table().'<br />'."\n");
12056: }
12057: 
12058: ######################################################
12059: ######################################################
12060: 
12061: =pod
12062: 
12063: =item * &csv_print_select_table($r,$records,$d)
12064: 
12065: Prints a table to create associations between values and table columns.
12066: 
12067: $r is an Apache Request ref,
12068: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12069: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12070: 
12071: =cut
12072: 
12073: ######################################################
12074: ######################################################
12075: sub csv_print_select_table {
12076:     my ($r,$records,$d) = @_;
12077:     my $i=0;
12078:     my $samples = &get_samples($records,1);
12079:     $r->print(&mt('Associate columns with student attributes.')."\n".
12080: 	      &start_data_table().&start_data_table_header_row().
12081:               '<th>'.&mt('Attribute').'</th>'.
12082:               '<th>'.&mt('Column').'</th>'.
12083:               &end_data_table_header_row()."\n");
12084:     foreach my $array_ref (@$d) {
12085: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12086: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12087: 
12088: 	$r->print('<td><select name="f'.$i.'"'.
12089: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12090: 	$r->print('<option value="none"></option>');
12091: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12092: 	    $r->print('<option value="'.$sample.'"'.
12093:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12094:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12095: 	}
12096: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12097: 	$i++;
12098:     }
12099:     $r->print(&end_data_table());
12100:     $i--;
12101:     return $i;
12102: }
12103: 
12104: ######################################################
12105: ######################################################
12106: 
12107: =pod
12108: 
12109: =item * &csv_samples_select_table($r,$records,$d)
12110: 
12111: Prints a table of sample values from the upload and can make associate samples to internal names.
12112: 
12113: $r is an Apache Request ref,
12114: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12115: $d is an array of 2 element arrays (internal name, displayed name)
12116: 
12117: =cut
12118: 
12119: ######################################################
12120: ######################################################
12121: sub csv_samples_select_table {
12122:     my ($r,$records,$d) = @_;
12123:     my $i=0;
12124:     #
12125:     my $max_samples = 5;
12126:     my $samples = &get_samples($records,$max_samples);
12127:     $r->print(&start_data_table().
12128:               &start_data_table_header_row().'<th>'.
12129:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12130:               &end_data_table_header_row());
12131: 
12132:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12133: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12134: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12135: 	foreach my $option (@$d) {
12136: 	    my ($value,$display,$defaultcol)=@{ $option };
12137: 	    $r->print('<option value="'.$value.'"'.
12138:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12139:                       $display.'</option>');
12140: 	}
12141: 	$r->print('</select></td><td>');
12142: 	foreach my $line (0..($max_samples-1)) {
12143: 	    if (defined($samples->[$line]{$key})) { 
12144: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12145: 	    }
12146: 	}
12147: 	$r->print('</td>'.&end_data_table_row());
12148: 	$i++;
12149:     }
12150:     $r->print(&end_data_table());
12151:     $i--;
12152:     return($i);
12153: }
12154: 
12155: ######################################################
12156: ######################################################
12157: 
12158: =pod
12159: 
12160: =item * &clean_excel_name($name)
12161: 
12162: Returns a replacement for $name which does not contain any illegal characters.
12163: 
12164: =cut
12165: 
12166: ######################################################
12167: ######################################################
12168: sub clean_excel_name {
12169:     my ($name) = @_;
12170:     $name =~ s/[:\*\?\/\\]//g;
12171:     if (length($name) > 31) {
12172:         $name = substr($name,0,31);
12173:     }
12174:     return $name;
12175: }
12176: 
12177: =pod
12178: 
12179: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12180: 
12181: Returns either 1 or undef
12182: 
12183: 1 if the part is to be hidden, undef if it is to be shown
12184: 
12185: Arguments are:
12186: 
12187: $id the id of the part to be checked
12188: $symb, optional the symb of the resource to check
12189: $udom, optional the domain of the user to check for
12190: $uname, optional the username of the user to check for
12191: 
12192: =cut
12193: 
12194: sub check_if_partid_hidden {
12195:     my ($id,$symb,$udom,$uname) = @_;
12196:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12197: 					 $symb,$udom,$uname);
12198:     my $truth=1;
12199:     #if the string starts with !, then the list is the list to show not hide
12200:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12201:     my @hiddenlist=split(/,/,$hiddenparts);
12202:     foreach my $checkid (@hiddenlist) {
12203: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12204:     }
12205:     return !$truth;
12206: }
12207: 
12208: 
12209: ############################################################
12210: ############################################################
12211: 
12212: =pod
12213: 
12214: =back 
12215: 
12216: =head1 cgi-bin script and graphing routines
12217: 
12218: =over 4
12219: 
12220: =item * &get_cgi_id()
12221: 
12222: Inputs: none
12223: 
12224: Returns an id which can be used to pass environment variables
12225: to various cgi-bin scripts.  These environment variables will
12226: be removed from the users environment after a given time by
12227: the routine &Apache::lonnet::transfer_profile_to_env.
12228: 
12229: =cut
12230: 
12231: ############################################################
12232: ############################################################
12233: my $uniq=0;
12234: sub get_cgi_id {
12235:     $uniq=($uniq+1)%100000;
12236:     return (time.'_'.$$.'_'.$uniq);
12237: }
12238: 
12239: ############################################################
12240: ############################################################
12241: 
12242: =pod
12243: 
12244: =item * &DrawBarGraph()
12245: 
12246: Facilitates the plotting of data in a (stacked) bar graph.
12247: Puts plot definition data into the users environment in order for 
12248: graph.png to plot it.  Returns an <img> tag for the plot.
12249: The bars on the plot are labeled '1','2',...,'n'.
12250: 
12251: Inputs:
12252: 
12253: =over 4
12254: 
12255: =item $Title: string, the title of the plot
12256: 
12257: =item $xlabel: string, text describing the X-axis of the plot
12258: 
12259: =item $ylabel: string, text describing the Y-axis of the plot
12260: 
12261: =item $Max: scalar, the maximum Y value to use in the plot
12262: If $Max is < any data point, the graph will not be rendered.
12263: 
12264: =item $colors: array ref holding the colors to be used for the data sets when
12265: they are plotted.  If undefined, default values will be used.
12266: 
12267: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12268: 
12269: =item @Values: An array of array references.  Each array reference holds data
12270: to be plotted in a stacked bar chart.
12271: 
12272: =item If the final element of @Values is a hash reference the key/value
12273: pairs will be added to the graph definition.
12274: 
12275: =back
12276: 
12277: Returns:
12278: 
12279: An <img> tag which references graph.png and the appropriate identifying
12280: information for the plot.
12281: 
12282: =cut
12283: 
12284: ############################################################
12285: ############################################################
12286: sub DrawBarGraph {
12287:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12288:     #
12289:     if (! defined($colors)) {
12290:         $colors = ['#33ff00', 
12291:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12292:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12293:                   ]; 
12294:     }
12295:     my $extra_settings = {};
12296:     if (ref($Values[-1]) eq 'HASH') {
12297:         $extra_settings = pop(@Values);
12298:     }
12299:     #
12300:     my $identifier = &get_cgi_id();
12301:     my $id = 'cgi.'.$identifier;        
12302:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12303:         return '';
12304:     }
12305:     #
12306:     my @Labels;
12307:     if (defined($labels)) {
12308:         @Labels = @$labels;
12309:     } else {
12310:         for (my $i=0;$i<@{$Values[0]};$i++) {
12311:             push (@Labels,$i+1);
12312:         }
12313:     }
12314:     #
12315:     my $NumBars = scalar(@{$Values[0]});
12316:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12317:     my %ValuesHash;
12318:     my $NumSets=1;
12319:     foreach my $array (@Values) {
12320:         next if (! ref($array));
12321:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12322:             join(',',@$array);
12323:     }
12324:     #
12325:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12326:     if ($NumBars < 3) {
12327:         $width = 120+$NumBars*32;
12328:         $xskip = 1;
12329:         $bar_width = 30;
12330:     } elsif ($NumBars < 5) {
12331:         $width = 120+$NumBars*20;
12332:         $xskip = 1;
12333:         $bar_width = 20;
12334:     } elsif ($NumBars < 10) {
12335:         $width = 120+$NumBars*15;
12336:         $xskip = 1;
12337:         $bar_width = 15;
12338:     } elsif ($NumBars <= 25) {
12339:         $width = 120+$NumBars*11;
12340:         $xskip = 5;
12341:         $bar_width = 8;
12342:     } elsif ($NumBars <= 50) {
12343:         $width = 120+$NumBars*8;
12344:         $xskip = 5;
12345:         $bar_width = 4;
12346:     } else {
12347:         $width = 120+$NumBars*8;
12348:         $xskip = 5;
12349:         $bar_width = 4;
12350:     }
12351:     #
12352:     $Max = 1 if ($Max < 1);
12353:     if ( int($Max) < $Max ) {
12354:         $Max++;
12355:         $Max = int($Max);
12356:     }
12357:     $Title  = '' if (! defined($Title));
12358:     $xlabel = '' if (! defined($xlabel));
12359:     $ylabel = '' if (! defined($ylabel));
12360:     $ValuesHash{$id.'.title'}    = &escape($Title);
12361:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12362:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12363:     $ValuesHash{$id.'.y_max_value'} = $Max;
12364:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12365:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12366:     $ValuesHash{$id.'.PlotType'} = 'bar';
12367:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12368:     $ValuesHash{$id.'.height'}   = $height;
12369:     $ValuesHash{$id.'.width'}    = $width;
12370:     $ValuesHash{$id.'.xskip'}    = $xskip;
12371:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12372:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12373:     #
12374:     # Deal with other parameters
12375:     while (my ($key,$value) = each(%$extra_settings)) {
12376:         $ValuesHash{$id.'.'.$key} = $value;
12377:     }
12378:     #
12379:     &Apache::lonnet::appenv(\%ValuesHash);
12380:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12381: }
12382: 
12383: ############################################################
12384: ############################################################
12385: 
12386: =pod
12387: 
12388: =item * &DrawXYGraph()
12389: 
12390: Facilitates the plotting of data in an XY graph.
12391: Puts plot definition data into the users environment in order for 
12392: graph.png to plot it.  Returns an <img> tag for the plot.
12393: 
12394: Inputs:
12395: 
12396: =over 4
12397: 
12398: =item $Title: string, the title of the plot
12399: 
12400: =item $xlabel: string, text describing the X-axis of the plot
12401: 
12402: =item $ylabel: string, text describing the Y-axis of the plot
12403: 
12404: =item $Max: scalar, the maximum Y value to use in the plot
12405: If $Max is < any data point, the graph will not be rendered.
12406: 
12407: =item $colors: Array ref containing the hex color codes for the data to be 
12408: plotted in.  If undefined, default values will be used.
12409: 
12410: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12411: 
12412: =item $Ydata: Array ref containing Array refs.  
12413: Each of the contained arrays will be plotted as a separate curve.
12414: 
12415: =item %Values: hash indicating or overriding any default values which are 
12416: passed to graph.png.  
12417: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12418: 
12419: =back
12420: 
12421: Returns:
12422: 
12423: An <img> tag which references graph.png and the appropriate identifying
12424: information for the plot.
12425: 
12426: =cut
12427: 
12428: ############################################################
12429: ############################################################
12430: sub DrawXYGraph {
12431:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12432:     #
12433:     # Create the identifier for the graph
12434:     my $identifier = &get_cgi_id();
12435:     my $id = 'cgi.'.$identifier;
12436:     #
12437:     $Title  = '' if (! defined($Title));
12438:     $xlabel = '' if (! defined($xlabel));
12439:     $ylabel = '' if (! defined($ylabel));
12440:     my %ValuesHash = 
12441:         (
12442:          $id.'.title'  => &escape($Title),
12443:          $id.'.xlabel' => &escape($xlabel),
12444:          $id.'.ylabel' => &escape($ylabel),
12445:          $id.'.y_max_value'=> $Max,
12446:          $id.'.labels'     => join(',',@$Xlabels),
12447:          $id.'.PlotType'   => 'XY',
12448:          );
12449:     #
12450:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12451:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12452:     }
12453:     #
12454:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12455:         return '';
12456:     }
12457:     my $NumSets=1;
12458:     foreach my $array (@{$Ydata}){
12459:         next if (! ref($array));
12460:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12461:     }
12462:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12463:     #
12464:     # Deal with other parameters
12465:     while (my ($key,$value) = each(%Values)) {
12466:         $ValuesHash{$id.'.'.$key} = $value;
12467:     }
12468:     #
12469:     &Apache::lonnet::appenv(\%ValuesHash);
12470:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12471: }
12472: 
12473: ############################################################
12474: ############################################################
12475: 
12476: =pod
12477: 
12478: =item * &DrawXYYGraph()
12479: 
12480: Facilitates the plotting of data in an XY graph with two Y axes.
12481: Puts plot definition data into the users environment in order for 
12482: graph.png to plot it.  Returns an <img> tag for the plot.
12483: 
12484: Inputs:
12485: 
12486: =over 4
12487: 
12488: =item $Title: string, the title of the plot
12489: 
12490: =item $xlabel: string, text describing the X-axis of the plot
12491: 
12492: =item $ylabel: string, text describing the Y-axis of the plot
12493: 
12494: =item $colors: Array ref containing the hex color codes for the data to be 
12495: plotted in.  If undefined, default values will be used.
12496: 
12497: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12498: 
12499: =item $Ydata1: The first data set
12500: 
12501: =item $Min1: The minimum value of the left Y-axis
12502: 
12503: =item $Max1: The maximum value of the left Y-axis
12504: 
12505: =item $Ydata2: The second data set
12506: 
12507: =item $Min2: The minimum value of the right Y-axis
12508: 
12509: =item $Max2: The maximum value of the left Y-axis
12510: 
12511: =item %Values: hash indicating or overriding any default values which are 
12512: passed to graph.png.  
12513: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12514: 
12515: =back
12516: 
12517: Returns:
12518: 
12519: An <img> tag which references graph.png and the appropriate identifying
12520: information for the plot.
12521: 
12522: =cut
12523: 
12524: ############################################################
12525: ############################################################
12526: sub DrawXYYGraph {
12527:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12528:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12529:     #
12530:     # Create the identifier for the graph
12531:     my $identifier = &get_cgi_id();
12532:     my $id = 'cgi.'.$identifier;
12533:     #
12534:     $Title  = '' if (! defined($Title));
12535:     $xlabel = '' if (! defined($xlabel));
12536:     $ylabel = '' if (! defined($ylabel));
12537:     my %ValuesHash = 
12538:         (
12539:          $id.'.title'  => &escape($Title),
12540:          $id.'.xlabel' => &escape($xlabel),
12541:          $id.'.ylabel' => &escape($ylabel),
12542:          $id.'.labels' => join(',',@$Xlabels),
12543:          $id.'.PlotType' => 'XY',
12544:          $id.'.NumSets' => 2,
12545:          $id.'.two_axes' => 1,
12546:          $id.'.y1_max_value' => $Max1,
12547:          $id.'.y1_min_value' => $Min1,
12548:          $id.'.y2_max_value' => $Max2,
12549:          $id.'.y2_min_value' => $Min2,
12550:          );
12551:     #
12552:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12553:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12554:     }
12555:     #
12556:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12557:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12558:         return '';
12559:     }
12560:     my $NumSets=1;
12561:     foreach my $array ($Ydata1,$Ydata2){
12562:         next if (! ref($array));
12563:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12564:     }
12565:     #
12566:     # Deal with other parameters
12567:     while (my ($key,$value) = each(%Values)) {
12568:         $ValuesHash{$id.'.'.$key} = $value;
12569:     }
12570:     #
12571:     &Apache::lonnet::appenv(\%ValuesHash);
12572:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12573: }
12574: 
12575: ############################################################
12576: ############################################################
12577: 
12578: =pod
12579: 
12580: =back 
12581: 
12582: =head1 Statistics helper routines?  
12583: 
12584: Bad place for them but what the hell.
12585: 
12586: =over 4
12587: 
12588: =item * &chartlink()
12589: 
12590: Returns a link to the chart for a specific student.  
12591: 
12592: Inputs:
12593: 
12594: =over 4
12595: 
12596: =item $linktext: The text of the link
12597: 
12598: =item $sname: The students username
12599: 
12600: =item $sdomain: The students domain
12601: 
12602: =back
12603: 
12604: =back
12605: 
12606: =cut
12607: 
12608: ############################################################
12609: ############################################################
12610: sub chartlink {
12611:     my ($linktext, $sname, $sdomain) = @_;
12612:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12613:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
12614:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
12615:        '">'.$linktext.'</a>';
12616: }
12617: 
12618: #######################################################
12619: #######################################################
12620: 
12621: =pod
12622: 
12623: =head1 Course Environment Routines
12624: 
12625: =over 4
12626: 
12627: =item * &restore_course_settings()
12628: 
12629: =item * &store_course_settings()
12630: 
12631: Restores/Store indicated form parameters from the course environment.
12632: Will not overwrite existing values of the form parameters.
12633: 
12634: Inputs: 
12635: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12636: 
12637: a hash ref describing the data to be stored.  For example:
12638:    
12639: %Save_Parameters = ('Status' => 'scalar',
12640:     'chartoutputmode' => 'scalar',
12641:     'chartoutputdata' => 'scalar',
12642:     'Section' => 'array',
12643:     'Group' => 'array',
12644:     'StudentData' => 'array',
12645:     'Maps' => 'array');
12646: 
12647: Returns: both routines return nothing
12648: 
12649: =back
12650: 
12651: =cut
12652: 
12653: #######################################################
12654: #######################################################
12655: sub store_course_settings {
12656:     return &store_settings($env{'request.course.id'},@_);
12657: }
12658: 
12659: sub store_settings {
12660:     # save to the environment
12661:     # appenv the same items, just to be safe
12662:     my $udom  = $env{'user.domain'};
12663:     my $uname = $env{'user.name'};
12664:     my ($context,$prefix,$Settings) = @_;
12665:     my %SaveHash;
12666:     my %AppHash;
12667:     while (my ($setting,$type) = each(%$Settings)) {
12668:         my $basename = join('.','internal',$context,$prefix,$setting);
12669:         my $envname = 'environment.'.$basename;
12670:         if (exists($env{'form.'.$setting})) {
12671:             # Save this value away
12672:             if ($type eq 'scalar' &&
12673:                 (! exists($env{$envname}) || 
12674:                  $env{$envname} ne $env{'form.'.$setting})) {
12675:                 $SaveHash{$basename} = $env{'form.'.$setting};
12676:                 $AppHash{$envname}   = $env{'form.'.$setting};
12677:             } elsif ($type eq 'array') {
12678:                 my $stored_form;
12679:                 if (ref($env{'form.'.$setting})) {
12680:                     $stored_form = join(',',
12681:                                         map {
12682:                                             &escape($_);
12683:                                         } sort(@{$env{'form.'.$setting}}));
12684:                 } else {
12685:                     $stored_form = 
12686:                         &escape($env{'form.'.$setting});
12687:                 }
12688:                 # Determine if the array contents are the same.
12689:                 if ($stored_form ne $env{$envname}) {
12690:                     $SaveHash{$basename} = $stored_form;
12691:                     $AppHash{$envname}   = $stored_form;
12692:                 }
12693:             }
12694:         }
12695:     }
12696:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12697:                                           $udom,$uname);
12698:     if ($put_result !~ /^(ok|delayed)/) {
12699:         &Apache::lonnet::logthis('unable to save form parameters, '.
12700:                                  'got error:'.$put_result);
12701:     }
12702:     # Make sure these settings stick around in this session, too
12703:     &Apache::lonnet::appenv(\%AppHash);
12704:     return;
12705: }
12706: 
12707: sub restore_course_settings {
12708:     return &restore_settings($env{'request.course.id'},@_);
12709: }
12710: 
12711: sub restore_settings {
12712:     my ($context,$prefix,$Settings) = @_;
12713:     while (my ($setting,$type) = each(%$Settings)) {
12714:         next if (exists($env{'form.'.$setting}));
12715:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
12716:             '.'.$setting;
12717:         if (exists($env{$envname})) {
12718:             if ($type eq 'scalar') {
12719:                 $env{'form.'.$setting} = $env{$envname};
12720:             } elsif ($type eq 'array') {
12721:                 $env{'form.'.$setting} = [ 
12722:                                            map { 
12723:                                                &unescape($_); 
12724:                                            } split(',',$env{$envname})
12725:                                            ];
12726:             }
12727:         }
12728:     }
12729: }
12730: 
12731: #######################################################
12732: #######################################################
12733: 
12734: =pod
12735: 
12736: =head1 Domain E-mail Routines  
12737: 
12738: =over 4
12739: 
12740: =item * &build_recipient_list()
12741: 
12742: Build recipient lists for five types of e-mail:
12743: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12744: (d) Help requests, (e) Course requests needing approval,  generated by
12745: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12746: loncoursequeueadmin.pm respectively.
12747: 
12748: Inputs:
12749: defmail (scalar - email address of default recipient), 
12750: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
12751: defdom (domain for which to retrieve configuration settings),
12752: origmail (scalar - email address of recipient from loncapa.conf, 
12753: i.e., predates configuration by DC via domainprefs.pm 
12754: 
12755: Returns: comma separated list of addresses to which to send e-mail.
12756: 
12757: =back
12758: 
12759: =cut
12760: 
12761: ############################################################
12762: ############################################################
12763: sub build_recipient_list {
12764:     my ($defmail,$mailing,$defdom,$origmail) = @_;
12765:     my @recipients;
12766:     my $otheremails;
12767:     my %domconfig =
12768:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12769:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12770:         if (exists($domconfig{'contacts'}{$mailing})) {
12771:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12772:                 my @contacts = ('adminemail','supportemail');
12773:                 foreach my $item (@contacts) {
12774:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
12775:                         my $addr = $domconfig{'contacts'}{$item}; 
12776:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
12777:                             push(@recipients,$addr);
12778:                         }
12779:                     }
12780:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12781:                 }
12782:             }
12783:         } elsif ($origmail ne '') {
12784:             push(@recipients,$origmail);
12785:         }
12786:     } elsif ($origmail ne '') {
12787:         push(@recipients,$origmail);
12788:     }
12789:     if (defined($defmail)) {
12790:         if ($defmail ne '') {
12791:             push(@recipients,$defmail);
12792:         }
12793:     }
12794:     if ($otheremails) {
12795:         my @others;
12796:         if ($otheremails =~ /,/) {
12797:             @others = split(/,/,$otheremails);
12798:         } else {
12799:             push(@others,$otheremails);
12800:         }
12801:         foreach my $addr (@others) {
12802:             if (!grep(/^\Q$addr\E$/,@recipients)) {
12803:                 push(@recipients,$addr);
12804:             }
12805:         }
12806:     }
12807:     my $recipientlist = join(',',@recipients); 
12808:     return $recipientlist;
12809: }
12810: 
12811: ############################################################
12812: ############################################################
12813: 
12814: =pod
12815: 
12816: =head1 Course Catalog Routines
12817: 
12818: =over 4
12819: 
12820: =item * &gather_categories()
12821: 
12822: Converts category definitions - keys of categories hash stored in  
12823: coursecategories in configuration.db on the primary library server in a 
12824: domain - to an array.  Also generates javascript and idx hash used to 
12825: generate Domain Coordinator interface for editing Course Categories.
12826: 
12827: Inputs:
12828: 
12829: categories (reference to hash of category definitions).
12830: 
12831: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12832:       categories and subcategories).
12833: 
12834: idx (reference to hash of counters used in Domain Coordinator interface for 
12835:       editing Course Categories).
12836: 
12837: jsarray (reference to array of categories used to create Javascript arrays for
12838:          Domain Coordinator interface for editing Course Categories).
12839: 
12840: Returns: nothing
12841: 
12842: Side effects: populates cats, idx and jsarray. 
12843: 
12844: =cut
12845: 
12846: sub gather_categories {
12847:     my ($categories,$cats,$idx,$jsarray) = @_;
12848:     my %counters;
12849:     my $num = 0;
12850:     foreach my $item (keys(%{$categories})) {
12851:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12852:         if ($container eq '' && $depth == 0) {
12853:             $cats->[$depth][$categories->{$item}] = $cat;
12854:         } else {
12855:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12856:         }
12857:         my ($escitem,$tail) = split(/:/,$item,2);
12858:         if ($counters{$tail} eq '') {
12859:             $counters{$tail} = $num;
12860:             $num ++;
12861:         }
12862:         if (ref($idx) eq 'HASH') {
12863:             $idx->{$item} = $counters{$tail};
12864:         }
12865:         if (ref($jsarray) eq 'ARRAY') {
12866:             push(@{$jsarray->[$counters{$tail}]},$item);
12867:         }
12868:     }
12869:     return;
12870: }
12871: 
12872: =pod
12873: 
12874: =item * &extract_categories()
12875: 
12876: Used to generate breadcrumb trails for course categories.
12877: 
12878: Inputs:
12879: 
12880: categories (reference to hash of category definitions).
12881: 
12882: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12883:       categories and subcategories).
12884: 
12885: trails (reference to array of breacrumb trails for each category).
12886: 
12887: allitems (reference to hash - key is category key 
12888:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12889: 
12890: idx (reference to hash of counters used in Domain Coordinator interface for
12891:       editing Course Categories).
12892: 
12893: jsarray (reference to array of categories used to create Javascript arrays for
12894:          Domain Coordinator interface for editing Course Categories).
12895: 
12896: subcats (reference to hash of arrays containing all subcategories within each 
12897:          category, -recursive)
12898: 
12899: Returns: nothing
12900: 
12901: Side effects: populates trails and allitems hash references.
12902: 
12903: =cut
12904: 
12905: sub extract_categories {
12906:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12907:     if (ref($categories) eq 'HASH') {
12908:         &gather_categories($categories,$cats,$idx,$jsarray);
12909:         if (ref($cats->[0]) eq 'ARRAY') {
12910:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
12911:                 my $name = $cats->[0][$i];
12912:                 my $item = &escape($name).'::0';
12913:                 my $trailstr;
12914:                 if ($name eq 'instcode') {
12915:                     $trailstr = &mt('Official courses (with institutional codes)');
12916:                 } elsif ($name eq 'communities') {
12917:                     $trailstr = &mt('Communities');
12918:                 } else {
12919:                     $trailstr = $name;
12920:                 }
12921:                 if ($allitems->{$item} eq '') {
12922:                     push(@{$trails},$trailstr);
12923:                     $allitems->{$item} = scalar(@{$trails})-1;
12924:                 }
12925:                 my @parents = ($name);
12926:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
12927:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12928:                         my $category = $cats->[1]{$name}[$j];
12929:                         if (ref($subcats) eq 'HASH') {
12930:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12931:                         }
12932:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12933:                     }
12934:                 } else {
12935:                     if (ref($subcats) eq 'HASH') {
12936:                         $subcats->{$item} = [];
12937:                     }
12938:                 }
12939:             }
12940:         }
12941:     }
12942:     return;
12943: }
12944: 
12945: =pod
12946: 
12947: =item *&recurse_categories()
12948: 
12949: Recursively used to generate breadcrumb trails for course categories.
12950: 
12951: Inputs:
12952: 
12953: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12954:       categories and subcategories).
12955: 
12956: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12957: 
12958: category (current course category, for which breadcrumb trail is being generated).
12959: 
12960: trails (reference to array of breadcrumb trails for each category).
12961: 
12962: allitems (reference to hash - key is category key
12963:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12964: 
12965: parents (array containing containers directories for current category, 
12966:          back to top level). 
12967: 
12968: Returns: nothing
12969: 
12970: Side effects: populates trails and allitems hash references
12971: 
12972: =cut
12973: 
12974: sub recurse_categories {
12975:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12976:     my $shallower = $depth - 1;
12977:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12978:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12979:             my $name = $cats->[$depth]{$category}[$k];
12980:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12981:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
12982:             if ($allitems->{$item} eq '') {
12983:                 push(@{$trails},$trailstr);
12984:                 $allitems->{$item} = scalar(@{$trails})-1;
12985:             }
12986:             my $deeper = $depth+1;
12987:             push(@{$parents},$category);
12988:             if (ref($subcats) eq 'HASH') {
12989:                 my $subcat = &escape($name).':'.$category.':'.$depth;
12990:                 for (my $j=@{$parents}; $j>=0; $j--) {
12991:                     my $higher;
12992:                     if ($j > 0) {
12993:                         $higher = &escape($parents->[$j]).':'.
12994:                                   &escape($parents->[$j-1]).':'.$j;
12995:                     } else {
12996:                         $higher = &escape($parents->[$j]).'::'.$j;
12997:                     }
12998:                     push(@{$subcats->{$higher}},$subcat);
12999:                 }
13000:             }
13001:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13002:                                 $subcats);
13003:             pop(@{$parents});
13004:         }
13005:     } else {
13006:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13007:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13008:         if ($allitems->{$item} eq '') {
13009:             push(@{$trails},$trailstr);
13010:             $allitems->{$item} = scalar(@{$trails})-1;
13011:         }
13012:     }
13013:     return;
13014: }
13015: 
13016: =pod
13017: 
13018: =item *&assign_categories_table()
13019: 
13020: Create a datatable for display of hierarchical categories in a domain,
13021: with checkboxes to allow a course to be categorized. 
13022: 
13023: Inputs:
13024: 
13025: cathash - reference to hash of categories defined for the domain (from
13026:           configuration.db)
13027: 
13028: currcat - scalar with an & separated list of categories assigned to a course. 
13029: 
13030: type    - scalar contains course type (Course or Community).
13031: 
13032: Returns: $output (markup to be displayed) 
13033: 
13034: =cut
13035: 
13036: sub assign_categories_table {
13037:     my ($cathash,$currcat,$type) = @_;
13038:     my $output;
13039:     if (ref($cathash) eq 'HASH') {
13040:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13041:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13042:         $maxdepth = scalar(@cats);
13043:         if (@cats > 0) {
13044:             my $itemcount = 0;
13045:             if (ref($cats[0]) eq 'ARRAY') {
13046:                 my @currcategories;
13047:                 if ($currcat ne '') {
13048:                     @currcategories = split('&',$currcat);
13049:                 }
13050:                 my $table;
13051:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13052:                     my $parent = $cats[0][$i];
13053:                     next if ($parent eq 'instcode');
13054:                     if ($type eq 'Community') {
13055:                         next unless ($parent eq 'communities');
13056:                     } else {
13057:                         next if ($parent eq 'communities');
13058:                     }
13059:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13060:                     my $item = &escape($parent).'::0';
13061:                     my $checked = '';
13062:                     if (@currcategories > 0) {
13063:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13064:                             $checked = ' checked="checked"';
13065:                         }
13066:                     }
13067:                     my $parent_title = $parent;
13068:                     if ($parent eq 'communities') {
13069:                         $parent_title = &mt('Communities');
13070:                     }
13071:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13072:                               '<input type="checkbox" name="usecategory" value="'.
13073:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13074:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13075:                     my $depth = 1;
13076:                     push(@path,$parent);
13077:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13078:                     pop(@path);
13079:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13080:                     $itemcount ++;
13081:                 }
13082:                 if ($itemcount) {
13083:                     $output = &Apache::loncommon::start_data_table().
13084:                               $table.
13085:                               &Apache::loncommon::end_data_table();
13086:                 }
13087:             }
13088:         }
13089:     }
13090:     return $output;
13091: }
13092: 
13093: =pod
13094: 
13095: =item *&assign_category_rows()
13096: 
13097: Create a datatable row for display of nested categories in a domain,
13098: with checkboxes to allow a course to be categorized,called recursively.
13099: 
13100: Inputs:
13101: 
13102: itemcount - track row number for alternating colors
13103: 
13104: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13105:       categories and subcategories.
13106: 
13107: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13108: 
13109: parent - parent of current category item
13110: 
13111: path - Array containing all categories back up through the hierarchy from the
13112:        current category to the top level.
13113: 
13114: currcategories - reference to array of current categories assigned to the course
13115: 
13116: Returns: $output (markup to be displayed).
13117: 
13118: =cut
13119: 
13120: sub assign_category_rows {
13121:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13122:     my ($text,$name,$item,$chgstr);
13123:     if (ref($cats) eq 'ARRAY') {
13124:         my $maxdepth = scalar(@{$cats});
13125:         if (ref($cats->[$depth]) eq 'HASH') {
13126:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13127:                 my $numchildren = @{$cats->[$depth]{$parent}};
13128:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13129:                 $text .= '<td><table class="LC_datatable">';
13130:                 for (my $j=0; $j<$numchildren; $j++) {
13131:                     $name = $cats->[$depth]{$parent}[$j];
13132:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13133:                     my $deeper = $depth+1;
13134:                     my $checked = '';
13135:                     if (ref($currcategories) eq 'ARRAY') {
13136:                         if (@{$currcategories} > 0) {
13137:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13138:                                 $checked = ' checked="checked"';
13139:                             }
13140:                         }
13141:                     }
13142:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13143:                              '<input type="checkbox" name="usecategory" value="'.
13144:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13145:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13146:                              '</td><td>';
13147:                     if (ref($path) eq 'ARRAY') {
13148:                         push(@{$path},$name);
13149:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13150:                         pop(@{$path});
13151:                     }
13152:                     $text .= '</td></tr>';
13153:                 }
13154:                 $text .= '</table></td>';
13155:             }
13156:         }
13157:     }
13158:     return $text;
13159: }
13160: 
13161: ############################################################
13162: ############################################################
13163: 
13164: 
13165: sub commit_customrole {
13166:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13167:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13168:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13169:                          ($end?', ending '.localtime($end):'').': <b>'.
13170:               &Apache::lonnet::assigncustomrole(
13171:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13172:                  '</b><br />';
13173:     return $output;
13174: }
13175: 
13176: sub commit_standardrole {
13177:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13178:     my ($output,$logmsg,$linefeed);
13179:     if ($context eq 'auto') {
13180:         $linefeed = "\n";
13181:     } else {
13182:         $linefeed = "<br />\n";
13183:     }  
13184:     if ($three eq 'st') {
13185:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13186:                                          $one,$two,$sec,$context);
13187:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13188:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13189:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13190:         } else {
13191:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13192:                ($start?', '.&mt('starting').' '.localtime($start):'').
13193:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13194:             if ($context eq 'auto') {
13195:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13196:             } else {
13197:                $output .= '<b>'.$result.'</b>'.$linefeed.
13198:                &mt('Add to classlist').': <b>ok</b>';
13199:             }
13200:             $output .= $linefeed;
13201:         }
13202:     } else {
13203:         $output = &mt('Assigning').' '.$three.' in '.$url.
13204:                ($start?', '.&mt('starting').' '.localtime($start):'').
13205:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13206:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13207:         if ($context eq 'auto') {
13208:             $output .= $result.$linefeed;
13209:         } else {
13210:             $output .= '<b>'.$result.'</b>'.$linefeed;
13211:         }
13212:     }
13213:     return $output;
13214: }
13215: 
13216: sub commit_studentrole {
13217:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13218:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13219:     if ($context eq 'auto') {
13220:         $linefeed = "\n";
13221:     } else {
13222:         $linefeed = '<br />'."\n";
13223:     }
13224:     if (defined($one) && defined($two)) {
13225:         my $cid=$one.'_'.$two;
13226:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13227:         my $secchange = 0;
13228:         my $expire_role_result;
13229:         my $modify_section_result;
13230:         if ($oldsec ne '-1') { 
13231:             if ($oldsec ne $sec) {
13232:                 $secchange = 1;
13233:                 my $now = time;
13234:                 my $uurl='/'.$cid;
13235:                 $uurl=~s/\_/\//g;
13236:                 if ($oldsec) {
13237:                     $uurl.='/'.$oldsec;
13238:                 }
13239:                 $oldsecurl = $uurl;
13240:                 $expire_role_result = 
13241:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13242:                 if ($env{'request.course.sec'} ne '') { 
13243:                     if ($expire_role_result eq 'refused') {
13244:                         my @roles = ('st');
13245:                         my @statuses = ('previous');
13246:                         my @roledoms = ($one);
13247:                         my $withsec = 1;
13248:                         my %roleshash = 
13249:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13250:                                               \@statuses,\@roles,\@roledoms,$withsec);
13251:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13252:                             my ($oldstart,$oldend) = 
13253:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13254:                             if ($oldend > 0 && $oldend <= $now) {
13255:                                 $expire_role_result = 'ok';
13256:                             }
13257:                         }
13258:                     }
13259:                 }
13260:                 $result = $expire_role_result;
13261:             }
13262:         }
13263:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13264:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
13265:             if ($modify_section_result =~ /^ok/) {
13266:                 if ($secchange == 1) {
13267:                     if ($sec eq '') {
13268:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13269:                     } else {
13270:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13271:                     }
13272:                 } elsif ($oldsec eq '-1') {
13273:                     if ($sec eq '') {
13274:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13275:                     } else {
13276:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13277:                     }
13278:                 } else {
13279:                     if ($sec eq '') {
13280:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13281:                     } else {
13282:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13283:                     }
13284:                 }
13285:             } else {
13286:                 if ($secchange) {       
13287:                     $$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;
13288:                 } else {
13289:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13290:                 }
13291:             }
13292:             $result = $modify_section_result;
13293:         } elsif ($secchange == 1) {
13294:             if ($oldsec eq '') {
13295:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13296:             } else {
13297:                 $$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;
13298:             }
13299:             if ($expire_role_result eq 'refused') {
13300:                 my $newsecurl = '/'.$cid;
13301:                 $newsecurl =~ s/\_/\//g;
13302:                 if ($sec ne '') {
13303:                     $newsecurl.='/'.$sec;
13304:                 }
13305:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13306:                     if ($sec eq '') {
13307:                         $$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;
13308:                     } else {
13309:                         $$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;
13310:                     }
13311:                 }
13312:             }
13313:         }
13314:     } else {
13315:         $$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;
13316:         $result = "error: incomplete course id\n";
13317:     }
13318:     return $result;
13319: }
13320: 
13321: sub show_role_extent {
13322:     my ($scope,$context,$role) = @_;
13323:     $scope =~ s{^/}{};
13324:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13325:     push(@courseroles,'co');
13326:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13327:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13328:         $scope =~ s{/}{_};
13329:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13330:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13331:         my ($audom,$auname) = split(/\//,$scope);
13332:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13333:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13334:     } else {
13335:         $scope =~ s{/$}{};
13336:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13337:                    &Apache::lonnet::domain($scope,'description').'</span>');
13338:     }
13339: }
13340: 
13341: ############################################################
13342: ############################################################
13343: 
13344: sub check_clone {
13345:     my ($args,$linefeed) = @_;
13346:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13347:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13348:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13349:     my $clonemsg;
13350:     my $can_clone = 0;
13351:     my $lctype = lc($args->{'crstype'});
13352:     if ($lctype ne 'community') {
13353:         $lctype = 'course';
13354:     }
13355:     if ($clonehome eq 'no_host') {
13356:         if ($args->{'crstype'} eq 'Community') {
13357:             $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'});
13358:         } else {
13359:             $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'});
13360:         }     
13361:     } else {
13362: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13363:         if ($args->{'crstype'} eq 'Community') {
13364:             if ($clonedesc{'type'} ne 'Community') {
13365:                  $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'});
13366:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13367:             }
13368:         }
13369: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13370:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13371: 	    $can_clone = 1;
13372: 	} else {
13373: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13374: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13375: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13376:             if (grep(/^\*$/,@cloners)) {
13377:                 $can_clone = 1;
13378:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13379:                 $can_clone = 1;
13380:             } else {
13381:                 my $ccrole = 'cc';
13382:                 if ($args->{'crstype'} eq 'Community') {
13383:                     $ccrole = 'co';
13384:                 }
13385: 	        my %roleshash =
13386: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13387: 					 $args->{'ccdomain'},
13388:                                          'userroles',['active'],[$ccrole],
13389: 					 [$args->{'clonedomain'}]);
13390: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13391:                     $can_clone = 1;
13392:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13393:                     $can_clone = 1;
13394:                 } else {
13395:                     if ($args->{'crstype'} eq 'Community') {
13396:                         $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'});
13397:                     } else {
13398:                         $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'});
13399:                     }
13400: 	        }
13401: 	    }
13402:         }
13403:     }
13404:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13405: }
13406: 
13407: sub construct_course {
13408:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13409:     my $outcome;
13410:     my $linefeed =  '<br />'."\n";
13411:     if ($context eq 'auto') {
13412:         $linefeed = "\n";
13413:     }
13414: 
13415: #
13416: # Are we cloning?
13417: #
13418:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13419:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13420: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13421: 	if ($context ne 'auto') {
13422:             if ($clonemsg ne '') {
13423: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13424:             }
13425: 	}
13426: 	$outcome .= $clonemsg.$linefeed;
13427: 
13428:         if (!$can_clone) {
13429: 	    return (0,$outcome);
13430: 	}
13431:     }
13432: 
13433: #
13434: # Open course
13435: #
13436:     my $crstype = lc($args->{'crstype'});
13437:     my %cenv=();
13438:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13439:                                              $args->{'cdescr'},
13440:                                              $args->{'curl'},
13441:                                              $args->{'course_home'},
13442:                                              $args->{'nonstandard'},
13443:                                              $args->{'crscode'},
13444:                                              $args->{'ccuname'}.':'.
13445:                                              $args->{'ccdomain'},
13446:                                              $args->{'crstype'},
13447:                                              $cnum,$context,$category);
13448: 
13449:     # Note: The testing routines depend on this being output; see 
13450:     # Utils::Course. This needs to at least be output as a comment
13451:     # if anyone ever decides to not show this, and Utils::Course::new
13452:     # will need to be suitably modified.
13453:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13454:     if ($$courseid =~ /^error:/) {
13455:         return (0,$outcome);
13456:     }
13457: 
13458: #
13459: # Check if created correctly
13460: #
13461:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13462:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13463:     if ($crsuhome eq 'no_host') {
13464:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13465:         return (0,$outcome);
13466:     }
13467:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13468: 
13469: #
13470: # Do the cloning
13471: #   
13472:     if ($can_clone && $cloneid) {
13473: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13474: 	if ($context ne 'auto') {
13475: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13476: 	}
13477: 	$outcome .= $clonemsg.$linefeed;
13478: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13479: # Copy all files
13480: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13481: # Restore URL
13482: 	$cenv{'url'}=$oldcenv{'url'};
13483: # Restore title
13484: 	$cenv{'description'}=$oldcenv{'description'};
13485: # Restore creation date, creator and creation context.
13486:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13487:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13488:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13489: # Mark as cloned
13490: 	$cenv{'clonedfrom'}=$cloneid;
13491: # Need to clone grading mode
13492:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13493:         $cenv{'grading'}=$newenv{'grading'};
13494: # Do not clone these environment entries
13495:         &Apache::lonnet::del('environment',
13496:                   ['default_enrollment_start_date',
13497:                    'default_enrollment_end_date',
13498:                    'question.email',
13499:                    'policy.email',
13500:                    'comment.email',
13501:                    'pch.users.denied',
13502:                    'plc.users.denied',
13503:                    'hidefromcat',
13504:                    'categories'],
13505:                    $$crsudom,$$crsunum);
13506:     }
13507: 
13508: #
13509: # Set environment (will override cloned, if existing)
13510: #
13511:     my @sections = ();
13512:     my @xlists = ();
13513:     if ($args->{'crstype'}) {
13514:         $cenv{'type'}=$args->{'crstype'};
13515:     }
13516:     if ($args->{'crsid'}) {
13517:         $cenv{'courseid'}=$args->{'crsid'};
13518:     }
13519:     if ($args->{'crscode'}) {
13520:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13521:     }
13522:     if ($args->{'crsquota'} ne '') {
13523:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13524:     } else {
13525:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13526:     }
13527:     if ($args->{'ccuname'}) {
13528:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13529:                                         ':'.$args->{'ccdomain'};
13530:     } else {
13531:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13532:     }
13533:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13534:     if ($args->{'crssections'}) {
13535:         $cenv{'internal.sectionnums'} = '';
13536:         if ($args->{'crssections'} =~ m/,/) {
13537:             @sections = split/,/,$args->{'crssections'};
13538:         } else {
13539:             $sections[0] = $args->{'crssections'};
13540:         }
13541:         if (@sections > 0) {
13542:             foreach my $item (@sections) {
13543:                 my ($sec,$gp) = split/:/,$item;
13544:                 my $class = $args->{'crscode'}.$sec;
13545:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13546:                 $cenv{'internal.sectionnums'} .= $item.',';
13547:                 unless ($addcheck eq 'ok') {
13548:                     push @badclasses, $class;
13549:                 }
13550:             }
13551:             $cenv{'internal.sectionnums'} =~ s/,$//;
13552:         }
13553:     }
13554: # do not hide course coordinator from staff listing, 
13555: # even if privileged
13556:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13557: # add crosslistings
13558:     if ($args->{'crsxlist'}) {
13559:         $cenv{'internal.crosslistings'}='';
13560:         if ($args->{'crsxlist'} =~ m/,/) {
13561:             @xlists = split/,/,$args->{'crsxlist'};
13562:         } else {
13563:             $xlists[0] = $args->{'crsxlist'};
13564:         }
13565:         if (@xlists > 0) {
13566:             foreach my $item (@xlists) {
13567:                 my ($xl,$gp) = split/:/,$item;
13568:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13569:                 $cenv{'internal.crosslistings'} .= $item.',';
13570:                 unless ($addcheck eq 'ok') {
13571:                     push @badclasses, $xl;
13572:                 }
13573:             }
13574:             $cenv{'internal.crosslistings'} =~ s/,$//;
13575:         }
13576:     }
13577:     if ($args->{'autoadds'}) {
13578:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
13579:     }
13580:     if ($args->{'autodrops'}) {
13581:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
13582:     }
13583: # check for notification of enrollment changes
13584:     my @notified = ();
13585:     if ($args->{'notify_owner'}) {
13586:         if ($args->{'ccuname'} ne '') {
13587:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13588:         }
13589:     }
13590:     if ($args->{'notify_dc'}) {
13591:         if ($uname ne '') { 
13592:             push(@notified,$uname.':'.$udom);
13593:         }
13594:     }
13595:     if (@notified > 0) {
13596:         my $notifylist;
13597:         if (@notified > 1) {
13598:             $notifylist = join(',',@notified);
13599:         } else {
13600:             $notifylist = $notified[0];
13601:         }
13602:         $cenv{'internal.notifylist'} = $notifylist;
13603:     }
13604:     if (@badclasses > 0) {
13605:         my %lt=&Apache::lonlocal::texthash(
13606:                 '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',
13607:                 'dnhr' => 'does not have rights to access enrollment in these classes',
13608:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
13609:         );
13610:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13611:                            ' ('.$lt{'adby'}.')';
13612:         if ($context eq 'auto') {
13613:             $outcome .= $badclass_msg.$linefeed;
13614:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13615:             foreach my $item (@badclasses) {
13616:                 if ($context eq 'auto') {
13617:                     $outcome .= " - $item\n";
13618:                 } else {
13619:                     $outcome .= "<li>$item</li>\n";
13620:                 }
13621:             }
13622:             if ($context eq 'auto') {
13623:                 $outcome .= $linefeed;
13624:             } else {
13625:                 $outcome .= "</ul><br /><br /></div>\n";
13626:             }
13627:         } 
13628:     }
13629:     if ($args->{'no_end_date'}) {
13630:         $args->{'endaccess'} = 0;
13631:     }
13632:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
13633:     $cenv{'internal.autoend'}=$args->{'enrollend'};
13634:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13635:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13636:     if ($args->{'showphotos'}) {
13637:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
13638:     }
13639:     $cenv{'internal.authtype'} = $args->{'authtype'};
13640:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
13641:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13642:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
13643:             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'); 
13644:             if ($context eq 'auto') {
13645:                 $outcome .= $krb_msg;
13646:             } else {
13647:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13648:             }
13649:             $outcome .= $linefeed;
13650:         }
13651:     }
13652:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13653:        if ($args->{'setpolicy'}) {
13654:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13655:        }
13656:        if ($args->{'setcontent'}) {
13657:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13658:        }
13659:     }
13660:     if ($args->{'reshome'}) {
13661: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
13662: 	$cenv{'reshome'}=~s/\/+$/\//;
13663:     }
13664: #
13665: # course has keyed access
13666: #
13667:     if ($args->{'setkeys'}) {
13668:        $cenv{'keyaccess'}='yes';
13669:     }
13670: # if specified, key authority is not course, but user
13671: # only active if keyaccess is yes
13672:     if ($args->{'keyauth'}) {
13673: 	my ($user,$domain) = split(':',$args->{'keyauth'});
13674: 	$user = &LONCAPA::clean_username($user);
13675: 	$domain = &LONCAPA::clean_username($domain);
13676: 	if ($user ne '' && $domain ne '') {
13677: 	    $cenv{'keyauth'}=$user.':'.$domain;
13678: 	}
13679:     }
13680: 
13681:     if ($args->{'disresdis'}) {
13682:         $cenv{'pch.roles.denied'}='st';
13683:     }
13684:     if ($args->{'disablechat'}) {
13685:         $cenv{'plc.roles.denied'}='st';
13686:     }
13687: 
13688:     # Record we've not yet viewed the Course Initialization Helper for this 
13689:     # course
13690:     $cenv{'course.helper.not.run'} = 1;
13691:     #
13692:     # Use new Randomseed
13693:     #
13694:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13695:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13696:     #
13697:     # The encryption code and receipt prefix for this course
13698:     #
13699:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13700:     $cenv{'internal.encpref'}=100+int(9*rand(99));
13701:     #
13702:     # By default, use standard grading
13703:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13704: 
13705:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
13706:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13707: #
13708: # Open all assignments
13709: #
13710:     if ($args->{'openall'}) {
13711:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13712:        my %storecontent = ($storeunder         => time,
13713:                            $storeunder.'.type' => 'date_start');
13714:        
13715:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13716:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13717:    }
13718: #
13719: # Set first page
13720: #
13721:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13722: 	    || ($cloneid)) {
13723: 	use LONCAPA::map;
13724: 	$outcome .= &mt('Setting first resource').': ';
13725: 
13726: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13727:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13728: 
13729:         $outcome .= ($fatal?$errtext:'read ok').' - ';
13730:         my $title; my $url;
13731:         if ($args->{'firstres'} eq 'syl') {
13732: 	    $title=&mt('Syllabus');
13733:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13734:         } else {
13735:             $title=&mt('Table of Contents');
13736:             $url='/adm/navmaps';
13737:         }
13738: 
13739:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13740: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13741: 
13742: 	if ($errtext) { $fatal=2; }
13743:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13744:     }
13745: 
13746:     return (1,$outcome);
13747: }
13748: 
13749: ############################################################
13750: ############################################################
13751: 
13752: #SD
13753: # only Community and Course, or anything else?
13754: sub course_type {
13755:     my ($cid) = @_;
13756:     if (!defined($cid)) {
13757:         $cid = $env{'request.course.id'};
13758:     }
13759:     if (defined($env{'course.'.$cid.'.type'})) {
13760:         return $env{'course.'.$cid.'.type'};
13761:     } else {
13762:         return 'Course';
13763:     }
13764: }
13765: 
13766: sub group_term {
13767:     my $crstype = &course_type();
13768:     my %names = (
13769:                   'Course' => 'group',
13770:                   'Community' => 'group',
13771:                 );
13772:     return $names{$crstype};
13773: }
13774: 
13775: sub course_types {
13776:     my @types = ('official','unofficial','community');
13777:     my %typename = (
13778:                          official   => 'Official course',
13779:                          unofficial => 'Unofficial course',
13780:                          community  => 'Community',
13781:                    );
13782:     return (\@types,\%typename);
13783: }
13784: 
13785: sub icon {
13786:     my ($file)=@_;
13787:     my $curfext = lc((split(/\./,$file))[-1]);
13788:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13789:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13790:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13791: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13792: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13793: 	            $curfext.".gif") {
13794: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13795: 		$curfext.".gif";
13796: 	}
13797:     }
13798:     return &lonhttpdurl($iconname);
13799: } 
13800: 
13801: sub lonhttpdurl {
13802: #
13803: # Had been used for "small fry" static images on separate port 8080.
13804: # Modify here if lightweight http functionality desired again.
13805: # Currently eliminated due to increasing firewall issues.
13806: #
13807:     my ($url)=@_;
13808:     return $url;
13809: }
13810: 
13811: sub connection_aborted {
13812:     my ($r)=@_;
13813:     $r->print(" ");$r->rflush();
13814:     my $c = $r->connection;
13815:     return $c->aborted();
13816: }
13817: 
13818: #    Escapes strings that may have embedded 's that will be put into
13819: #    strings as 'strings'.
13820: sub escape_single {
13821:     my ($input) = @_;
13822:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
13823:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
13824:     return $input;
13825: }
13826: 
13827: #  Same as escape_single, but escape's "'s  This 
13828: #  can be used for  "strings"
13829: sub escape_double {
13830:     my ($input) = @_;
13831:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
13832:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
13833:     return $input;
13834: }
13835:  
13836: #   Escapes the last element of a full URL.
13837: sub escape_url {
13838:     my ($url)   = @_;
13839:     my @urlslices = split(/\//, $url,-1);
13840:     my $lastitem = &escape(pop(@urlslices));
13841:     return join('/',@urlslices).'/'.$lastitem;
13842: }
13843: 
13844: sub compare_arrays {
13845:     my ($arrayref1,$arrayref2) = @_;
13846:     my (@difference,%count);
13847:     @difference = ();
13848:     %count = ();
13849:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
13850:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
13851:         foreach my $element (keys(%count)) {
13852:             if ($count{$element} == 1) {
13853:                 push(@difference,$element);
13854:             }
13855:         }
13856:     }
13857:     return @difference;
13858: }
13859: 
13860: # -------------------------------------------------------- Initialize user login
13861: sub init_user_environment {
13862:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
13863:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13864: 
13865:     my $public=($username eq 'public' && $domain eq 'public');
13866: 
13867: # See if old ID present, if so, remove
13868: 
13869:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13870:     my $now=time;
13871: 
13872:     if ($public) {
13873: 	my $max_public=100;
13874: 	my $oldest;
13875: 	my $oldest_time=0;
13876: 	for(my $next=1;$next<=$max_public;$next++) {
13877: 	    if (-e $lonids."/publicuser_$next.id") {
13878: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13879: 		if ($mtime<$oldest_time || !$oldest_time) {
13880: 		    $oldest_time=$mtime;
13881: 		    $oldest=$next;
13882: 		}
13883: 	    } else {
13884: 		$cookie="publicuser_$next";
13885: 		last;
13886: 	    }
13887: 	}
13888: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
13889:     } else {
13890: 	# if this isn't a robot, kill any existing non-robot sessions
13891: 	if (!$args->{'robot'}) {
13892: 	    opendir(DIR,$lonids);
13893: 	    while ($filename=readdir(DIR)) {
13894: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13895: 		    unlink($lonids.'/'.$filename);
13896: 		}
13897: 	    }
13898: 	    closedir(DIR);
13899: 	}
13900: # Give them a new cookie
13901: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13902: 		                   : $now.$$.int(rand(10000)));
13903: 	$cookie="$username\_$id\_$domain\_$authhost";
13904:     
13905: # Initialize roles
13906: 
13907: 	($userroles,$firstaccenv,$timerintenv) = 
13908:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
13909:     }
13910: # ------------------------------------ Check browser type and MathML capability
13911: 
13912:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13913:         $clientunicode,$clientos) = &decode_user_agent($r);
13914: 
13915: # ------------------------------------------------------------- Get environment
13916: 
13917:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13918:     my ($tmp) = keys(%userenv);
13919:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13920:     } else {
13921: 	undef(%userenv);
13922:     }
13923:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
13924: 	$form->{'interface'}=$userenv{'interface'};
13925:     }
13926:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13927: 
13928: # --------------- Do not trust query string to be put directly into environment
13929:     foreach my $option ('interface','localpath','localres') {
13930:         $form->{$option}=~s/[\n\r\=]//gs;
13931:     }
13932: # --------------------------------------------------------- Write first profile
13933: 
13934:     {
13935: 	my %initial_env = 
13936: 	    ("user.name"          => $username,
13937: 	     "user.domain"        => $domain,
13938: 	     "user.home"          => $authhost,
13939: 	     "browser.type"       => $clientbrowser,
13940: 	     "browser.version"    => $clientversion,
13941: 	     "browser.mathml"     => $clientmathml,
13942: 	     "browser.unicode"    => $clientunicode,
13943: 	     "browser.os"         => $clientos,
13944: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
13945: 	     "request.course.fn"  => '',
13946: 	     "request.course.uri" => '',
13947: 	     "request.course.sec" => '',
13948: 	     "request.role"       => 'cm',
13949: 	     "request.role.adv"   => $env{'user.adv'},
13950: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
13951: 
13952:         if ($form->{'localpath'}) {
13953: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
13954: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
13955:         }
13956: 	
13957: 	if ($form->{'interface'}) {
13958: 	    $form->{'interface'}=~s/\W//gs;
13959: 	    $initial_env{"browser.interface"} = $form->{'interface'};
13960: 	    $env{'browser.interface'}=$form->{'interface'};
13961: 	}
13962: 
13963:         my %is_adv = ( is_adv => $env{'user.adv'} );
13964:         my %domdef;
13965:         unless ($domain eq 'public') {
13966:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
13967:         }
13968: 
13969:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
13970:             $userenv{'availabletools.'.$tool} = 
13971:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13972:                                                   undef,\%userenv,\%domdef,\%is_adv);
13973:         }
13974: 
13975:         foreach my $crstype ('official','unofficial','community') {
13976:             $userenv{'canrequest.'.$crstype} =
13977:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
13978:                                                   'reload','requestcourses',
13979:                                                   \%userenv,\%domdef,\%is_adv);
13980:         }
13981: 
13982:         $userenv{'canrequest.author'} =
13983:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
13984:                                         'reload','requestauthor',
13985:                                         \%userenv,\%domdef,\%is_adv);
13986:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
13987:                                              $domain,$username);
13988:         my $reqstatus = $reqauthor{'author_status'};
13989:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
13990:             if (ref($reqauthor{'author'}) eq 'HASH') {
13991:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
13992:                                                   $reqauthor{'author'}{'timestamp'};
13993:             }
13994:         }
13995: 
13996: 	$env{'user.environment'} = "$lonids/$cookie.id";
13997: 
13998: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
13999: 		 &GDBM_WRCREAT(),0640)) {
14000: 	    &_add_to_env(\%disk_env,\%initial_env);
14001: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14002: 	    &_add_to_env(\%disk_env,$userroles);
14003:             if (ref($firstaccenv) eq 'HASH') {
14004:                 &_add_to_env(\%disk_env,$firstaccenv);
14005:             }
14006:             if (ref($timerintenv) eq 'HASH') {
14007:                 &_add_to_env(\%disk_env,$timerintenv);
14008:             }
14009: 	    if (ref($args->{'extra_env'})) {
14010: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14011: 	    }
14012: 	    untie(%disk_env);
14013: 	} else {
14014: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14015: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14016: 	    return 'error: '.$!;
14017: 	}
14018:     }
14019:     $env{'request.role'}='cm';
14020:     $env{'request.role.adv'}=$env{'user.adv'};
14021:     $env{'browser.type'}=$clientbrowser;
14022: 
14023:     return $cookie;
14024: 
14025: }
14026: 
14027: sub _add_to_env {
14028:     my ($idf,$env_data,$prefix) = @_;
14029:     if (ref($env_data) eq 'HASH') {
14030:         while (my ($key,$value) = each(%$env_data)) {
14031: 	    $idf->{$prefix.$key} = $value;
14032: 	    $env{$prefix.$key}   = $value;
14033:         }
14034:     }
14035: }
14036: 
14037: # --- Get the symbolic name of a problem and the url
14038: sub get_symb {
14039:     my ($request,$silent) = @_;
14040:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14041:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14042:     if ($symb eq '') {
14043:         if (!$silent) {
14044:             if (ref($request)) { 
14045:                 $request->print("Unable to handle ambiguous references:$url:.");
14046:             }
14047:             return ();
14048:         }
14049:     }
14050:     &Apache::lonenc::check_decrypt(\$symb);
14051:     return ($symb);
14052: }
14053: 
14054: # --------------------------------------------------------------Get annotation
14055: 
14056: sub get_annotation {
14057:     my ($symb,$enc) = @_;
14058: 
14059:     my $key = $symb;
14060:     if (!$enc) {
14061:         $key =
14062:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14063:     }
14064:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14065:     return $annotation{$key};
14066: }
14067: 
14068: sub clean_symb {
14069:     my ($symb,$delete_enc) = @_;
14070: 
14071:     &Apache::lonenc::check_decrypt(\$symb);
14072:     my $enc = $env{'request.enc'};
14073:     if ($delete_enc) {
14074:         delete($env{'request.enc'});
14075:     }
14076: 
14077:     return ($symb,$enc);
14078: }
14079: 
14080: sub build_release_hashes {
14081:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14082:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14083:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14084:                   (ref($randomizetry) eq 'HASH'));
14085:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14086:         my ($item,$name,$value) = split(/:/,$key);
14087:         if ($item eq 'parameter') {
14088:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14089:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14090:                     push(@{$checkparms->{$name}},$value);
14091:                 }
14092:             } else {
14093:                 push(@{$checkparms->{$name}},$value);
14094:             }
14095:         } elsif ($item eq 'resourcetag') {
14096:             if ($name eq 'responsetype') {
14097:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14098:             }
14099:         } elsif ($item eq 'course') {
14100:             if ($name eq 'crstype') {
14101:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14102:             }
14103:         }
14104:     }
14105:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14106:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14107:     return;
14108: }
14109: 
14110: sub update_content_constraints {
14111:     my ($cdom,$cnum,$chome,$cid) = @_;
14112:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14113:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14114:     my %checkresponsetypes;
14115:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14116:         my ($item,$name,$value) = split(/:/,$key);
14117:         if ($item eq 'resourcetag') {
14118:             if ($name eq 'responsetype') {
14119:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14120:             }
14121:         }
14122:     }
14123:     my $navmap = Apache::lonnavmaps::navmap->new();
14124:     if (defined($navmap)) {
14125:         my %allresponses;
14126:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14127:             my %responses = $res->responseTypes();
14128:             foreach my $key (keys(%responses)) {
14129:                 next unless(exists($checkresponsetypes{$key}));
14130:                 $allresponses{$key} += $responses{$key};
14131:             }
14132:         }
14133:         foreach my $key (keys(%allresponses)) {
14134:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14135:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14136:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14137:             }
14138:         }
14139:         undef($navmap);
14140:     }
14141:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14142:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14143:     }
14144:     return;
14145: }
14146: 
14147: sub parse_supplemental_title {
14148:     my ($title) = @_;
14149: 
14150:     my ($foldertitle,$renametitle);
14151:     if ($title =~ /&amp;&amp;&amp;/) {
14152:         $title = &HTML::Entites::decode($title);
14153:     }
14154:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14155:         $renametitle=$4;
14156:         my ($time,$uname,$udom) = ($1,$2,$3);
14157:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14158:         my $name =  &plainname($uname,$udom);
14159:         $name = &HTML::Entities::encode($name,'"<>&\'');
14160:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14161:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14162:             $name.': <br />'.$foldertitle;
14163:     }
14164:     if (wantarray) {
14165:         return ($title,$foldertitle,$renametitle);
14166:     }
14167:     return $title;
14168: }
14169: 
14170: sub symb_to_docspath {
14171:     my ($symb) = @_;
14172:     return unless ($symb);
14173:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14174:     if ($resurl=~/\.(sequence|page)$/) {
14175:         $mapurl=$resurl;
14176:     } elsif ($resurl eq 'adm/navmaps') {
14177:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14178:     }
14179:     my $mapresobj;
14180:     my $navmap = Apache::lonnavmaps::navmap->new();
14181:     if (ref($navmap)) {
14182:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14183:     }
14184:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14185:     my $type=$2;
14186:     my $path;
14187:     if (ref($mapresobj)) {
14188:         my $pcslist = $mapresobj->map_hierarchy();
14189:         if ($pcslist ne '') {
14190:             foreach my $pc (split(/,/,$pcslist)) {
14191:                 next if ($pc <= 1);
14192:                 my $res = $navmap->getByMapPc($pc);
14193:                 if (ref($res)) {
14194:                     my $thisurl = $res->src();
14195:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14196:                     my $thistitle = $res->title();
14197:                     $path .= '&'.
14198:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14199:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
14200:                              ':'.$res->randompick().
14201:                              ':'.$res->randomout().
14202:                              ':'.$res->encrypted().
14203:                              ':'.$res->randomorder().
14204:                              ':'.$res->is_page();
14205:                 }
14206:             }
14207:         }
14208:         $path =~ s/^\&//;
14209:         my $maptitle = $mapresobj->title();
14210:         if ($mapurl eq 'default') {
14211:             $maptitle = 'Main Course Documents';
14212:         }
14213:         $path .= (($path ne '')? '&' : '').
14214:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14215:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
14216:                  ':'.$mapresobj->randompick().
14217:                  ':'.$mapresobj->randomout().
14218:                  ':'.$mapresobj->encrypted().
14219:                  ':'.$mapresobj->randomorder().
14220:                  ':'.$mapresobj->is_page();
14221:     } else {
14222:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14223:         my $ispage = (($type eq 'page')? 1 : '');
14224:         if ($mapurl eq 'default') {
14225:             $maptitle = 'Main Course Documents';
14226:         }
14227:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14228:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
14229:     }
14230:     unless ($mapurl eq 'default') {
14231:         $path = 'default&'.
14232:                 &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
14233:                 ':::::&'.$path;
14234:     }
14235:     return $path;
14236: }
14237: 
14238: sub captcha_display {
14239:     my ($context,$lonhost) = @_;
14240:     my ($output,$error);
14241:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14242:     if ($captcha eq 'original') {
14243:         $output = &create_captcha();
14244:         unless ($output) {
14245:             $error = 'captcha'; 
14246:         }
14247:     } elsif ($captcha eq 'recaptcha') {
14248:         $output = &create_recaptcha($pubkey);
14249:         unless ($output) {
14250:             $error = 'recaptcha'; 
14251:         }
14252:     }
14253:     return ($output,$error);
14254: }
14255: 
14256: sub captcha_response {
14257:     my ($context,$lonhost) = @_;
14258:     my ($captcha_chk,$captcha_error);
14259:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14260:     if ($captcha eq 'original') {
14261:         ($captcha_chk,$captcha_error) = &check_captcha();
14262:     } elsif ($captcha eq 'recaptcha') {
14263:         $captcha_chk = &check_recaptcha($privkey);
14264:     } else {
14265:         $captcha_chk = 1;
14266:     }
14267:     return ($captcha_chk,$captcha_error);
14268: }
14269: 
14270: sub get_captcha_config {
14271:     my ($context,$lonhost) = @_;
14272:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14273:     my $hostname = &Apache::lonnet::hostname($lonhost);
14274:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14275:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14276:     if ($context eq 'usercreation') {
14277:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14278:         if (ref($domconfig{$context}) eq 'HASH') {
14279:             $hashtocheck = $domconfig{$context}{'cancreate'};
14280:             if (ref($hashtocheck) eq 'HASH') {
14281:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14282:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14283:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14284:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14285:                     }
14286:                     if ($privkey && $pubkey) {
14287:                         $captcha = 'recaptcha';
14288:                     } else {
14289:                         $captcha = 'original';
14290:                     }
14291:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14292:                     $captcha = 'original';
14293:                 }
14294:             }
14295:         } else {
14296:             $captcha = 'captcha';
14297:         }
14298:     } elsif ($context eq 'login') {
14299:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14300:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14301:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14302:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14303:             if ($privkey && $pubkey) {
14304:                 $captcha = 'recaptcha';
14305:             } else {
14306:                 $captcha = 'original';
14307:             }
14308:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14309:             $captcha = 'original';
14310:         }
14311:     }
14312:     return ($captcha,$pubkey,$privkey);
14313: }
14314: 
14315: sub create_captcha {
14316:     my %captcha_params = &captcha_settings();
14317:     my ($output,$maxtries,$tries) = ('',10,0);
14318:     while ($tries < $maxtries) {
14319:         $tries ++;
14320:         my $captcha = Authen::Captcha->new (
14321:                                            output_folder => $captcha_params{'output_dir'},
14322:                                            data_folder   => $captcha_params{'db_dir'},
14323:                                           );
14324:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14325: 
14326:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14327:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14328:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14329:                      '<input type="text" size="5" name="code" value="" /><br />'.
14330:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14331:             last;
14332:         }
14333:     }
14334:     return $output;
14335: }
14336: 
14337: sub captcha_settings {
14338:     my %captcha_params = (
14339:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14340:                            www_output_dir => "/captchaspool",
14341:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14342:                            numchars       => '5',
14343:                          );
14344:     return %captcha_params;
14345: }
14346: 
14347: sub check_captcha {
14348:     my ($captcha_chk,$captcha_error);
14349:     my $code = $env{'form.code'};
14350:     my $md5sum = $env{'form.crypt'};
14351:     my %captcha_params = &captcha_settings();
14352:     my $captcha = Authen::Captcha->new(
14353:                       output_folder => $captcha_params{'output_dir'},
14354:                       data_folder   => $captcha_params{'db_dir'},
14355:                   );
14356:     $captcha_chk = $captcha->check_code($code,$md5sum);
14357:     my %captcha_hash = (
14358:                         0       => 'Code not checked (file error)',
14359:                        -1      => 'Failed: code expired',
14360:                        -2      => 'Failed: invalid code (not in database)',
14361:                        -3      => 'Failed: invalid code (code does not match crypt)',
14362:     );
14363:     if ($captcha_chk != 1) {
14364:         $captcha_error = $captcha_hash{$captcha_chk}
14365:     }
14366:     return ($captcha_chk,$captcha_error);
14367: }
14368: 
14369: sub create_recaptcha {
14370:     my ($pubkey) = @_;
14371:     my $captcha = Captcha::reCAPTCHA->new;
14372:     return $captcha->get_options_setter({theme => 'white'})."\n".
14373:            $captcha->get_html($pubkey).
14374:            &mt('If either word is hard to read, [_1] will replace them.',
14375:                '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14376:            '<br /><br />';
14377: }
14378: 
14379: sub check_recaptcha {
14380:     my ($privkey) = @_;
14381:     my $captcha_chk;
14382:     my $captcha = Captcha::reCAPTCHA->new;
14383:     my $captcha_result =
14384:         $captcha->check_answer(
14385:                                 $privkey,
14386:                                 $ENV{'REMOTE_ADDR'},
14387:                                 $env{'form.recaptcha_challenge_field'},
14388:                                 $env{'form.recaptcha_response_field'},
14389:                               );
14390:     if ($captcha_result->{is_valid}) {
14391:         $captcha_chk = 1;
14392:     }
14393:     return $captcha_chk;
14394: }
14395: 
14396: =pod
14397: 
14398: =back
14399: 
14400: =cut
14401: 
14402: 1;
14403: __END__;
14404: 

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