File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.60: download - view: text, annotated - select for diffs
Mon Dec 30 01:31:55 2013 UTC (10 years, 4 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Provide Remote Contol users with access to help menu (will open in new
    window).

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.60 2013/12/30 01:31:55 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use LONCAPA qw(:DEFAULT :match);
   73: use DateTime::TimeZone;
   74: use DateTime::Locale::Catalog;
   75: use Authen::Captcha;
   76: use Captcha::reCAPTCHA;
   77: 
   78: # ---------------------------------------------- Designs
   79: use vars qw(%defaultdesign);
   80: 
   81: my $readit;
   82: 
   83: 
   84: ##
   85: ## Global Variables
   86: ##
   87: 
   88: 
   89: # ----------------------------------------------- SSI with retries:
   90: #
   91: 
   92: =pod
   93: 
   94: =head1 Server Side include with retries:
   95: 
   96: =over 4
   97: 
   98: =item * &ssi_with_retries(resource,retries form)
   99: 
  100: Performs an ssi with some number of retries.  Retries continue either
  101: until the result is ok or until the retry count supplied by the
  102: caller is exhausted.  
  103: 
  104: Inputs:
  105: 
  106: =over 4
  107: 
  108: resource   - Identifies the resource to insert.
  109: 
  110: retries    - Count of the number of retries allowed.
  111: 
  112: form       - Hash that identifies the rendering options.
  113: 
  114: =back
  115: 
  116: Returns:
  117: 
  118: =over 4
  119: 
  120: content    - The content of the response.  If retries were exhausted this is empty.
  121: 
  122: response   - The response from the last attempt (which may or may not have been successful.
  123: 
  124: =back
  125: 
  126: =back
  127: 
  128: =cut
  129: 
  130: sub ssi_with_retries {
  131:     my ($resource, $retries, %form) = @_;
  132: 
  133: 
  134:     my $ok = 0;			# True if we got a good response.
  135:     my $content;
  136:     my $response;
  137: 
  138:     # Try to get the ssi done. within the retries count:
  139: 
  140:     do {
  141: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  142: 	$ok      = $response->is_success;
  143:         if (!$ok) {
  144:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  145:         }
  146: 	$retries--;
  147:     } while (!$ok && ($retries > 0));
  148: 
  149:     if (!$ok) {
  150: 	$content = '';		# On error return an empty content.
  151:     }
  152:     return ($content, $response);
  153: 
  154: }
  155: 
  156: 
  157: 
  158: # ----------------------------------------------- Filetypes/Languages/Copyright
  159: my %language;
  160: my %supported_language;
  161: my %latex_language;		# For choosing hyphenation in <transl..>
  162: my %latex_language_bykey;	# for choosing hyphenation from metadata
  163: my %cprtag;
  164: my %scprtag;
  165: my %fe; my %fd; my %fm;
  166: my %category_extensions;
  167: 
  168: # ---------------------------------------------- Thesaurus variables
  169: #
  170: # %Keywords:
  171: #      A hash used by &keyword to determine if a word is considered a keyword.
  172: # $thesaurus_db_file 
  173: #      Scalar containing the full path to the thesaurus database.
  174: 
  175: my %Keywords;
  176: my $thesaurus_db_file;
  177: 
  178: #
  179: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  180: # thesaurus.tab, and filecategories.tab.
  181: #
  182: BEGIN {
  183:     # Variable initialization
  184:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  185:     #
  186:     unless ($readit) {
  187: # ------------------------------------------------------------------- languages
  188:     {
  189:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  190:                                    '/language.tab';
  191:         if ( open(my $fh,"<$langtabfile") ) {
  192:             while (my $line = <$fh>) {
  193:                 next if ($line=~/^\#/);
  194:                 chomp($line);
  195:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  196:                 $language{$key}=$val.' - '.$enc;
  197:                 if ($sup) {
  198:                     $supported_language{$key}=$sup;
  199:                 }
  200: 		if ($latex) {
  201: 		    $latex_language_bykey{$key} = $latex;
  202: 		    $latex_language{$two} = $latex;
  203: 		}
  204:             }
  205:             close($fh);
  206:         }
  207:     }
  208: # ------------------------------------------------------------------ copyrights
  209:     {
  210:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  211:                                   '/copyright.tab';
  212:         if ( open (my $fh,"<$copyrightfile") ) {
  213:             while (my $line = <$fh>) {
  214:                 next if ($line=~/^\#/);
  215:                 chomp($line);
  216:                 my ($key,$val)=(split(/\s+/,$line,2));
  217:                 $cprtag{$key}=$val;
  218:             }
  219:             close($fh);
  220:         }
  221:     }
  222: # ----------------------------------------------------------- source copyrights
  223:     {
  224:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  225:                                   '/source_copyright.tab';
  226:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  227:             while (my $line = <$fh>) {
  228:                 next if ($line =~ /^\#/);
  229:                 chomp($line);
  230:                 my ($key,$val)=(split(/\s+/,$line,2));
  231:                 $scprtag{$key}=$val;
  232:             }
  233:             close($fh);
  234:         }
  235:     }
  236: 
  237: # -------------------------------------------------------------- default domain designs
  238:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  239:     my $designfile = $designdir.'/default.tab';
  240:     if ( open (my $fh,"<$designfile") ) {
  241:         while (my $line = <$fh>) {
  242:             next if ($line =~ /^\#/);
  243:             chomp($line);
  244:             my ($key,$val)=(split(/\=/,$line));
  245:             if ($val) { $defaultdesign{$key}=$val; }
  246:         }
  247:         close($fh);
  248:     }
  249: 
  250: # ------------------------------------------------------------- file categories
  251:     {
  252:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  253:                                   '/filecategories.tab';
  254:         if ( open (my $fh,"<$categoryfile") ) {
  255: 	    while (my $line = <$fh>) {
  256: 		next if ($line =~ /^\#/);
  257: 		chomp($line);
  258:                 my ($extension,$category)=(split(/\s+/,$line,2));
  259:                 push @{$category_extensions{lc($category)}},$extension;
  260:             }
  261:             close($fh);
  262:         }
  263: 
  264:     }
  265: # ------------------------------------------------------------------ file types
  266:     {
  267:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  268:                '/filetypes.tab';
  269:         if ( open (my $fh,"<$typesfile") ) {
  270:             while (my $line = <$fh>) {
  271: 		next if ($line =~ /^\#/);
  272: 		chomp($line);
  273:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  274:                 if ($descr ne '') {
  275:                     $fe{$ending}=lc($emb);
  276:                     $fd{$ending}=$descr;
  277:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  278:                 }
  279:             }
  280:             close($fh);
  281:         }
  282:     }
  283:     &Apache::lonnet::logthis(
  284:              "<span style='color:yellow;'>INFO: Read file types</span>");
  285:     $readit=1;
  286:     }  # end of unless($readit) 
  287:     
  288: }
  289: 
  290: ###############################################################
  291: ##           HTML and Javascript Helper Functions            ##
  292: ###############################################################
  293: 
  294: =pod 
  295: 
  296: =head1 HTML and Javascript Functions
  297: 
  298: =over 4
  299: 
  300: =item * &browser_and_searcher_javascript()
  301: 
  302: X<browsing, javascript>X<searching, javascript>Returns a string
  303: containing javascript with two functions, C<openbrowser> and
  304: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  305: tags.
  306: 
  307: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  308: 
  309: inputs: formname, elementname, only, omit
  310: 
  311: formname and elementname indicate the name of the html form and name of
  312: the element that the results of the browsing selection are to be placed in. 
  313: 
  314: Specifying 'only' will restrict the browser to displaying only files
  315: with the given extension.  Can be a comma separated list.
  316: 
  317: Specifying 'omit' will restrict the browser to NOT displaying files
  318: with the given extension.  Can be a comma separated list.
  319: 
  320: =item * &opensearcher(formname,elementname) [javascript]
  321: 
  322: Inputs: formname, elementname
  323: 
  324: formname and elementname specify the name of the html form and the name
  325: of the element the selection from the search results will be placed in.
  326: 
  327: =cut
  328: 
  329: sub browser_and_searcher_javascript {
  330:     my ($mode)=@_;
  331:     if (!defined($mode)) { $mode='edit'; }
  332:     my $resurl=&escape_single(&lastresurl());
  333:     return <<END;
  334: // <!-- BEGIN LON-CAPA Internal
  335:     var editbrowser = null;
  336:     function openbrowser(formname,elementname,only,omit,titleelement) {
  337:         var url = '$resurl/?';
  338:         if (editbrowser == null) {
  339:             url += 'launch=1&';
  340:         }
  341:         url += 'catalogmode=interactive&';
  342:         url += 'mode=$mode&';
  343:         url += 'inhibitmenu=yes&';
  344:         url += 'form=' + formname + '&';
  345:         if (only != null) {
  346:             url += 'only=' + only + '&';
  347:         } else {
  348:             url += 'only=&';
  349: 	}
  350:         if (omit != null) {
  351:             url += 'omit=' + omit + '&';
  352:         } else {
  353:             url += 'omit=&';
  354: 	}
  355:         if (titleelement != null) {
  356:             url += 'titleelement=' + titleelement + '&';
  357:         } else {
  358: 	    url += 'titleelement=&';
  359: 	}
  360:         url += 'element=' + elementname + '';
  361:         var title = 'Browser';
  362:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  363:         options += ',width=700,height=600';
  364:         editbrowser = open(url,title,options,'1');
  365:         editbrowser.focus();
  366:     }
  367:     var editsearcher;
  368:     function opensearcher(formname,elementname,titleelement) {
  369:         var url = '/adm/searchcat?';
  370:         if (editsearcher == null) {
  371:             url += 'launch=1&';
  372:         }
  373:         url += 'catalogmode=interactive&';
  374:         url += 'mode=$mode&';
  375:         url += 'form=' + formname + '&';
  376:         if (titleelement != null) {
  377:             url += 'titleelement=' + titleelement + '&';
  378:         } else {
  379: 	    url += 'titleelement=&';
  380: 	}
  381:         url += 'element=' + elementname + '';
  382:         var title = 'Search';
  383:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  384:         options += ',width=700,height=600';
  385:         editsearcher = open(url,title,options,'1');
  386:         editsearcher.focus();
  387:     }
  388: // END LON-CAPA Internal -->
  389: END
  390: }
  391: 
  392: sub lastresurl {
  393:     if ($env{'environment.lastresurl'}) {
  394: 	return $env{'environment.lastresurl'}
  395:     } else {
  396: 	return '/res';
  397:     }
  398: }
  399: 
  400: sub storeresurl {
  401:     my $resurl=&Apache::lonnet::clutter(shift);
  402:     unless ($resurl=~/^\/res/) { return 0; }
  403:     $resurl=~s/\/$//;
  404:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  405:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  406:     return 1;
  407: }
  408: 
  409: sub studentbrowser_javascript {
  410:    unless (
  411:             (($env{'request.course.id'}) && 
  412:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  413: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  414: 					  '/'.$env{'request.course.sec'})
  415: 	      ))
  416:          || ($env{'request.role'}=~/^(au|dc|su)/)
  417:           ) { return ''; }  
  418:    return (<<'ENDSTDBRW');
  419: <script type="text/javascript" language="Javascript">
  420: // <![CDATA[
  421:     var stdeditbrowser;
  422:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  423:         var url = '/adm/pickstudent?';
  424:         var filter;
  425: 	if (!ignorefilter) {
  426: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  427: 	}
  428:         if (filter != null) {
  429:            if (filter != '') {
  430:                url += 'filter='+filter+'&';
  431: 	   }
  432:         }
  433:         url += 'form=' + formname + '&unameelement='+uname+
  434:                                     '&udomelement='+udom+
  435:                                     '&clicker='+clicker;
  436: 	if (roleflag) { url+="&roles=1"; }
  437:         if (courseadvonly) { url+="&courseadvonly=1"; }
  438:         var title = 'Student_Browser';
  439:         var options = 'scrollbars=1,resizable=1,menubar=0';
  440:         options += ',width=700,height=600';
  441:         stdeditbrowser = open(url,title,options,'1');
  442:         stdeditbrowser.focus();
  443:     }
  444: // ]]>
  445: </script>
  446: ENDSTDBRW
  447: }
  448: 
  449: sub resourcebrowser_javascript {
  450:    unless ($env{'request.course.id'}) { return ''; }
  451:    return (<<'ENDRESBRW');
  452: <script type="text/javascript" language="Javascript">
  453: // <![CDATA[
  454:     var reseditbrowser;
  455:     function openresbrowser(formname,reslink) {
  456:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  457:         var title = 'Resource_Browser';
  458:         var options = 'scrollbars=1,resizable=1,menubar=0';
  459:         options += ',width=700,height=500';
  460:         reseditbrowser = open(url,title,options,'1');
  461:         reseditbrowser.focus();
  462:     }
  463: // ]]>
  464: </script>
  465: ENDRESBRW
  466: }
  467: 
  468: sub selectstudent_link {
  469:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  470:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  471:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  472:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  473:    if ($env{'request.course.id'}) {  
  474:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  475: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  476: 					'/'.$env{'request.course.sec'})) {
  477: 	   return '';
  478:        }
  479:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  480:        if ($courseadvonly)  {
  481:            $callargs .= ",'',1,1";
  482:        }
  483:        return '<span class="LC_nobreak">'.
  484:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  485:               &mt('Select User').'</a></span>';
  486:    }
  487:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  488:        $callargs .= ",'',1"; 
  489:        return '<span class="LC_nobreak">'.
  490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  491:               &mt('Select User').'</a></span>';
  492:    }
  493:    return '';
  494: }
  495: 
  496: sub selectresource_link {
  497:    my ($form,$reslink,$arg)=@_;
  498:    
  499:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  500:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  501:    unless ($env{'request.course.id'}) { return $arg; }
  502:    return '<span class="LC_nobreak">'.
  503:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  504:               $arg.'</a></span>';
  505: }
  506: 
  507: 
  508: 
  509: sub authorbrowser_javascript {
  510:     return <<"ENDAUTHORBRW";
  511: <script type="text/javascript" language="JavaScript">
  512: // <![CDATA[
  513: var stdeditbrowser;
  514: 
  515: function openauthorbrowser(formname,udom) {
  516:     var url = '/adm/pickauthor?';
  517:     url += 'form='+formname+'&roledom='+udom;
  518:     var title = 'Author_Browser';
  519:     var options = 'scrollbars=1,resizable=1,menubar=0';
  520:     options += ',width=700,height=600';
  521:     stdeditbrowser = open(url,title,options,'1');
  522:     stdeditbrowser.focus();
  523: }
  524: 
  525: // ]]>
  526: </script>
  527: ENDAUTHORBRW
  528: }
  529: 
  530: sub coursebrowser_javascript {
  531:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  532:         $credits_element) = @_;
  533:     my $wintitle = 'Course_Browser';
  534:     if ($crstype eq 'Community') {
  535:         $wintitle = 'Community_Browser';
  536:     }
  537:     my $id_functions = &javascript_index_functions();
  538:     my $output = '
  539: <script type="text/javascript" language="JavaScript">
  540: // <![CDATA[
  541:     var stdeditbrowser;'."\n";
  542: 
  543:     $output .= <<"ENDSTDBRW";
  544:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  545:         var url = '/adm/pickcourse?';
  546:         var formid = getFormIdByName(formname);
  547:         var domainfilter = getDomainFromSelectbox(formname,udom);
  548:         if (domainfilter != null) {
  549:            if (domainfilter != '') {
  550:                url += 'domainfilter='+domainfilter+'&';
  551: 	   }
  552:         }
  553:         url += 'form=' + formname + '&cnumelement='+uname+
  554: 	                            '&cdomelement='+udom+
  555:                                     '&cnameelement='+desc;
  556:         if (extra_element !=null && extra_element != '') {
  557:             if (formname == 'rolechoice' || formname == 'studentform') {
  558:                 url += '&roleelement='+extra_element;
  559:                 if (domainfilter == null || domainfilter == '') {
  560:                     url += '&domainfilter='+extra_element;
  561:                 }
  562:             }
  563:             else {
  564:                 if (formname == 'portform') {
  565:                     url += '&setroles='+extra_element;
  566:                 } else {
  567:                     if (formname == 'rules') {
  568:                         url += '&fixeddom='+extra_element; 
  569:                     }
  570:                 }
  571:             }     
  572:         }
  573:         if (type != null && type != '') {
  574:             url += '&type='+type;
  575:         }
  576:         if (type_elem != null && type_elem != '') {
  577:             url += '&typeelement='+type_elem;
  578:         }
  579:         if (formname == 'ccrs') {
  580:             var ownername = document.forms[formid].ccuname.value;
  581:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  582:             url += '&cloner='+ownername+':'+ownerdom;
  583:         }
  584:         if (multflag !=null && multflag != '') {
  585:             url += '&multiple='+multflag;
  586:         }
  587:         var title = '$wintitle';
  588:         var options = 'scrollbars=1,resizable=1,menubar=0';
  589:         options += ',width=700,height=600';
  590:         stdeditbrowser = open(url,title,options,'1');
  591:         stdeditbrowser.focus();
  592:     }
  593: $id_functions
  594: ENDSTDBRW
  595:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  596:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  597:                                       $credits_element);
  598:     }
  599:     $output .= '
  600: // ]]>
  601: </script>';
  602:     return $output;
  603: }
  604: 
  605: sub javascript_index_functions {
  606:     return <<"ENDJS";
  607: 
  608: function getFormIdByName(formname) {
  609:     for (var i=0;i<document.forms.length;i++) {
  610:         if (document.forms[i].name == formname) {
  611:             return i;
  612:         }
  613:     }
  614:     return -1;
  615: }
  616: 
  617: function getIndexByName(formid,item) {
  618:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  619:         if (document.forms[formid].elements[i].name == item) {
  620:             return i;
  621:         }
  622:     }
  623:     return -1;
  624: }
  625: 
  626: function getDomainFromSelectbox(formname,udom) {
  627:     var userdom;
  628:     var formid = getFormIdByName(formname);
  629:     if (formid > -1) {
  630:         var domid = getIndexByName(formid,udom);
  631:         if (domid > -1) {
  632:             if (document.forms[formid].elements[domid].type == 'select-one') {
  633:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  634:             }
  635:             if (document.forms[formid].elements[domid].type == 'hidden') {
  636:                 userdom=document.forms[formid].elements[domid].value;
  637:             }
  638:         }
  639:     }
  640:     return userdom;
  641: }
  642: 
  643: ENDJS
  644: 
  645: }
  646: 
  647: sub javascript_array_indexof {
  648:     return <<ENDJS;
  649: <script type="text/javascript" language="JavaScript">
  650: // <![CDATA[
  651: 
  652: if (!Array.prototype.indexOf) {
  653:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  654:         "use strict";
  655:         if (this === void 0 || this === null) {
  656:             throw new TypeError();
  657:         }
  658:         var t = Object(this);
  659:         var len = t.length >>> 0;
  660:         if (len === 0) {
  661:             return -1;
  662:         }
  663:         var n = 0;
  664:         if (arguments.length > 0) {
  665:             n = Number(arguments[1]);
  666:             if (n !== n) { // shortcut for verifying if it's NaN
  667:                 n = 0;
  668:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  669:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  670:             }
  671:         }
  672:         if (n >= len) {
  673:             return -1;
  674:         }
  675:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  676:         for (; k < len; k++) {
  677:             if (k in t && t[k] === searchElement) {
  678:                 return k;
  679:             }
  680:         }
  681:         return -1;
  682:     }
  683: }
  684: 
  685: // ]]>
  686: </script>
  687: 
  688: ENDJS
  689: 
  690: }
  691: 
  692: sub userbrowser_javascript {
  693:     my $id_functions = &javascript_index_functions();
  694:     return <<"ENDUSERBRW";
  695: 
  696: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  697:     var url = '/adm/pickuser?';
  698:     var userdom = getDomainFromSelectbox(formname,udom);
  699:     if (userdom != null) {
  700:        if (userdom != '') {
  701:            url += 'srchdom='+userdom+'&';
  702:        }
  703:     }
  704:     url += 'form=' + formname + '&unameelement='+uname+
  705:                                 '&udomelement='+udom+
  706:                                 '&ulastelement='+ulast+
  707:                                 '&ufirstelement='+ufirst+
  708:                                 '&uemailelement='+uemail+
  709:                                 '&hideudomelement='+hideudom+
  710:                                 '&coursedom='+crsdom;
  711:     if ((caller != null) && (caller != undefined)) {
  712:         url += '&caller='+caller;
  713:     }
  714:     var title = 'User_Browser';
  715:     var options = 'scrollbars=1,resizable=1,menubar=0';
  716:     options += ',width=700,height=600';
  717:     var stdeditbrowser = open(url,title,options,'1');
  718:     stdeditbrowser.focus();
  719: }
  720: 
  721: function fix_domain (formname,udom,origdom,uname) {
  722:     var formid = getFormIdByName(formname);
  723:     if (formid > -1) {
  724:         var unameid = getIndexByName(formid,uname);
  725:         var domid = getIndexByName(formid,udom);
  726:         var hidedomid = getIndexByName(formid,origdom);
  727:         if (hidedomid > -1) {
  728:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  729:             var unameval = document.forms[formid].elements[unameid].value;
  730:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  731:                 if (domid > -1) {
  732:                     var slct = document.forms[formid].elements[domid];
  733:                     if (slct.type == 'select-one') {
  734:                         var i;
  735:                         for (i=0;i<slct.length;i++) {
  736:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  737:                         }
  738:                     }
  739:                     if (slct.type == 'hidden') {
  740:                         slct.value = fixeddom;
  741:                     }
  742:                 }
  743:             }
  744:         }
  745:     }
  746:     return;
  747: }
  748: 
  749: $id_functions
  750: ENDUSERBRW
  751: }
  752: 
  753: sub setsec_javascript {
  754:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  755:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  756:         $communityrolestr);
  757:     if ($role_element ne '') {
  758:         my @allroles = ('st','ta','ep','in','ad');
  759:         foreach my $crstype ('Course','Community') {
  760:             if ($crstype eq 'Community') {
  761:                 foreach my $role (@allroles) {
  762:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  763:                 }
  764:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  765:             } else {
  766:                 foreach my $role (@allroles) {
  767:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  768:                 }
  769:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  770:             }
  771:         }
  772:         $rolestr = '"'.join('","',@allroles).'"';
  773:         $courserolestr = '"'.join('","',@courserolenames).'"';
  774:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  775:     }
  776:     my $setsections = qq|
  777: function setSect(sectionlist) {
  778:     var sectionsArray = new Array();
  779:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  780:         sectionsArray = sectionlist.split(",");
  781:     }
  782:     var numSections = sectionsArray.length;
  783:     document.$formname.$sec_element.length = 0;
  784:     if (numSections == 0) {
  785:         document.$formname.$sec_element.multiple=false;
  786:         document.$formname.$sec_element.size=1;
  787:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  788:     } else {
  789:         if (numSections == 1) {
  790:             document.$formname.$sec_element.multiple=false;
  791:             document.$formname.$sec_element.size=1;
  792:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  793:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  794:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  795:         } else {
  796:             for (var i=0; i<numSections; i++) {
  797:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  798:             }
  799:             document.$formname.$sec_element.multiple=true
  800:             if (numSections < 3) {
  801:                 document.$formname.$sec_element.size=numSections;
  802:             } else {
  803:                 document.$formname.$sec_element.size=3;
  804:             }
  805:             document.$formname.$sec_element.options[0].selected = false
  806:         }
  807:     }
  808: }
  809: 
  810: function setRole(crstype) {
  811: |;
  812:     if ($role_element eq '') {
  813:         $setsections .= '    return;
  814: }
  815: ';
  816:     } else {
  817:         $setsections .= qq|
  818:     var elementLength = document.$formname.$role_element.length;
  819:     var allroles = Array($rolestr);
  820:     var courserolenames = Array($courserolestr);
  821:     var communityrolenames = Array($communityrolestr);
  822:     if (elementLength != undefined) {
  823:         if (document.$formname.$role_element.options[5].value == 'cc') {
  824:             if (crstype == 'Course') {
  825:                 return;
  826:             } else {
  827:                 allroles[5] = 'co';
  828:                 for (var i=0; i<6; i++) {
  829:                     document.$formname.$role_element.options[i].value = allroles[i];
  830:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  831:                 }
  832:             }
  833:         } else {
  834:             if (crstype == 'Community') {
  835:                 return;
  836:             } else {
  837:                 allroles[5] = 'cc';
  838:                 for (var i=0; i<6; i++) {
  839:                     document.$formname.$role_element.options[i].value = allroles[i];
  840:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  841:                 }
  842:             }
  843:         }
  844:     }
  845:     return;
  846: }
  847: |;
  848:     }
  849:     if ($credits_element) {
  850:         $setsections .= qq|
  851: function setCredits(defaultcredits) {
  852:     document.$formname.$credits_element.value = defaultcredits;
  853:     return;
  854: }
  855: |;
  856:     }
  857:     return $setsections;
  858: }
  859: 
  860: sub selectcourse_link {
  861:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  862:        $typeelement) = @_;
  863:    my $type = $selecttype;
  864:    my $linktext = &mt('Select Course');
  865:    if ($selecttype eq 'Community') {
  866:        $linktext = &mt('Select Community');
  867:    } elsif ($selecttype eq 'Course/Community') {
  868:        $linktext = &mt('Select Course/Community');
  869:        $type = '';
  870:    } elsif ($selecttype eq 'Select') {
  871:        $linktext = &mt('Select');
  872:        $type = '';
  873:    }
  874:    return '<span class="LC_nobreak">'
  875:          ."<a href='"
  876:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  877:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  878:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  879:          ."'>".$linktext.'</a>'
  880:          .'</span>';
  881: }
  882: 
  883: sub selectauthor_link {
  884:    my ($form,$udom)=@_;
  885:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  886:           &mt('Select Author').'</a>';
  887: }
  888: 
  889: sub selectuser_link {
  890:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  891:         $coursedom,$linktext,$caller) = @_;
  892:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  893:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  894:            ');">'.$linktext.'</a>';
  895: }
  896: 
  897: sub check_uncheck_jscript {
  898:     my $jscript = <<"ENDSCRT";
  899: function checkAll(field) {
  900:     if (field.length > 0) {
  901:         for (i = 0; i < field.length; i++) {
  902:             if (!field[i].disabled) {
  903:                 field[i].checked = true;
  904:             }
  905:         }
  906:     } else {
  907:         if (!field.disabled) {
  908:             field.checked = true;
  909:         }
  910:     }
  911: }
  912:  
  913: function uncheckAll(field) {
  914:     if (field.length > 0) {
  915:         for (i = 0; i < field.length; i++) {
  916:             field[i].checked = false ;
  917:         }
  918:     } else {
  919:         field.checked = false ;
  920:     }
  921: }
  922: ENDSCRT
  923:     return $jscript;
  924: }
  925: 
  926: sub select_timezone {
  927:    my ($name,$selected,$onchange,$includeempty)=@_;
  928:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  929:    if ($includeempty) {
  930:        $output .= '<option value=""';
  931:        if (($selected eq '') || ($selected eq 'local')) {
  932:            $output .= ' selected="selected" ';
  933:        }
  934:        $output .= '> </option>';
  935:    }
  936:    my @timezones = DateTime::TimeZone->all_names;
  937:    foreach my $tzone (@timezones) {
  938:        $output.= '<option value="'.$tzone.'"';
  939:        if ($tzone eq $selected) {
  940:            $output.=' selected="selected"';
  941:        }
  942:        $output.=">$tzone</option>\n";
  943:    }
  944:    $output.="</select>";
  945:    return $output;
  946: }
  947: 
  948: sub select_datelocale {
  949:     my ($name,$selected,$onchange,$includeempty)=@_;
  950:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  951:     if ($includeempty) {
  952:         $output .= '<option value=""';
  953:         if ($selected eq '') {
  954:             $output .= ' selected="selected" ';
  955:         }
  956:         $output .= '> </option>';
  957:     }
  958:     my (@possibles,%locale_names);
  959:     my @locales = DateTime::Locale::Catalog::Locales;
  960:     foreach my $locale (@locales) {
  961:         if (ref($locale) eq 'HASH') {
  962:             my $id = $locale->{'id'};
  963:             if ($id ne '') {
  964:                 my $en_terr = $locale->{'en_territory'};
  965:                 my $native_terr = $locale->{'native_territory'};
  966:                 my @languages = &Apache::lonlocal::preferred_languages();
  967:                 if (grep(/^en$/,@languages) || !@languages) {
  968:                     if ($en_terr ne '') {
  969:                         $locale_names{$id} = '('.$en_terr.')';
  970:                     } elsif ($native_terr ne '') {
  971:                         $locale_names{$id} = $native_terr;
  972:                     }
  973:                 } else {
  974:                     if ($native_terr ne '') {
  975:                         $locale_names{$id} = $native_terr.' ';
  976:                     } elsif ($en_terr ne '') {
  977:                         $locale_names{$id} = '('.$en_terr.')';
  978:                     }
  979:                 }
  980:                 push (@possibles,$id);
  981:             }
  982:         }
  983:     }
  984:     foreach my $item (sort(@possibles)) {
  985:         $output.= '<option value="'.$item.'"';
  986:         if ($item eq $selected) {
  987:             $output.=' selected="selected"';
  988:         }
  989:         $output.=">$item";
  990:         if ($locale_names{$item} ne '') {
  991:             $output.="  $locale_names{$item}</option>\n";
  992:         }
  993:         $output.="</option>\n";
  994:     }
  995:     $output.="</select>";
  996:     return $output;
  997: }
  998: 
  999: sub select_language {
 1000:     my ($name,$selected,$includeempty) = @_;
 1001:     my %langchoices;
 1002:     if ($includeempty) {
 1003:         %langchoices = ('' => 'No language preference');
 1004:     }
 1005:     foreach my $id (&languageids()) {
 1006:         my $code = &supportedlanguagecode($id);
 1007:         if ($code) {
 1008:             $langchoices{$code} = &plainlanguagedescription($id);
 1009:         }
 1010:     }
 1011:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1012:     return &select_form($selected,$name,\%langchoices);
 1013: }
 1014: 
 1015: =pod
 1016: 
 1017: =item * &linked_select_forms(...)
 1018: 
 1019: linked_select_forms returns a string containing a <script></script> block
 1020: and html for two <select> menus.  The select menus will be linked in that
 1021: changing the value of the first menu will result in new values being placed
 1022: in the second menu.  The values in the select menu will appear in alphabetical
 1023: order unless a defined order is provided.
 1024: 
 1025: linked_select_forms takes the following ordered inputs:
 1026: 
 1027: =over 4
 1028: 
 1029: =item * $formname, the name of the <form> tag
 1030: 
 1031: =item * $middletext, the text which appears between the <select> tags
 1032: 
 1033: =item * $firstdefault, the default value for the first menu
 1034: 
 1035: =item * $firstselectname, the name of the first <select> tag
 1036: 
 1037: =item * $secondselectname, the name of the second <select> tag
 1038: 
 1039: =item * $hashref, a reference to a hash containing the data for the menus.
 1040: 
 1041: =item * $menuorder, the order of values in the first menu
 1042: 
 1043: =item * $onchangefirst, additional javascript call to execute for an onchange
 1044:         event for the first <select> tag
 1045: 
 1046: =item * $onchangesecond, additional javascript call to execute for an onchange
 1047:         event for the second <select> tag
 1048: 
 1049: =back 
 1050: 
 1051: Below is an example of such a hash.  Only the 'text', 'default', and 
 1052: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1053: values for the first select menu.  The text that coincides with the 
 1054: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1055: and text for the second menu are given in the hash pointed to by 
 1056: $menu{$choice1}->{'select2'}.  
 1057: 
 1058:  my %menu = ( A1 => { text =>"Choice A1" ,
 1059:                        default => "B3",
 1060:                        select2 => { 
 1061:                            B1 => "Choice B1",
 1062:                            B2 => "Choice B2",
 1063:                            B3 => "Choice B3",
 1064:                            B4 => "Choice B4"
 1065:                            },
 1066:                        order => ['B4','B3','B1','B2'],
 1067:                    },
 1068:                A2 => { text =>"Choice A2" ,
 1069:                        default => "C2",
 1070:                        select2 => { 
 1071:                            C1 => "Choice C1",
 1072:                            C2 => "Choice C2",
 1073:                            C3 => "Choice C3"
 1074:                            },
 1075:                        order => ['C2','C1','C3'],
 1076:                    },
 1077:                A3 => { text =>"Choice A3" ,
 1078:                        default => "D6",
 1079:                        select2 => { 
 1080:                            D1 => "Choice D1",
 1081:                            D2 => "Choice D2",
 1082:                            D3 => "Choice D3",
 1083:                            D4 => "Choice D4",
 1084:                            D5 => "Choice D5",
 1085:                            D6 => "Choice D6",
 1086:                            D7 => "Choice D7"
 1087:                            },
 1088:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1089:                    }
 1090:                );
 1091: 
 1092: =cut
 1093: 
 1094: sub linked_select_forms {
 1095:     my ($formname,
 1096:         $middletext,
 1097:         $firstdefault,
 1098:         $firstselectname,
 1099:         $secondselectname, 
 1100:         $hashref,
 1101:         $menuorder,
 1102:         $onchangefirst,
 1103:         $onchangesecond
 1104:         ) = @_;
 1105:     my $second = "document.$formname.$secondselectname";
 1106:     my $first = "document.$formname.$firstselectname";
 1107:     # output the javascript to do the changing
 1108:     my $result = '';
 1109:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1110:     $result.="// <![CDATA[\n";
 1111:     $result.="var select2data = new Object();\n";
 1112:     $" = '","';
 1113:     my $debug = '';
 1114:     foreach my $s1 (sort(keys(%$hashref))) {
 1115:         $result.="select2data.d_$s1 = new Object();\n";        
 1116:         $result.="select2data.d_$s1.def = new String('".
 1117:             $hashref->{$s1}->{'default'}."');\n";
 1118:         $result.="select2data.d_$s1.values = new Array(";
 1119:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1120:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1121:             @s2values = @{$hashref->{$s1}->{'order'}};
 1122:         }
 1123:         $result.="\"@s2values\");\n";
 1124:         $result.="select2data.d_$s1.texts = new Array(";        
 1125:         my @s2texts;
 1126:         foreach my $value (@s2values) {
 1127:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1128:         }
 1129:         $result.="\"@s2texts\");\n";
 1130:     }
 1131:     $"=' ';
 1132:     $result.= <<"END";
 1133: 
 1134: function select1_changed() {
 1135:     // Determine new choice
 1136:     var newvalue = "d_" + $first.value;
 1137:     // update select2
 1138:     var values     = select2data[newvalue].values;
 1139:     var texts      = select2data[newvalue].texts;
 1140:     var select2def = select2data[newvalue].def;
 1141:     var i;
 1142:     // out with the old
 1143:     for (i = 0; i < $second.options.length; i++) {
 1144:         $second.options[i] = null;
 1145:     }
 1146:     // in with the nuclear
 1147:     for (i=0;i<values.length; i++) {
 1148:         $second.options[i] = new Option(values[i]);
 1149:         $second.options[i].value = values[i];
 1150:         $second.options[i].text = texts[i];
 1151:         if (values[i] == select2def) {
 1152:             $second.options[i].selected = true;
 1153:         }
 1154:     }
 1155: }
 1156: // ]]>
 1157: </script>
 1158: END
 1159:     # output the initial values for the selection lists
 1160:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1161:     my @order = sort(keys(%{$hashref}));
 1162:     if (ref($menuorder) eq 'ARRAY') {
 1163:         @order = @{$menuorder};
 1164:     }
 1165:     foreach my $value (@order) {
 1166:         $result.="    <option value=\"$value\" ";
 1167:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1168:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1169:     }
 1170:     $result .= "</select>\n";
 1171:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1172:     $result .= $middletext;
 1173:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1174:     if ($onchangesecond) {
 1175:         $result .= ' onchange="'.$onchangesecond.'"';
 1176:     }
 1177:     $result .= ">\n";
 1178:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1179:     
 1180:     my @secondorder = sort(keys(%select2));
 1181:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1182:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1183:     }
 1184:     foreach my $value (@secondorder) {
 1185:         $result.="    <option value=\"$value\" ";        
 1186:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1187:         $result.=">".&mt($select2{$value})."</option>\n";
 1188:     }
 1189:     $result .= "</select>\n";
 1190:     #    return $debug;
 1191:     return $result;
 1192: }   #  end of sub linked_select_forms {
 1193: 
 1194: =pod
 1195: 
 1196: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1197: 
 1198: Returns a string corresponding to an HTML link to the given help
 1199: $topic, where $topic corresponds to the name of a .tex file in
 1200: /home/httpd/html/adm/help/tex, with underscores replaced by
 1201: spaces. 
 1202: 
 1203: $text will optionally be linked to the same topic, allowing you to
 1204: link text in addition to the graphic. If you do not want to link
 1205: text, but wish to specify one of the later parameters, pass an
 1206: empty string. 
 1207: 
 1208: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1209: the link will not open a new window. If false, the link will open
 1210: a new window using Javascript. (Default is false.) 
 1211: 
 1212: $width and $height are optional numerical parameters that will
 1213: override the width and height of the popped up window, which may
 1214: be useful for certain help topics with big pictures included.
 1215: 
 1216: $imgid is the id of the img tag used for the help icon. This may be
 1217: used in a javascript call to switch the image src.  See 
 1218: lonhtmlcommon::htmlareaselectactive() for an example.
 1219: 
 1220: =cut
 1221: 
 1222: sub help_open_topic {
 1223:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1224:     $text = "" if (not defined $text);
 1225:     $stayOnPage = 0 if (not defined $stayOnPage);
 1226:     $width = 500 if (not defined $width);
 1227:     $height = 400 if (not defined $height);
 1228:     my $filename = $topic;
 1229:     $filename =~ s/ /_/g;
 1230: 
 1231:     my $template = "";
 1232:     my $link;
 1233:     
 1234:     $topic=~s/\W/\_/g;
 1235: 
 1236:     if (!$stayOnPage) {
 1237:         if ($env{'browser.mobile'}) {
 1238: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1239:         } else {
 1240:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1241:         }
 1242:     } elsif ($stayOnPage eq 'popup') {
 1243:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1244:     } else {
 1245: 	$link = "/adm/help/${filename}.hlp";
 1246:     }
 1247: 
 1248:     # Add the text
 1249:     if ($text ne "") {	
 1250: 	$template.='<span class="LC_help_open_topic">'
 1251:                   .'<a target="_top" href="'.$link.'">'
 1252:                   .$text.'</a>';
 1253:     }
 1254: 
 1255:     # (Always) Add the graphic
 1256:     my $title = &mt('Online Help');
 1257:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1258:     if ($imgid ne '') {
 1259:         $imgid = ' id="'.$imgid.'"';
 1260:     }
 1261:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1262:               .'<img src="'.$helpicon.'" border="0"'
 1263:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1264:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1265:               .' /></a>';
 1266:     if ($text ne "") {	
 1267:         $template.='</span>';
 1268:     }
 1269:     return $template;
 1270: 
 1271: }
 1272: 
 1273: # This is a quicky function for Latex cheatsheet editing, since it 
 1274: # appears in at least four places
 1275: sub helpLatexCheatsheet {
 1276:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1277:     my $out;
 1278:     my $addOther = '';
 1279:     if ($topic) {
 1280: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1281:     }
 1282:     $out = '<span>' # Start cheatsheet
 1283: 	  .$addOther
 1284:           .'<span>'
 1285: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1286: 	  .'</span> <span>'
 1287: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1288: 	  .'</span>';
 1289:     unless ($not_author) {
 1290:         $out .= ' <span>'
 1291: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1292: 	       .'</span>';
 1293:     }
 1294:     $out .= '</span>'; # End cheatsheet
 1295:     return $out;
 1296: }
 1297: 
 1298: sub general_help {
 1299:     my $helptopic='Student_Intro';
 1300:     if ($env{'request.role'}=~/^(ca|au)/) {
 1301: 	$helptopic='Authoring_Intro';
 1302:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1303: 	$helptopic='Course_Coordination_Intro';
 1304:     } elsif ($env{'request.role'}=~/^dc/) {
 1305:         $helptopic='Domain_Coordination_Intro';
 1306:     }
 1307:     return $helptopic;
 1308: }
 1309: 
 1310: sub update_help_link {
 1311:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1312:     my $origurl = $ENV{'REQUEST_URI'};
 1313:     $origurl=~s|^/~|/priv/|;
 1314:     my $timestamp = time;
 1315:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1316:         $$datum = &escape($$datum);
 1317:     }
 1318: 
 1319:     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";
 1320:     my $output .= <<"ENDOUTPUT";
 1321: <script type="text/javascript">
 1322: // <![CDATA[
 1323: banner_link = '$banner_link';
 1324: // ]]>
 1325: </script>
 1326: ENDOUTPUT
 1327:     return $output;
 1328: }
 1329: 
 1330: # now just updates the help link and generates a blue icon
 1331: sub help_open_menu {
 1332:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1333: 	= @_;    
 1334:     $stayOnPage = 1;
 1335:     my $output;
 1336:     if ($component_help) {
 1337: 	if (!$text) {
 1338: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1339: 				       $width,$height);
 1340: 	} else {
 1341: 	    my $help_text;
 1342: 	    $help_text=&unescape($topic);
 1343: 	    $output='<table><tr><td>'.
 1344: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1345: 				 $width,$height).'</td></tr></table>';
 1346: 	}
 1347:     }
 1348:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1349:     return $output.$banner_link;
 1350: }
 1351: 
 1352: sub top_nav_help {
 1353:     my ($text) = @_;
 1354:     $text = &mt($text);
 1355:     my $stay_on_page;
 1356:     unless ($env{'environment.remote'} eq 'on') {
 1357:         $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 ($httphost) = @_;
 1373:     my $stayOnPage = 1;
 1374:     my $width = 620;
 1375:     my $height = 600;
 1376:     my $helptopic=&general_help();
 1377:     my $details_link = $httphost.'/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:                                         'use_absolute' => $httphost, 
 1384: 					'add_entries' => {
 1385: 					    'border' => '0',
 1386: 					    'rows'   => "110,*",},});
 1387:     my $end_page =
 1388:         &Apache::loncommon::end_page({'frameset' => 1,
 1389: 				      'js_ready' => 1,});
 1390: 
 1391:     my $template .= <<"ENDTEMPLATE";
 1392: <script type="text/javascript">
 1393: // <![CDATA[
 1394: // <!-- BEGIN LON-CAPA Internal
 1395: var banner_link = '';
 1396: function helpMenu(target) {
 1397:     var caller = this;
 1398:     if (target == 'open') {
 1399:         var newWindow = null;
 1400:         try {
 1401:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1402:         }
 1403:         catch(error) {
 1404:             writeHelp(caller);
 1405:             return;
 1406:         }
 1407:         if (newWindow) {
 1408:             caller = newWindow;
 1409:         }
 1410:     }
 1411:     writeHelp(caller);
 1412:     return;
 1413: }
 1414: function writeHelp(caller) {
 1415:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1416:     caller.document.close()
 1417:     caller.focus()
 1418: }
 1419: // END LON-CAPA Internal -->
 1420: // ]]>
 1421: </script>
 1422: ENDTEMPLATE
 1423:     return $template;
 1424: }
 1425: 
 1426: sub help_open_bug {
 1427:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1428:     unless ($env{'user.adv'}) { return ''; }
 1429:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1430:     $text = "" if (not defined $text);
 1431: 	$stayOnPage=1;
 1432:     $width = 600 if (not defined $width);
 1433:     $height = 600 if (not defined $height);
 1434: 
 1435:     $topic=~s/\W+/\+/g;
 1436:     my $link='';
 1437:     my $template='';
 1438:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1439: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1440:     if (!$stayOnPage)
 1441:     {
 1442: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1443:     }
 1444:     else
 1445:     {
 1446: 	$link = $url;
 1447:     }
 1448:     # Add the text
 1449:     if ($text ne "")
 1450:     {
 1451: 	$template .= 
 1452:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1453:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1454:     }
 1455: 
 1456:     # Add the graphic
 1457:     my $title = &mt('Report a Bug');
 1458:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1459:     $template .= <<"ENDTEMPLATE";
 1460:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1461: ENDTEMPLATE
 1462:     if ($text ne '') { $template.='</td></tr></table>' };
 1463:     return $template;
 1464: 
 1465: }
 1466: 
 1467: sub help_open_faq {
 1468:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1469:     unless ($env{'user.adv'}) { return ''; }
 1470:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1471:     $text = "" if (not defined $text);
 1472: 	$stayOnPage=1;
 1473:     $width = 350 if (not defined $width);
 1474:     $height = 400 if (not defined $height);
 1475: 
 1476:     $topic=~s/\W+/\+/g;
 1477:     my $link='';
 1478:     my $template='';
 1479:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1480:     if (!$stayOnPage)
 1481:     {
 1482: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1483:     }
 1484:     else
 1485:     {
 1486: 	$link = $url;
 1487:     }
 1488: 
 1489:     # Add the text
 1490:     if ($text ne "")
 1491:     {
 1492: 	$template .= 
 1493:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1494:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1495:     }
 1496: 
 1497:     # Add the graphic
 1498:     my $title = &mt('View the FAQ');
 1499:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1500:     $template .= <<"ENDTEMPLATE";
 1501:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1502: ENDTEMPLATE
 1503:     if ($text ne '') { $template.='</td></tr></table>' };
 1504:     return $template;
 1505: 
 1506: }
 1507: 
 1508: ###############################################################
 1509: ###############################################################
 1510: 
 1511: =pod
 1512: 
 1513: =item * &change_content_javascript():
 1514: 
 1515: This and the next function allow you to create small sections of an
 1516: otherwise static HTML page that you can update on the fly with
 1517: Javascript, even in Netscape 4.
 1518: 
 1519: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1520: must be written to the HTML page once. It will prove the Javascript
 1521: function "change(name, content)". Calling the change function with the
 1522: name of the section 
 1523: you want to update, matching the name passed to C<changable_area>, and
 1524: the new content you want to put in there, will put the content into
 1525: that area.
 1526: 
 1527: B<Note>: Netscape 4 only reserves enough space for the changable area
 1528: to contain room for the original contents. You need to "make space"
 1529: for whatever changes you wish to make, and be B<sure> to check your
 1530: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1531: it's adequate for updating a one-line status display, but little more.
 1532: This script will set the space to 100% width, so you only need to
 1533: worry about height in Netscape 4.
 1534: 
 1535: Modern browsers are much less limiting, and if you can commit to the
 1536: user not using Netscape 4, this feature may be used freely with
 1537: pretty much any HTML.
 1538: 
 1539: =cut
 1540: 
 1541: sub change_content_javascript {
 1542:     # If we're on Netscape 4, we need to use Layer-based code
 1543:     if ($env{'browser.type'} eq 'netscape' &&
 1544: 	$env{'browser.version'} =~ /^4\./) {
 1545: 	return (<<NETSCAPE4);
 1546: 	function change(name, content) {
 1547: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1548: 	    doc.open();
 1549: 	    doc.write(content);
 1550: 	    doc.close();
 1551: 	}
 1552: NETSCAPE4
 1553:     } else {
 1554: 	# Otherwise, we need to use semi-standards-compliant code
 1555: 	# (technically, "innerHTML" isn't standard but the equivalent
 1556: 	# is really scary, and every useful browser supports it
 1557: 	return (<<DOMBASED);
 1558: 	function change(name, content) {
 1559: 	    element = document.getElementById(name);
 1560: 	    element.innerHTML = content;
 1561: 	}
 1562: DOMBASED
 1563:     }
 1564: }
 1565: 
 1566: =pod
 1567: 
 1568: =item * &changable_area($name,$origContent):
 1569: 
 1570: This provides a "changable area" that can be modified on the fly via
 1571: the Javascript code provided in C<change_content_javascript>. $name is
 1572: the name you will use to reference the area later; do not repeat the
 1573: same name on a given HTML page more then once. $origContent is what
 1574: the area will originally contain, which can be left blank.
 1575: 
 1576: =cut
 1577: 
 1578: sub changable_area {
 1579:     my ($name, $origContent) = @_;
 1580: 
 1581:     if ($env{'browser.type'} eq 'netscape' &&
 1582: 	$env{'browser.version'} =~ /^4\./) {
 1583: 	# If this is netscape 4, we need to use the Layer tag
 1584: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1585:     } else {
 1586: 	return "<span id='$name'>$origContent</span>";
 1587:     }
 1588: }
 1589: 
 1590: =pod
 1591: 
 1592: =item * &viewport_geometry_js 
 1593: 
 1594: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1595: 
 1596: =cut
 1597: 
 1598: 
 1599: sub viewport_geometry_js { 
 1600:     return <<"GEOMETRY";
 1601: var Geometry = {};
 1602: function init_geometry() {
 1603:     if (Geometry.init) { return };
 1604:     Geometry.init=1;
 1605:     if (window.innerHeight) {
 1606:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1607:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1608:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1609:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1610:     }
 1611:     else if (document.documentElement && document.documentElement.clientHeight) {
 1612:         Geometry.getViewportHeight =
 1613:             function() { return document.documentElement.clientHeight; };
 1614:         Geometry.getViewportWidth =
 1615:             function() { return document.documentElement.clientWidth; };
 1616: 
 1617:         Geometry.getHorizontalScroll =
 1618:             function() { return document.documentElement.scrollLeft; };
 1619:         Geometry.getVerticalScroll =
 1620:             function() { return document.documentElement.scrollTop; };
 1621:     }
 1622:     else if (document.body.clientHeight) {
 1623:         Geometry.getViewportHeight =
 1624:             function() { return document.body.clientHeight; };
 1625:         Geometry.getViewportWidth =
 1626:             function() { return document.body.clientWidth; };
 1627:         Geometry.getHorizontalScroll =
 1628:             function() { return document.body.scrollLeft; };
 1629:         Geometry.getVerticalScroll =
 1630:             function() { return document.body.scrollTop; };
 1631:     }
 1632: }
 1633: 
 1634: GEOMETRY
 1635: }
 1636: 
 1637: =pod
 1638: 
 1639: =item * &viewport_size_js()
 1640: 
 1641: 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. 
 1642: 
 1643: =cut
 1644: 
 1645: sub viewport_size_js {
 1646:     my $geometry = &viewport_geometry_js();
 1647:     return <<"DIMS";
 1648: 
 1649: $geometry
 1650: 
 1651: function getViewportDims(width,height) {
 1652:     init_geometry();
 1653:     width.value = Geometry.getViewportWidth();
 1654:     height.value = Geometry.getViewportHeight();
 1655:     return;
 1656: }
 1657: 
 1658: DIMS
 1659: }
 1660: 
 1661: =pod
 1662: 
 1663: =item * &resize_textarea_js()
 1664: 
 1665: emits the needed javascript to resize a textarea to be as big as possible
 1666: 
 1667: creates a function resize_textrea that takes two IDs first should be
 1668: the id of the element to resize, second should be the id of a div that
 1669: surrounds everything that comes after the textarea, this routine needs
 1670: to be attached to the <body> for the onload and onresize events.
 1671: 
 1672: =back
 1673: 
 1674: =cut
 1675: 
 1676: sub resize_textarea_js {
 1677:     my $geometry = &viewport_geometry_js();
 1678:     return <<"RESIZE";
 1679:     <script type="text/javascript">
 1680: // <![CDATA[
 1681: $geometry
 1682: 
 1683: function getX(element) {
 1684:     var x = 0;
 1685:     while (element) {
 1686: 	x += element.offsetLeft;
 1687: 	element = element.offsetParent;
 1688:     }
 1689:     return x;
 1690: }
 1691: function getY(element) {
 1692:     var y = 0;
 1693:     while (element) {
 1694: 	y += element.offsetTop;
 1695: 	element = element.offsetParent;
 1696:     }
 1697:     return y;
 1698: }
 1699: 
 1700: 
 1701: function resize_textarea(textarea_id,bottom_id) {
 1702:     init_geometry();
 1703:     var textarea        = document.getElementById(textarea_id);
 1704:     //alert(textarea);
 1705: 
 1706:     var textarea_top    = getY(textarea);
 1707:     var textarea_height = textarea.offsetHeight;
 1708:     var bottom          = document.getElementById(bottom_id);
 1709:     var bottom_top      = getY(bottom);
 1710:     var bottom_height   = bottom.offsetHeight;
 1711:     var window_height   = Geometry.getViewportHeight();
 1712:     var fudge           = 23;
 1713:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1714:     if (new_height < 300) {
 1715: 	new_height = 300;
 1716:     }
 1717:     textarea.style.height=new_height+'px';
 1718: }
 1719: // ]]>
 1720: </script>
 1721: RESIZE
 1722: 
 1723: }
 1724: 
 1725: =pod
 1726: 
 1727: =head1 Excel and CSV file utility routines
 1728: 
 1729: =cut
 1730: 
 1731: ###############################################################
 1732: ###############################################################
 1733: 
 1734: =pod
 1735: 
 1736: =over 4
 1737: 
 1738: =item * &csv_translate($text) 
 1739: 
 1740: Translate $text to allow it to be output as a 'comma separated values' 
 1741: format.
 1742: 
 1743: =cut
 1744: 
 1745: ###############################################################
 1746: ###############################################################
 1747: sub csv_translate {
 1748:     my $text = shift;
 1749:     $text =~ s/\"/\"\"/g;
 1750:     $text =~ s/\n/ /g;
 1751:     return $text;
 1752: }
 1753: 
 1754: ###############################################################
 1755: ###############################################################
 1756: 
 1757: =pod
 1758: 
 1759: =item * &define_excel_formats()
 1760: 
 1761: Define some commonly used Excel cell formats.
 1762: 
 1763: Currently supported formats:
 1764: 
 1765: =over 4
 1766: 
 1767: =item header
 1768: 
 1769: =item bold
 1770: 
 1771: =item h1
 1772: 
 1773: =item h2
 1774: 
 1775: =item h3
 1776: 
 1777: =item h4
 1778: 
 1779: =item i
 1780: 
 1781: =item date
 1782: 
 1783: =back
 1784: 
 1785: Inputs: $workbook
 1786: 
 1787: Returns: $format, a hash reference.
 1788: 
 1789: 
 1790: =cut
 1791: 
 1792: ###############################################################
 1793: ###############################################################
 1794: sub define_excel_formats {
 1795:     my ($workbook) = @_;
 1796:     my $format;
 1797:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1798:                                                 bottom    => 1,
 1799:                                                 align     => 'center');
 1800:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1801:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1802:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1803:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1804:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1805:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1806:     $format->{'date'} = $workbook->add_format(num_format=>
 1807:                                             'mm/dd/yyyy hh:mm:ss');
 1808:     return $format;
 1809: }
 1810: 
 1811: ###############################################################
 1812: ###############################################################
 1813: 
 1814: =pod
 1815: 
 1816: =item * &create_workbook()
 1817: 
 1818: Create an Excel worksheet.  If it fails, output message on the
 1819: request object and return undefs.
 1820: 
 1821: Inputs: Apache request object
 1822: 
 1823: Returns (undef) on failure, 
 1824:     Excel worksheet object, scalar with filename, and formats 
 1825:     from &Apache::loncommon::define_excel_formats on success
 1826: 
 1827: =cut
 1828: 
 1829: ###############################################################
 1830: ###############################################################
 1831: sub create_workbook {
 1832:     my ($r) = @_;
 1833:         #
 1834:     # Create the excel spreadsheet
 1835:     my $filename = '/prtspool/'.
 1836:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1837:         time.'_'.rand(1000000000).'.xls';
 1838:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1839:     if (! defined($workbook)) {
 1840:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1841:         $r->print(
 1842:             '<p class="LC_error">'
 1843:            .&mt('Problems occurred in creating the new Excel file.')
 1844:            .' '.&mt('This error has been logged.')
 1845:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1846:            .'</p>'
 1847:         );
 1848:         return (undef);
 1849:     }
 1850:     #
 1851:     $workbook->set_tempdir(LONCAPA::tempdir());
 1852:     #
 1853:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1854:     return ($workbook,$filename,$format);
 1855: }
 1856: 
 1857: ###############################################################
 1858: ###############################################################
 1859: 
 1860: =pod
 1861: 
 1862: =item * &create_text_file()
 1863: 
 1864: Create a file to write to and eventually make available to the user.
 1865: If file creation fails, outputs an error message on the request object and 
 1866: return undefs.
 1867: 
 1868: Inputs: Apache request object, and file suffix
 1869: 
 1870: Returns (undef) on failure, 
 1871:     Filehandle and filename on success.
 1872: 
 1873: =cut
 1874: 
 1875: ###############################################################
 1876: ###############################################################
 1877: sub create_text_file {
 1878:     my ($r,$suffix) = @_;
 1879:     if (! defined($suffix)) { $suffix = 'txt'; };
 1880:     my $fh;
 1881:     my $filename = '/prtspool/'.
 1882:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1883:         time.'_'.rand(1000000000).'.'.$suffix;
 1884:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1885:     if (! defined($fh)) {
 1886:         $r->log_error("Couldn't open $filename for output $!");
 1887:         $r->print(
 1888:             '<p class="LC_error">'
 1889:            .&mt('Problems occurred in creating the output file.')
 1890:            .' '.&mt('This error has been logged.')
 1891:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1892:            .'</p>'
 1893:         );
 1894:     }
 1895:     return ($fh,$filename)
 1896: }
 1897: 
 1898: 
 1899: =pod 
 1900: 
 1901: =back
 1902: 
 1903: =cut
 1904: 
 1905: ###############################################################
 1906: ##        Home server <option> list generating code          ##
 1907: ###############################################################
 1908: 
 1909: # ------------------------------------------
 1910: 
 1911: sub domain_select {
 1912:     my ($name,$value,$multiple)=@_;
 1913:     my %domains=map { 
 1914: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1915:     } &Apache::lonnet::all_domains();
 1916:     if ($multiple) {
 1917: 	$domains{''}=&mt('Any domain');
 1918: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1919: 	return &multiple_select_form($name,$value,4,\%domains);
 1920:     } else {
 1921: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1922: 	return &select_form($name,$value,\%domains);
 1923:     }
 1924: }
 1925: 
 1926: #-------------------------------------------
 1927: 
 1928: =pod
 1929: 
 1930: =head1 Routines for form select boxes
 1931: 
 1932: =over 4
 1933: 
 1934: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1935: 
 1936: Returns a string containing a <select> element int multiple mode
 1937: 
 1938: 
 1939: Args:
 1940:   $name - name of the <select> element
 1941:   $value - scalar or array ref of values that should already be selected
 1942:   $size - number of rows long the select element is
 1943:   $hash - the elements should be 'option' => 'shown text'
 1944:           (shown text should already have been &mt())
 1945:   $order - (optional) array ref of the order to show the elements in
 1946: 
 1947: =cut
 1948: 
 1949: #-------------------------------------------
 1950: sub multiple_select_form {
 1951:     my ($name,$value,$size,$hash,$order)=@_;
 1952:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1953:     my $output='';
 1954:     if (! defined($size)) {
 1955:         $size = 4;
 1956:         if (scalar(keys(%$hash))<4) {
 1957:             $size = scalar(keys(%$hash));
 1958:         }
 1959:     }
 1960:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1961:     my @order;
 1962:     if (ref($order) eq 'ARRAY')  {
 1963:         @order = @{$order};
 1964:     } else {
 1965:         @order = sort(keys(%$hash));
 1966:     }
 1967:     if (exists($$hash{'select_form_order'})) {
 1968:         @order = @{$$hash{'select_form_order'}};
 1969:     }
 1970:         
 1971:     foreach my $key (@order) {
 1972:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1973:         $output.='selected="selected" ' if ($selected{$key});
 1974:         $output.='>'.$hash->{$key}."</option>\n";
 1975:     }
 1976:     $output.="</select>\n";
 1977:     return $output;
 1978: }
 1979: 
 1980: #-------------------------------------------
 1981: 
 1982: =pod
 1983: 
 1984: =item * &select_form($defdom,$name,$hashref,$onchange)
 1985: 
 1986: Returns a string containing a <select name='$name' size='1'> form to 
 1987: allow a user to select options from a ref to a hash containing:
 1988: option_name => displayed text. An optional $onchange can include
 1989: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1990: 
 1991: See lonrights.pm for an example invocation and use.
 1992: 
 1993: =cut
 1994: 
 1995: #-------------------------------------------
 1996: sub select_form {
 1997:     my ($def,$name,$hashref,$onchange) = @_;
 1998:     return unless (ref($hashref) eq 'HASH');
 1999:     if ($onchange) {
 2000:         $onchange = ' onchange="'.$onchange.'"';
 2001:     }
 2002:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2003:     my @keys;
 2004:     if (exists($hashref->{'select_form_order'})) {
 2005: 	@keys=@{$hashref->{'select_form_order'}};
 2006:     } else {
 2007: 	@keys=sort(keys(%{$hashref}));
 2008:     }
 2009:     foreach my $key (@keys) {
 2010:         $selectform.=
 2011: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2012:             ($key eq $def ? 'selected="selected" ' : '').
 2013:                 ">".$hashref->{$key}."</option>\n";
 2014:     }
 2015:     $selectform.="</select>";
 2016:     return $selectform;
 2017: }
 2018: 
 2019: # For display filters
 2020: 
 2021: sub display_filter {
 2022:     my ($context) = @_;
 2023:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2024:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2025:     my $phraseinput = 'hidden';
 2026:     my $includeinput = 'hidden';
 2027:     my ($checked,$includetypestext);
 2028:     if ($env{'form.displayfilter'} eq 'containing') {
 2029:         $phraseinput = 'text'; 
 2030:         if ($context eq 'parmslog') {
 2031:             $includeinput = 'checkbox';
 2032:             if ($env{'form.includetypes'}) {
 2033:                 $checked = ' checked="checked"';
 2034:             }
 2035:             $includetypestext = &mt('Include parameter types');
 2036:         }
 2037:     } else {
 2038:         $includetypestext = '&nbsp;';
 2039:     }
 2040:     my ($additional,$secondid,$thirdid);
 2041:     if ($context eq 'parmslog') {
 2042:         $additional = 
 2043:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2044:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2045:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2046:             '</label>';
 2047:         $secondid = 'includetypes';
 2048:         $thirdid = 'includetypestext';
 2049:     }
 2050:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2051:                                                     '$secondid','$thirdid')";
 2052:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2053: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2054: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2055: 	   '</label></span> <span class="LC_nobreak">'.
 2056:            &mt('Filter: [_1]',
 2057: 	   &select_form($env{'form.displayfilter'},
 2058: 			'displayfilter',
 2059: 			{'currentfolder' => 'Current folder/page',
 2060: 			 'containing' => 'Containing phrase',
 2061: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2062: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2063:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2064:                          '" />'.$additional;
 2065: }
 2066: 
 2067: sub display_filter_js {
 2068:     my $includetext = &mt('Include parameter types');
 2069:     return <<"ENDJS";
 2070:   
 2071: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2072:     var firstType = 'hidden';
 2073:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2074:         firstType = 'text';
 2075:     }
 2076:     firstObject = document.getElementById(firstid);
 2077:     if (typeof(firstObject) == 'object') {
 2078:         if (firstObject.type != firstType) {
 2079:             changeInputType(firstObject,firstType);
 2080:         }
 2081:     }
 2082:     if (context == 'parmslog') {
 2083:         var secondType = 'hidden';
 2084:         if (firstType == 'text') {
 2085:             secondType = 'checkbox';
 2086:         }
 2087:         secondObject = document.getElementById(secondid);  
 2088:         if (typeof(secondObject) == 'object') {
 2089:             if (secondObject.type != secondType) {
 2090:                 changeInputType(secondObject,secondType);
 2091:             }
 2092:         }
 2093:         var textItem = document.getElementById(thirdid);
 2094:         var currtext = textItem.innerHTML;
 2095:         var newtext;
 2096:         if (firstType == 'text') {
 2097:             newtext = '$includetext';
 2098:         } else {
 2099:             newtext = '&nbsp;';
 2100:         }
 2101:         if (currtext != newtext) {
 2102:             textItem.innerHTML = newtext;
 2103:         }
 2104:     }
 2105:     return;
 2106: }
 2107: 
 2108: function changeInputType(oldObject,newType) {
 2109:     var newObject = document.createElement('input');
 2110:     newObject.type = newType;
 2111:     if (oldObject.size) {
 2112:         newObject.size = oldObject.size;
 2113:     }
 2114:     if (oldObject.value) {
 2115:         newObject.value = oldObject.value;
 2116:     }
 2117:     if (oldObject.name) {
 2118:         newObject.name = oldObject.name;
 2119:     }
 2120:     if (oldObject.id) {
 2121:         newObject.id = oldObject.id;
 2122:     }
 2123:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2124:     return;
 2125: }
 2126: 
 2127: ENDJS
 2128: }
 2129: 
 2130: sub gradeleveldescription {
 2131:     my $gradelevel=shift;
 2132:     my %gradelevels=(0 => 'Not specified',
 2133: 		     1 => 'Grade 1',
 2134: 		     2 => 'Grade 2',
 2135: 		     3 => 'Grade 3',
 2136: 		     4 => 'Grade 4',
 2137: 		     5 => 'Grade 5',
 2138: 		     6 => 'Grade 6',
 2139: 		     7 => 'Grade 7',
 2140: 		     8 => 'Grade 8',
 2141: 		     9 => 'Grade 9',
 2142: 		     10 => 'Grade 10',
 2143: 		     11 => 'Grade 11',
 2144: 		     12 => 'Grade 12',
 2145: 		     13 => 'Grade 13',
 2146: 		     14 => '100 Level',
 2147: 		     15 => '200 Level',
 2148: 		     16 => '300 Level',
 2149: 		     17 => '400 Level',
 2150: 		     18 => 'Graduate Level');
 2151:     return &mt($gradelevels{$gradelevel});
 2152: }
 2153: 
 2154: sub select_level_form {
 2155:     my ($deflevel,$name)=@_;
 2156:     unless ($deflevel) { $deflevel=0; }
 2157:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2158:     for (my $i=0; $i<=18; $i++) {
 2159:         $selectform.="<option value=\"$i\" ".
 2160:             ($i==$deflevel ? 'selected="selected" ' : '').
 2161:                 ">".&gradeleveldescription($i)."</option>\n";
 2162:     }
 2163:     $selectform.="</select>";
 2164:     return $selectform;
 2165: }
 2166: 
 2167: #-------------------------------------------
 2168: 
 2169: =pod
 2170: 
 2171: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2172: 
 2173: Returns a string containing a <select name='$name' size='1'> form to 
 2174: allow a user to select the domain to preform an operation in.  
 2175: See loncreateuser.pm for an example invocation and use.
 2176: 
 2177: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2178: selected");
 2179: 
 2180: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2181: 
 2182: 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.
 2183: 
 2184: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2185: 
 2186: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
 2187: 
 2188: =cut
 2189: 
 2190: #-------------------------------------------
 2191: sub select_dom_form {
 2192:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2193:     if ($onchange) {
 2194:         $onchange = ' onchange="'.$onchange.'"';
 2195:     }
 2196:     my (@domains,%exclude);
 2197:     if (ref($incdoms) eq 'ARRAY') {
 2198:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2199:     } else {
 2200:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2201:     }
 2202:     if ($includeempty) { @domains=('',@domains); }
 2203:     if (ref($excdoms) eq 'ARRAY') {
 2204:         map { $exclude{$_} = 1; } @{$excdoms};
 2205:     }
 2206:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2207:     foreach my $dom (@domains) {
 2208:         next if ($exclude{$dom});
 2209:         $selectdomain.="<option value=\"$dom\" ".
 2210:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2211:         if ($showdomdesc) {
 2212:             if ($dom ne '') {
 2213:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2214:                 if ($domdesc ne '') {
 2215:                     $selectdomain .= ' ('.$domdesc.')';
 2216:                 }
 2217:             } 
 2218:         }
 2219:         $selectdomain .= "</option>\n";
 2220:     }
 2221:     $selectdomain.="</select>";
 2222:     return $selectdomain;
 2223: }
 2224: 
 2225: #-------------------------------------------
 2226: 
 2227: =pod
 2228: 
 2229: =item * &home_server_form_item($domain,$name,$defaultflag)
 2230: 
 2231: input: 4 arguments (two required, two optional) - 
 2232:     $domain - domain of new user
 2233:     $name - name of form element
 2234:     $default - Value of 'default' causes a default item to be first 
 2235:                             option, and selected by default. 
 2236:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2237:                             if 1 server found, or default, if 0 found.
 2238: output: returns 2 items: 
 2239: (a) form element which contains either:
 2240:    (i) <select name="$name">
 2241:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2242:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2243:        </select>
 2244:        form item if there are multiple library servers in $domain, or
 2245:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2246:        if there is only one library server in $domain.
 2247: 
 2248: (b) number of library servers found.
 2249: 
 2250: See loncreateuser.pm for example of use.
 2251: 
 2252: =cut
 2253: 
 2254: #-------------------------------------------
 2255: sub home_server_form_item {
 2256:     my ($domain,$name,$default,$hide) = @_;
 2257:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2258:     my $result;
 2259:     my $numlib = keys(%servers);
 2260:     if ($numlib > 1) {
 2261:         $result .= '<select name="'.$name.'" />'."\n";
 2262:         if ($default) {
 2263:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2264:                        '</option>'."\n";
 2265:         }
 2266:         foreach my $hostid (sort(keys(%servers))) {
 2267:             $result.= '<option value="'.$hostid.'">'.
 2268: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2269:         }
 2270:         $result .= '</select>'."\n";
 2271:     } elsif ($numlib == 1) {
 2272:         my $hostid;
 2273:         foreach my $item (keys(%servers)) {
 2274:             $hostid = $item;
 2275:         }
 2276:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2277:                    $hostid.'" />';
 2278:                    if (!$hide) {
 2279:                        $result .= $hostid.' '.$servers{$hostid};
 2280:                    }
 2281:                    $result .= "\n";
 2282:     } elsif ($default) {
 2283:         $result .= '<input type="hidden" name="'.$name.
 2284:                    '" value="default" />';
 2285:                    if (!$hide) {
 2286:                        $result .= &mt('default');
 2287:                    }
 2288:                    $result .= "\n";
 2289:     }
 2290:     return ($result,$numlib);
 2291: }
 2292: 
 2293: =pod
 2294: 
 2295: =back 
 2296: 
 2297: =cut
 2298: 
 2299: ###############################################################
 2300: ##                  Decoding User Agent                      ##
 2301: ###############################################################
 2302: 
 2303: =pod
 2304: 
 2305: =head1 Decoding the User Agent
 2306: 
 2307: =over 4
 2308: 
 2309: =item * &decode_user_agent()
 2310: 
 2311: Inputs: $r
 2312: 
 2313: Outputs:
 2314: 
 2315: =over 4
 2316: 
 2317: =item * $httpbrowser
 2318: 
 2319: =item * $clientbrowser
 2320: 
 2321: =item * $clientversion
 2322: 
 2323: =item * $clientmathml
 2324: 
 2325: =item * $clientunicode
 2326: 
 2327: =item * $clientos
 2328: 
 2329: =item * $clientmobile
 2330: 
 2331: =item * $clientinfo
 2332: 
 2333: =back
 2334: 
 2335: =back 
 2336: 
 2337: =cut
 2338: 
 2339: ###############################################################
 2340: ###############################################################
 2341: sub decode_user_agent {
 2342:     my ($r)=@_;
 2343:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2344:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2345:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2346:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2347:     my $clientbrowser='unknown';
 2348:     my $clientversion='0';
 2349:     my $clientmathml='';
 2350:     my $clientunicode='0';
 2351:     my $clientmobile=0;
 2352:     for (my $i=0;$i<=$#browsertype;$i++) {
 2353:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2354: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2355: 	    $clientbrowser=$bname;
 2356:             $httpbrowser=~/$vreg/i;
 2357: 	    $clientversion=$1;
 2358:             $clientmathml=($clientversion>=$minv);
 2359:             $clientunicode=($clientversion>=$univ);
 2360: 	}
 2361:     }
 2362:     my $clientos='unknown';
 2363:     my $clientinfo;
 2364:     if (($httpbrowser=~/linux/i) ||
 2365:         ($httpbrowser=~/unix/i) ||
 2366:         ($httpbrowser=~/ux/i) ||
 2367:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2368:     if (($httpbrowser=~/vax/i) ||
 2369:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2370:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2371:     if (($httpbrowser=~/mac/i) ||
 2372:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2373:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2374:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2375:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2376:         $clientmobile=lc($1);
 2377:     }
 2378:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2379:         $clientinfo = 'firefox-'.$1;
 2380:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2381:         $clientinfo = 'chromeframe-'.$1;
 2382:     }
 2383:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2384:             $clientunicode,$clientos,$clientmobile,$clientinfo);
 2385: }
 2386: 
 2387: ###############################################################
 2388: ##    Authentication changing form generation subroutines    ##
 2389: ###############################################################
 2390: ##
 2391: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2392: ## hash, and have reasonable default values.
 2393: ##
 2394: ##    formname = the name given in the <form> tag.
 2395: #-------------------------------------------
 2396: 
 2397: =pod
 2398: 
 2399: =head1 Authentication Routines
 2400: 
 2401: =over 4
 2402: 
 2403: =item * &authform_xxxxxx()
 2404: 
 2405: The authform_xxxxxx subroutines provide javascript and html forms which 
 2406: handle some of the conveniences required for authentication forms.  
 2407: This is not an optimal method, but it works.  
 2408: 
 2409: =over 4
 2410: 
 2411: =item * authform_header
 2412: 
 2413: =item * authform_authorwarning
 2414: 
 2415: =item * authform_nochange
 2416: 
 2417: =item * authform_kerberos
 2418: 
 2419: =item * authform_internal
 2420: 
 2421: =item * authform_filesystem
 2422: 
 2423: =back
 2424: 
 2425: See loncreateuser.pm for invocation and use examples.
 2426: 
 2427: =cut
 2428: 
 2429: #-------------------------------------------
 2430: sub authform_header{  
 2431:     my %in = (
 2432:         formname => 'cu',
 2433:         kerb_def_dom => '',
 2434:         @_,
 2435:     );
 2436:     $in{'formname'} = 'document.' . $in{'formname'};
 2437:     my $result='';
 2438: 
 2439: #---------------------------------------------- Code for upper case translation
 2440:     my $Javascript_toUpperCase;
 2441:     unless ($in{kerb_def_dom}) {
 2442:         $Javascript_toUpperCase =<<"END";
 2443:         switch (choice) {
 2444:            case 'krb': currentform.elements[choicearg].value =
 2445:                currentform.elements[choicearg].value.toUpperCase();
 2446:                break;
 2447:            default:
 2448:         }
 2449: END
 2450:     } else {
 2451:         $Javascript_toUpperCase = "";
 2452:     }
 2453: 
 2454:     my $radioval = "'nochange'";
 2455:     if (defined($in{'curr_authtype'})) {
 2456:         if ($in{'curr_authtype'} ne '') {
 2457:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2458:         }
 2459:     }
 2460:     my $argfield = 'null';
 2461:     if (defined($in{'mode'})) {
 2462:         if ($in{'mode'} eq 'modifycourse')  {
 2463:             if (defined($in{'curr_autharg'})) {
 2464:                 if ($in{'curr_autharg'} ne '') {
 2465:                     $argfield = "'$in{'curr_autharg'}'";
 2466:                 }
 2467:             }
 2468:         }
 2469:     }
 2470: 
 2471:     $result.=<<"END";
 2472: var current = new Object();
 2473: current.radiovalue = $radioval;
 2474: current.argfield = $argfield;
 2475: 
 2476: function changed_radio(choice,currentform) {
 2477:     var choicearg = choice + 'arg';
 2478:     // If a radio button in changed, we need to change the argfield
 2479:     if (current.radiovalue != choice) {
 2480:         current.radiovalue = choice;
 2481:         if (current.argfield != null) {
 2482:             currentform.elements[current.argfield].value = '';
 2483:         }
 2484:         if (choice == 'nochange') {
 2485:             current.argfield = null;
 2486:         } else {
 2487:             current.argfield = choicearg;
 2488:             switch(choice) {
 2489:                 case 'krb': 
 2490:                     currentform.elements[current.argfield].value = 
 2491:                         "$in{'kerb_def_dom'}";
 2492:                 break;
 2493:               default:
 2494:                 break;
 2495:             }
 2496:         }
 2497:     }
 2498:     return;
 2499: }
 2500: 
 2501: function changed_text(choice,currentform) {
 2502:     var choicearg = choice + 'arg';
 2503:     if (currentform.elements[choicearg].value !='') {
 2504:         $Javascript_toUpperCase
 2505:         // clear old field
 2506:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2507:             currentform.elements[current.argfield].value = '';
 2508:         }
 2509:         current.argfield = choicearg;
 2510:     }
 2511:     set_auth_radio_buttons(choice,currentform);
 2512:     return;
 2513: }
 2514: 
 2515: function set_auth_radio_buttons(newvalue,currentform) {
 2516:     var numauthchoices = currentform.login.length;
 2517:     if (typeof numauthchoices  == "undefined") {
 2518:         return;
 2519:     } 
 2520:     var i=0;
 2521:     while (i < numauthchoices) {
 2522:         if (currentform.login[i].value == newvalue) { break; }
 2523:         i++;
 2524:     }
 2525:     if (i == numauthchoices) {
 2526:         return;
 2527:     }
 2528:     current.radiovalue = newvalue;
 2529:     currentform.login[i].checked = true;
 2530:     return;
 2531: }
 2532: END
 2533:     return $result;
 2534: }
 2535: 
 2536: sub authform_authorwarning {
 2537:     my $result='';
 2538:     $result='<i>'.
 2539:         &mt('As a general rule, only authors or co-authors should be '.
 2540:             'filesystem authenticated '.
 2541:             '(which allows access to the server filesystem).')."</i>\n";
 2542:     return $result;
 2543: }
 2544: 
 2545: sub authform_nochange {
 2546:     my %in = (
 2547:               formname => 'document.cu',
 2548:               kerb_def_dom => 'MSU.EDU',
 2549:               @_,
 2550:           );
 2551:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2552:     my $result;
 2553:     if (!$authnum) {
 2554:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2555:     } else {
 2556:         $result = '<label>'.&mt('[_1] Do not change login data',
 2557:                   '<input type="radio" name="login" value="nochange" '.
 2558:                   'checked="checked" onclick="'.
 2559:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2560: 	    '</label>';
 2561:     }
 2562:     return $result;
 2563: }
 2564: 
 2565: sub authform_kerberos {
 2566:     my %in = (
 2567:               formname => 'document.cu',
 2568:               kerb_def_dom => 'MSU.EDU',
 2569:               kerb_def_auth => 'krb4',
 2570:               @_,
 2571:               );
 2572:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2573:         $autharg,$jscall);
 2574:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2575:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2576:        $check5 = ' checked="checked"';
 2577:     } else {
 2578:        $check4 = ' checked="checked"';
 2579:     }
 2580:     $krbarg = $in{'kerb_def_dom'};
 2581:     if (defined($in{'curr_authtype'})) {
 2582:         if ($in{'curr_authtype'} eq 'krb') {
 2583:             $krbcheck = ' checked="checked"';
 2584:             if (defined($in{'mode'})) {
 2585:                 if ($in{'mode'} eq 'modifyuser') {
 2586:                     $krbcheck = '';
 2587:                 }
 2588:             }
 2589:             if (defined($in{'curr_kerb_ver'})) {
 2590:                 if ($in{'curr_krb_ver'} eq '5') {
 2591:                     $check5 = ' checked="checked"';
 2592:                     $check4 = '';
 2593:                 } else {
 2594:                     $check4 = ' checked="checked"';
 2595:                     $check5 = '';
 2596:                 }
 2597:             }
 2598:             if (defined($in{'curr_autharg'})) {
 2599:                 $krbarg = $in{'curr_autharg'};
 2600:             }
 2601:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2602:                 if (defined($in{'curr_autharg'})) {
 2603:                     $result = 
 2604:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2605:         $in{'curr_autharg'},$krbver);
 2606:                 } else {
 2607:                     $result =
 2608:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2609:                 }
 2610:                 return $result; 
 2611:             }
 2612:         }
 2613:     } else {
 2614:         if ($authnum == 1) {
 2615:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2616:         }
 2617:     }
 2618:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2619:         return;
 2620:     } elsif ($authtype eq '') {
 2621:         if (defined($in{'mode'})) {
 2622:             if ($in{'mode'} eq 'modifycourse') {
 2623:                 if ($authnum == 1) {
 2624:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2625:                 }
 2626:             }
 2627:         }
 2628:     }
 2629:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2630:     if ($authtype eq '') {
 2631:         $authtype = '<input type="radio" name="login" value="krb" '.
 2632:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2633:                     $krbcheck.' />';
 2634:     }
 2635:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2636:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2637:          $in{'curr_authtype'} eq 'krb5') ||
 2638:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2639:          $in{'curr_authtype'} eq 'krb4')) {
 2640:         $result .= &mt
 2641:         ('[_1] Kerberos authenticated with domain [_2] '.
 2642:          '[_3] Version 4 [_4] Version 5 [_5]',
 2643:          '<label>'.$authtype,
 2644:          '</label><input type="text" size="10" name="krbarg" '.
 2645:              'value="'.$krbarg.'" '.
 2646:              'onchange="'.$jscall.'" />',
 2647:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2648:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2649: 	 '</label>');
 2650:     } elsif ($can_assign{'krb4'}) {
 2651:         $result .= &mt
 2652:         ('[_1] Kerberos authenticated with domain [_2] '.
 2653:          '[_3] Version 4 [_4]',
 2654:          '<label>'.$authtype,
 2655:          '</label><input type="text" size="10" name="krbarg" '.
 2656:              'value="'.$krbarg.'" '.
 2657:              'onchange="'.$jscall.'" />',
 2658:          '<label><input type="hidden" name="krbver" value="4" />',
 2659:          '</label>');
 2660:     } elsif ($can_assign{'krb5'}) {
 2661:         $result .= &mt
 2662:         ('[_1] Kerberos authenticated with domain [_2] '.
 2663:          '[_3] Version 5 [_4]',
 2664:          '<label>'.$authtype,
 2665:          '</label><input type="text" size="10" name="krbarg" '.
 2666:              'value="'.$krbarg.'" '.
 2667:              'onchange="'.$jscall.'" />',
 2668:          '<label><input type="hidden" name="krbver" value="5" />',
 2669:          '</label>');
 2670:     }
 2671:     return $result;
 2672: }
 2673: 
 2674: sub authform_internal {
 2675:     my %in = (
 2676:                 formname => 'document.cu',
 2677:                 kerb_def_dom => 'MSU.EDU',
 2678:                 @_,
 2679:                 );
 2680:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2681:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2682:     if (defined($in{'curr_authtype'})) {
 2683:         if ($in{'curr_authtype'} eq 'int') {
 2684:             if ($can_assign{'int'}) {
 2685:                 $intcheck = 'checked="checked" ';
 2686:                 if (defined($in{'mode'})) {
 2687:                     if ($in{'mode'} eq 'modifyuser') {
 2688:                         $intcheck = '';
 2689:                     }
 2690:                 }
 2691:                 if (defined($in{'curr_autharg'})) {
 2692:                     $intarg = $in{'curr_autharg'};
 2693:                 }
 2694:             } else {
 2695:                 $result = &mt('Currently internally authenticated.');
 2696:                 return $result;
 2697:             }
 2698:         }
 2699:     } else {
 2700:         if ($authnum == 1) {
 2701:             $authtype = '<input type="hidden" name="login" value="int" />';
 2702:         }
 2703:     }
 2704:     if (!$can_assign{'int'}) {
 2705:         return;
 2706:     } elsif ($authtype eq '') {
 2707:         if (defined($in{'mode'})) {
 2708:             if ($in{'mode'} eq 'modifycourse') {
 2709:                 if ($authnum == 1) {
 2710:                     $authtype = '<input type="radio" name="login" value="int" />';
 2711:                 }
 2712:             }
 2713:         }
 2714:     }
 2715:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2716:     if ($authtype eq '') {
 2717:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2718:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2719:     }
 2720:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2721:                $intarg.'" onchange="'.$jscall.'" />';
 2722:     $result = &mt
 2723:         ('[_1] Internally authenticated (with initial password [_2])',
 2724:          '<label>'.$authtype,'</label>'.$autharg);
 2725:     $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>';
 2726:     return $result;
 2727: }
 2728: 
 2729: sub authform_local {
 2730:     my %in = (
 2731:               formname => 'document.cu',
 2732:               kerb_def_dom => 'MSU.EDU',
 2733:               @_,
 2734:               );
 2735:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2736:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2737:     if (defined($in{'curr_authtype'})) {
 2738:         if ($in{'curr_authtype'} eq 'loc') {
 2739:             if ($can_assign{'loc'}) {
 2740:                 $loccheck = 'checked="checked" ';
 2741:                 if (defined($in{'mode'})) {
 2742:                     if ($in{'mode'} eq 'modifyuser') {
 2743:                         $loccheck = '';
 2744:                     }
 2745:                 }
 2746:                 if (defined($in{'curr_autharg'})) {
 2747:                     $locarg = $in{'curr_autharg'};
 2748:                 }
 2749:             } else {
 2750:                 $result = &mt('Currently using local (institutional) authentication.');
 2751:                 return $result;
 2752:             }
 2753:         }
 2754:     } else {
 2755:         if ($authnum == 1) {
 2756:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2757:         }
 2758:     }
 2759:     if (!$can_assign{'loc'}) {
 2760:         return;
 2761:     } elsif ($authtype eq '') {
 2762:         if (defined($in{'mode'})) {
 2763:             if ($in{'mode'} eq 'modifycourse') {
 2764:                 if ($authnum == 1) {
 2765:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2766:                 }
 2767:             }
 2768:         }
 2769:     }
 2770:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2771:     if ($authtype eq '') {
 2772:         $authtype = '<input type="radio" name="login" value="loc" '.
 2773:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2774:                     $jscall.'" />';
 2775:     }
 2776:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2777:                $locarg.'" onchange="'.$jscall.'" />';
 2778:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2779:                   '<label>'.$authtype,'</label>'.$autharg);
 2780:     return $result;
 2781: }
 2782: 
 2783: sub authform_filesystem {
 2784:     my %in = (
 2785:               formname => 'document.cu',
 2786:               kerb_def_dom => 'MSU.EDU',
 2787:               @_,
 2788:               );
 2789:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2790:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2791:     if (defined($in{'curr_authtype'})) {
 2792:         if ($in{'curr_authtype'} eq 'fsys') {
 2793:             if ($can_assign{'fsys'}) {
 2794:                 $fsyscheck = 'checked="checked" ';
 2795:                 if (defined($in{'mode'})) {
 2796:                     if ($in{'mode'} eq 'modifyuser') {
 2797:                         $fsyscheck = '';
 2798:                     }
 2799:                 }
 2800:             } else {
 2801:                 $result = &mt('Currently Filesystem Authenticated.');
 2802:                 return $result;
 2803:             }           
 2804:         }
 2805:     } else {
 2806:         if ($authnum == 1) {
 2807:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2808:         }
 2809:     }
 2810:     if (!$can_assign{'fsys'}) {
 2811:         return;
 2812:     } elsif ($authtype eq '') {
 2813:         if (defined($in{'mode'})) {
 2814:             if ($in{'mode'} eq 'modifycourse') {
 2815:                 if ($authnum == 1) {
 2816:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2817:                 }
 2818:             }
 2819:         }
 2820:     }
 2821:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2822:     if ($authtype eq '') {
 2823:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2824:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2825:                     $jscall.'" />';
 2826:     }
 2827:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2828:                ' onchange="'.$jscall.'" />';
 2829:     $result = &mt
 2830:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2831:          '<label><input type="radio" name="login" value="fsys" '.
 2832:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2833:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2834:                   'onchange="'.$jscall.'" />');
 2835:     return $result;
 2836: }
 2837: 
 2838: sub get_assignable_auth {
 2839:     my ($dom) = @_;
 2840:     if ($dom eq '') {
 2841:         $dom = $env{'request.role.domain'};
 2842:     }
 2843:     my %can_assign = (
 2844:                           krb4 => 1,
 2845:                           krb5 => 1,
 2846:                           int  => 1,
 2847:                           loc  => 1,
 2848:                      );
 2849:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2850:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2851:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2852:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2853:             my $context;
 2854:             if ($env{'request.role'} =~ /^au/) {
 2855:                 $context = 'author';
 2856:             } elsif ($env{'request.role'} =~ /^dc/) {
 2857:                 $context = 'domain';
 2858:             } elsif ($env{'request.course.id'}) {
 2859:                 $context = 'course';
 2860:             }
 2861:             if ($context) {
 2862:                 if (ref($authhash->{$context}) eq 'HASH') {
 2863:                    %can_assign = %{$authhash->{$context}}; 
 2864:                 }
 2865:             }
 2866:         }
 2867:     }
 2868:     my $authnum = 0;
 2869:     foreach my $key (keys(%can_assign)) {
 2870:         if ($can_assign{$key}) {
 2871:             $authnum ++;
 2872:         }
 2873:     }
 2874:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2875:         $authnum --;
 2876:     }
 2877:     return ($authnum,%can_assign);
 2878: }
 2879: 
 2880: ###############################################################
 2881: ##    Get Kerberos Defaults for Domain                 ##
 2882: ###############################################################
 2883: ##
 2884: ## Returns default kerberos version and an associated argument
 2885: ## as listed in file domain.tab. If not listed, provides
 2886: ## appropriate default domain and kerberos version.
 2887: ##
 2888: #-------------------------------------------
 2889: 
 2890: =pod
 2891: 
 2892: =item * &get_kerberos_defaults()
 2893: 
 2894: get_kerberos_defaults($target_domain) returns the default kerberos
 2895: version and domain. If not found, it defaults to version 4 and the 
 2896: domain of the server.
 2897: 
 2898: =over 4
 2899: 
 2900: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2901: 
 2902: =back
 2903: 
 2904: =back
 2905: 
 2906: =cut
 2907: 
 2908: #-------------------------------------------
 2909: sub get_kerberos_defaults {
 2910:     my $domain=shift;
 2911:     my ($krbdef,$krbdefdom);
 2912:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2913:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2914:         $krbdef = $domdefaults{'auth_def'};
 2915:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2916:     } else {
 2917:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2918:         my $krbdefdom=$1;
 2919:         $krbdefdom=~tr/a-z/A-Z/;
 2920:         $krbdef = "krb4";
 2921:     }
 2922:     return ($krbdef,$krbdefdom);
 2923: }
 2924: 
 2925: 
 2926: ###############################################################
 2927: ##                Thesaurus Functions                        ##
 2928: ###############################################################
 2929: 
 2930: =pod
 2931: 
 2932: =head1 Thesaurus Functions
 2933: 
 2934: =over 4
 2935: 
 2936: =item * &initialize_keywords()
 2937: 
 2938: Initializes the package variable %Keywords if it is empty.  Uses the
 2939: package variable $thesaurus_db_file.
 2940: 
 2941: =cut
 2942: 
 2943: ###################################################
 2944: 
 2945: sub initialize_keywords {
 2946:     return 1 if (scalar keys(%Keywords));
 2947:     # If we are here, %Keywords is empty, so fill it up
 2948:     #   Make sure the file we need exists...
 2949:     if (! -e $thesaurus_db_file) {
 2950:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2951:                                  " failed because it does not exist");
 2952:         return 0;
 2953:     }
 2954:     #   Set up the hash as a database
 2955:     my %thesaurus_db;
 2956:     if (! tie(%thesaurus_db,'GDBM_File',
 2957:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2958:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2959:                                  $thesaurus_db_file);
 2960:         return 0;
 2961:     } 
 2962:     #  Get the average number of appearances of a word.
 2963:     my $avecount = $thesaurus_db{'average.count'};
 2964:     #  Put keywords (those that appear > average) into %Keywords
 2965:     while (my ($word,$data)=each (%thesaurus_db)) {
 2966:         my ($count,undef) = split /:/,$data;
 2967:         $Keywords{$word}++ if ($count > $avecount);
 2968:     }
 2969:     untie %thesaurus_db;
 2970:     # Remove special values from %Keywords.
 2971:     foreach my $value ('total.count','average.count') {
 2972:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2973:   }
 2974:     return 1;
 2975: }
 2976: 
 2977: ###################################################
 2978: 
 2979: =pod
 2980: 
 2981: =item * &keyword($word)
 2982: 
 2983: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2984: than the average number of times in the thesaurus database.  Calls 
 2985: &initialize_keywords
 2986: 
 2987: =cut
 2988: 
 2989: ###################################################
 2990: 
 2991: sub keyword {
 2992:     return if (!&initialize_keywords());
 2993:     my $word=lc(shift());
 2994:     $word=~s/\W//g;
 2995:     return exists($Keywords{$word});
 2996: }
 2997: 
 2998: ###############################################################
 2999: 
 3000: =pod 
 3001: 
 3002: =item * &get_related_words()
 3003: 
 3004: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3005: an array of words.  If the keyword is not in the thesaurus, an empty array
 3006: will be returned.  The order of the words returned is determined by the
 3007: database which holds them.
 3008: 
 3009: Uses global $thesaurus_db_file.
 3010: 
 3011: 
 3012: =cut
 3013: 
 3014: ###############################################################
 3015: sub get_related_words {
 3016:     my $keyword = shift;
 3017:     my %thesaurus_db;
 3018:     if (! -e $thesaurus_db_file) {
 3019:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3020:                                  "failed because the file does not exist");
 3021:         return ();
 3022:     }
 3023:     if (! tie(%thesaurus_db,'GDBM_File',
 3024:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3025:         return ();
 3026:     } 
 3027:     my @Words=();
 3028:     my $count=0;
 3029:     if (exists($thesaurus_db{$keyword})) {
 3030: 	# The first element is the number of times
 3031: 	# the word appears.  We do not need it now.
 3032: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3033: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3034: 	my $threshold=$mostfrequentcount/10;
 3035:         foreach my $possibleword (@RelatedWords) {
 3036:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3037:             if ($wordcount>$threshold) {
 3038: 		push(@Words,$word);
 3039:                 $count++;
 3040:                 if ($count>10) { last; }
 3041: 	    }
 3042:         }
 3043:     }
 3044:     untie %thesaurus_db;
 3045:     return @Words;
 3046: }
 3047: 
 3048: =pod
 3049: 
 3050: =back
 3051: 
 3052: =cut
 3053: 
 3054: # -------------------------------------------------------------- Plaintext name
 3055: =pod
 3056: 
 3057: =head1 User Name Functions
 3058: 
 3059: =over 4
 3060: 
 3061: =item * &plainname($uname,$udom,$first)
 3062: 
 3063: Takes a users logon name and returns it as a string in
 3064: "first middle last generation" form 
 3065: if $first is set to 'lastname' then it returns it as
 3066: 'lastname generation, firstname middlename' if their is a lastname
 3067: 
 3068: =cut
 3069: 
 3070: 
 3071: ###############################################################
 3072: sub plainname {
 3073:     my ($uname,$udom,$first)=@_;
 3074:     return if (!defined($uname) || !defined($udom));
 3075:     my %names=&getnames($uname,$udom);
 3076:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3077: 					  $names{'middlename'},
 3078: 					  $names{'lastname'},
 3079: 					  $names{'generation'},$first);
 3080:     $name=~s/^\s+//;
 3081:     $name=~s/\s+$//;
 3082:     $name=~s/\s+/ /g;
 3083:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3084:     return $name;
 3085: }
 3086: 
 3087: # -------------------------------------------------------------------- Nickname
 3088: =pod
 3089: 
 3090: =item * &nickname($uname,$udom)
 3091: 
 3092: Gets a users name and returns it as a string as
 3093: 
 3094: "&quot;nickname&quot;"
 3095: 
 3096: if the user has a nickname or
 3097: 
 3098: "first middle last generation"
 3099: 
 3100: if the user does not
 3101: 
 3102: =cut
 3103: 
 3104: sub nickname {
 3105:     my ($uname,$udom)=@_;
 3106:     return if (!defined($uname) || !defined($udom));
 3107:     my %names=&getnames($uname,$udom);
 3108:     my $name=$names{'nickname'};
 3109:     if ($name) {
 3110:        $name='&quot;'.$name.'&quot;'; 
 3111:     } else {
 3112:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3113: 	     $names{'lastname'}.' '.$names{'generation'};
 3114:        $name=~s/\s+$//;
 3115:        $name=~s/\s+/ /g;
 3116:     }
 3117:     return $name;
 3118: }
 3119: 
 3120: sub getnames {
 3121:     my ($uname,$udom)=@_;
 3122:     return if (!defined($uname) || !defined($udom));
 3123:     if ($udom eq 'public' && $uname eq 'public') {
 3124: 	return ('lastname' => &mt('Public'));
 3125:     }
 3126:     my $id=$uname.':'.$udom;
 3127:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3128:     if ($cached) {
 3129: 	return %{$names};
 3130:     } else {
 3131: 	my %loadnames=&Apache::lonnet::get('environment',
 3132:                     ['firstname','middlename','lastname','generation','nickname'],
 3133: 					 $udom,$uname);
 3134: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3135: 	return %loadnames;
 3136:     }
 3137: }
 3138: 
 3139: # -------------------------------------------------------------------- getemails
 3140: 
 3141: =pod
 3142: 
 3143: =item * &getemails($uname,$udom)
 3144: 
 3145: Gets a user's email information and returns it as a hash with keys:
 3146: notification, critnotification, permanentemail
 3147: 
 3148: For notification and critnotification, values are comma-separated lists 
 3149: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3150:  
 3151: 
 3152: =cut
 3153: 
 3154: 
 3155: sub getemails {
 3156:     my ($uname,$udom)=@_;
 3157:     if ($udom eq 'public' && $uname eq 'public') {
 3158: 	return;
 3159:     }
 3160:     if (!$udom) { $udom=$env{'user.domain'}; }
 3161:     if (!$uname) { $uname=$env{'user.name'}; }
 3162:     my $id=$uname.':'.$udom;
 3163:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3164:     if ($cached) {
 3165: 	return %{$names};
 3166:     } else {
 3167: 	my %loadnames=&Apache::lonnet::get('environment',
 3168:                     			   ['notification','critnotification',
 3169: 					    'permanentemail'],
 3170: 					   $udom,$uname);
 3171: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3172: 	return %loadnames;
 3173:     }
 3174: }
 3175: 
 3176: sub flush_email_cache {
 3177:     my ($uname,$udom)=@_;
 3178:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3179:     if (!$uname) { $uname=$env{'user.name'};   }
 3180:     return if ($udom eq 'public' && $uname eq 'public');
 3181:     my $id=$uname.':'.$udom;
 3182:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3183: }
 3184: 
 3185: # -------------------------------------------------------------------- getlangs
 3186: 
 3187: =pod
 3188: 
 3189: =item * &getlangs($uname,$udom)
 3190: 
 3191: Gets a user's language preference and returns it as a hash with key:
 3192: language.
 3193: 
 3194: =cut
 3195: 
 3196: 
 3197: sub getlangs {
 3198:     my ($uname,$udom) = @_;
 3199:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3200:     if (!$uname) { $uname=$env{'user.name'};   }
 3201:     my $id=$uname.':'.$udom;
 3202:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3203:     if ($cached) {
 3204:         return %{$langs};
 3205:     } else {
 3206:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3207:                                            $udom,$uname);
 3208:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3209:         return %loadlangs;
 3210:     }
 3211: }
 3212: 
 3213: sub flush_langs_cache {
 3214:     my ($uname,$udom)=@_;
 3215:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3216:     if (!$uname) { $uname=$env{'user.name'};   }
 3217:     return if ($udom eq 'public' && $uname eq 'public');
 3218:     my $id=$uname.':'.$udom;
 3219:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3220: }
 3221: 
 3222: # ------------------------------------------------------------------ Screenname
 3223: 
 3224: =pod
 3225: 
 3226: =item * &screenname($uname,$udom)
 3227: 
 3228: Gets a users screenname and returns it as a string
 3229: 
 3230: =cut
 3231: 
 3232: sub screenname {
 3233:     my ($uname,$udom)=@_;
 3234:     if ($uname eq $env{'user.name'} &&
 3235: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3236:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3237:     return $names{'screenname'};
 3238: }
 3239: 
 3240: 
 3241: # ------------------------------------------------------------- Confirm Wrapper
 3242: =pod
 3243: 
 3244: =item * &confirmwrapper($message)
 3245: 
 3246: Wrap messages about completion of operation in box
 3247: 
 3248: =cut
 3249: 
 3250: sub confirmwrapper {
 3251:     my ($message)=@_;
 3252:     if ($message) {
 3253:         return "\n".'<div class="LC_confirm_box">'."\n"
 3254:                .$message."\n"
 3255:                .'</div>'."\n";
 3256:     } else {
 3257:         return $message;
 3258:     }
 3259: }
 3260: 
 3261: # ------------------------------------------------------------- Message Wrapper
 3262: 
 3263: sub messagewrapper {
 3264:     my ($link,$username,$domain,$subject,$text)=@_;
 3265:     return 
 3266:         '<a href="/adm/email?compose=individual&amp;'.
 3267:         'recname='.$username.'&amp;recdom='.$domain.
 3268: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3269:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3270: }
 3271: 
 3272: # --------------------------------------------------------------- Notes Wrapper
 3273: 
 3274: sub noteswrapper {
 3275:     my ($link,$un,$do)=@_;
 3276:     return 
 3277: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3278: }
 3279: 
 3280: # ------------------------------------------------------------- Aboutme Wrapper
 3281: 
 3282: sub aboutmewrapper {
 3283:     my ($link,$username,$domain,$target,$class)=@_;
 3284:     if (!defined($username)  && !defined($domain)) {
 3285:         return;
 3286:     }
 3287:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3288: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3289: }
 3290: 
 3291: # ------------------------------------------------------------ Syllabus Wrapper
 3292: 
 3293: sub syllabuswrapper {
 3294:     my ($linktext,$coursedir,$domain)=@_;
 3295:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3296: }
 3297: 
 3298: # -----------------------------------------------------------------------------
 3299: 
 3300: sub track_student_link {
 3301:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3302:     my $link ="/adm/trackstudent?";
 3303:     my $title = 'View recent activity';
 3304:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3305:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3306:         $link .= "selected_student=$sname:$sdom";
 3307:         $title .= ' of this student';
 3308:     } 
 3309:     if (defined($target) && $target !~ /^\s*$/) {
 3310:         $target = qq{target="$target"};
 3311:     } else {
 3312:         $target = '';
 3313:     }
 3314:     if ($start) { $link.='&amp;start='.$start; }
 3315:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3316:     $title = &mt($title);
 3317:     $linktext = &mt($linktext);
 3318:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3319: 	&help_open_topic('View_recent_activity');
 3320: }
 3321: 
 3322: sub slot_reservations_link {
 3323:     my ($linktext,$sname,$sdom,$target) = @_;
 3324:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3325:     my $title = 'View slot reservation history';
 3326:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3327:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3328:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3329:         $title .= ' of this student';
 3330:     }
 3331:     if (defined($target) && $target !~ /^\s*$/) {
 3332:         $target = qq{target="$target"};
 3333:     } else {
 3334:         $target = '';
 3335:     }
 3336:     $title = &mt($title);
 3337:     $linktext = &mt($linktext);
 3338:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3339: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3340: 
 3341: }
 3342: 
 3343: # ===================================================== Display a student photo
 3344: 
 3345: 
 3346: sub student_image_tag {
 3347:     my ($domain,$user)=@_;
 3348:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3349:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3350: 	return '<img src="'.$imgsrc.'" align="right" />';
 3351:     } else {
 3352: 	return '';
 3353:     }
 3354: }
 3355: 
 3356: =pod
 3357: 
 3358: =back
 3359: 
 3360: =head1 Access .tab File Data
 3361: 
 3362: =over 4
 3363: 
 3364: =item * &languageids() 
 3365: 
 3366: returns list of all language ids
 3367: 
 3368: =cut
 3369: 
 3370: sub languageids {
 3371:     return sort(keys(%language));
 3372: }
 3373: 
 3374: =pod
 3375: 
 3376: =item * &languagedescription() 
 3377: 
 3378: returns description of a specified language id
 3379: 
 3380: =cut
 3381: 
 3382: sub languagedescription {
 3383:     my $code=shift;
 3384:     return  ($supported_language{$code}?'* ':'').
 3385:             $language{$code}.
 3386: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3387: }
 3388: 
 3389: =pod
 3390: 
 3391: =item * &plainlanguagedescription
 3392: 
 3393: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3394: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3395: 
 3396: =cut
 3397: 
 3398: sub plainlanguagedescription {
 3399:     my $code=shift;
 3400:     return $language{$code};
 3401: }
 3402: 
 3403: =pod
 3404: 
 3405: =item * &supportedlanguagecode
 3406: 
 3407: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3408: code.
 3409: 
 3410: =cut
 3411: 
 3412: sub supportedlanguagecode {
 3413:     my $code=shift;
 3414:     return $supported_language{$code};
 3415: }
 3416: 
 3417: =pod
 3418: 
 3419: =item * &latexlanguage()
 3420: 
 3421: Given a language key code returns the correspondnig language to use
 3422: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3423: is no supported hyphenation for the language code.
 3424: 
 3425: =cut
 3426: 
 3427: sub latexlanguage {
 3428:     my $code = shift;
 3429:     return $latex_language{$code};
 3430: }
 3431: 
 3432: =pod
 3433: 
 3434: =item * &latexhyphenation()
 3435: 
 3436: Same as above but what's supplied is the language as it might be stored
 3437: in the metadata.
 3438: 
 3439: =cut
 3440: 
 3441: sub latexhyphenation {
 3442:     my $key = shift;
 3443:     return $latex_language_bykey{$key};
 3444: }
 3445: 
 3446: =pod
 3447: 
 3448: =item * &copyrightids() 
 3449: 
 3450: returns list of all copyrights
 3451: 
 3452: =cut
 3453: 
 3454: sub copyrightids {
 3455:     return sort(keys(%cprtag));
 3456: }
 3457: 
 3458: =pod
 3459: 
 3460: =item * &copyrightdescription() 
 3461: 
 3462: returns description of a specified copyright id
 3463: 
 3464: =cut
 3465: 
 3466: sub copyrightdescription {
 3467:     return &mt($cprtag{shift(@_)});
 3468: }
 3469: 
 3470: =pod
 3471: 
 3472: =item * &source_copyrightids() 
 3473: 
 3474: returns list of all source copyrights
 3475: 
 3476: =cut
 3477: 
 3478: sub source_copyrightids {
 3479:     return sort(keys(%scprtag));
 3480: }
 3481: 
 3482: =pod
 3483: 
 3484: =item * &source_copyrightdescription() 
 3485: 
 3486: returns description of a specified source copyright id
 3487: 
 3488: =cut
 3489: 
 3490: sub source_copyrightdescription {
 3491:     return &mt($scprtag{shift(@_)});
 3492: }
 3493: 
 3494: =pod
 3495: 
 3496: =item * &filecategories() 
 3497: 
 3498: returns list of all file categories
 3499: 
 3500: =cut
 3501: 
 3502: sub filecategories {
 3503:     return sort(keys(%category_extensions));
 3504: }
 3505: 
 3506: =pod
 3507: 
 3508: =item * &filecategorytypes() 
 3509: 
 3510: returns list of file types belonging to a given file
 3511: category
 3512: 
 3513: =cut
 3514: 
 3515: sub filecategorytypes {
 3516:     my ($cat) = @_;
 3517:     return @{$category_extensions{lc($cat)}};
 3518: }
 3519: 
 3520: =pod
 3521: 
 3522: =item * &fileembstyle() 
 3523: 
 3524: returns embedding style for a specified file type
 3525: 
 3526: =cut
 3527: 
 3528: sub fileembstyle {
 3529:     return $fe{lc(shift(@_))};
 3530: }
 3531: 
 3532: sub filemimetype {
 3533:     return $fm{lc(shift(@_))};
 3534: }
 3535: 
 3536: 
 3537: sub filecategoryselect {
 3538:     my ($name,$value)=@_;
 3539:     return &select_form($value,$name,
 3540:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3541: }
 3542: 
 3543: =pod
 3544: 
 3545: =item * &filedescription() 
 3546: 
 3547: returns description for a specified file type
 3548: 
 3549: =cut
 3550: 
 3551: sub filedescription {
 3552:     my $file_description = $fd{lc(shift())};
 3553:     $file_description =~ s:([\[\]]):~$1:g;
 3554:     return &mt($file_description);
 3555: }
 3556: 
 3557: =pod
 3558: 
 3559: =item * &filedescriptionex() 
 3560: 
 3561: returns description for a specified file type with
 3562: extra formatting
 3563: 
 3564: =cut
 3565: 
 3566: sub filedescriptionex {
 3567:     my $ex=shift;
 3568:     my $file_description = $fd{lc($ex)};
 3569:     $file_description =~ s:([\[\]]):~$1:g;
 3570:     return '.'.$ex.' '.&mt($file_description);
 3571: }
 3572: 
 3573: # End of .tab access
 3574: =pod
 3575: 
 3576: =back
 3577: 
 3578: =cut
 3579: 
 3580: # ------------------------------------------------------------------ File Types
 3581: sub fileextensions {
 3582:     return sort(keys(%fe));
 3583: }
 3584: 
 3585: # ----------------------------------------------------------- Display Languages
 3586: # returns a hash with all desired display languages
 3587: #
 3588: 
 3589: sub display_languages {
 3590:     my %languages=();
 3591:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3592: 	$languages{$lang}=1;
 3593:     }
 3594:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3595:     if ($env{'form.displaylanguage'}) {
 3596: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3597: 	    $languages{$lang}=1;
 3598:         }
 3599:     }
 3600:     return %languages;
 3601: }
 3602: 
 3603: sub languages {
 3604:     my ($possible_langs) = @_;
 3605:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3606:     if (!ref($possible_langs)) {
 3607: 	if( wantarray ) {
 3608: 	    return @preferred_langs;
 3609: 	} else {
 3610: 	    return $preferred_langs[0];
 3611: 	}
 3612:     }
 3613:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3614:     my @preferred_possibilities;
 3615:     foreach my $preferred_lang (@preferred_langs) {
 3616: 	if (exists($possibilities{$preferred_lang})) {
 3617: 	    push(@preferred_possibilities, $preferred_lang);
 3618: 	}
 3619:     }
 3620:     if( wantarray ) {
 3621: 	return @preferred_possibilities;
 3622:     }
 3623:     return $preferred_possibilities[0];
 3624: }
 3625: 
 3626: sub user_lang {
 3627:     my ($touname,$toudom,$fromcid) = @_;
 3628:     my @userlangs;
 3629:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3630:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3631:                     $env{'course.'.$fromcid.'.languages'}));
 3632:     } else {
 3633:         my %langhash = &getlangs($touname,$toudom);
 3634:         if ($langhash{'languages'} ne '') {
 3635:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3636:         } else {
 3637:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3638:             if ($domdefs{'lang_def'} ne '') {
 3639:                 @userlangs = ($domdefs{'lang_def'});
 3640:             }
 3641:         }
 3642:     }
 3643:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3644:     my $user_lh = Apache::localize->get_handle(@languages);
 3645:     return $user_lh;
 3646: }
 3647: 
 3648: 
 3649: ###############################################################
 3650: ##               Student Answer Attempts                     ##
 3651: ###############################################################
 3652: 
 3653: =pod
 3654: 
 3655: =head1 Alternate Problem Views
 3656: 
 3657: =over 4
 3658: 
 3659: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3660:     $getattempt, $regexp, $gradesub)
 3661: 
 3662: Return string with previous attempt on problem. Arguments:
 3663: 
 3664: =over 4
 3665: 
 3666: =item * $symb: Problem, including path
 3667: 
 3668: =item * $username: username of the desired student
 3669: 
 3670: =item * $domain: domain of the desired student
 3671: 
 3672: =item * $course: Course ID
 3673: 
 3674: =item * $getattempt: Leave blank for all attempts, otherwise put
 3675:     something
 3676: 
 3677: =item * $regexp: if string matches this regexp, the string will be
 3678:     sent to $gradesub
 3679: 
 3680: =item * $gradesub: routine that processes the string if it matches $regexp
 3681: 
 3682: =back
 3683: 
 3684: The output string is a table containing all desired attempts, if any.
 3685: 
 3686: =cut
 3687: 
 3688: sub get_previous_attempt {
 3689:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3690:   my $prevattempts='';
 3691:   no strict 'refs';
 3692:   if ($symb) {
 3693:     my (%returnhash)=
 3694:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3695:     if ($returnhash{'version'}) {
 3696:       my %lasthash=();
 3697:       my $version;
 3698:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3699:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3700: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3701:         }
 3702:       }
 3703:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3704:       $prevattempts.='<th>'.&mt('History').'</th>';
 3705:       my (%typeparts,%lasthidden);
 3706:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3707:       foreach my $key (sort(keys(%lasthash))) {
 3708: 	my ($ign,@parts) = split(/\./,$key);
 3709: 	if ($#parts > 0) {
 3710: 	  my $data=$parts[-1];
 3711:           next if ($data eq 'foilorder');
 3712: 	  pop(@parts);
 3713:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3714:           if ($data eq 'type') {
 3715:               unless ($showsurv) {
 3716:                   my $id = join(',',@parts);
 3717:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3718:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3719:                       $lasthidden{$ign.'.'.$id} = 1;
 3720:                   }
 3721:               }
 3722:           } 
 3723: 	} else {
 3724: 	  if ($#parts == 0) {
 3725: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3726: 	  } else {
 3727: 	    $prevattempts.='<th>'.$ign.'</th>';
 3728: 	  }
 3729: 	}
 3730:       }
 3731:       $prevattempts.=&end_data_table_header_row();
 3732:       if ($getattempt eq '') {
 3733: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3734:             my @hidden;
 3735:             if (%typeparts) {
 3736:                 foreach my $id (keys(%typeparts)) {
 3737:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3738:                         push(@hidden,$id);
 3739:                     }
 3740:                 }
 3741:             }
 3742:             $prevattempts.=&start_data_table_row().
 3743:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3744:             if (@hidden) {
 3745:                 foreach my $key (sort(keys(%lasthash))) {
 3746:                     next if ($key =~ /\.foilorder$/);
 3747:                     my $hide;
 3748:                     foreach my $id (@hidden) {
 3749:                         if ($key =~ /^\Q$id\E/) {
 3750:                             $hide = 1;
 3751:                             last;
 3752:                         }
 3753:                     }
 3754:                     if ($hide) {
 3755:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3756:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3757:                             my $value = &format_previous_attempt_value($key,
 3758:                                              $returnhash{$version.':'.$key});
 3759:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3760:                         } else {
 3761:                             $prevattempts.='<td>&nbsp;</td>';
 3762:                         }
 3763:                     } else {
 3764:                         if ($key =~ /\./) {
 3765:                             my $value = &format_previous_attempt_value($key,
 3766:                                               $returnhash{$version.':'.$key});
 3767:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3768:                         } else {
 3769:                             $prevattempts.='<td>&nbsp;</td>';
 3770:                         }
 3771:                     }
 3772:                 }
 3773:             } else {
 3774: 	        foreach my $key (sort(keys(%lasthash))) {
 3775:                     next if ($key =~ /\.foilorder$/);
 3776: 		    my $value = &format_previous_attempt_value($key,
 3777: 			            $returnhash{$version.':'.$key});
 3778: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3779: 	        }
 3780:             }
 3781: 	    $prevattempts.=&end_data_table_row();
 3782: 	 }
 3783:       }
 3784:       my @currhidden = keys(%lasthidden);
 3785:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3786:       foreach my $key (sort(keys(%lasthash))) {
 3787:           next if ($key =~ /\.foilorder$/);
 3788:           if (%typeparts) {
 3789:               my $hidden;
 3790:               foreach my $id (@currhidden) {
 3791:                   if ($key =~ /^\Q$id\E/) {
 3792:                       $hidden = 1;
 3793:                       last;
 3794:                   }
 3795:               }
 3796:               if ($hidden) {
 3797:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3798:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3799:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3800:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3801:                           $value = &$gradesub($value);
 3802:                       }
 3803:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3804:                   } else {
 3805:                       $prevattempts.='<td>&nbsp;</td>';
 3806:                   }
 3807:               } else {
 3808:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3809:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3810:                       $value = &$gradesub($value);
 3811:                   }
 3812:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3813:               }
 3814:           } else {
 3815: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3816: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3817:                   $value = &$gradesub($value);
 3818:               }
 3819: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3820:           }
 3821:       }
 3822:       $prevattempts.= &end_data_table_row().&end_data_table();
 3823:     } else {
 3824:       $prevattempts=
 3825: 	  &start_data_table().&start_data_table_row().
 3826: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3827: 	  &end_data_table_row().&end_data_table();
 3828:     }
 3829:   } else {
 3830:     $prevattempts=
 3831: 	  &start_data_table().&start_data_table_row().
 3832: 	  '<td>'.&mt('No data.').'</td>'.
 3833: 	  &end_data_table_row().&end_data_table();
 3834:   }
 3835: }
 3836: 
 3837: sub format_previous_attempt_value {
 3838:     my ($key,$value) = @_;
 3839:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3840: 	$value = &Apache::lonlocal::locallocaltime($value);
 3841:     } elsif (ref($value) eq 'ARRAY') {
 3842: 	$value = '('.join(', ', @{ $value }).')';
 3843:     } elsif ($key =~ /answerstring$/) {
 3844:         my %answers = &Apache::lonnet::str2hash($value);
 3845:         my @anskeys = sort(keys(%answers));
 3846:         if (@anskeys == 1) {
 3847:             my $answer = $answers{$anskeys[0]};
 3848:             if ($answer =~ m{\0}) {
 3849:                 $answer =~ s{\0}{,}g;
 3850:             }
 3851:             my $tag_internal_answer_name = 'INTERNAL';
 3852:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3853:                 $value = $answer; 
 3854:             } else {
 3855:                 $value = $anskeys[0].'='.$answer;
 3856:             }
 3857:         } else {
 3858:             foreach my $ans (@anskeys) {
 3859:                 my $answer = $answers{$ans};
 3860:                 if ($answer =~ m{\0}) {
 3861:                     $answer =~ s{\0}{,}g;
 3862:                 }
 3863:                 $value .=  $ans.'='.$answer.'<br />';;
 3864:             } 
 3865:         }
 3866:     } else {
 3867: 	$value = &unescape($value);
 3868:     }
 3869:     return $value;
 3870: }
 3871: 
 3872: 
 3873: sub relative_to_absolute {
 3874:     my ($url,$output)=@_;
 3875:     my $parser=HTML::TokeParser->new(\$output);
 3876:     my $token;
 3877:     my $thisdir=$url;
 3878:     my @rlinks=();
 3879:     while ($token=$parser->get_token) {
 3880: 	if ($token->[0] eq 'S') {
 3881: 	    if ($token->[1] eq 'a') {
 3882: 		if ($token->[2]->{'href'}) {
 3883: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3884: 		}
 3885: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3886: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3887: 	    } elsif ($token->[1] eq 'base') {
 3888: 		$thisdir=$token->[2]->{'href'};
 3889: 	    }
 3890: 	}
 3891:     }
 3892:     $thisdir=~s-/[^/]*$--;
 3893:     foreach my $link (@rlinks) {
 3894: 	unless (($link=~/^https?\:\/\//i) ||
 3895: 		($link=~/^\//) ||
 3896: 		($link=~/^javascript:/i) ||
 3897: 		($link=~/^mailto:/i) ||
 3898: 		($link=~/^\#/)) {
 3899: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3900: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3901: 	}
 3902:     }
 3903: # -------------------------------------------------- Deal with Applet codebases
 3904:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3905:     return $output;
 3906: }
 3907: 
 3908: =pod
 3909: 
 3910: =item * &get_student_view()
 3911: 
 3912: show a snapshot of what student was looking at
 3913: 
 3914: =cut
 3915: 
 3916: sub get_student_view {
 3917:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3918:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3919:   my (%form);
 3920:   my @elements=('symb','courseid','domain','username');
 3921:   foreach my $element (@elements) {
 3922:       $form{'grade_'.$element}=eval '$'.$element #'
 3923:   }
 3924:   if (defined($moreenv)) {
 3925:       %form=(%form,%{$moreenv});
 3926:   }
 3927:   if (defined($target)) { $form{'grade_target'} = $target; }
 3928:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3929:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3930:   $userview=~s/\<body[^\>]*\>//gi;
 3931:   $userview=~s/\<\/body\>//gi;
 3932:   $userview=~s/\<html\>//gi;
 3933:   $userview=~s/\<\/html\>//gi;
 3934:   $userview=~s/\<head\>//gi;
 3935:   $userview=~s/\<\/head\>//gi;
 3936:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3937:   $userview=&relative_to_absolute($feedurl,$userview);
 3938:   if (wantarray) {
 3939:      return ($userview,$response);
 3940:   } else {
 3941:      return $userview;
 3942:   }
 3943: }
 3944: 
 3945: sub get_student_view_with_retries {
 3946:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3947: 
 3948:     my $ok = 0;                 # True if we got a good response.
 3949:     my $content;
 3950:     my $response;
 3951: 
 3952:     # Try to get the student_view done. within the retries count:
 3953:     
 3954:     do {
 3955:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3956:          $ok      = $response->is_success;
 3957:          if (!$ok) {
 3958:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3959:          }
 3960:          $retries--;
 3961:     } while (!$ok && ($retries > 0));
 3962:     
 3963:     if (!$ok) {
 3964:        $content = '';          # On error return an empty content.
 3965:     }
 3966:     if (wantarray) {
 3967:        return ($content, $response);
 3968:     } else {
 3969:        return $content;
 3970:     }
 3971: }
 3972: 
 3973: =pod
 3974: 
 3975: =item * &get_student_answers() 
 3976: 
 3977: show a snapshot of how student was answering problem
 3978: 
 3979: =cut
 3980: 
 3981: sub get_student_answers {
 3982:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3983:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3984:   my (%moreenv);
 3985:   my @elements=('symb','courseid','domain','username');
 3986:   foreach my $element (@elements) {
 3987:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3988:   }
 3989:   $moreenv{'grade_target'}='answer';
 3990:   %moreenv=(%form,%moreenv);
 3991:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3992:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3993:   return $userview;
 3994: }
 3995: 
 3996: =pod
 3997: 
 3998: =item * &submlink()
 3999: 
 4000: Inputs: $text $uname $udom $symb $target
 4001: 
 4002: Returns: A link to grades.pm such as to see the SUBM view of a student
 4003: 
 4004: =cut
 4005: 
 4006: ###############################################
 4007: sub submlink {
 4008:     my ($text,$uname,$udom,$symb,$target)=@_;
 4009:     if (!($uname && $udom)) {
 4010: 	(my $cursymb, my $courseid,$udom,$uname)=
 4011: 	    &Apache::lonnet::whichuser($symb);
 4012: 	if (!$symb) { $symb=$cursymb; }
 4013:     }
 4014:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4015:     $symb=&escape($symb);
 4016:     if ($target) { $target=" target=\"$target\""; }
 4017:     return
 4018:         '<a href="/adm/grades?command=submission'.
 4019:         '&amp;symb='.$symb.
 4020:         '&amp;student='.$uname.
 4021:         '&amp;userdom='.$udom.'"'.
 4022:         $target.'>'.$text.'</a>';
 4023: }
 4024: ##############################################
 4025: 
 4026: =pod
 4027: 
 4028: =item * &pgrdlink()
 4029: 
 4030: Inputs: $text $uname $udom $symb $target
 4031: 
 4032: Returns: A link to grades.pm such as to see the PGRD view of a student
 4033: 
 4034: =cut
 4035: 
 4036: ###############################################
 4037: sub pgrdlink {
 4038:     my $link=&submlink(@_);
 4039:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4040:     return $link;
 4041: }
 4042: ##############################################
 4043: 
 4044: =pod
 4045: 
 4046: =item * &pprmlink()
 4047: 
 4048: Inputs: $text $uname $udom $symb $target
 4049: 
 4050: Returns: A link to parmset.pm such as to see the PPRM view of a
 4051: student and a specific resource
 4052: 
 4053: =cut
 4054: 
 4055: ###############################################
 4056: sub pprmlink {
 4057:     my ($text,$uname,$udom,$symb,$target)=@_;
 4058:     if (!($uname && $udom)) {
 4059: 	(my $cursymb, my $courseid,$udom,$uname)=
 4060: 	    &Apache::lonnet::whichuser($symb);
 4061: 	if (!$symb) { $symb=$cursymb; }
 4062:     }
 4063:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4064:     $symb=&escape($symb);
 4065:     if ($target) { $target="target=\"$target\""; }
 4066:     return '<a href="/adm/parmset?command=set&amp;'.
 4067: 	'symb='.$symb.'&amp;uname='.$uname.
 4068: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4069: }
 4070: ##############################################
 4071: 
 4072: =pod
 4073: 
 4074: =back
 4075: 
 4076: =cut
 4077: 
 4078: ###############################################
 4079: 
 4080: 
 4081: sub timehash {
 4082:     my ($thistime) = @_;
 4083:     my $timezone = &Apache::lonlocal::gettimezone();
 4084:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4085:                      ->set_time_zone($timezone);
 4086:     my $wday = $dt->day_of_week();
 4087:     if ($wday == 7) { $wday = 0; }
 4088:     return ( 'second' => $dt->second(),
 4089:              'minute' => $dt->minute(),
 4090:              'hour'   => $dt->hour(),
 4091:              'day'     => $dt->day_of_month(),
 4092:              'month'   => $dt->month(),
 4093:              'year'    => $dt->year(),
 4094:              'weekday' => $wday,
 4095:              'dayyear' => $dt->day_of_year(),
 4096:              'dlsav'   => $dt->is_dst() );
 4097: }
 4098: 
 4099: sub utc_string {
 4100:     my ($date)=@_;
 4101:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4102: }
 4103: 
 4104: sub maketime {
 4105:     my %th=@_;
 4106:     my ($epoch_time,$timezone,$dt);
 4107:     $timezone = &Apache::lonlocal::gettimezone();
 4108:     eval {
 4109:         $dt = DateTime->new( year   => $th{'year'},
 4110:                              month  => $th{'month'},
 4111:                              day    => $th{'day'},
 4112:                              hour   => $th{'hour'},
 4113:                              minute => $th{'minute'},
 4114:                              second => $th{'second'},
 4115:                              time_zone => $timezone,
 4116:                          );
 4117:     };
 4118:     if (!$@) {
 4119:         $epoch_time = $dt->epoch;
 4120:         if ($epoch_time) {
 4121:             return $epoch_time;
 4122:         }
 4123:     }
 4124:     return POSIX::mktime(
 4125:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4126:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4127: }
 4128: 
 4129: #########################################
 4130: 
 4131: sub findallcourses {
 4132:     my ($roles,$uname,$udom) = @_;
 4133:     my %roles;
 4134:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4135:     my %courses;
 4136:     my $now=time;
 4137:     if (!defined($uname)) {
 4138:         $uname = $env{'user.name'};
 4139:     }
 4140:     if (!defined($udom)) {
 4141:         $udom = $env{'user.domain'};
 4142:     }
 4143:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4144:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4145:         if (!%roles) {
 4146:             %roles = (
 4147:                        cc => 1,
 4148:                        co => 1,
 4149:                        in => 1,
 4150:                        ep => 1,
 4151:                        ta => 1,
 4152:                        cr => 1,
 4153:                        st => 1,
 4154:              );
 4155:         }
 4156:         foreach my $entry (keys(%roleshash)) {
 4157:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4158:             if ($trole =~ /^cr/) { 
 4159:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4160:             } else {
 4161:                 next if (!exists($roles{$trole}));
 4162:             }
 4163:             if ($tend) {
 4164:                 next if ($tend < $now);
 4165:             }
 4166:             if ($tstart) {
 4167:                 next if ($tstart > $now);
 4168:             }
 4169:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4170:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4171:             my $value = $trole.'/'.$cdom.'/';
 4172:             if ($secpart eq '') {
 4173:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4174:                 $sec = 'none';
 4175:                 $value .= $cnum.'/';
 4176:             } else {
 4177:                 $cnum = $cnumpart;
 4178:                 ($sec,$role) = split(/_/,$secpart);
 4179:                 $value .= $cnum.'/'.$sec;
 4180:             }
 4181:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4182:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4183:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4184:                 }
 4185:             } else {
 4186:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4187:             }
 4188:         }
 4189:     } else {
 4190:         foreach my $key (keys(%env)) {
 4191: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4192:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4193: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4194: 	        next if ($role eq 'ca' || $role eq 'aa');
 4195: 	        next if (%roles && !exists($roles{$role}));
 4196: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4197:                 my $active=1;
 4198:                 if ($starttime) {
 4199: 		    if ($now<$starttime) { $active=0; }
 4200:                 }
 4201:                 if ($endtime) {
 4202:                     if ($now>$endtime) { $active=0; }
 4203:                 }
 4204:                 if ($active) {
 4205:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4206:                     if ($sec eq '') {
 4207:                         $sec = 'none';
 4208:                     } else {
 4209:                         $value .= $sec;
 4210:                     }
 4211:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4212:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4213:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4214:                         }
 4215:                     } else {
 4216:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4217:                     }
 4218:                 }
 4219:             }
 4220:         }
 4221:     }
 4222:     return %courses;
 4223: }
 4224: 
 4225: ###############################################
 4226: 
 4227: sub blockcheck {
 4228:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4229: 
 4230:     if (!defined($udom)) {
 4231:         $udom = $env{'user.domain'};
 4232:     }
 4233:     if (!defined($uname)) {
 4234:         $uname = $env{'user.name'};
 4235:     }
 4236: 
 4237:     # If uname and udom are for a course, check for blocks in the course.
 4238: 
 4239:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4240:         my ($startblock,$endblock,$triggerblock) = 
 4241:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4242:         return ($startblock,$endblock,$triggerblock);
 4243:     }
 4244: 
 4245:     my $startblock = 0;
 4246:     my $endblock = 0;
 4247:     my $triggerblock = '';
 4248:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4249: 
 4250:     # If uname is for a user, and activity is course-specific, i.e.,
 4251:     # boards, chat or groups, check for blocking in current course only.
 4252: 
 4253:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4254:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4255:         foreach my $key (keys(%live_courses)) {
 4256:             if ($key ne $env{'request.course.id'}) {
 4257:                 delete($live_courses{$key});
 4258:             }
 4259:         }
 4260:     }
 4261: 
 4262:     my $otheruser = 0;
 4263:     my %own_courses;
 4264:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4265:         # Resource belongs to user other than current user.
 4266:         $otheruser = 1;
 4267:         # Gather courses for current user
 4268:         %own_courses = 
 4269:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4270:     }
 4271: 
 4272:     # Gather active course roles - course coordinator, instructor, 
 4273:     # exam proctor, ta, student, or custom role.
 4274: 
 4275:     foreach my $course (keys(%live_courses)) {
 4276:         my ($cdom,$cnum);
 4277:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4278:             $cdom = $env{'course.'.$course.'.domain'};
 4279:             $cnum = $env{'course.'.$course.'.num'};
 4280:         } else {
 4281:             ($cdom,$cnum) = split(/_/,$course); 
 4282:         }
 4283:         my $no_ownblock = 0;
 4284:         my $no_userblock = 0;
 4285:         if ($otheruser && $activity ne 'com') {
 4286:             # Check if current user has 'evb' priv for this
 4287:             if (defined($own_courses{$course})) {
 4288:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4289:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4290:                     if ($sec ne 'none') {
 4291:                         $checkrole .= '/'.$sec;
 4292:                     }
 4293:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4294:                         $no_ownblock = 1;
 4295:                         last;
 4296:                     }
 4297:                 }
 4298:             }
 4299:             # if they have 'evb' priv and are currently not playing student
 4300:             next if (($no_ownblock) &&
 4301:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4302:         }
 4303:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4304:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4305:             if ($sec ne 'none') {
 4306:                 $checkrole .= '/'.$sec;
 4307:             }
 4308:             if ($otheruser) {
 4309:                 # Resource belongs to user other than current user.
 4310:                 # Assemble privs for that user, and check for 'evb' priv.
 4311:                 my (%allroles,%userroles);
 4312:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4313:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4314:                         my ($trole,$tdom,$tnum,$tsec);
 4315:                         if ($entry =~ /^cr/) {
 4316:                             ($trole,$tdom,$tnum,$tsec) = 
 4317:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4318:                         } else {
 4319:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4320:                         }
 4321:                         my ($spec,$area,$trest);
 4322:                         $area = '/'.$tdom.'/'.$tnum;
 4323:                         $trest = $tnum;
 4324:                         if ($tsec ne '') {
 4325:                             $area .= '/'.$tsec;
 4326:                             $trest .= '/'.$tsec;
 4327:                         }
 4328:                         $spec = $trole.'.'.$area;
 4329:                         if ($trole =~ /^cr/) {
 4330:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4331:                                                               $tdom,$spec,$trest,$area);
 4332:                         } else {
 4333:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4334:                                                                 $tdom,$spec,$trest,$area);
 4335:                         }
 4336:                     }
 4337:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4338:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4339:                         if ($1) {
 4340:                             $no_userblock = 1;
 4341:                             last;
 4342:                         }
 4343:                     }
 4344:                 }
 4345:             } else {
 4346:                 # Resource belongs to current user
 4347:                 # Check for 'evb' priv via lonnet::allowed().
 4348:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4349:                     $no_ownblock = 1;
 4350:                     last;
 4351:                 }
 4352:             }
 4353:         }
 4354:         # if they have the evb priv and are currently not playing student
 4355:         next if (($no_ownblock) &&
 4356:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4357:         next if ($no_userblock);
 4358: 
 4359:         # Retrieve blocking times and identity of locker for course
 4360:         # of specified user, unless user has 'evb' privilege.
 4361:         
 4362:         my ($start,$end,$trigger) = 
 4363:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4364:         if (($start != 0) && 
 4365:             (($startblock == 0) || ($startblock > $start))) {
 4366:             $startblock = $start;
 4367:             if ($trigger ne '') {
 4368:                 $triggerblock = $trigger;
 4369:             }
 4370:         }
 4371:         if (($end != 0)  &&
 4372:             (($endblock == 0) || ($endblock < $end))) {
 4373:             $endblock = $end;
 4374:             if ($trigger ne '') {
 4375:                 $triggerblock = $trigger;
 4376:             }
 4377:         }
 4378:     }
 4379:     return ($startblock,$endblock,$triggerblock);
 4380: }
 4381: 
 4382: sub get_blocks {
 4383:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4384:     my $startblock = 0;
 4385:     my $endblock = 0;
 4386:     my $triggerblock = '';
 4387:     my $course = $cdom.'_'.$cnum;
 4388:     $setters->{$course} = {};
 4389:     $setters->{$course}{'staff'} = [];
 4390:     $setters->{$course}{'times'} = [];
 4391:     $setters->{$course}{'triggers'} = [];
 4392:     my (@blockers,%triggered);
 4393:     my $now = time;
 4394:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4395:     if ($activity eq 'docs') {
 4396:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4397:         foreach my $block (@blockers) {
 4398:             if ($block =~ /^firstaccess____(.+)$/) {
 4399:                 my $item = $1;
 4400:                 my $type = 'map';
 4401:                 my $timersymb = $item;
 4402:                 if ($item eq 'course') {
 4403:                     $type = 'course';
 4404:                 } elsif ($item =~ /___\d+___/) {
 4405:                     $type = 'resource';
 4406:                 } else {
 4407:                     $timersymb = &Apache::lonnet::symbread($item);
 4408:                 }
 4409:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4410:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4411:                 $triggered{$block} = {
 4412:                                        start => $start,
 4413:                                        end   => $end,
 4414:                                        type  => $type,
 4415:                                      };
 4416:             }
 4417:         }
 4418:     } else {
 4419:         foreach my $block (keys(%commblocks)) {
 4420:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4421:                 my ($start,$end) = ($1,$2);
 4422:                 if ($start <= time && $end >= time) {
 4423:                     if (ref($commblocks{$block}) eq 'HASH') {
 4424:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4425:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4426:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4427:                                     push(@blockers,$block);
 4428:                                 }
 4429:                             }
 4430:                         }
 4431:                     }
 4432:                 }
 4433:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4434:                 my $item = $1;
 4435:                 my $timersymb = $item; 
 4436:                 my $type = 'map';
 4437:                 if ($item eq 'course') {
 4438:                     $type = 'course';
 4439:                 } elsif ($item =~ /___\d+___/) {
 4440:                     $type = 'resource';
 4441:                 } else {
 4442:                     $timersymb = &Apache::lonnet::symbread($item);
 4443:                 }
 4444:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4445:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4446:                 if ($start && $end) {
 4447:                     if (($start <= time) && ($end >= time)) {
 4448:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4449:                             push(@blockers,$block);
 4450:                             $triggered{$block} = {
 4451:                                                    start => $start,
 4452:                                                    end   => $end,
 4453:                                                    type  => $type,
 4454:                                                  };
 4455:                         }
 4456:                     }
 4457:                 }
 4458:             }
 4459:         }
 4460:     }
 4461:     foreach my $blocker (@blockers) {
 4462:         my ($staff_name,$staff_dom,$title,$blocks) =
 4463:             &parse_block_record($commblocks{$blocker});
 4464:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4465:         my ($start,$end,$triggertype);
 4466:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4467:             ($start,$end) = ($1,$2);
 4468:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4469:             $start = $triggered{$blocker}{'start'};
 4470:             $end = $triggered{$blocker}{'end'};
 4471:             $triggertype = $triggered{$blocker}{'type'};
 4472:         }
 4473:         if ($start) {
 4474:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4475:             if ($triggertype) {
 4476:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4477:             } else {
 4478:                 push(@{$$setters{$course}{'triggers'}},0);
 4479:             }
 4480:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4481:                 $startblock = $start;
 4482:                 if ($triggertype) {
 4483:                     $triggerblock = $blocker;
 4484:                 }
 4485:             }
 4486:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4487:                $endblock = $end;
 4488:                if ($triggertype) {
 4489:                    $triggerblock = $blocker;
 4490:                }
 4491:             }
 4492:         }
 4493:     }
 4494:     return ($startblock,$endblock,$triggerblock);
 4495: }
 4496: 
 4497: sub parse_block_record {
 4498:     my ($record) = @_;
 4499:     my ($setuname,$setudom,$title,$blocks);
 4500:     if (ref($record) eq 'HASH') {
 4501:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4502:         $title = &unescape($record->{'event'});
 4503:         $blocks = $record->{'blocks'};
 4504:     } else {
 4505:         my @data = split(/:/,$record,3);
 4506:         if (scalar(@data) eq 2) {
 4507:             $title = $data[1];
 4508:             ($setuname,$setudom) = split(/@/,$data[0]);
 4509:         } else {
 4510:             ($setuname,$setudom,$title) = @data;
 4511:         }
 4512:         $blocks = { 'com' => 'on' };
 4513:     }
 4514:     return ($setuname,$setudom,$title,$blocks);
 4515: }
 4516: 
 4517: sub blocking_status {
 4518:     my ($activity,$uname,$udom,$url) = @_;
 4519:     my %setters;
 4520: 
 4521: # check for active blocking
 4522:     my ($startblock,$endblock,$triggerblock) = 
 4523:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4524:     my $blocked = 0;
 4525:     if ($startblock && $endblock) {
 4526:         $blocked = 1;
 4527:     }
 4528: 
 4529: # caller just wants to know whether a block is active
 4530:     if (!wantarray) { return $blocked; }
 4531: 
 4532: # build a link to a popup window containing the details
 4533:     my $querystring  = "?activity=$activity";
 4534: # $uname and $udom decide whose portfolio the user is trying to look at
 4535:     if ($activity eq 'port') {
 4536:         $querystring .= "&amp;udom=$udom"      if $udom;
 4537:         $querystring .= "&amp;uname=$uname"    if $uname;
 4538:     } elsif ($activity eq 'docs') {
 4539:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4540:     }
 4541: 
 4542:     my $output .= <<'END_MYBLOCK';
 4543: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4544:     var options = "width=" + w + ",height=" + h + ",";
 4545:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4546:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4547:     var newWin = window.open(url, wdwName, options);
 4548:     newWin.focus();
 4549: }
 4550: END_MYBLOCK
 4551: 
 4552:     $output = Apache::lonhtmlcommon::scripttag($output);
 4553:   
 4554:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4555:     my $text = &mt('Communication Blocked');
 4556:     if ($activity eq 'docs') {
 4557:         $text = &mt('Content Access Blocked');
 4558:     } elsif ($activity eq 'printout') {
 4559:         $text = &mt('Printing Blocked');
 4560:     }
 4561:     $output .= <<"END_BLOCK";
 4562: <div class='LC_comblock'>
 4563:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4564:   title='$text'>
 4565:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4566:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4567:   title='$text'>$text</a>
 4568: </div>
 4569: 
 4570: END_BLOCK
 4571: 
 4572:     return ($blocked, $output);
 4573: }
 4574: 
 4575: ###############################################
 4576: 
 4577: sub check_ip_acc {
 4578:     my ($acc)=@_;
 4579:     &Apache::lonxml::debug("acc is $acc");
 4580:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4581:         return 1;
 4582:     }
 4583:     my $allowed=0;
 4584:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4585: 
 4586:     my $name;
 4587:     foreach my $pattern (split(',',$acc)) {
 4588:         $pattern =~ s/^\s*//;
 4589:         $pattern =~ s/\s*$//;
 4590:         if ($pattern =~ /\*$/) {
 4591:             #35.8.*
 4592:             $pattern=~s/\*//;
 4593:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4594:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4595:             #35.8.3.[34-56]
 4596:             my $low=$2;
 4597:             my $high=$3;
 4598:             $pattern=$1;
 4599:             if ($ip =~ /^\Q$pattern\E/) {
 4600:                 my $last=(split(/\./,$ip))[3];
 4601:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4602:             }
 4603:         } elsif ($pattern =~ /^\*/) {
 4604:             #*.msu.edu
 4605:             $pattern=~s/\*//;
 4606:             if (!defined($name)) {
 4607:                 use Socket;
 4608:                 my $netaddr=inet_aton($ip);
 4609:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4610:             }
 4611:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4612:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4613:             #127.0.0.1
 4614:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4615:         } else {
 4616:             #some.name.com
 4617:             if (!defined($name)) {
 4618:                 use Socket;
 4619:                 my $netaddr=inet_aton($ip);
 4620:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4621:             }
 4622:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4623:         }
 4624:         if ($allowed) { last; }
 4625:     }
 4626:     return $allowed;
 4627: }
 4628: 
 4629: ###############################################
 4630: 
 4631: =pod
 4632: 
 4633: =head1 Domain Template Functions
 4634: 
 4635: =over 4
 4636: 
 4637: =item * &determinedomain()
 4638: 
 4639: Inputs: $domain (usually will be undef)
 4640: 
 4641: Returns: Determines which domain should be used for designs
 4642: 
 4643: =cut
 4644: 
 4645: ###############################################
 4646: sub determinedomain {
 4647:     my $domain=shift;
 4648:     if (! $domain) {
 4649:         # Determine domain if we have not been given one
 4650:         $domain = &Apache::lonnet::default_login_domain();
 4651:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4652:         if ($env{'request.role.domain'}) { 
 4653:             $domain=$env{'request.role.domain'}; 
 4654:         }
 4655:     }
 4656:     return $domain;
 4657: }
 4658: ###############################################
 4659: 
 4660: sub devalidate_domconfig_cache {
 4661:     my ($udom)=@_;
 4662:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4663: }
 4664: 
 4665: # ---------------------- Get domain configuration for a domain
 4666: sub get_domainconf {
 4667:     my ($udom) = @_;
 4668:     my $cachetime=1800;
 4669:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4670:     if (defined($cached)) { return %{$result}; }
 4671: 
 4672:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4673: 					     ['login','rolecolors','autoenroll'],$udom);
 4674:     my (%designhash,%legacy);
 4675:     if (keys(%domconfig) > 0) {
 4676:         if (ref($domconfig{'login'}) eq 'HASH') {
 4677:             if (keys(%{$domconfig{'login'}})) {
 4678:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4679:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4680:                         if ($key eq 'loginvia') {
 4681:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4682:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4683:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4684:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4685:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4686:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4687:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4688: 
 4689:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4690:                                             } else {
 4691:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4692:                                             }
 4693:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4694:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4695:                                             }
 4696:                                         }
 4697:                                     }
 4698:                                 }
 4699:                             }
 4700:                         } else {
 4701:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4702:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4703:                                     $domconfig{'login'}{$key}{$img};
 4704:                             }
 4705:                         }
 4706:                     } else {
 4707:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4708:                     }
 4709:                 }
 4710:             } else {
 4711:                 $legacy{'login'} = 1;
 4712:             }
 4713:         } else {
 4714:             $legacy{'login'} = 1;
 4715:         }
 4716:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4717:             if (keys(%{$domconfig{'rolecolors'}})) {
 4718:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4719:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4720:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4721:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4722:                         }
 4723:                     }
 4724:                 }
 4725:             } else {
 4726:                 $legacy{'rolecolors'} = 1;
 4727:             }
 4728:         } else {
 4729:             $legacy{'rolecolors'} = 1;
 4730:         }
 4731:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4732:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4733:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4734:             }
 4735:         }
 4736:         if (keys(%legacy) > 0) {
 4737:             my %legacyhash = &get_legacy_domconf($udom);
 4738:             foreach my $item (keys(%legacyhash)) {
 4739:                 if ($item =~ /^\Q$udom\E\.login/) {
 4740:                     if ($legacy{'login'}) { 
 4741:                         $designhash{$item} = $legacyhash{$item};
 4742:                     }
 4743:                 } else {
 4744:                     if ($legacy{'rolecolors'}) {
 4745:                         $designhash{$item} = $legacyhash{$item};
 4746:                     }
 4747:                 }
 4748:             }
 4749:         }
 4750:     } else {
 4751:         %designhash = &get_legacy_domconf($udom); 
 4752:     }
 4753:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4754: 				  $cachetime);
 4755:     return %designhash;
 4756: }
 4757: 
 4758: sub get_legacy_domconf {
 4759:     my ($udom) = @_;
 4760:     my %legacyhash;
 4761:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4762:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4763:     if (-e $designfile) {
 4764:         if ( open (my $fh,"<$designfile") ) {
 4765:             while (my $line = <$fh>) {
 4766:                 next if ($line =~ /^\#/);
 4767:                 chomp($line);
 4768:                 my ($key,$val)=(split(/\=/,$line));
 4769:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4770:             }
 4771:             close($fh);
 4772:         }
 4773:     }
 4774:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4775:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4776:     }
 4777:     return %legacyhash;
 4778: }
 4779: 
 4780: =pod
 4781: 
 4782: =item * &domainlogo()
 4783: 
 4784: Inputs: $domain (usually will be undef)
 4785: 
 4786: Returns: A link to a domain logo, if the domain logo exists.
 4787: If the domain logo does not exist, a description of the domain.
 4788: 
 4789: =cut
 4790: 
 4791: ###############################################
 4792: sub domainlogo {
 4793:     my $domain = &determinedomain(shift);
 4794:     my %designhash = &get_domainconf($domain);    
 4795:     # See if there is a logo
 4796:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4797:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4798:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4799: 	    if ($imgsrc =~ m{^/res/}) {
 4800: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4801: 		&Apache::lonnet::repcopy($local_name);
 4802: 	    }
 4803: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4804:         } 
 4805:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4806:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4807:         return &Apache::lonnet::domain($domain,'description');
 4808:     } else {
 4809:         return '';
 4810:     }
 4811: }
 4812: ##############################################
 4813: 
 4814: =pod
 4815: 
 4816: =item * &designparm()
 4817: 
 4818: Inputs: $which parameter; $domain (usually will be undef)
 4819: 
 4820: Returns: value of designparamter $which
 4821: 
 4822: =cut
 4823: 
 4824: 
 4825: ##############################################
 4826: sub designparm {
 4827:     my ($which,$domain)=@_;
 4828:     if (exists($env{'environment.color.'.$which})) {
 4829:         return $env{'environment.color.'.$which};
 4830:     }
 4831:     $domain=&determinedomain($domain);
 4832:     my %domdesign;
 4833:     unless ($domain eq 'public') {
 4834:         %domdesign = &get_domainconf($domain);
 4835:     }
 4836:     my $output;
 4837:     if ($domdesign{$domain.'.'.$which} ne '') {
 4838:         $output = $domdesign{$domain.'.'.$which};
 4839:     } else {
 4840:         $output = $defaultdesign{$which};
 4841:     }
 4842:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4843:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4844:         if ($output =~ m{^/(adm|res)/}) {
 4845:             if ($output =~ m{^/res/}) {
 4846:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4847:                 &Apache::lonnet::repcopy($local_name);
 4848:             }
 4849:             $output = &lonhttpdurl($output);
 4850:         }
 4851:     }
 4852:     return $output;
 4853: }
 4854: 
 4855: ##############################################
 4856: =pod
 4857: 
 4858: =item * &authorspace()
 4859: 
 4860: Inputs: $url (usually will be undef).
 4861: 
 4862: Returns: Path to Authoring Space containing the resource or 
 4863:          directory being viewed (or for which action is being taken). 
 4864:          If $url is provided, and begins /priv/<domain>/<uname>
 4865:          the path will be that portion of the $context argument.
 4866:          Otherwise the path will be for the author space of the current
 4867:          user when the current role is author, or for that of the 
 4868:          co-author/assistant co-author space when the current role 
 4869:          is co-author or assistant co-author.
 4870: 
 4871: =cut
 4872: 
 4873: sub authorspace {
 4874:     my ($url) = @_;
 4875:     if ($url ne '') {
 4876:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4877:            return $1;
 4878:         }
 4879:     }
 4880:     my $caname = '';
 4881:     my $cadom = '';
 4882:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4883:         ($cadom,$caname) =
 4884:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4885:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4886:         $caname = $env{'user.name'};
 4887:         $cadom = $env{'user.domain'};
 4888:     }
 4889:     if (($caname ne '') && ($cadom ne '')) {
 4890:         return "/priv/$cadom/$caname/";
 4891:     }
 4892:     return;
 4893: }
 4894: 
 4895: ##############################################
 4896: =pod
 4897: 
 4898: =item * &head_subbox()
 4899: 
 4900: Inputs: $content (contains HTML code with page functions, etc.)
 4901: 
 4902: Returns: HTML div with $content
 4903:          To be included in page header
 4904: 
 4905: =cut
 4906: 
 4907: sub head_subbox {
 4908:     my ($content)=@_;
 4909:     my $output =
 4910:         '<div class="LC_head_subbox">'
 4911:        .$content
 4912:        .'</div>'
 4913: }
 4914: 
 4915: ##############################################
 4916: =pod
 4917: 
 4918: =item * &CSTR_pageheader()
 4919: 
 4920: Input: (optional) filename from which breadcrumb trail is built.
 4921:        In most cases no input as needed, as $env{'request.filename'}
 4922:        is appropriate for use in building the breadcrumb trail.
 4923: 
 4924: Returns: HTML div with CSTR path and recent box
 4925:          To be included on Authoring Space pages
 4926: 
 4927: =cut
 4928: 
 4929: sub CSTR_pageheader {
 4930:     my ($trailfile) = @_;
 4931:     if ($trailfile eq '') {
 4932:         $trailfile = $env{'request.filename'};
 4933:     }
 4934: 
 4935: # this is for resources; directories have customtitle, and crumbs
 4936: # and select recent are created in lonpubdir.pm
 4937: 
 4938:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4939:     my ($udom,$uname,$thisdisfn)=
 4940:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 4941:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4942:     $formaction =~ s{/+}{/}g;
 4943: 
 4944:     my $parentpath = '';
 4945:     my $lastitem = '';
 4946:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4947:         $parentpath = $1;
 4948:         $lastitem = $2;
 4949:     } else {
 4950:         $lastitem = $thisdisfn;
 4951:     }
 4952: 
 4953:     my $output =
 4954:          '<div>'
 4955:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4956:         .'<b>'.&mt('Authoring Space:').'</b> '
 4957:         .'<form name="dirs" method="post" action="'.$formaction
 4958:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4959:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4960: 
 4961:     if ($lastitem) {
 4962:         $output .=
 4963:              '<span class="LC_filename">'
 4964:             .$lastitem
 4965:             .'</span>';
 4966:     }
 4967:     $output .=
 4968:          '<br />'
 4969:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4970:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4971:         .'</form>'
 4972:         .&Apache::lonmenu::constspaceform()
 4973:         .'</div>';
 4974: 
 4975:     return $output;
 4976: }
 4977: 
 4978: ###############################################
 4979: ###############################################
 4980: 
 4981: =pod
 4982: 
 4983: =back
 4984: 
 4985: =head1 HTML Helpers
 4986: 
 4987: =over 4
 4988: 
 4989: =item * &bodytag()
 4990: 
 4991: Returns a uniform header for LON-CAPA web pages.
 4992: 
 4993: Inputs: 
 4994: 
 4995: =over 4
 4996: 
 4997: =item * $title, A title to be displayed on the page.
 4998: 
 4999: =item * $function, the current role (can be undef).
 5000: 
 5001: =item * $addentries, extra parameters for the <body> tag.
 5002: 
 5003: =item * $bodyonly, if defined, only return the <body> tag.
 5004: 
 5005: =item * $domain, if defined, force a given domain.
 5006: 
 5007: =item * $forcereg, if page should register as content page (relevant for 
 5008:             text interface only)
 5009: 
 5010: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5011:                      navigational links
 5012: 
 5013: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5014: 
 5015: =item * $no_inline_link, if true and in remote mode, don't show the
 5016:          'Switch To Inline Menu' link
 5017: 
 5018: =item * $args, optional argument valid values are
 5019:             no_auto_mt_title -> prevents &mt()ing the title arg
 5020:             inherit_jsmath -> when creating popup window in a page,
 5021:                               should it have jsmath forced on by the
 5022:                               current page
 5023: 
 5024: =item * $advtoolsref, optional argument, ref to an array containing
 5025:             inlineremote items to be added in "Functions" menu below
 5026:             breadcrumbs.
 5027: 
 5028: =back
 5029: 
 5030: Returns: A uniform header for LON-CAPA web pages.  
 5031: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5032: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5033: other decorations will be returned.
 5034: 
 5035: =cut
 5036: 
 5037: sub bodytag {
 5038:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5039:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5040: 
 5041:     my $public;
 5042:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5043:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5044:         $public = 1;
 5045:     }
 5046:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5047:     my $httphost = $args->{'use_absolute'};
 5048: 
 5049:     $function = &get_users_function() if (!$function);
 5050:     my $img =    &designparm($function.'.img',$domain);
 5051:     my $font =   &designparm($function.'.font',$domain);
 5052:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5053: 
 5054:     my %design = ( 'style'   => 'margin-top: 0',
 5055: 		   'bgcolor' => $pgbg,
 5056: 		   'text'    => $font,
 5057:                    'alink'   => &designparm($function.'.alink',$domain),
 5058: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5059: 		   'link'    => &designparm($function.'.link',$domain),);
 5060:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5061: 
 5062:  # role and realm
 5063:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5064:     if ($role  eq 'ca') {
 5065:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5066:         $realm = &plainname($rname,$rdom);
 5067:     } 
 5068: # realm
 5069:     if ($env{'request.course.id'}) {
 5070:         if ($env{'request.role'} !~ /^cr/) {
 5071:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5072:         }
 5073:         if ($env{'request.course.sec'}) {
 5074:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5075:         }   
 5076: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5077:     } else {
 5078:         $role = &Apache::lonnet::plaintext($role);
 5079:     }
 5080: 
 5081:     if (!$realm) { $realm='&nbsp;'; }
 5082: 
 5083:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5084: 
 5085: # construct main body tag
 5086:     my $bodytag = "<body $extra_body_attr>".
 5087: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5088: 
 5089:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5090: 
 5091:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5092:         return $bodytag;
 5093:     }
 5094: 
 5095:     if ($public) {
 5096: 	undef($role);
 5097:     }
 5098:     
 5099:     my $titleinfo = '<h1>'.$title.'</h1>';
 5100:     #
 5101:     # Extra info if you are the DC
 5102:     my $dc_info = '';
 5103:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5104:                         $env{'course.'.$env{'request.course.id'}.
 5105:                                  '.domain'}.'/'})) {
 5106:         my $cid = $env{'request.course.id'};
 5107:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5108:         $dc_info =~ s/\s+$//;
 5109:     }
 5110: 
 5111:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5112: 
 5113:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5114: 
 5115: 
 5116: 
 5117:     my $funclist;
 5118:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5119:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5120:                     Apache::lonmenu::serverform();
 5121:         my $forbodytag;
 5122:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5123:                                             $forcereg,$args->{'group'},
 5124:                                             $args->{'bread_crumbs'},
 5125:                                             $advtoolsref,'',\$forbodytag);
 5126:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5127:             $funclist = $forbodytag;
 5128:         }
 5129:     } else {
 5130: 
 5131:         #    if ($env{'request.state'} eq 'construct') {
 5132:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5133:         #    }
 5134: 
 5135:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5136:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5137: 
 5138:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5139: 
 5140:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5141:             if ($dc_info) {
 5142:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5143:             }
 5144:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5145:                            <em>$realm</em> $dc_info</div>|;
 5146:             return $bodytag;
 5147:         }
 5148: 
 5149:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5150:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5151:         }
 5152: 
 5153:         $bodytag .= $right;
 5154: 
 5155:         if ($dc_info) {
 5156:             $dc_info = &dc_courseid_toggle($dc_info);
 5157:         }
 5158:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5159: 
 5160:         #don't show menus for public users
 5161:         if (!$public){
 5162:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5163:             $bodytag .= Apache::lonmenu::serverform();
 5164:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5165:             if ($env{'request.state'} eq 'construct') {
 5166:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5167:                                 $args->{'bread_crumbs'});
 5168:             } elsif ($forcereg) { 
 5169:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5170:                                                             $args->{'group'});
 5171:             } else {
 5172:                 my $forbodytag;
 5173:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5174:                                                     $forcereg,$args->{'group'},
 5175:                                                     $args->{'bread_crumbs'},
 5176:                                                     $advtoolsref,'',\$forbodytag);
 5177:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5178:                     $bodytag .= $forbodytag;
 5179:                 }
 5180:             }
 5181:         }else{
 5182:             # this is to seperate menu from content when there's no secondary
 5183:             # menu. Especially needed for public accessible ressources.
 5184:             $bodytag .= '<hr style="clear:both" />';
 5185:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5186:         }
 5187: 
 5188:         return $bodytag;
 5189:     }
 5190: 
 5191: #
 5192: # Top frame rendering, Remote is up
 5193: #
 5194: 
 5195:     my $imgsrc = $img;
 5196:     if ($img =~ /^\/adm/) {
 5197:         $imgsrc = &lonhttpdurl($img);
 5198:     }
 5199:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5200: 
 5201:     my $help=($no_inline_link?''
 5202:               :&Apache::loncommon::top_nav_help('Help'));
 5203: 
 5204:     # Explicit link to get inline menu
 5205:     my $menu= ($no_inline_link?''
 5206:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5207: 
 5208:     if ($dc_info) {
 5209:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5210:     }
 5211: 
 5212:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5213:     unless ($public) {
 5214:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5215:                                 undef,'LC_menubuttons_link');
 5216:     }
 5217: 
 5218:     unless ($env{'form.inhibitmenu'}) {
 5219:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5220:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5221:                        <li>$help</li>
 5222:                        <li>$menu</li>
 5223:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5224:     }
 5225:     if ($env{'request.state'} eq 'construct') {
 5226:         if (!$public){
 5227:             if ($env{'request.state'} eq 'construct') {
 5228:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5229:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5230:                             &Apache::lonhtmlcommon::scripttag('','end').
 5231:                             &Apache::lonmenu::innerregister($forcereg,
 5232:                                                             $args->{'bread_crumbs'});
 5233:             }
 5234:         }
 5235:     }
 5236:     return $bodytag."\n".$funclist;
 5237: }
 5238: 
 5239: sub dc_courseid_toggle {
 5240:     my ($dc_info) = @_;
 5241:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5242:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5243:            &mt('(More ...)').'</a></span>'.
 5244:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5245: }
 5246: 
 5247: sub make_attr_string {
 5248:     my ($register,$attr_ref) = @_;
 5249: 
 5250:     if ($attr_ref && !ref($attr_ref)) {
 5251: 	die("addentries Must be a hash ref ".
 5252: 	    join(':',caller(1))." ".
 5253: 	    join(':',caller(0))." ");
 5254:     }
 5255: 
 5256:     if ($register) {
 5257: 	my ($on_load,$on_unload);
 5258: 	foreach my $key (keys(%{$attr_ref})) {
 5259: 	    if      (lc($key) eq 'onload') {
 5260: 		$on_load.=$attr_ref->{$key}.';';
 5261: 		delete($attr_ref->{$key});
 5262: 
 5263: 	    } elsif (lc($key) eq 'onunload') {
 5264: 		$on_unload.=$attr_ref->{$key}.';';
 5265: 		delete($attr_ref->{$key});
 5266: 	    }
 5267: 	}
 5268:         if ($env{'environment.remote'} eq 'on') {
 5269:             $attr_ref->{'onload'}  =
 5270:                 &Apache::lonmenu::loadevents().  $on_load;
 5271:             $attr_ref->{'onunload'}=
 5272:                 &Apache::lonmenu::unloadevents().$on_unload;
 5273:         } else {  
 5274: 	    $attr_ref->{'onload'}  = $on_load;
 5275: 	    $attr_ref->{'onunload'}= $on_unload;
 5276:         }
 5277:     }
 5278: 
 5279:     my $attr_string;
 5280:     foreach my $attr (sort(keys(%$attr_ref))) {
 5281: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5282:     }
 5283:     return $attr_string;
 5284: }
 5285: 
 5286: 
 5287: ###############################################
 5288: ###############################################
 5289: 
 5290: =pod
 5291: 
 5292: =item * &endbodytag()
 5293: 
 5294: Returns a uniform footer for LON-CAPA web pages.
 5295: 
 5296: Inputs: 1 - optional reference to an args hash
 5297: If in the hash, key for noredirectlink has a value which evaluates to true,
 5298: a 'Continue' link is not displayed if the page contains an
 5299: internal redirect in the <head></head> section,
 5300: i.e., $env{'internal.head.redirect'} exists   
 5301: 
 5302: =cut
 5303: 
 5304: sub endbodytag {
 5305:     my ($args) = @_;
 5306:     my $endbodytag;
 5307:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5308:         $endbodytag='</body>';
 5309:     }
 5310:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5311:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5312:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5313: 	    $endbodytag=
 5314: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5315: 	        &mt('Continue').'</a>'.
 5316: 	        $endbodytag;
 5317:         }
 5318:     }
 5319:     return $endbodytag;
 5320: }
 5321: 
 5322: =pod
 5323: 
 5324: =item * &standard_css()
 5325: 
 5326: Returns a style sheet
 5327: 
 5328: Inputs: (all optional)
 5329:             domain         -> force to color decorate a page for a specific
 5330:                                domain
 5331:             function       -> force usage of a specific rolish color scheme
 5332:             bgcolor        -> override the default page bgcolor
 5333: 
 5334: =cut
 5335: 
 5336: sub standard_css {
 5337:     my ($function,$domain,$bgcolor) = @_;
 5338:     $function  = &get_users_function() if (!$function);
 5339:     my $img    = &designparm($function.'.img',   $domain);
 5340:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5341:     my $font   = &designparm($function.'.font',  $domain);
 5342:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5343: #second colour for later usage
 5344:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5345:     my $pgbg_or_bgcolor =
 5346: 	         $bgcolor ||
 5347: 	         &designparm($function.'.pgbg',  $domain);
 5348:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5349:     my $alink  = &designparm($function.'.alink', $domain);
 5350:     my $vlink  = &designparm($function.'.vlink', $domain);
 5351:     my $link   = &designparm($function.'.link',  $domain);
 5352: 
 5353:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5354:     my $mono                 = 'monospace';
 5355:     my $data_table_head      = $sidebg;
 5356:     my $data_table_light     = '#FAFAFA';
 5357:     my $data_table_dark      = '#E0E0E0';
 5358:     my $data_table_darker    = '#CCCCCC';
 5359:     my $data_table_highlight = '#FFFF00';
 5360:     my $mail_new             = '#FFBB77';
 5361:     my $mail_new_hover       = '#DD9955';
 5362:     my $mail_read            = '#BBBB77';
 5363:     my $mail_read_hover      = '#999944';
 5364:     my $mail_replied         = '#AAAA88';
 5365:     my $mail_replied_hover   = '#888855';
 5366:     my $mail_other           = '#99BBBB';
 5367:     my $mail_other_hover     = '#669999';
 5368:     my $table_header         = '#DDDDDD';
 5369:     my $feedback_link_bg     = '#BBBBBB';
 5370:     my $lg_border_color      = '#C8C8C8';
 5371:     my $button_hover         = '#BF2317';
 5372: 
 5373:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5374:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5375:                                              : '0 3px 0 4px';
 5376: 
 5377: 
 5378:     return <<END;
 5379: 
 5380: /* needed for iframe to allow 100% height in FF */
 5381: body, html { 
 5382:     margin: 0;
 5383:     padding: 0 0.5%;
 5384:     height: 99%; /* to avoid scrollbars */
 5385: }
 5386: 
 5387: body {
 5388:   font-family: $sans;
 5389:   line-height:130%;
 5390:   font-size:0.83em;
 5391:   color:$font;
 5392: }
 5393: 
 5394: a:focus,
 5395: a:focus img {
 5396:   color: red;
 5397: }
 5398: 
 5399: form, .inline {
 5400:   display: inline;
 5401: }
 5402: 
 5403: .LC_right {
 5404:   text-align:right;
 5405: }
 5406: 
 5407: .LC_middle {
 5408:   vertical-align:middle;
 5409: }
 5410: 
 5411: .LC_floatleft {
 5412:   float: left;
 5413: }
 5414: 
 5415: .LC_floatright {
 5416:   float: right;
 5417: }
 5418: 
 5419: .LC_400Box {
 5420:   width:400px;
 5421: }
 5422: 
 5423: .LC_iframecontainer {
 5424:     width: 98%;
 5425:     margin: 0;
 5426:     position: fixed;
 5427:     top: 8.5em;
 5428:     bottom: 0;
 5429: }
 5430: 
 5431: .LC_iframecontainer iframe{
 5432:     border: none;
 5433:     width: 100%;
 5434:     height: 100%;
 5435: }
 5436: 
 5437: .LC_filename {
 5438:   font-family: $mono;
 5439:   white-space:pre;
 5440:   font-size: 120%;
 5441: }
 5442: 
 5443: .LC_fileicon {
 5444:   border: none;
 5445:   height: 1.3em;
 5446:   vertical-align: text-bottom;
 5447:   margin-right: 0.3em;
 5448:   text-decoration:none;
 5449: }
 5450: 
 5451: .LC_setting {
 5452:   text-decoration:underline;
 5453: }
 5454: 
 5455: .LC_error {
 5456:   color: red;
 5457: }
 5458: 
 5459: .LC_warning {
 5460:   color: darkorange;
 5461: }
 5462: 
 5463: .LC_diff_removed {
 5464:   color: red;
 5465: }
 5466: 
 5467: .LC_info,
 5468: .LC_success,
 5469: .LC_diff_added {
 5470:   color: green;
 5471: }
 5472: 
 5473: div.LC_confirm_box {
 5474:   background-color: #FAFAFA;
 5475:   border: 1px solid $lg_border_color;
 5476:   margin-right: 0;
 5477:   padding: 5px;
 5478: }
 5479: 
 5480: div.LC_confirm_box .LC_error img,
 5481: div.LC_confirm_box .LC_success img {
 5482:   vertical-align: middle;
 5483: }
 5484: 
 5485: .LC_icon {
 5486:   border: none;
 5487:   vertical-align: middle;
 5488: }
 5489: 
 5490: .LC_docs_spacer {
 5491:   width: 25px;
 5492:   height: 1px;
 5493:   border: none;
 5494: }
 5495: 
 5496: .LC_internal_info {
 5497:   color: #999999;
 5498: }
 5499: 
 5500: .LC_discussion {
 5501:   background: $data_table_dark;
 5502:   border: 1px solid black;
 5503:   margin: 2px;
 5504: }
 5505: 
 5506: .LC_disc_action_left {
 5507:   background: $sidebg;
 5508:   text-align: left;
 5509:   padding: 4px;
 5510:   margin: 2px;
 5511: }
 5512: 
 5513: .LC_disc_action_right {
 5514:   background: $sidebg;
 5515:   text-align: right;
 5516:   padding: 4px;
 5517:   margin: 2px;
 5518: }
 5519: 
 5520: .LC_disc_new_item {
 5521:   background: white;
 5522:   border: 2px solid red;
 5523:   margin: 4px;
 5524:   padding: 4px;
 5525: }
 5526: 
 5527: .LC_disc_old_item {
 5528:   background: white;
 5529:   margin: 4px;
 5530:   padding: 4px;
 5531: }
 5532: 
 5533: table.LC_pastsubmission {
 5534:   border: 1px solid black;
 5535:   margin: 2px;
 5536: }
 5537: 
 5538: table#LC_menubuttons {
 5539:   width: 100%;
 5540:   background: $pgbg;
 5541:   border: 2px;
 5542:   border-collapse: separate;
 5543:   padding: 0;
 5544: }
 5545: 
 5546: table#LC_title_bar a {
 5547:   color: $fontmenu;
 5548: }
 5549: 
 5550: table#LC_title_bar {
 5551:   clear: both;
 5552:   display: none;
 5553: }
 5554: 
 5555: table#LC_title_bar,
 5556: table.LC_breadcrumbs, /* obsolete? */
 5557: table#LC_title_bar.LC_with_remote {
 5558:   width: 100%;
 5559:   border-color: $pgbg;
 5560:   border-style: solid;
 5561:   border-width: $border;
 5562:   background: $pgbg;
 5563:   color: $fontmenu;
 5564:   border-collapse: collapse;
 5565:   padding: 0;
 5566:   margin: 0;
 5567: }
 5568: 
 5569: ul.LC_breadcrumb_tools_outerlist {
 5570:     margin: 0;
 5571:     padding: 0;
 5572:     position: relative;
 5573:     list-style: none;
 5574: }
 5575: ul.LC_breadcrumb_tools_outerlist li {
 5576:     display: inline;
 5577: }
 5578: 
 5579: .LC_breadcrumb_tools_navigation {
 5580:     padding: 0;
 5581:     margin: 0;
 5582:     float: left;
 5583: }
 5584: .LC_breadcrumb_tools_tools {
 5585:     padding: 0;
 5586:     margin: 0;
 5587:     float: right;
 5588: }
 5589: 
 5590: table#LC_title_bar td {
 5591:   background: $tabbg;
 5592: }
 5593: 
 5594: table#LC_menubuttons img {
 5595:   border: none;
 5596: }
 5597: 
 5598: .LC_breadcrumbs_component {
 5599:   float: right;
 5600:   margin: 0 1em;
 5601: }
 5602: .LC_breadcrumbs_component img {
 5603:   vertical-align: middle;
 5604: }
 5605: 
 5606: td.LC_table_cell_checkbox {
 5607:   text-align: center;
 5608: }
 5609: 
 5610: .LC_fontsize_small {
 5611:   font-size: 70%;
 5612: }
 5613: 
 5614: #LC_breadcrumbs {
 5615:   clear:both;
 5616:   background: $sidebg;
 5617:   border-bottom: 1px solid $lg_border_color;
 5618:   line-height: 2.5em;
 5619:   overflow: hidden;
 5620:   margin: 0;
 5621:   padding: 0;
 5622:   text-align: left;
 5623: }
 5624: 
 5625: .LC_head_subbox, .LC_actionbox {
 5626:   clear:both;
 5627:   background: #F8F8F8; /* $sidebg; */
 5628:   border: 1px solid $sidebg;
 5629:   margin: 0 0 10px 0;
 5630:   padding: 3px;
 5631:   text-align: left;
 5632: }
 5633: 
 5634: .LC_fontsize_medium {
 5635:   font-size: 85%;
 5636: }
 5637: 
 5638: .LC_fontsize_large {
 5639:   font-size: 120%;
 5640: }
 5641: 
 5642: .LC_menubuttons_inline_text {
 5643:   color: $font;
 5644:   font-size: 90%;
 5645:   padding-left:3px;
 5646: }
 5647: 
 5648: .LC_menubuttons_inline_text img{
 5649:   vertical-align: middle;
 5650: }
 5651: 
 5652: li.LC_menubuttons_inline_text img {
 5653:   cursor:pointer;
 5654:   text-decoration: none;
 5655: }
 5656: 
 5657: .LC_menubuttons_link {
 5658:   text-decoration: none;
 5659: }
 5660: 
 5661: .LC_menubuttons_category {
 5662:   color: $font;
 5663:   background: $pgbg;
 5664:   font-size: larger;
 5665:   font-weight: bold;
 5666: }
 5667: 
 5668: td.LC_menubuttons_text {
 5669:   color: $font;
 5670: }
 5671: 
 5672: .LC_current_location {
 5673:   background: $tabbg;
 5674: }
 5675: 
 5676: table.LC_data_table {
 5677:   border: 1px solid #000000;
 5678:   border-collapse: separate;
 5679:   border-spacing: 1px;
 5680:   background: $pgbg;
 5681: }
 5682: 
 5683: .LC_data_table_dense {
 5684:   font-size: small;
 5685: }
 5686: 
 5687: table.LC_nested_outer {
 5688:   border: 1px solid #000000;
 5689:   border-collapse: collapse;
 5690:   border-spacing: 0;
 5691:   width: 100%;
 5692: }
 5693: 
 5694: table.LC_innerpickbox,
 5695: table.LC_nested {
 5696:   border: none;
 5697:   border-collapse: collapse;
 5698:   border-spacing: 0;
 5699:   width: 100%;
 5700: }
 5701: 
 5702: table.LC_data_table tr th,
 5703: table.LC_calendar tr th,
 5704: table.LC_prior_tries tr th,
 5705: table.LC_innerpickbox tr th {
 5706:   font-weight: bold;
 5707:   background-color: $data_table_head;
 5708:   color:$fontmenu;
 5709:   font-size:90%;
 5710: }
 5711: 
 5712: table.LC_innerpickbox tr th,
 5713: table.LC_innerpickbox tr td {
 5714:   vertical-align: top;
 5715: }
 5716: 
 5717: table.LC_data_table tr.LC_info_row > td {
 5718:   background-color: #CCCCCC;
 5719:   font-weight: bold;
 5720:   text-align: left;
 5721: }
 5722: 
 5723: table.LC_data_table tr.LC_odd_row > td {
 5724:   background-color: $data_table_light;
 5725:   padding: 2px;
 5726:   vertical-align: top;
 5727: }
 5728: 
 5729: table.LC_pick_box tr > td.LC_odd_row {
 5730:   background-color: $data_table_light;
 5731:   vertical-align: top;
 5732: }
 5733: 
 5734: table.LC_data_table tr.LC_even_row > td {
 5735:   background-color: $data_table_dark;
 5736:   padding: 2px;
 5737:   vertical-align: top;
 5738: }
 5739: 
 5740: table.LC_pick_box tr > td.LC_even_row {
 5741:   background-color: $data_table_dark;
 5742:   vertical-align: top;
 5743: }
 5744: 
 5745: table.LC_data_table tr.LC_data_table_highlight td {
 5746:   background-color: $data_table_darker;
 5747: }
 5748: 
 5749: table.LC_data_table tr td.LC_leftcol_header {
 5750:   background-color: $data_table_head;
 5751:   font-weight: bold;
 5752: }
 5753: 
 5754: table.LC_data_table tr.LC_empty_row td,
 5755: table.LC_nested tr.LC_empty_row td {
 5756:   font-weight: bold;
 5757:   font-style: italic;
 5758:   text-align: center;
 5759:   padding: 8px;
 5760: }
 5761: 
 5762: table.LC_data_table tr.LC_empty_row td,
 5763: table.LC_data_table tr.LC_footer_row td {
 5764:   background-color: $sidebg;
 5765: }
 5766: 
 5767: table.LC_nested tr.LC_empty_row td {
 5768:   background-color: #FFFFFF;
 5769: }
 5770: 
 5771: table.LC_caption {
 5772: }
 5773: 
 5774: table.LC_nested tr.LC_empty_row td {
 5775:   padding: 4ex
 5776: }
 5777: 
 5778: table.LC_nested_outer tr th {
 5779:   font-weight: bold;
 5780:   color:$fontmenu;
 5781:   background-color: $data_table_head;
 5782:   font-size: small;
 5783:   border-bottom: 1px solid #000000;
 5784: }
 5785: 
 5786: table.LC_nested_outer tr td.LC_subheader {
 5787:   background-color: $data_table_head;
 5788:   font-weight: bold;
 5789:   font-size: small;
 5790:   border-bottom: 1px solid #000000;
 5791:   text-align: right;
 5792: }
 5793: 
 5794: table.LC_nested tr.LC_info_row td {
 5795:   background-color: #CCCCCC;
 5796:   font-weight: bold;
 5797:   font-size: small;
 5798:   text-align: center;
 5799: }
 5800: 
 5801: table.LC_nested tr.LC_info_row td.LC_left_item,
 5802: table.LC_nested_outer tr th.LC_left_item {
 5803:   text-align: left;
 5804: }
 5805: 
 5806: table.LC_nested td {
 5807:   background-color: #FFFFFF;
 5808:   font-size: small;
 5809: }
 5810: 
 5811: table.LC_nested_outer tr th.LC_right_item,
 5812: table.LC_nested tr.LC_info_row td.LC_right_item,
 5813: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5814: table.LC_nested tr td.LC_right_item {
 5815:   text-align: right;
 5816: }
 5817: 
 5818: table.LC_nested tr.LC_odd_row td {
 5819:   background-color: #EEEEEE;
 5820: }
 5821: 
 5822: table.LC_createuser {
 5823: }
 5824: 
 5825: table.LC_createuser tr.LC_section_row td {
 5826:   font-size: small;
 5827: }
 5828: 
 5829: table.LC_createuser tr.LC_info_row td  {
 5830:   background-color: #CCCCCC;
 5831:   font-weight: bold;
 5832:   text-align: center;
 5833: }
 5834: 
 5835: table.LC_calendar {
 5836:   border: 1px solid #000000;
 5837:   border-collapse: collapse;
 5838:   width: 98%;
 5839: }
 5840: 
 5841: table.LC_calendar_pickdate {
 5842:   font-size: xx-small;
 5843: }
 5844: 
 5845: table.LC_calendar tr td {
 5846:   border: 1px solid #000000;
 5847:   vertical-align: top;
 5848:   width: 14%;
 5849: }
 5850: 
 5851: table.LC_calendar tr td.LC_calendar_day_empty {
 5852:   background-color: $data_table_dark;
 5853: }
 5854: 
 5855: table.LC_calendar tr td.LC_calendar_day_current {
 5856:   background-color: $data_table_highlight;
 5857: }
 5858: 
 5859: table.LC_data_table tr td.LC_mail_new {
 5860:   background-color: $mail_new;
 5861: }
 5862: 
 5863: table.LC_data_table tr.LC_mail_new:hover {
 5864:   background-color: $mail_new_hover;
 5865: }
 5866: 
 5867: table.LC_data_table tr td.LC_mail_read {
 5868:   background-color: $mail_read;
 5869: }
 5870: 
 5871: /*
 5872: table.LC_data_table tr.LC_mail_read:hover {
 5873:   background-color: $mail_read_hover;
 5874: }
 5875: */
 5876: 
 5877: table.LC_data_table tr td.LC_mail_replied {
 5878:   background-color: $mail_replied;
 5879: }
 5880: 
 5881: /*
 5882: table.LC_data_table tr.LC_mail_replied:hover {
 5883:   background-color: $mail_replied_hover;
 5884: }
 5885: */
 5886: 
 5887: table.LC_data_table tr td.LC_mail_other {
 5888:   background-color: $mail_other;
 5889: }
 5890: 
 5891: /*
 5892: table.LC_data_table tr.LC_mail_other:hover {
 5893:   background-color: $mail_other_hover;
 5894: }
 5895: */
 5896: 
 5897: table.LC_data_table tr > td.LC_browser_file,
 5898: table.LC_data_table tr > td.LC_browser_file_published {
 5899:   background: #AAEE77;
 5900: }
 5901: 
 5902: table.LC_data_table tr > td.LC_browser_file_locked,
 5903: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5904:   background: #FFAA99;
 5905: }
 5906: 
 5907: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5908:   background: #888888;
 5909: }
 5910: 
 5911: table.LC_data_table tr > td.LC_browser_file_modified,
 5912: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5913:   background: #F8F866;
 5914: }
 5915: 
 5916: table.LC_data_table tr.LC_browser_folder > td {
 5917:   background: #E0E8FF;
 5918: }
 5919: 
 5920: table.LC_data_table tr > td.LC_roles_is {
 5921:   /* background: #77FF77; */
 5922: }
 5923: 
 5924: table.LC_data_table tr > td.LC_roles_future {
 5925:   border-right: 8px solid #FFFF77;
 5926: }
 5927: 
 5928: table.LC_data_table tr > td.LC_roles_will {
 5929:   border-right: 8px solid #FFAA77;
 5930: }
 5931: 
 5932: table.LC_data_table tr > td.LC_roles_expired {
 5933:   border-right: 8px solid #FF7777;
 5934: }
 5935: 
 5936: table.LC_data_table tr > td.LC_roles_will_not {
 5937:   border-right: 8px solid #AAFF77;
 5938: }
 5939: 
 5940: table.LC_data_table tr > td.LC_roles_selected {
 5941:   border-right: 8px solid #11CC55;
 5942: }
 5943: 
 5944: span.LC_current_location {
 5945:   font-size:larger;
 5946:   background: $pgbg;
 5947: }
 5948: 
 5949: span.LC_current_nav_location {
 5950:   font-weight:bold;
 5951:   background: $sidebg;
 5952: }
 5953: 
 5954: span.LC_parm_menu_item {
 5955:   font-size: larger;
 5956: }
 5957: 
 5958: span.LC_parm_scope_all {
 5959:   color: red;
 5960: }
 5961: 
 5962: span.LC_parm_scope_folder {
 5963:   color: green;
 5964: }
 5965: 
 5966: span.LC_parm_scope_resource {
 5967:   color: orange;
 5968: }
 5969: 
 5970: span.LC_parm_part {
 5971:   color: blue;
 5972: }
 5973: 
 5974: span.LC_parm_folder,
 5975: span.LC_parm_symb {
 5976:   font-size: x-small;
 5977:   font-family: $mono;
 5978:   color: #AAAAAA;
 5979: }
 5980: 
 5981: ul.LC_parm_parmlist li {
 5982:   display: inline-block;
 5983:   padding: 0.3em 0.8em;
 5984:   vertical-align: top;
 5985:   width: 150px;
 5986:   border-top:1px solid $lg_border_color;
 5987: }
 5988: 
 5989: td.LC_parm_overview_level_menu,
 5990: td.LC_parm_overview_map_menu,
 5991: td.LC_parm_overview_parm_selectors,
 5992: td.LC_parm_overview_restrictions  {
 5993:   border: 1px solid black;
 5994:   border-collapse: collapse;
 5995: }
 5996: 
 5997: table.LC_parm_overview_restrictions td {
 5998:   border-width: 1px 4px 1px 4px;
 5999:   border-style: solid;
 6000:   border-color: $pgbg;
 6001:   text-align: center;
 6002: }
 6003: 
 6004: table.LC_parm_overview_restrictions th {
 6005:   background: $tabbg;
 6006:   border-width: 1px 4px 1px 4px;
 6007:   border-style: solid;
 6008:   border-color: $pgbg;
 6009: }
 6010: 
 6011: table#LC_helpmenu {
 6012:   border: none;
 6013:   height: 55px;
 6014:   border-spacing: 0;
 6015: }
 6016: 
 6017: table#LC_helpmenu fieldset legend {
 6018:   font-size: larger;
 6019: }
 6020: 
 6021: table#LC_helpmenu_links {
 6022:   width: 100%;
 6023:   border: 1px solid black;
 6024:   background: $pgbg;
 6025:   padding: 0;
 6026:   border-spacing: 1px;
 6027: }
 6028: 
 6029: table#LC_helpmenu_links tr td {
 6030:   padding: 1px;
 6031:   background: $tabbg;
 6032:   text-align: center;
 6033:   font-weight: bold;
 6034: }
 6035: 
 6036: table#LC_helpmenu_links a:link,
 6037: table#LC_helpmenu_links a:visited,
 6038: table#LC_helpmenu_links a:active {
 6039:   text-decoration: none;
 6040:   color: $font;
 6041: }
 6042: 
 6043: table#LC_helpmenu_links a:hover {
 6044:   text-decoration: underline;
 6045:   color: $vlink;
 6046: }
 6047: 
 6048: .LC_chrt_popup_exists {
 6049:   border: 1px solid #339933;
 6050:   margin: -1px;
 6051: }
 6052: 
 6053: .LC_chrt_popup_up {
 6054:   border: 1px solid yellow;
 6055:   margin: -1px;
 6056: }
 6057: 
 6058: .LC_chrt_popup {
 6059:   border: 1px solid #8888FF;
 6060:   background: #CCCCFF;
 6061: }
 6062: 
 6063: table.LC_pick_box {
 6064:   border-collapse: separate;
 6065:   background: white;
 6066:   border: 1px solid black;
 6067:   border-spacing: 1px;
 6068: }
 6069: 
 6070: table.LC_pick_box td.LC_pick_box_title {
 6071:   background: $sidebg;
 6072:   font-weight: bold;
 6073:   text-align: left;
 6074:   vertical-align: top;
 6075:   width: 184px;
 6076:   padding: 8px;
 6077: }
 6078: 
 6079: table.LC_pick_box td.LC_pick_box_value {
 6080:   text-align: left;
 6081:   padding: 8px;
 6082: }
 6083: 
 6084: table.LC_pick_box td.LC_pick_box_select {
 6085:   text-align: left;
 6086:   padding: 8px;
 6087: }
 6088: 
 6089: table.LC_pick_box td.LC_pick_box_separator {
 6090:   padding: 0;
 6091:   height: 1px;
 6092:   background: black;
 6093: }
 6094: 
 6095: table.LC_pick_box td.LC_pick_box_submit {
 6096:   text-align: right;
 6097: }
 6098: 
 6099: table.LC_pick_box td.LC_evenrow_value {
 6100:   text-align: left;
 6101:   padding: 8px;
 6102:   background-color: $data_table_light;
 6103: }
 6104: 
 6105: table.LC_pick_box td.LC_oddrow_value {
 6106:   text-align: left;
 6107:   padding: 8px;
 6108:   background-color: $data_table_light;
 6109: }
 6110: 
 6111: span.LC_helpform_receipt_cat {
 6112:   font-weight: bold;
 6113: }
 6114: 
 6115: table.LC_group_priv_box {
 6116:   background: white;
 6117:   border: 1px solid black;
 6118:   border-spacing: 1px;
 6119: }
 6120: 
 6121: table.LC_group_priv_box td.LC_pick_box_title {
 6122:   background: $tabbg;
 6123:   font-weight: bold;
 6124:   text-align: right;
 6125:   width: 184px;
 6126: }
 6127: 
 6128: table.LC_group_priv_box td.LC_groups_fixed {
 6129:   background: $data_table_light;
 6130:   text-align: center;
 6131: }
 6132: 
 6133: table.LC_group_priv_box td.LC_groups_optional {
 6134:   background: $data_table_dark;
 6135:   text-align: center;
 6136: }
 6137: 
 6138: table.LC_group_priv_box td.LC_groups_functionality {
 6139:   background: $data_table_darker;
 6140:   text-align: center;
 6141:   font-weight: bold;
 6142: }
 6143: 
 6144: table.LC_group_priv td {
 6145:   text-align: left;
 6146:   padding: 0;
 6147: }
 6148: 
 6149: .LC_navbuttons {
 6150:   margin: 2ex 0ex 2ex 0ex;
 6151: }
 6152: 
 6153: .LC_topic_bar {
 6154:   font-weight: bold;
 6155:   background: $tabbg;
 6156:   margin: 1em 0em 1em 2em;
 6157:   padding: 3px;
 6158:   font-size: 1.2em;
 6159: }
 6160: 
 6161: .LC_topic_bar span {
 6162:   left: 0.5em;
 6163:   position: absolute;
 6164:   vertical-align: middle;
 6165:   font-size: 1.2em;
 6166: }
 6167: 
 6168: table.LC_course_group_status {
 6169:   margin: 20px;
 6170: }
 6171: 
 6172: table.LC_status_selector td {
 6173:   vertical-align: top;
 6174:   text-align: center;
 6175:   padding: 4px;
 6176: }
 6177: 
 6178: div.LC_feedback_link {
 6179:   clear: both;
 6180:   background: $sidebg;
 6181:   width: 100%;
 6182:   padding-bottom: 10px;
 6183:   border: 1px $tabbg solid;
 6184:   height: 22px;
 6185:   line-height: 22px;
 6186:   padding-top: 5px;
 6187: }
 6188: 
 6189: div.LC_feedback_link img {
 6190:   height: 22px;
 6191:   vertical-align:middle;
 6192: }
 6193: 
 6194: div.LC_feedback_link a {
 6195:   text-decoration: none;
 6196: }
 6197: 
 6198: div.LC_comblock {
 6199:   display:inline;
 6200:   color:$font;
 6201:   font-size:90%;
 6202: }
 6203: 
 6204: div.LC_feedback_link div.LC_comblock {
 6205:   padding-left:5px;
 6206: }
 6207: 
 6208: div.LC_feedback_link div.LC_comblock a {
 6209:   color:$font;
 6210: }
 6211: 
 6212: span.LC_feedback_link {
 6213:   /* background: $feedback_link_bg; */
 6214:   font-size: larger;
 6215: }
 6216: 
 6217: span.LC_message_link {
 6218:   /* background: $feedback_link_bg; */
 6219:   font-size: larger;
 6220:   position: absolute;
 6221:   right: 1em;
 6222: }
 6223: 
 6224: table.LC_prior_tries {
 6225:   border: 1px solid #000000;
 6226:   border-collapse: separate;
 6227:   border-spacing: 1px;
 6228: }
 6229: 
 6230: table.LC_prior_tries td {
 6231:   padding: 2px;
 6232: }
 6233: 
 6234: .LC_answer_correct {
 6235:   background: lightgreen;
 6236:   color: darkgreen;
 6237:   padding: 6px;
 6238: }
 6239: 
 6240: .LC_answer_charged_try {
 6241:   background: #FFAAAA;
 6242:   color: darkred;
 6243:   padding: 6px;
 6244: }
 6245: 
 6246: .LC_answer_not_charged_try,
 6247: .LC_answer_no_grade,
 6248: .LC_answer_late {
 6249:   background: lightyellow;
 6250:   color: black;
 6251:   padding: 6px;
 6252: }
 6253: 
 6254: .LC_answer_previous {
 6255:   background: lightblue;
 6256:   color: darkblue;
 6257:   padding: 6px;
 6258: }
 6259: 
 6260: .LC_answer_no_message {
 6261:   background: #FFFFFF;
 6262:   color: black;
 6263:   padding: 6px;
 6264: }
 6265: 
 6266: .LC_answer_unknown {
 6267:   background: orange;
 6268:   color: black;
 6269:   padding: 6px;
 6270: }
 6271: 
 6272: span.LC_prior_numerical,
 6273: span.LC_prior_string,
 6274: span.LC_prior_custom,
 6275: span.LC_prior_reaction,
 6276: span.LC_prior_math {
 6277:   font-family: $mono;
 6278:   white-space: pre;
 6279: }
 6280: 
 6281: span.LC_prior_string {
 6282:   font-family: $mono;
 6283:   white-space: pre;
 6284: }
 6285: 
 6286: table.LC_prior_option {
 6287:   width: 100%;
 6288:   border-collapse: collapse;
 6289: }
 6290: 
 6291: table.LC_prior_rank,
 6292: table.LC_prior_match {
 6293:   border-collapse: collapse;
 6294: }
 6295: 
 6296: table.LC_prior_option tr td,
 6297: table.LC_prior_rank tr td,
 6298: table.LC_prior_match tr td {
 6299:   border: 1px solid #000000;
 6300: }
 6301: 
 6302: .LC_nobreak {
 6303:   white-space: nowrap;
 6304: }
 6305: 
 6306: span.LC_cusr_emph {
 6307:   font-style: italic;
 6308: }
 6309: 
 6310: span.LC_cusr_subheading {
 6311:   font-weight: normal;
 6312:   font-size: 85%;
 6313: }
 6314: 
 6315: div.LC_docs_entry_move {
 6316:   border: 1px solid #BBBBBB;
 6317:   background: #DDDDDD;
 6318:   width: 22px;
 6319:   padding: 1px;
 6320:   margin: 0;
 6321: }
 6322: 
 6323: table.LC_data_table tr > td.LC_docs_entry_commands,
 6324: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6325:   font-size: x-small;
 6326: }
 6327: 
 6328: .LC_docs_entry_parameter {
 6329:   white-space: nowrap;
 6330: }
 6331: 
 6332: .LC_docs_copy {
 6333:   color: #000099;
 6334: }
 6335: 
 6336: .LC_docs_cut {
 6337:   color: #550044;
 6338: }
 6339: 
 6340: .LC_docs_rename {
 6341:   color: #009900;
 6342: }
 6343: 
 6344: .LC_docs_remove {
 6345:   color: #990000;
 6346: }
 6347: 
 6348: .LC_docs_reinit_warn,
 6349: .LC_docs_ext_edit {
 6350:   font-size: x-small;
 6351: }
 6352: 
 6353: table.LC_docs_adddocs td,
 6354: table.LC_docs_adddocs th {
 6355:   border: 1px solid #BBBBBB;
 6356:   padding: 4px;
 6357:   background: #DDDDDD;
 6358: }
 6359: 
 6360: table.LC_sty_begin {
 6361:   background: #BBFFBB;
 6362: }
 6363: 
 6364: table.LC_sty_end {
 6365:   background: #FFBBBB;
 6366: }
 6367: 
 6368: table.LC_double_column {
 6369:   border-width: 0;
 6370:   border-collapse: collapse;
 6371:   width: 100%;
 6372:   padding: 2px;
 6373: }
 6374: 
 6375: table.LC_double_column tr td.LC_left_col {
 6376:   top: 2px;
 6377:   left: 2px;
 6378:   width: 47%;
 6379:   vertical-align: top;
 6380: }
 6381: 
 6382: table.LC_double_column tr td.LC_right_col {
 6383:   top: 2px;
 6384:   right: 2px;
 6385:   width: 47%;
 6386:   vertical-align: top;
 6387: }
 6388: 
 6389: div.LC_left_float {
 6390:   float: left;
 6391:   padding-right: 5%;
 6392:   padding-bottom: 4px;
 6393: }
 6394: 
 6395: div.LC_clear_float_header {
 6396:   padding-bottom: 2px;
 6397: }
 6398: 
 6399: div.LC_clear_float_footer {
 6400:   padding-top: 10px;
 6401:   clear: both;
 6402: }
 6403: 
 6404: div.LC_grade_show_user {
 6405: /*  border-left: 5px solid $sidebg; */
 6406:   border-top: 5px solid #000000;
 6407:   margin: 50px 0 0 0;
 6408:   padding: 15px 0 5px 10px;
 6409: }
 6410: 
 6411: div.LC_grade_show_user_odd_row {
 6412: /*  border-left: 5px solid #000000; */
 6413: }
 6414: 
 6415: div.LC_grade_show_user div.LC_Box {
 6416:   margin-right: 50px;
 6417: }
 6418: 
 6419: div.LC_grade_submissions,
 6420: div.LC_grade_message_center,
 6421: div.LC_grade_info_links {
 6422:   margin: 5px;
 6423:   width: 99%;
 6424:   background: #FFFFFF;
 6425: }
 6426: 
 6427: div.LC_grade_submissions_header,
 6428: div.LC_grade_message_center_header {
 6429:   font-weight: bold;
 6430:   font-size: large;
 6431: }
 6432: 
 6433: div.LC_grade_submissions_body,
 6434: div.LC_grade_message_center_body {
 6435:   border: 1px solid black;
 6436:   width: 99%;
 6437:   background: #FFFFFF;
 6438: }
 6439: 
 6440: table.LC_scantron_action {
 6441:   width: 100%;
 6442: }
 6443: 
 6444: table.LC_scantron_action tr th {
 6445:   font-weight:bold;
 6446:   font-style:normal;
 6447: }
 6448: 
 6449: .LC_edit_problem_header,
 6450: div.LC_edit_problem_footer {
 6451:   font-weight: normal;
 6452:   font-size:  medium;
 6453:   margin: 2px;
 6454:   background-color: $sidebg;
 6455: }
 6456: 
 6457: div.LC_edit_problem_header,
 6458: div.LC_edit_problem_header div,
 6459: div.LC_edit_problem_footer,
 6460: div.LC_edit_problem_footer div,
 6461: div.LC_edit_problem_editxml_header,
 6462: div.LC_edit_problem_editxml_header div {
 6463:   margin-top: 5px;
 6464: }
 6465: 
 6466: div.LC_edit_problem_header_title {
 6467:   font-weight: bold;
 6468:   font-size: larger;
 6469:   background: $tabbg;
 6470:   padding: 3px;
 6471:   margin: 0 0 5px 0;
 6472: }
 6473: 
 6474: table.LC_edit_problem_header_title {
 6475:   width: 100%;
 6476:   background: $tabbg;
 6477: }
 6478: 
 6479: div.LC_edit_problem_discards {
 6480:   float: left;
 6481:   padding-bottom: 5px;
 6482: }
 6483: 
 6484: div.LC_edit_problem_saves {
 6485:   float: right;
 6486:   padding-bottom: 5px;
 6487: }
 6488: 
 6489: .LC_edit_opt {
 6490:   padding-left: 1em;
 6491:   white-space: nowrap;
 6492: }
 6493: 
 6494: .LC_edit_problem_latexhelper{
 6495:     text-align: right;
 6496: }
 6497: 
 6498: #LC_edit_problem_colorful div{
 6499:     margin-left: 40px;
 6500: }
 6501: 
 6502: img.stift {
 6503:   border-width: 0;
 6504:   vertical-align: middle;
 6505: }
 6506: 
 6507: table td.LC_mainmenu_col_fieldset {
 6508:   vertical-align: top;
 6509: }
 6510: 
 6511: div.LC_createcourse {
 6512:   margin: 10px 10px 10px 10px;
 6513: }
 6514: 
 6515: .LC_dccid {
 6516:   float: right;
 6517:   margin: 0.2em 0 0 0;
 6518:   padding: 0;
 6519:   font-size: 90%;
 6520:   display:none;
 6521: }
 6522: 
 6523: ol.LC_primary_menu a:hover,
 6524: ol#LC_MenuBreadcrumbs a:hover,
 6525: ol#LC_PathBreadcrumbs a:hover,
 6526: ul#LC_secondary_menu a:hover,
 6527: .LC_FormSectionClearButton input:hover
 6528: ul.LC_TabContent   li:hover a {
 6529:   color:$button_hover;
 6530:   text-decoration:none;
 6531: }
 6532: 
 6533: h1 {
 6534:   padding: 0;
 6535:   line-height:130%;
 6536: }
 6537: 
 6538: h2,
 6539: h3,
 6540: h4,
 6541: h5,
 6542: h6 {
 6543:   margin: 5px 0 5px 0;
 6544:   padding: 0;
 6545:   line-height:130%;
 6546: }
 6547: 
 6548: .LC_hcell {
 6549:   padding:3px 15px 3px 15px;
 6550:   margin: 0;
 6551:   background-color:$tabbg;
 6552:   color:$fontmenu;
 6553:   border-bottom:solid 1px $lg_border_color;
 6554: }
 6555: 
 6556: .LC_Box > .LC_hcell {
 6557:   margin: 0 -10px 10px -10px;
 6558: }
 6559: 
 6560: .LC_noBorder {
 6561:   border: 0;
 6562: }
 6563: 
 6564: .LC_FormSectionClearButton input {
 6565:   background-color:transparent;
 6566:   border: none;
 6567:   cursor:pointer;
 6568:   text-decoration:underline;
 6569: }
 6570: 
 6571: .LC_help_open_topic {
 6572:   color: #FFFFFF;
 6573:   background-color: #EEEEFF;
 6574:   margin: 1px;
 6575:   padding: 4px;
 6576:   border: 1px solid #000033;
 6577:   white-space: nowrap;
 6578:   /* vertical-align: middle; */
 6579: }
 6580: 
 6581: dl,
 6582: ul,
 6583: div,
 6584: fieldset {
 6585:   margin: 10px 10px 10px 0;
 6586:   /* overflow: hidden; */
 6587: }
 6588: 
 6589: fieldset > legend {
 6590:   font-weight: bold;
 6591:   padding: 0 5px 0 5px;
 6592: }
 6593: 
 6594: #LC_nav_bar {
 6595:   float: left;
 6596:   background-color: $pgbg_or_bgcolor;
 6597:   margin: 0 0 2px 0;
 6598: }
 6599: 
 6600: #LC_realm {
 6601:   margin: 0.2em 0 0 0;
 6602:   padding: 0;
 6603:   font-weight: bold;
 6604:   text-align: center;
 6605:   background-color: $pgbg_or_bgcolor;
 6606: }
 6607: 
 6608: #LC_nav_bar em {
 6609:   font-weight: bold;
 6610:   font-style: normal;
 6611: }
 6612: 
 6613: ol.LC_primary_menu {
 6614:   margin: 0;
 6615:   padding: 0;
 6616:   background-color: $pgbg_or_bgcolor;
 6617: }
 6618: 
 6619: ol#LC_PathBreadcrumbs {
 6620:   margin: 0;
 6621: }
 6622: 
 6623: ol.LC_primary_menu li {
 6624:   color: RGB(80, 80, 80);
 6625:   vertical-align: middle;
 6626:   text-align: left;
 6627:   list-style: none;
 6628:   float: left;
 6629: }
 6630: 
 6631: ol.LC_primary_menu li a {
 6632:   display: block;
 6633:   margin: 0;
 6634:   padding: 0 5px 0 10px;
 6635:   text-decoration: none;
 6636: }
 6637: 
 6638: ol.LC_primary_menu li ul {
 6639:   display: none;
 6640:   width: 10em;
 6641:   background-color: $data_table_light;
 6642: }
 6643: 
 6644: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6645:   display: block;
 6646:   position: absolute;
 6647:   margin: 0;
 6648:   padding: 0;
 6649:   z-index: 2;
 6650: }
 6651: 
 6652: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6653:   font-size: 90%;
 6654:   vertical-align: top;
 6655:   float: none;
 6656:   border-left: 1px solid black;
 6657:   border-right: 1px solid black;
 6658: }
 6659: 
 6660: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6661:   background-color:$data_table_light;
 6662: }
 6663: 
 6664: ol.LC_primary_menu li li a:hover {
 6665:    color:$button_hover;
 6666:    background-color:$data_table_dark;
 6667: }
 6668: 
 6669: ol.LC_primary_menu li img {
 6670:   vertical-align: bottom;
 6671:   height: 1.1em;
 6672:   margin: 0.2em 0 0 0;
 6673: }
 6674: 
 6675: ol.LC_primary_menu a {
 6676:   color: RGB(80, 80, 80);
 6677:   text-decoration: none;
 6678: }
 6679: 
 6680: ol.LC_primary_menu a.LC_new_message {
 6681:   font-weight:bold;
 6682:   color: darkred;
 6683: }
 6684: 
 6685: ol.LC_docs_parameters {
 6686:   margin-left: 0;
 6687:   padding: 0;
 6688:   list-style: none;
 6689: }
 6690: 
 6691: ol.LC_docs_parameters li {
 6692:   margin: 0;
 6693:   padding-right: 20px;
 6694:   display: inline;
 6695: }
 6696: 
 6697: ol.LC_docs_parameters li:before {
 6698:   content: "\\002022 \\0020";
 6699: }
 6700: 
 6701: li.LC_docs_parameters_title {
 6702:   font-weight: bold;
 6703: }
 6704: 
 6705: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6706:   content: "";
 6707: }
 6708: 
 6709: ul#LC_secondary_menu {
 6710:   clear: right;
 6711:   color: $fontmenu;
 6712:   background: $tabbg;
 6713:   list-style: none;
 6714:   padding: 0;
 6715:   margin: 0;
 6716:   width: 100%;
 6717:   text-align: left;
 6718:   float: left;
 6719: }
 6720: 
 6721: ul#LC_secondary_menu li {
 6722:   font-weight: bold;
 6723:   line-height: 1.8em;
 6724:   border-right: 1px solid black;
 6725:   vertical-align: middle;
 6726:   float: left;
 6727: }
 6728: 
 6729: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6730:   background-color: $data_table_light;
 6731: }
 6732: 
 6733: ul#LC_secondary_menu li a {
 6734:   padding: 0 0.8em;
 6735: }
 6736: 
 6737: ul#LC_secondary_menu li ul {
 6738:   display: none;
 6739: }
 6740: 
 6741: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6742:   display: block;
 6743:   position: absolute;
 6744:   margin: 0;
 6745:   padding: 0;
 6746:   list-style:none;
 6747:   float: none;
 6748:   background-color: $data_table_light;
 6749:   z-index: 2;
 6750:   margin-left: -1px;
 6751: }
 6752: 
 6753: ul#LC_secondary_menu li ul li {
 6754:   font-size: 90%;
 6755:   vertical-align: top;
 6756:   border-left: 1px solid black;
 6757:   border-right: 1px solid black;
 6758:   background-color: $data_table_light;
 6759:   list-style:none;
 6760:   float: none;
 6761: }
 6762: 
 6763: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6764:   background-color: $data_table_dark;
 6765: }
 6766: 
 6767: ul.LC_TabContent {
 6768:   display:block;
 6769:   background: $sidebg;
 6770:   border-bottom: solid 1px $lg_border_color;
 6771:   list-style:none;
 6772:   margin: -1px -10px 0 -10px;
 6773:   padding: 0;
 6774: }
 6775: 
 6776: ul.LC_TabContent li,
 6777: ul.LC_TabContentBigger li {
 6778:   float:left;
 6779: }
 6780: 
 6781: ul#LC_secondary_menu li a {
 6782:   color: $fontmenu;
 6783:   text-decoration: none;
 6784: }
 6785: 
 6786: ul.LC_TabContent {
 6787:   min-height:20px;
 6788: }
 6789: 
 6790: ul.LC_TabContent li {
 6791:   vertical-align:middle;
 6792:   padding: 0 16px 0 10px;
 6793:   background-color:$tabbg;
 6794:   border-bottom:solid 1px $lg_border_color;
 6795:   border-left: solid 1px $font;
 6796: }
 6797: 
 6798: ul.LC_TabContent .right {
 6799:   float:right;
 6800: }
 6801: 
 6802: ul.LC_TabContent li a,
 6803: ul.LC_TabContent li {
 6804:   color:rgb(47,47,47);
 6805:   text-decoration:none;
 6806:   font-size:95%;
 6807:   font-weight:bold;
 6808:   min-height:20px;
 6809: }
 6810: 
 6811: ul.LC_TabContent li a:hover,
 6812: ul.LC_TabContent li a:focus {
 6813:   color: $button_hover;
 6814:   background:none;
 6815:   outline:none;
 6816: }
 6817: 
 6818: ul.LC_TabContent li:hover {
 6819:   color: $button_hover;
 6820:   cursor:pointer;
 6821: }
 6822: 
 6823: ul.LC_TabContent li.active {
 6824:   color: $font;
 6825:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6826:   border-bottom:solid 1px #FFFFFF;
 6827:   cursor: default;
 6828: }
 6829: 
 6830: ul.LC_TabContent li.active a {
 6831:   color:$font;
 6832:   background:#FFFFFF;
 6833:   outline: none;
 6834: }
 6835: 
 6836: ul.LC_TabContent li.goback {
 6837:   float: left;
 6838:   border-left: none;
 6839: }
 6840: 
 6841: #maincoursedoc {
 6842:   clear:both;
 6843: }
 6844: 
 6845: ul.LC_TabContentBigger {
 6846:   display:block;
 6847:   list-style:none;
 6848:   padding: 0;
 6849: }
 6850: 
 6851: ul.LC_TabContentBigger li {
 6852:   vertical-align:bottom;
 6853:   height: 30px;
 6854:   font-size:110%;
 6855:   font-weight:bold;
 6856:   color: #737373;
 6857: }
 6858: 
 6859: ul.LC_TabContentBigger li.active {
 6860:   position: relative;
 6861:   top: 1px;
 6862: }
 6863: 
 6864: ul.LC_TabContentBigger li a {
 6865:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6866:   height: 30px;
 6867:   line-height: 30px;
 6868:   text-align: center;
 6869:   display: block;
 6870:   text-decoration: none;
 6871:   outline: none;  
 6872: }
 6873: 
 6874: ul.LC_TabContentBigger li.active a {
 6875:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6876:   color:$font;
 6877: }
 6878: 
 6879: ul.LC_TabContentBigger li b {
 6880:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6881:   display: block;
 6882:   float: left;
 6883:   padding: 0 30px;
 6884:   border-bottom: 1px solid $lg_border_color;
 6885: }
 6886: 
 6887: ul.LC_TabContentBigger li:hover b {
 6888:   color:$button_hover;
 6889: }
 6890: 
 6891: ul.LC_TabContentBigger li.active b {
 6892:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6893:   color:$font;
 6894:   border: 0;
 6895: }
 6896: 
 6897: 
 6898: ul.LC_CourseBreadcrumbs {
 6899:   background: $sidebg;
 6900:   height: 2em;
 6901:   padding-left: 10px;
 6902:   margin: 0;
 6903:   list-style-position: inside;
 6904: }
 6905: 
 6906: ol#LC_MenuBreadcrumbs,
 6907: ol#LC_PathBreadcrumbs {
 6908:   padding-left: 10px;
 6909:   margin: 0;
 6910:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6911: }
 6912: 
 6913: ol#LC_MenuBreadcrumbs li,
 6914: ol#LC_PathBreadcrumbs li,
 6915: ul.LC_CourseBreadcrumbs li {
 6916:   display: inline;
 6917:   white-space: normal;  
 6918: }
 6919: 
 6920: ol#LC_MenuBreadcrumbs li a,
 6921: ul.LC_CourseBreadcrumbs li a {
 6922:   text-decoration: none;
 6923:   font-size:90%;
 6924: }
 6925: 
 6926: ol#LC_MenuBreadcrumbs h1 {
 6927:   display: inline;
 6928:   font-size: 90%;
 6929:   line-height: 2.5em;
 6930:   margin: 0;
 6931:   padding: 0;
 6932: }
 6933: 
 6934: ol#LC_PathBreadcrumbs li a {
 6935:   text-decoration:none;
 6936:   font-size:100%;
 6937:   font-weight:bold;
 6938: }
 6939: 
 6940: .LC_Box {
 6941:   border: solid 1px $lg_border_color;
 6942:   padding: 0 10px 10px 10px;
 6943: }
 6944: 
 6945: .LC_DocsBox {
 6946:   border: solid 1px $lg_border_color;
 6947:   padding: 0 0 10px 10px;
 6948: }
 6949: 
 6950: .LC_AboutMe_Image {
 6951:   float:left;
 6952:   margin-right:10px;
 6953: }
 6954: 
 6955: .LC_Clear_AboutMe_Image {
 6956:   clear:left;
 6957: }
 6958: 
 6959: dl.LC_ListStyleClean dt {
 6960:   padding-right: 5px;
 6961:   display: table-header-group;
 6962: }
 6963: 
 6964: dl.LC_ListStyleClean dd {
 6965:   display: table-row;
 6966: }
 6967: 
 6968: .LC_ListStyleClean,
 6969: .LC_ListStyleSimple,
 6970: .LC_ListStyleNormal,
 6971: .LC_ListStyleSpecial {
 6972:   /* display:block; */
 6973:   list-style-position: inside;
 6974:   list-style-type: none;
 6975:   overflow: hidden;
 6976:   padding: 0;
 6977: }
 6978: 
 6979: .LC_ListStyleSimple li,
 6980: .LC_ListStyleSimple dd,
 6981: .LC_ListStyleNormal li,
 6982: .LC_ListStyleNormal dd,
 6983: .LC_ListStyleSpecial li,
 6984: .LC_ListStyleSpecial dd {
 6985:   margin: 0;
 6986:   padding: 5px 5px 5px 10px;
 6987:   clear: both;
 6988: }
 6989: 
 6990: .LC_ListStyleClean li,
 6991: .LC_ListStyleClean dd {
 6992:   padding-top: 0;
 6993:   padding-bottom: 0;
 6994: }
 6995: 
 6996: .LC_ListStyleSimple dd,
 6997: .LC_ListStyleSimple li {
 6998:   border-bottom: solid 1px $lg_border_color;
 6999: }
 7000: 
 7001: .LC_ListStyleSpecial li,
 7002: .LC_ListStyleSpecial dd {
 7003:   list-style-type: none;
 7004:   background-color: RGB(220, 220, 220);
 7005:   margin-bottom: 4px;
 7006: }
 7007: 
 7008: table.LC_SimpleTable {
 7009:   margin:5px;
 7010:   border:solid 1px $lg_border_color;
 7011: }
 7012: 
 7013: table.LC_SimpleTable tr {
 7014:   padding: 0;
 7015:   border:solid 1px $lg_border_color;
 7016: }
 7017: 
 7018: table.LC_SimpleTable thead {
 7019:   background:rgb(220,220,220);
 7020: }
 7021: 
 7022: div.LC_columnSection {
 7023:   display: block;
 7024:   clear: both;
 7025:   overflow: hidden;
 7026:   margin: 0;
 7027: }
 7028: 
 7029: div.LC_columnSection>* {
 7030:   float: left;
 7031:   margin: 10px 20px 10px 0;
 7032:   overflow:hidden;
 7033: }
 7034: 
 7035: table em {
 7036:   font-weight: bold;
 7037:   font-style: normal;
 7038: }
 7039: 
 7040: table.LC_tableBrowseRes,
 7041: table.LC_tableOfContent {
 7042:   border:none;
 7043:   border-spacing: 1px;
 7044:   padding: 3px;
 7045:   background-color: #FFFFFF;
 7046:   font-size: 90%;
 7047: }
 7048: 
 7049: table.LC_tableOfContent {
 7050:   border-collapse: collapse;
 7051: }
 7052: 
 7053: table.LC_tableBrowseRes a,
 7054: table.LC_tableOfContent a {
 7055:   background-color: transparent;
 7056:   text-decoration: none;
 7057: }
 7058: 
 7059: table.LC_tableOfContent img {
 7060:   border: none;
 7061:   height: 1.3em;
 7062:   vertical-align: text-bottom;
 7063:   margin-right: 0.3em;
 7064: }
 7065: 
 7066: a#LC_content_toolbar_firsthomework {
 7067:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7068: }
 7069: 
 7070: a#LC_content_toolbar_everything {
 7071:   background-image:url(/res/adm/pages/show-all.gif);
 7072: }
 7073: 
 7074: a#LC_content_toolbar_uncompleted {
 7075:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7076: }
 7077: 
 7078: #LC_content_toolbar_clearbubbles {
 7079:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7080: }
 7081: 
 7082: a#LC_content_toolbar_changefolder {
 7083:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7084: }
 7085: 
 7086: a#LC_content_toolbar_changefolder_toggled {
 7087:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7088: }
 7089: 
 7090: a#LC_content_toolbar_edittoplevel {
 7091:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7092: }
 7093: 
 7094: ul#LC_toolbar li a:hover {
 7095:   background-position: bottom center;
 7096: }
 7097: 
 7098: ul#LC_toolbar {
 7099:   padding: 0;
 7100:   margin: 2px;
 7101:   list-style:none;
 7102:   position:relative;
 7103:   background-color:white;
 7104:   overflow: auto;
 7105: }
 7106: 
 7107: ul#LC_toolbar li {
 7108:   border:1px solid white;
 7109:   padding: 0;
 7110:   margin: 0;
 7111:   float: left;
 7112:   display:inline;
 7113:   vertical-align:middle;
 7114:   white-space: nowrap;
 7115: }
 7116: 
 7117: 
 7118: a.LC_toolbarItem {
 7119:   display:block;
 7120:   padding: 0;
 7121:   margin: 0;
 7122:   height: 32px;
 7123:   width: 32px;
 7124:   color:white;
 7125:   border: none;
 7126:   background-repeat:no-repeat;
 7127:   background-color:transparent;
 7128: }
 7129: 
 7130: ul.LC_funclist {
 7131:     margin: 0;
 7132:     padding: 0.5em 1em 0.5em 0;
 7133: }
 7134: 
 7135: ul.LC_funclist > li:first-child {
 7136:     font-weight:bold; 
 7137:     margin-left:0.8em;
 7138: }
 7139: 
 7140: ul.LC_funclist + ul.LC_funclist {
 7141:     /* 
 7142:        left border as a seperator if we have more than
 7143:        one list 
 7144:     */
 7145:     border-left: 1px solid $sidebg;
 7146:     /* 
 7147:        this hides the left border behind the border of the 
 7148:        outer box if element is wrapped to the next 'line' 
 7149:     */
 7150:     margin-left: -1px;
 7151: }
 7152: 
 7153: ul.LC_funclist li {
 7154:   display: inline;
 7155:   white-space: nowrap;
 7156:   margin: 0 0 0 25px;
 7157:   line-height: 150%;
 7158: }
 7159: 
 7160: .LC_hidden {
 7161:   display: none;
 7162: }
 7163: 
 7164: .LCmodal-overlay {
 7165: 		position:fixed;
 7166: 		top:0;
 7167: 		right:0;
 7168: 		bottom:0;
 7169: 		left:0;
 7170: 		height:100%;
 7171: 		width:100%;
 7172: 		margin:0;
 7173: 		padding:0;
 7174: 		background:#999;
 7175: 		opacity:.75;
 7176: 		filter: alpha(opacity=75);
 7177: 		-moz-opacity: 0.75;
 7178: 		z-index:101;
 7179: }
 7180: 
 7181: * html .LCmodal-overlay {   
 7182: 		position: absolute;
 7183: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7184: }
 7185: 
 7186: .LCmodal-window {
 7187: 		position:fixed;
 7188: 		top:50%;
 7189: 		left:50%;
 7190: 		margin:0;
 7191: 		padding:0;
 7192: 		z-index:102;
 7193: 	}
 7194: 
 7195: * html .LCmodal-window {
 7196: 		position:absolute;
 7197: }
 7198: 
 7199: .LCclose-window {
 7200: 		position:absolute;
 7201: 		width:32px;
 7202: 		height:32px;
 7203: 		right:8px;
 7204: 		top:8px;
 7205: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7206: 		text-indent:-99999px;
 7207: 		overflow:hidden;
 7208: 		cursor:pointer;
 7209: }
 7210: 
 7211: /*
 7212:   styles used by TTH when "Default set of options to pass to tth/m
 7213:   when converting TeX" in course settings has been set
 7214: 
 7215:   option passed: -t
 7216: 
 7217: */
 7218: 
 7219: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7220: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7221: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7222: td div.norm {line-height:normal;}
 7223: 
 7224: /*
 7225:   option passed -y3
 7226: */
 7227: 
 7228: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7229: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7230: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7231: 
 7232: END
 7233: }
 7234: 
 7235: =pod
 7236: 
 7237: =item * &headtag()
 7238: 
 7239: Returns a uniform footer for LON-CAPA web pages.
 7240: 
 7241: Inputs: $title - optional title for the head
 7242:         $head_extra - optional extra HTML to put inside the <head>
 7243:         $args - optional arguments
 7244:             force_register - if is true call registerurl so the remote is 
 7245:                              informed
 7246:             redirect       -> array ref of
 7247:                                    1- seconds before redirect occurs
 7248:                                    2- url to redirect to
 7249:                                    3- whether the side effect should occur
 7250:                            (side effect of setting 
 7251:                                $env{'internal.head.redirect'} to the url 
 7252:                                redirected too)
 7253:             domain         -> force to color decorate a page for a specific
 7254:                                domain
 7255:             function       -> force usage of a specific rolish color scheme
 7256:             bgcolor        -> override the default page bgcolor
 7257:             no_auto_mt_title
 7258:                            -> prevent &mt()ing the title arg
 7259: 
 7260: =cut
 7261: 
 7262: sub headtag {
 7263:     my ($title,$head_extra,$args) = @_;
 7264:     
 7265:     my $function = $args->{'function'} || &get_users_function();
 7266:     my $domain   = $args->{'domain'}   || &determinedomain();
 7267:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7268:     my $httphost = $args->{'use_absolute'};
 7269:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7270: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7271: 		   #time(),
 7272: 		   $env{'environment.color.timestamp'},
 7273: 		   $function,$domain,$bgcolor);
 7274: 
 7275:     $url = '/adm/css/'.&escape($url).'.css';
 7276: 
 7277:     my $result =
 7278: 	'<head>'.
 7279: 	&font_settings($args);
 7280: 
 7281:     my $inhibitprint = &print_suppression();
 7282: 
 7283:     if (!$args->{'frameset'}) {
 7284: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7285:     }
 7286:     if ($args->{'force_register'}) {
 7287:         $result .= &Apache::lonmenu::registerurl(1);
 7288:     }
 7289:     if (!$args->{'no_nav_bar'} 
 7290: 	&& !$args->{'only_body'}
 7291: 	&& !$args->{'frameset'}) {
 7292: 	$result .= &help_menu_js($httphost);
 7293:         $result.=&modal_window();
 7294:         $result.=&togglebox_script();
 7295:         $result.=&wishlist_window();
 7296:         $result.=&LCprogressbarUpdate_script();
 7297:     } else {
 7298:         if ($args->{'add_modal'}) {
 7299:            $result.=&modal_window();
 7300:         }
 7301:         if ($args->{'add_wishlist'}) {
 7302:            $result.=&wishlist_window();
 7303:         }
 7304:         if ($args->{'add_togglebox'}) {
 7305:            $result.=&togglebox_script();
 7306:         }
 7307:         if ($args->{'add_progressbar'}) {
 7308:            $result.=&LCprogressbarUpdate_script();
 7309:         }
 7310:     }
 7311:     if (ref($args->{'redirect'})) {
 7312: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7313: 	$url = &Apache::lonenc::check_encrypt($url);
 7314: 	if (!$inhibit_continue) {
 7315: 	    $env{'internal.head.redirect'} = $url;
 7316: 	}
 7317: 	$result.=<<ADDMETA
 7318: <meta http-equiv="pragma" content="no-cache" />
 7319: <meta http-equiv="Refresh" content="$time; url=$url" />
 7320: ADDMETA
 7321:     }
 7322:     if (!defined($title)) {
 7323: 	$title = 'The LearningOnline Network with CAPA';
 7324:     }
 7325:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7326:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7327: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7328:         .$inhibitprint
 7329: 	.$head_extra;
 7330:     if ($env{'browser.mobile'}) {
 7331:         $result .= '
 7332: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7333: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7334:     }
 7335:     return $result.'</head>';
 7336: }
 7337: 
 7338: =pod
 7339: 
 7340: =item * &font_settings()
 7341: 
 7342: Returns neccessary <meta> to set the proper encoding
 7343: 
 7344: Inputs: optional reference to HASH -- $args passed to &headtag()
 7345: 
 7346: =cut
 7347: 
 7348: sub font_settings {
 7349:     my ($args) = @_;
 7350:     my $headerstring='';
 7351:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7352:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7353: 	$headerstring.=
 7354: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n";
 7355:     }
 7356:     return $headerstring;
 7357: }
 7358: 
 7359: =pod
 7360: 
 7361: =item * &print_suppression()
 7362: 
 7363: In course context returns css which causes the body to be blank when media="print",
 7364: if printout generation is unavailable for the current resource.
 7365: 
 7366: This could be because:
 7367: 
 7368: (a) printstartdate is in the future
 7369: 
 7370: (b) printenddate is in the past
 7371: 
 7372: (c) there is an active exam block with "printout"
 7373: functionality blocked
 7374: 
 7375: Users with pav, pfo or evb privileges are exempt.
 7376: 
 7377: Inputs: none
 7378: 
 7379: =cut
 7380: 
 7381: 
 7382: sub print_suppression {
 7383:     my $noprint;
 7384:     if ($env{'request.course.id'}) {
 7385:         my $scope = $env{'request.course.id'};
 7386:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7387:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7388:             return;
 7389:         }
 7390:         if ($env{'request.course.sec'} ne '') {
 7391:             $scope .= "/$env{'request.course.sec'}";
 7392:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7393:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7394:                 return;
 7395:             }
 7396:         }
 7397:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7398:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7399:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7400:         if ($blocked) {
 7401:             my $checkrole = "cm./$cdom/$cnum";
 7402:             if ($env{'request.course.sec'} ne '') {
 7403:                 $checkrole .= "/$env{'request.course.sec'}";
 7404:             }
 7405:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7406:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7407:                 $noprint = 1;
 7408:             }
 7409:         }
 7410:         unless ($noprint) {
 7411:             my $symb = &Apache::lonnet::symbread();
 7412:             if ($symb ne '') {
 7413:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7414:                 if (ref($navmap)) {
 7415:                     my $res = $navmap->getBySymb($symb);
 7416:                     if (ref($res)) {
 7417:                         if (!$res->resprintable()) {
 7418:                             $noprint = 1;
 7419:                         }
 7420:                     }
 7421:                 }
 7422:             }
 7423:         }
 7424:         if ($noprint) {
 7425:             return <<"ENDSTYLE";
 7426: <style type="text/css" media="print">
 7427:     body { display:none }
 7428: </style>
 7429: ENDSTYLE
 7430:         }
 7431:     }
 7432:     return;
 7433: }
 7434: 
 7435: =pod
 7436: 
 7437: =item * &xml_begin()
 7438: 
 7439: Returns the needed doctype and <html>
 7440: 
 7441: Inputs: none
 7442: 
 7443: =cut
 7444: 
 7445: sub xml_begin {
 7446:     my $output='';
 7447: 
 7448:     if ($env{'browser.mathml'}) {
 7449: 	$output='<?xml version="1.0"?>'
 7450:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7451: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7452:             
 7453: #	    .'<!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">] >'
 7454: 	    .'<!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">'
 7455:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7456: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7457:     } else {
 7458: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n"
 7459:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7460:     }
 7461:     return $output;
 7462: }
 7463: 
 7464: =pod
 7465: 
 7466: =item * &start_page()
 7467: 
 7468: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7469: 
 7470: Inputs:
 7471: 
 7472: =over 4
 7473: 
 7474: $title - optional title for the page
 7475: 
 7476: $head_extra - optional extra HTML to incude inside the <head>
 7477: 
 7478: $args - additional optional args supported are:
 7479: 
 7480: =over 8
 7481: 
 7482:              only_body      -> is true will set &bodytag() onlybodytag
 7483:                                     arg on
 7484:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7485:              add_entries    -> additional attributes to add to the  <body>
 7486:              domain         -> force to color decorate a page for a 
 7487:                                     specific domain
 7488:              function       -> force usage of a specific rolish color
 7489:                                     scheme
 7490:              redirect       -> see &headtag()
 7491:              bgcolor        -> override the default page bg color
 7492:              js_ready       -> return a string ready for being used in 
 7493:                                     a javascript writeln
 7494:              html_encode    -> return a string ready for being used in 
 7495:                                     a html attribute
 7496:              force_register -> if is true will turn on the &bodytag()
 7497:                                     $forcereg arg
 7498:              frameset       -> if true will start with a <frameset>
 7499:                                     rather than <body>
 7500:              skip_phases    -> hash ref of 
 7501:                                     head -> skip the <html><head> generation
 7502:                                     body -> skip all <body> generation
 7503:              no_inline_link -> if true and in remote mode, don't show the
 7504:                                     'Switch To Inline Menu' link
 7505:              no_auto_mt_title -> prevent &mt()ing the title arg
 7506:              inherit_jsmath -> when creating popup window in a page,
 7507:                                     should it have jsmath forced on by the
 7508:                                     current page
 7509:              bread_crumbs ->             Array containing breadcrumbs
 7510:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7511:              group          -> includes the current group, if page is for a
 7512:                                specific group
 7513: 
 7514: =back
 7515: 
 7516: =back
 7517: 
 7518: =cut
 7519: 
 7520: sub start_page {
 7521:     my ($title,$head_extra,$args) = @_;
 7522:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7523: 
 7524:     $env{'internal.start_page'}++;
 7525:     my ($result,@advtools);
 7526: 
 7527:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7528:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7529:     }
 7530:     
 7531:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7532: 	if ($args->{'frameset'}) {
 7533: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7534: 						$args->{'add_entries'});
 7535: 	    $result .= "\n<frameset $attr_string>\n";
 7536:         } else {
 7537:             $result .=
 7538:                 &bodytag($title, 
 7539:                          $args->{'function'},       $args->{'add_entries'},
 7540:                          $args->{'only_body'},      $args->{'domain'},
 7541:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7542:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7543:                          $args,                     \@advtools);
 7544:         }
 7545:     }
 7546: 
 7547:     if ($args->{'js_ready'}) {
 7548: 		$result = &js_ready($result);
 7549:     }
 7550:     if ($args->{'html_encode'}) {
 7551: 		$result = &html_encode($result);
 7552:     }
 7553: 
 7554:     # Preparation for new and consistent functionlist at top of screen
 7555:     # if ($args->{'functionlist'}) {
 7556:     #            $result .= &build_functionlist();
 7557:     #}
 7558: 
 7559:     # Don't add anything more if only_body wanted or in const space
 7560:     return $result if    $args->{'only_body'} 
 7561:                       || $env{'request.state'} eq 'construct';
 7562: 
 7563:     #Breadcrumbs
 7564:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7565: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7566: 		#if any br links exists, add them to the breadcrumbs
 7567: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7568: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7569: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7570: 			}
 7571: 		}
 7572:                 # if @advtools array contains items add then to the breadcrumbs
 7573:                 if (@advtools > 0) {
 7574:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7575:                 }
 7576: 
 7577: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7578: 		if(exists($args->{'bread_crumbs_component'})){
 7579: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7580: 		}else{
 7581: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7582: 		}
 7583:     } elsif (($env{'environment.remote'} eq 'on') &&
 7584:              ($env{'form.inhibitmenu'} ne 'yes') &&
 7585:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 7586:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 7587:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 7588:     }
 7589:     return $result;
 7590: }
 7591: 
 7592: sub end_page {
 7593:     my ($args) = @_;
 7594:     $env{'internal.end_page'}++;
 7595:     my $result;
 7596:     if ($args->{'discussion'}) {
 7597: 	my ($target,$parser);
 7598: 	if (ref($args->{'discussion'})) {
 7599: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7600: 				$args->{'discussion'}{'parser'});
 7601: 	}
 7602: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7603:     }
 7604:     if ($args->{'frameset'}) {
 7605: 	$result .= '</frameset>';
 7606:     } else {
 7607: 	$result .= &endbodytag($args);
 7608:     }
 7609:     unless ($args->{'notbody'}) {
 7610:         $result .= "\n</html>";
 7611:     }
 7612: 
 7613:     if ($args->{'js_ready'}) {
 7614: 	$result = &js_ready($result);
 7615:     }
 7616: 
 7617:     if ($args->{'html_encode'}) {
 7618: 	$result = &html_encode($result);
 7619:     }
 7620: 
 7621:     return $result;
 7622: }
 7623: 
 7624: sub wishlist_window {
 7625:     return(<<'ENDWISHLIST');
 7626: <script type="text/javascript">
 7627: // <![CDATA[
 7628: // <!-- BEGIN LON-CAPA Internal
 7629: function set_wishlistlink(title, path) {
 7630:     if (!title) {
 7631:         title = document.title;
 7632:         title = title.replace(/^LON-CAPA /,'');
 7633:     }
 7634:     if (!path) {
 7635:         path = location.pathname;
 7636:     }
 7637:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7638:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7639: }
 7640: // END LON-CAPA Internal -->
 7641: // ]]>
 7642: </script>
 7643: ENDWISHLIST
 7644: }
 7645: 
 7646: sub modal_window {
 7647:     return(<<'ENDMODAL');
 7648: <script type="text/javascript">
 7649: // <![CDATA[
 7650: // <!-- BEGIN LON-CAPA Internal
 7651: var modalWindow = {
 7652: 	parent:"body",
 7653: 	windowId:null,
 7654: 	content:null,
 7655: 	width:null,
 7656: 	height:null,
 7657: 	close:function()
 7658: 	{
 7659: 	        $(".LCmodal-window").remove();
 7660: 	        $(".LCmodal-overlay").remove();
 7661: 	},
 7662: 	open:function()
 7663: 	{
 7664: 		var modal = "";
 7665: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7666: 		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;\">";
 7667: 		modal += this.content;
 7668: 		modal += "</div>";	
 7669: 
 7670: 		$(this.parent).append(modal);
 7671: 
 7672: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7673: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7674: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7675: 	}
 7676: };
 7677: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7678: 	{
 7679: 		modalWindow.windowId = "myModal";
 7680: 		modalWindow.width = width;
 7681: 		modalWindow.height = height;
 7682: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
 7683: 		modalWindow.open();
 7684: 	};	
 7685: // END LON-CAPA Internal -->
 7686: // ]]>
 7687: </script>
 7688: ENDMODAL
 7689: }
 7690: 
 7691: sub modal_link {
 7692:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7693:     unless ($width) { $width=480; }
 7694:     unless ($height) { $height=400; }
 7695:     unless ($scrolling) { $scrolling='yes'; }
 7696:     unless ($transparency) { $transparency='true'; }
 7697: 
 7698:     my $target_attr;
 7699:     if (defined($target)) {
 7700:         $target_attr = 'target="'.$target.'"';
 7701:     }
 7702:     return <<"ENDLINK";
 7703: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7704:            $linktext</a>
 7705: ENDLINK
 7706: }
 7707: 
 7708: sub modal_adhoc_script {
 7709:     my ($funcname,$width,$height,$content)=@_;
 7710:     return (<<ENDADHOC);
 7711: <script type="text/javascript">
 7712: // <![CDATA[
 7713:         var $funcname = function()
 7714:         {
 7715:                 modalWindow.windowId = "myModal";
 7716:                 modalWindow.width = $width;
 7717:                 modalWindow.height = $height;
 7718:                 modalWindow.content = '$content';
 7719:                 modalWindow.open();
 7720:         };  
 7721: // ]]>
 7722: </script>
 7723: ENDADHOC
 7724: }
 7725: 
 7726: sub modal_adhoc_inner {
 7727:     my ($funcname,$width,$height,$content)=@_;
 7728:     my $innerwidth=$width-20;
 7729:     $content=&js_ready(
 7730:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7731:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7732:                  $content.
 7733:                  &end_scrollbox().
 7734:                  &end_page()
 7735:              );
 7736:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7737: }
 7738: 
 7739: sub modal_adhoc_window {
 7740:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7741:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7742:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7743: }
 7744: 
 7745: sub modal_adhoc_launch {
 7746:     my ($funcname,$width,$height,$content)=@_;
 7747:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7748: <script type="text/javascript">
 7749: // <![CDATA[
 7750: $funcname();
 7751: // ]]>
 7752: </script>
 7753: ENDLAUNCH
 7754: }
 7755: 
 7756: sub modal_adhoc_close {
 7757:     return (<<ENDCLOSE);
 7758: <script type="text/javascript">
 7759: // <![CDATA[
 7760: modalWindow.close();
 7761: // ]]>
 7762: </script>
 7763: ENDCLOSE
 7764: }
 7765: 
 7766: sub togglebox_script {
 7767:    return(<<ENDTOGGLE);
 7768: <script type="text/javascript"> 
 7769: // <![CDATA[
 7770: function LCtoggleDisplay(id,hidetext,showtext) {
 7771:    link = document.getElementById(id + "link").childNodes[0];
 7772:    with (document.getElementById(id).style) {
 7773:       if (display == "none" ) {
 7774:           display = "inline";
 7775:           link.nodeValue = hidetext;
 7776:         } else {
 7777:           display = "none";
 7778:           link.nodeValue = showtext;
 7779:        }
 7780:    }
 7781: }
 7782: // ]]>
 7783: </script>
 7784: ENDTOGGLE
 7785: }
 7786: 
 7787: sub start_togglebox {
 7788:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7789:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7790:     unless ($showtext) { $showtext=&mt('show'); }
 7791:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7792:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7793:     return &start_data_table().
 7794:            &start_data_table_header_row().
 7795:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7796:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7797:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7798:            &end_data_table_header_row().
 7799:            '<tr id="'.$id.'" style="display:none""><td>';
 7800: }
 7801: 
 7802: sub end_togglebox {
 7803:     return '</td></tr>'.&end_data_table();
 7804: }
 7805: 
 7806: sub LCprogressbar_script {
 7807:    my ($id)=@_;
 7808:    return(<<ENDPROGRESS);
 7809: <script type="text/javascript">
 7810: // <![CDATA[
 7811: \$('#progressbar$id').progressbar({
 7812:   value: 0,
 7813:   change: function(event, ui) {
 7814:     var newVal = \$(this).progressbar('option', 'value');
 7815:     \$('.pblabel', this).text(LCprogressTxt);
 7816:   }
 7817: });
 7818: // ]]>
 7819: </script>
 7820: ENDPROGRESS
 7821: }
 7822: 
 7823: sub LCprogressbarUpdate_script {
 7824:    return(<<ENDPROGRESSUPDATE);
 7825: <style type="text/css">
 7826: .ui-progressbar { position:relative; }
 7827: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7828: </style>
 7829: <script type="text/javascript">
 7830: // <![CDATA[
 7831: var LCprogressTxt='---';
 7832: 
 7833: function LCupdateProgress(percent,progresstext,id) {
 7834:    LCprogressTxt=progresstext;
 7835:    \$('#progressbar'+id).progressbar('value',percent);
 7836: }
 7837: // ]]>
 7838: </script>
 7839: ENDPROGRESSUPDATE
 7840: }
 7841: 
 7842: my $LClastpercent;
 7843: my $LCidcnt;
 7844: my $LCcurrentid;
 7845: 
 7846: sub LCprogressbar {
 7847:     my ($r)=(@_);
 7848:     $LClastpercent=0;
 7849:     $LCidcnt++;
 7850:     $LCcurrentid=$$.'_'.$LCidcnt;
 7851:     my $starting=&mt('Starting');
 7852:     my $content=(<<ENDPROGBAR);
 7853:   <div id="progressbar$LCcurrentid">
 7854:     <span class="pblabel">$starting</span>
 7855:   </div>
 7856: ENDPROGBAR
 7857:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7858: }
 7859: 
 7860: sub LCprogressbarUpdate {
 7861:     my ($r,$val,$text)=@_;
 7862:     unless ($val) { 
 7863:        if ($LClastpercent) {
 7864:            $val=$LClastpercent;
 7865:        } else {
 7866:            $val=0;
 7867:        }
 7868:     }
 7869:     if ($val<0) { $val=0; }
 7870:     if ($val>100) { $val=0; }
 7871:     $LClastpercent=$val;
 7872:     unless ($text) { $text=$val.'%'; }
 7873:     $text=&js_ready($text);
 7874:     &r_print($r,<<ENDUPDATE);
 7875: <script type="text/javascript">
 7876: // <![CDATA[
 7877: LCupdateProgress($val,'$text','$LCcurrentid');
 7878: // ]]>
 7879: </script>
 7880: ENDUPDATE
 7881: }
 7882: 
 7883: sub LCprogressbarClose {
 7884:     my ($r)=@_;
 7885:     $LClastpercent=0;
 7886:     &r_print($r,<<ENDCLOSE);
 7887: <script type="text/javascript">
 7888: // <![CDATA[
 7889: \$("#progressbar$LCcurrentid").hide('slow'); 
 7890: // ]]>
 7891: </script>
 7892: ENDCLOSE
 7893: }
 7894: 
 7895: sub r_print {
 7896:     my ($r,$to_print)=@_;
 7897:     if ($r) {
 7898:       $r->print($to_print);
 7899:       $r->rflush();
 7900:     } else {
 7901:       print($to_print);
 7902:     }
 7903: }
 7904: 
 7905: sub html_encode {
 7906:     my ($result) = @_;
 7907: 
 7908:     $result = &HTML::Entities::encode($result,'<>&"');
 7909:     
 7910:     return $result;
 7911: }
 7912: 
 7913: sub js_ready {
 7914:     my ($result) = @_;
 7915: 
 7916:     $result =~ s/[\n\r]/ /xmsg;
 7917:     $result =~ s/\\/\\\\/xmsg;
 7918:     $result =~ s/'/\\'/xmsg;
 7919:     $result =~ s{</}{<\\/}xmsg;
 7920:     
 7921:     return $result;
 7922: }
 7923: 
 7924: sub validate_page {
 7925:     if (  exists($env{'internal.start_page'})
 7926: 	  &&     $env{'internal.start_page'} > 1) {
 7927: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7928: 				 $env{'internal.start_page'}.' '.
 7929: 				 $ENV{'request.filename'});
 7930:     }
 7931:     if (  exists($env{'internal.end_page'})
 7932: 	  &&     $env{'internal.end_page'} > 1) {
 7933: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7934: 				 $env{'internal.end_page'}.' '.
 7935: 				 $env{'request.filename'});
 7936:     }
 7937:     if (     exists($env{'internal.start_page'})
 7938: 	&& ! exists($env{'internal.end_page'})) {
 7939: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7940: 				 $env{'request.filename'});
 7941:     }
 7942:     if (   ! exists($env{'internal.start_page'})
 7943: 	&&   exists($env{'internal.end_page'})) {
 7944: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7945: 				 $env{'request.filename'});
 7946:     }
 7947: }
 7948: 
 7949: 
 7950: sub start_scrollbox {
 7951:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 7952:     unless ($outerwidth) { $outerwidth='520px'; }
 7953:     unless ($width) { $width='500px'; }
 7954:     unless ($height) { $height='200px'; }
 7955:     my ($table_id,$div_id,$tdcol);
 7956:     if ($id ne '') {
 7957:         $table_id = ' id="table_'.$id.'"';
 7958:         $div_id = ' id="div_'.$id.'"';
 7959:     }
 7960:     if ($bgcolor ne '') {
 7961:         $tdcol = "background-color: $bgcolor;";
 7962:     }
 7963:     my $nicescroll_js;
 7964:     if ($env{'browser.mobile'}) {
 7965:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 7966:     }
 7967:     return <<"END";
 7968: $nicescroll_js
 7969: 
 7970: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 7971: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 7972: END
 7973: }
 7974: 
 7975: sub end_scrollbox {
 7976:     return '</div></td></tr></table>';
 7977: }
 7978: 
 7979: sub nicescroll_javascript {
 7980:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 7981:     my %options;
 7982:     if (ref($cursor) eq 'HASH') {
 7983:         %options = %{$cursor};
 7984:     }
 7985:     unless ($options{'railalign'} =~ /^left|right$/) {
 7986:         $options{'railalign'} = 'left';
 7987:     }
 7988:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7989:         my $function  = &get_users_function();
 7990:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 7991:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7992:             $options{'cursorcolor'} = '#00F';
 7993:         }
 7994:     }
 7995:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 7996:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 7997:             $options{'cursoropacity'}='1.0';
 7998:         }
 7999:     } else {
 8000:         $options{'cursoropacity'}='1.0';
 8001:     }
 8002:     if ($options{'cursorfixedheight'} eq 'none') {
 8003:         delete($options{'cursorfixedheight'});
 8004:     } else {
 8005:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8006:     }
 8007:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8008:         delete($options{'railoffset'});
 8009:     }
 8010:     my @niceoptions;
 8011:     while (my($key,$value) = each(%options)) {
 8012:         if ($value =~ /^\{.+\}$/) {
 8013:             push(@niceoptions,$key.':'.$value);
 8014:         } else {
 8015:             push(@niceoptions,$key.':"'.$value.'"');
 8016:         }
 8017:     }
 8018:     my $nicescroll_js = '
 8019: $(document).ready(
 8020:       function() {
 8021:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8022:       }
 8023: );
 8024: ';
 8025:     if ($framecheck) {
 8026:         $nicescroll_js .= '
 8027: function expand_div(caller) {
 8028:     if (top === self) {
 8029:         document.getElementById("'.$id.'").style.width = "auto";
 8030:         document.getElementById("'.$id.'").style.height = "auto";
 8031:     } else {
 8032:         try {
 8033:             if (parent.frames) {
 8034:                 if (parent.frames.length > 1) {
 8035:                     var framesrc = parent.frames[1].location.href;
 8036:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8037:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8038:                         document.getElementById("'.$id.'").style.width = "auto";
 8039:                         document.getElementById("'.$id.'").style.height = "auto";
 8040:                     }
 8041:                 }
 8042:             }
 8043:         } catch (e) {
 8044:             return;
 8045:         }
 8046:     }
 8047:     return;
 8048: }
 8049: ';
 8050:     }
 8051:     if ($needjsready) {
 8052:         $nicescroll_js = '
 8053: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8054:     } else {
 8055:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8056:     }
 8057:     return $nicescroll_js;
 8058: }
 8059: 
 8060: sub simple_error_page {
 8061:     my ($r,$title,$msg,$args) = @_;
 8062:     if (ref($args) eq 'HASH') {
 8063:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8064:     } else {
 8065:         $msg = &mt($msg);
 8066:     }
 8067: 
 8068:     my $page =
 8069: 	&Apache::loncommon::start_page($title).
 8070: 	'<p class="LC_error">'.$msg.'</p>'.
 8071: 	&Apache::loncommon::end_page();
 8072:     if (ref($r)) {
 8073: 	$r->print($page);
 8074: 	return;
 8075:     }
 8076:     return $page;
 8077: }
 8078: 
 8079: {
 8080:     my @row_count;
 8081: 
 8082:     sub start_data_table_count {
 8083:         unshift(@row_count, 0);
 8084:         return;
 8085:     }
 8086: 
 8087:     sub end_data_table_count {
 8088:         shift(@row_count);
 8089:         return;
 8090:     }
 8091: 
 8092:     sub start_data_table {
 8093: 	my ($add_class,$id) = @_;
 8094: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8095:         my $table_id;
 8096:         if (defined($id)) {
 8097:             $table_id = ' id="'.$id.'"';
 8098:         }
 8099: 	&start_data_table_count();
 8100: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8101:     }
 8102: 
 8103:     sub end_data_table {
 8104: 	&end_data_table_count();
 8105: 	return '</table>'."\n";;
 8106:     }
 8107: 
 8108:     sub start_data_table_row {
 8109: 	my ($add_class, $id) = @_;
 8110: 	$row_count[0]++;
 8111: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8112: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8113:         $id = (' id="'.$id.'"') unless ($id eq '');
 8114:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8115:     }
 8116:     
 8117:     sub continue_data_table_row {
 8118: 	my ($add_class, $id) = @_;
 8119: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8120: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8121:         $id = (' id="'.$id.'"') unless ($id eq '');
 8122:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8123:     }
 8124: 
 8125:     sub end_data_table_row {
 8126: 	return '</tr>'."\n";;
 8127:     }
 8128: 
 8129:     sub start_data_table_empty_row {
 8130: #	$row_count[0]++;
 8131: 	return  '<tr class="LC_empty_row" >'."\n";;
 8132:     }
 8133: 
 8134:     sub end_data_table_empty_row {
 8135: 	return '</tr>'."\n";;
 8136:     }
 8137: 
 8138:     sub start_data_table_header_row {
 8139: 	return  '<tr class="LC_header_row">'."\n";;
 8140:     }
 8141: 
 8142:     sub end_data_table_header_row {
 8143: 	return '</tr>'."\n";;
 8144:     }
 8145: 
 8146:     sub data_table_caption {
 8147:         my $caption = shift;
 8148:         return "<caption class=\"LC_caption\">$caption</caption>";
 8149:     }
 8150: }
 8151: 
 8152: =pod
 8153: 
 8154: =item * &inhibit_menu_check($arg)
 8155: 
 8156: Checks for a inhibitmenu state and generates output to preserve it
 8157: 
 8158: Inputs:         $arg - can be any of
 8159:                      - undef - in which case the return value is a string 
 8160:                                to add  into arguments list of a uri
 8161:                      - 'input' - in which case the return value is a HTML
 8162:                                  <form> <input> field of type hidden to
 8163:                                  preserve the value
 8164:                      - a url - in which case the return value is the url with
 8165:                                the neccesary cgi args added to preserve the
 8166:                                inhibitmenu state
 8167:                      - a ref to a url - no return value, but the string is
 8168:                                         updated to include the neccessary cgi
 8169:                                         args to preserve the inhibitmenu state
 8170: 
 8171: =cut
 8172: 
 8173: sub inhibit_menu_check {
 8174:     my ($arg) = @_;
 8175:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8176:     if ($arg eq 'input') {
 8177: 	if ($env{'form.inhibitmenu'}) {
 8178: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8179: 	} else {
 8180: 	    return
 8181: 	}
 8182:     }
 8183:     if ($env{'form.inhibitmenu'}) {
 8184: 	if (ref($arg)) {
 8185: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8186: 	} elsif ($arg eq '') {
 8187: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8188: 	} else {
 8189: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8190: 	}
 8191:     }
 8192:     if (!ref($arg)) {
 8193: 	return $arg;
 8194:     }
 8195: }
 8196: 
 8197: ###############################################
 8198: 
 8199: =pod
 8200: 
 8201: =back
 8202: 
 8203: =head1 User Information Routines
 8204: 
 8205: =over 4
 8206: 
 8207: =item * &get_users_function()
 8208: 
 8209: Used by &bodytag to determine the current users primary role.
 8210: Returns either 'student','coordinator','admin', or 'author'.
 8211: 
 8212: =cut
 8213: 
 8214: ###############################################
 8215: sub get_users_function {
 8216:     my $function = 'norole';
 8217:     if ($env{'request.role'}=~/^(st)/) {
 8218:         $function='student';
 8219:     }
 8220:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8221:         $function='coordinator';
 8222:     }
 8223:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8224:         $function='admin';
 8225:     }
 8226:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8227:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8228:         $function='author';
 8229:     }
 8230:     return $function;
 8231: }
 8232: 
 8233: ###############################################
 8234: 
 8235: =pod
 8236: 
 8237: =item * &show_course()
 8238: 
 8239: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8240: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8241: 
 8242: Inputs:
 8243: None
 8244: 
 8245: Outputs:
 8246: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8247: 
 8248: =cut
 8249: 
 8250: ###############################################
 8251: sub show_course {
 8252:     my $course = !$env{'user.adv'};
 8253:     if (!$env{'user.adv'}) {
 8254:         foreach my $env (keys(%env)) {
 8255:             next if ($env !~ m/^user\.priv\./);
 8256:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8257:                 $course = 0;
 8258:                 last;
 8259:             }
 8260:         }
 8261:     }
 8262:     return $course;
 8263: }
 8264: 
 8265: ###############################################
 8266: 
 8267: =pod
 8268: 
 8269: =item * &check_user_status()
 8270: 
 8271: Determines current status of supplied role for a
 8272: specific user. Roles can be active, previous or future.
 8273: 
 8274: Inputs: 
 8275: user's domain, user's username, course's domain,
 8276: course's number, optional section ID.
 8277: 
 8278: Outputs:
 8279: role status: active, previous or future. 
 8280: 
 8281: =cut
 8282: 
 8283: sub check_user_status {
 8284:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8285:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8286:     my @uroles = keys %userinfo;
 8287:     my $srchstr;
 8288:     my $active_chk = 'none';
 8289:     my $now = time;
 8290:     if (@uroles > 0) {
 8291:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8292:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8293:         } else {
 8294:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8295:         }
 8296:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8297:             my $role_end = 0;
 8298:             my $role_start = 0;
 8299:             $active_chk = 'active';
 8300:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8301:                 $role_end = $1;
 8302:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8303:                     $role_start = $1;
 8304:                 }
 8305:             }
 8306:             if ($role_start > 0) {
 8307:                 if ($now < $role_start) {
 8308:                     $active_chk = 'future';
 8309:                 }
 8310:             }
 8311:             if ($role_end > 0) {
 8312:                 if ($now > $role_end) {
 8313:                     $active_chk = 'previous';
 8314:                 }
 8315:             }
 8316:         }
 8317:     }
 8318:     return $active_chk;
 8319: }
 8320: 
 8321: ###############################################
 8322: 
 8323: =pod
 8324: 
 8325: =item * &get_sections()
 8326: 
 8327: Determines all the sections for a course including
 8328: sections with students and sections containing other roles.
 8329: Incoming parameters: 
 8330: 
 8331: 1. domain
 8332: 2. course number 
 8333: 3. reference to array containing roles for which sections should 
 8334: be gathered (optional).
 8335: 4. reference to array containing status types for which sections 
 8336: should be gathered (optional).
 8337: 
 8338: If the third argument is undefined, sections are gathered for any role. 
 8339: If the fourth argument is undefined, sections are gathered for any status.
 8340: Permissible values are 'active' or 'future' or 'previous'.
 8341:  
 8342: Returns section hash (keys are section IDs, values are
 8343: number of users in each section), subject to the
 8344: optional roles filter, optional status filter 
 8345: 
 8346: =cut
 8347: 
 8348: ###############################################
 8349: sub get_sections {
 8350:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8351:     if (!defined($cdom) || !defined($cnum)) {
 8352:         my $cid =  $env{'request.course.id'};
 8353: 
 8354: 	return if (!defined($cid));
 8355: 
 8356:         $cdom = $env{'course.'.$cid.'.domain'};
 8357:         $cnum = $env{'course.'.$cid.'.num'};
 8358:     }
 8359: 
 8360:     my %sectioncount;
 8361:     my $now = time;
 8362: 
 8363:     my $check_students = 1;
 8364:     my $only_students = 0;
 8365:     if (ref($possible_roles) eq 'ARRAY') {
 8366:         if (grep(/^st$/,@{$possible_roles})) {
 8367:             if (@{$possible_roles} == 1) {
 8368:                 $only_students = 1;
 8369:             }
 8370:         } else {
 8371:             $check_students = 0;
 8372:         }
 8373:     }
 8374: 
 8375:     if ($check_students) {
 8376: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8377: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8378: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8379:         my $start_index = &Apache::loncoursedata::CL_START();
 8380:         my $end_index = &Apache::loncoursedata::CL_END();
 8381:         my $status;
 8382: 	while (my ($student,$data) = each(%$classlist)) {
 8383: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8384: 				                     $data->[$status_index],
 8385:                                                      $data->[$start_index],
 8386:                                                      $data->[$end_index]);
 8387:             if ($stu_status eq 'Active') {
 8388:                 $status = 'active';
 8389:             } elsif ($end < $now) {
 8390:                 $status = 'previous';
 8391:             } elsif ($start > $now) {
 8392:                 $status = 'future';
 8393:             } 
 8394: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8395:                 if ((!defined($possible_status)) || (($status ne '') && 
 8396:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8397: 		    $sectioncount{$section}++;
 8398:                 }
 8399: 	    }
 8400: 	}
 8401:     }
 8402:     if ($only_students) {
 8403:         return %sectioncount;
 8404:     }
 8405:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8406:     foreach my $user (sort(keys(%courseroles))) {
 8407: 	if ($user !~ /^(\w{2})/) { next; }
 8408: 	my ($role) = ($user =~ /^(\w{2})/);
 8409: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8410: 	my ($section,$status);
 8411: 	if ($role eq 'cr' &&
 8412: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8413: 	    $section=$1;
 8414: 	}
 8415: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8416: 	if (!defined($section) || $section eq '-1') { next; }
 8417:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8418:         if ($end == -1 && $start == -1) {
 8419:             next; #deleted role
 8420:         }
 8421:         if (!defined($possible_status)) { 
 8422:             $sectioncount{$section}++;
 8423:         } else {
 8424:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8425:                 $status = 'active';
 8426:             } elsif ($end < $now) {
 8427:                 $status = 'future';
 8428:             } elsif ($start > $now) {
 8429:                 $status = 'previous';
 8430:             }
 8431:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8432:                 $sectioncount{$section}++;
 8433:             }
 8434:         }
 8435:     }
 8436:     return %sectioncount;
 8437: }
 8438: 
 8439: ###############################################
 8440: 
 8441: =pod
 8442: 
 8443: =item * &get_course_users()
 8444: 
 8445: Retrieves usernames:domains for users in the specified course
 8446: with specific role(s), and access status. 
 8447: 
 8448: Incoming parameters:
 8449: 1. course domain
 8450: 2. course number
 8451: 3. access status: users must have - either active, 
 8452: previous, future, or all.
 8453: 4. reference to array of permissible roles
 8454: 5. reference to array of section restrictions (optional)
 8455: 6. reference to results object (hash of hashes).
 8456: 7. reference to optional userdata hash
 8457: 8. reference to optional statushash
 8458: 9. flag if privileged users (except those set to unhide in
 8459:    course settings) should be excluded    
 8460: Keys of top level results hash are roles.
 8461: Keys of inner hashes are username:domain, with 
 8462: values set to access type.
 8463: Optional userdata hash returns an array with arguments in the 
 8464: same order as loncoursedata::get_classlist() for student data.
 8465: 
 8466: Optional statushash returns
 8467: 
 8468: Entries for end, start, section and status are blank because
 8469: of the possibility of multiple values for non-student roles.
 8470: 
 8471: =cut
 8472: 
 8473: ###############################################
 8474: 
 8475: sub get_course_users {
 8476:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8477:     my %idx = ();
 8478:     my %seclists;
 8479: 
 8480:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8481:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8482:     $idx{end} = &Apache::loncoursedata::CL_END();
 8483:     $idx{start} = &Apache::loncoursedata::CL_START();
 8484:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8485:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8486:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8487:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8488: 
 8489:     if (grep(/^st$/,@{$roles})) {
 8490:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8491:         my $now = time;
 8492:         foreach my $student (keys(%{$classlist})) {
 8493:             my $match = 0;
 8494:             my $secmatch = 0;
 8495:             my $section = $$classlist{$student}[$idx{section}];
 8496:             my $status = $$classlist{$student}[$idx{status}];
 8497:             if ($section eq '') {
 8498:                 $section = 'none';
 8499:             }
 8500:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8501:                 if (grep(/^all$/,@{$sections})) {
 8502:                     $secmatch = 1;
 8503:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8504:                     if (grep(/^none$/,@{$sections})) {
 8505:                         $secmatch = 1;
 8506:                     }
 8507:                 } else {  
 8508: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8509: 		        $secmatch = 1;
 8510:                     }
 8511: 		}
 8512:                 if (!$secmatch) {
 8513:                     next;
 8514:                 }
 8515:             }
 8516:             if (defined($$types{'active'})) {
 8517:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8518:                     push(@{$$users{st}{$student}},'active');
 8519:                     $match = 1;
 8520:                 }
 8521:             }
 8522:             if (defined($$types{'previous'})) {
 8523:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8524:                     push(@{$$users{st}{$student}},'previous');
 8525:                     $match = 1;
 8526:                 }
 8527:             }
 8528:             if (defined($$types{'future'})) {
 8529:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8530:                     push(@{$$users{st}{$student}},'future');
 8531:                     $match = 1;
 8532:                 }
 8533:             }
 8534:             if ($match) {
 8535:                 push(@{$seclists{$student}},$section);
 8536:                 if (ref($userdata) eq 'HASH') {
 8537:                     $$userdata{$student} = $$classlist{$student};
 8538:                 }
 8539:                 if (ref($statushash) eq 'HASH') {
 8540:                     $statushash->{$student}{'st'}{$section} = $status;
 8541:                 }
 8542:             }
 8543:         }
 8544:     }
 8545:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8546:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8547:         my $now = time;
 8548:         my %displaystatus = ( previous => 'Expired',
 8549:                               active   => 'Active',
 8550:                               future   => 'Future',
 8551:                             );
 8552:         my (%nothide,@possdoms);
 8553:         if ($hidepriv) {
 8554:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8555:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8556:                 if ($user !~ /:/) {
 8557:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8558:                 } else {
 8559:                     $nothide{$user} = 1;
 8560:                 }
 8561:             }
 8562:             my @possdoms = ($cdom);
 8563:             if ($coursehash{'checkforpriv'}) {
 8564:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8565:             }
 8566:         }
 8567:         foreach my $person (sort(keys(%coursepersonnel))) {
 8568:             my $match = 0;
 8569:             my $secmatch = 0;
 8570:             my $status;
 8571:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8572:             $user =~ s/:$//;
 8573:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8574:             if ($end == -1 || $start == -1) {
 8575:                 next;
 8576:             }
 8577:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8578:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8579:                 my ($uname,$udom) = split(/:/,$user);
 8580:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8581:                     if (grep(/^all$/,@{$sections})) {
 8582:                         $secmatch = 1;
 8583:                     } elsif ($usec eq '') {
 8584:                         if (grep(/^none$/,@{$sections})) {
 8585:                             $secmatch = 1;
 8586:                         }
 8587:                     } else {
 8588:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8589:                             $secmatch = 1;
 8590:                         }
 8591:                     }
 8592:                     if (!$secmatch) {
 8593:                         next;
 8594:                     }
 8595:                 }
 8596:                 if ($usec eq '') {
 8597:                     $usec = 'none';
 8598:                 }
 8599:                 if ($uname ne '' && $udom ne '') {
 8600:                     if ($hidepriv) {
 8601:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8602:                             (!$nothide{$uname.':'.$udom})) {
 8603:                             next;
 8604:                         }
 8605:                     }
 8606:                     if ($end > 0 && $end < $now) {
 8607:                         $status = 'previous';
 8608:                     } elsif ($start > $now) {
 8609:                         $status = 'future';
 8610:                     } else {
 8611:                         $status = 'active';
 8612:                     }
 8613:                     foreach my $type (keys(%{$types})) { 
 8614:                         if ($status eq $type) {
 8615:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8616:                                 push(@{$$users{$role}{$user}},$type);
 8617:                             }
 8618:                             $match = 1;
 8619:                         }
 8620:                     }
 8621:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8622:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8623: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8624:                         }
 8625:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8626:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8627:                         }
 8628:                         if (ref($statushash) eq 'HASH') {
 8629:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8630:                         }
 8631:                     }
 8632:                 }
 8633:             }
 8634:         }
 8635:         if (grep(/^ow$/,@{$roles})) {
 8636:             if ((defined($cdom)) && (defined($cnum))) {
 8637:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8638:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8639:                     my $owner = $csettings{'internal.courseowner'};
 8640:                     next if ($owner eq '');
 8641:                     my ($ownername,$ownerdom);
 8642:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8643:                         $ownername = $1;
 8644:                         $ownerdom = $2;
 8645:                     } else {
 8646:                         $ownername = $owner;
 8647:                         $ownerdom = $cdom;
 8648:                         $owner = $ownername.':'.$ownerdom;
 8649:                     }
 8650:                     @{$$users{'ow'}{$owner}} = 'any';
 8651:                     if (defined($userdata) && 
 8652: 			!exists($$userdata{$owner})) {
 8653: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8654:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8655:                             push(@{$seclists{$owner}},'none');
 8656:                         }
 8657:                         if (ref($statushash) eq 'HASH') {
 8658:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8659:                         }
 8660: 		    }
 8661:                 }
 8662:             }
 8663:         }
 8664:         foreach my $user (keys(%seclists)) {
 8665:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8666:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8667:         }
 8668:     }
 8669:     return;
 8670: }
 8671: 
 8672: sub get_user_info {
 8673:     my ($udom,$uname,$idx,$userdata) = @_;
 8674:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8675: 	&plainname($uname,$udom,'lastname');
 8676:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8677:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8678:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8679:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8680:     return;
 8681: }
 8682: 
 8683: ###############################################
 8684: 
 8685: =pod
 8686: 
 8687: =item * &get_user_quota()
 8688: 
 8689: Retrieves quota assigned for storage of user files.
 8690: Default is to report quota for portfolio files.
 8691: 
 8692: Incoming parameters:
 8693: 1. user's username
 8694: 2. user's domain
 8695: 3. quota name - portfolio, author, or course
 8696:    (if no quota name provided, defaults to portfolio).
 8697: 4. crstype - official, unofficial, textbook or community, if quota name is
 8698:    course
 8699: 
 8700: Returns:
 8701: 1. Disk quota (in MB) assigned to student.
 8702: 2. (Optional) Type of setting: custom or default
 8703:    (individually assigned or default for user's 
 8704:    institutional status).
 8705: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8706:    or student - types as defined in localenroll::inst_usertypes 
 8707:    for user's domain, which determines default quota for user.
 8708: 4. (Optional) - Default quota which would apply to the user.
 8709: 
 8710: If a value has been stored in the user's environment, 
 8711: it will return that, otherwise it returns the maximal default
 8712: defined for the user's institutional status(es) in the domain.
 8713: 
 8714: =cut
 8715: 
 8716: ###############################################
 8717: 
 8718: 
 8719: sub get_user_quota {
 8720:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8721:     my ($quota,$quotatype,$settingstatus,$defquota);
 8722:     if (!defined($udom)) {
 8723:         $udom = $env{'user.domain'};
 8724:     }
 8725:     if (!defined($uname)) {
 8726:         $uname = $env{'user.name'};
 8727:     }
 8728:     if (($udom eq '' || $uname eq '') ||
 8729:         ($udom eq 'public') && ($uname eq 'public')) {
 8730:         $quota = 0;
 8731:         $quotatype = 'default';
 8732:         $defquota = 0; 
 8733:     } else {
 8734:         my $inststatus;
 8735:         if ($quotaname eq 'course') {
 8736:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8737:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8738:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8739:             } else {
 8740:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8741:                 $quota = $cenv{'internal.uploadquota'};
 8742:             }
 8743:         } else {
 8744:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8745:                 if ($quotaname eq 'author') {
 8746:                     $quota = $env{'environment.authorquota'};
 8747:                 } else {
 8748:                     $quota = $env{'environment.portfolioquota'};
 8749:                 }
 8750:                 $inststatus = $env{'environment.inststatus'};
 8751:             } else {
 8752:                 my %userenv = 
 8753:                     &Apache::lonnet::get('environment',['portfolioquota',
 8754:                                          'authorquota','inststatus'],$udom,$uname);
 8755:                 my ($tmp) = keys(%userenv);
 8756:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8757:                     if ($quotaname eq 'author') {
 8758:                         $quota = $userenv{'authorquota'};
 8759:                     } else {
 8760:                         $quota = $userenv{'portfolioquota'};
 8761:                     }
 8762:                     $inststatus = $userenv{'inststatus'};
 8763:                 } else {
 8764:                     undef(%userenv);
 8765:                 }
 8766:             }
 8767:         }
 8768:         if ($quota eq '' || wantarray) {
 8769:             if ($quotaname eq 'course') {
 8770:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8771:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 8772:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 8773:                     $defquota = $domdefs{$crstype.'quota'};
 8774:                 }
 8775:                 if ($defquota eq '') {
 8776:                     $defquota = 500;
 8777:                 }
 8778:             } else {
 8779:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8780:             }
 8781:             if ($quota eq '') {
 8782:                 $quota = $defquota;
 8783:                 $quotatype = 'default';
 8784:             } else {
 8785:                 $quotatype = 'custom';
 8786:             }
 8787:         }
 8788:     }
 8789:     if (wantarray) {
 8790:         return ($quota,$quotatype,$settingstatus,$defquota);
 8791:     } else {
 8792:         return $quota;
 8793:     }
 8794: }
 8795: 
 8796: ###############################################
 8797: 
 8798: =pod
 8799: 
 8800: =item * &default_quota()
 8801: 
 8802: Retrieves default quota assigned for storage of user portfolio files,
 8803: given an (optional) user's institutional status.
 8804: 
 8805: Incoming parameters:
 8806: 
 8807: 1. domain
 8808: 2. (Optional) institutional status(es).  This is a : separated list of 
 8809:    status types (e.g., faculty, staff, student etc.)
 8810:    which apply to the user for whom the default is being retrieved.
 8811:    If the institutional status string in undefined, the domain
 8812:    default quota will be returned.
 8813: 3.  quota name - portfolio, author, or course
 8814:    (if no quota name provided, defaults to portfolio).
 8815: 
 8816: Returns:
 8817: 
 8818: 1. Default disk quota (in MB) for user portfolios in the domain.
 8819: 2. (Optional) institutional type which determined the value of the
 8820:    default quota.
 8821: 
 8822: If a value has been stored in the domain's configuration db,
 8823: it will return that, otherwise it returns 20 (for backwards 
 8824: compatibility with domains which have not set up a configuration
 8825: db file; the original statically defined portfolio quota was 20 MB). 
 8826: 
 8827: If the user's status includes multiple types (e.g., staff and student),
 8828: the largest default quota which applies to the user determines the
 8829: default quota returned.
 8830: 
 8831: =cut
 8832: 
 8833: ###############################################
 8834: 
 8835: 
 8836: sub default_quota {
 8837:     my ($udom,$inststatus,$quotaname) = @_;
 8838:     my ($defquota,$settingstatus);
 8839:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8840:                                             ['quotas'],$udom);
 8841:     my $key = 'defaultquota';
 8842:     if ($quotaname eq 'author') {
 8843:         $key = 'authorquota';
 8844:     }
 8845:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8846:         if ($inststatus ne '') {
 8847:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8848:             foreach my $item (@statuses) {
 8849:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8850:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 8851:                         if ($defquota eq '') {
 8852:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8853:                             $settingstatus = $item;
 8854:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 8855:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8856:                             $settingstatus = $item;
 8857:                         }
 8858:                     }
 8859:                 } elsif ($key eq 'defaultquota') {
 8860:                     if ($quotahash{'quotas'}{$item} ne '') {
 8861:                         if ($defquota eq '') {
 8862:                             $defquota = $quotahash{'quotas'}{$item};
 8863:                             $settingstatus = $item;
 8864:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8865:                             $defquota = $quotahash{'quotas'}{$item};
 8866:                             $settingstatus = $item;
 8867:                         }
 8868:                     }
 8869:                 }
 8870:             }
 8871:         }
 8872:         if ($defquota eq '') {
 8873:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8874:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 8875:             } elsif ($key eq 'defaultquota') {
 8876:                 $defquota = $quotahash{'quotas'}{'default'};
 8877:             }
 8878:             $settingstatus = 'default';
 8879:             if ($defquota eq '') {
 8880:                 if ($quotaname eq 'author') {
 8881:                     $defquota = 500;
 8882:                 }
 8883:             }
 8884:         }
 8885:     } else {
 8886:         $settingstatus = 'default';
 8887:         if ($quotaname eq 'author') {
 8888:             $defquota = 500;
 8889:         } else {
 8890:             $defquota = 20;
 8891:         }
 8892:     }
 8893:     if (wantarray) {
 8894:         return ($defquota,$settingstatus);
 8895:     } else {
 8896:         return $defquota;
 8897:     }
 8898: }
 8899: 
 8900: ###############################################
 8901: 
 8902: =pod
 8903: 
 8904: =item * &excess_filesize_warning()
 8905: 
 8906: Returns warning message if upload of file to authoring space, or copying
 8907: of existing file within authoring space will cause quota for the authoring
 8908: space to be exceeded.
 8909: 
 8910: Same, if upload of a file directly to a course/community via Course Editor
 8911: will cause quota for uploaded content for the course to be exceeded.
 8912: 
 8913: Inputs: 6
 8914: 1. username or coursenum
 8915: 2. domain
 8916: 3. context ('author' or 'course')
 8917: 4. filename of file for which action is being requested
 8918: 5. filesize (kB) of file
 8919: 6. action being taken: copy or upload.
 8920: 7. quotatype (in course context -- official, unofficial, community or textbook).
 8921: 
 8922: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 8923:          otherwise return null.
 8924: 
 8925: =back
 8926: 
 8927: =cut
 8928: 
 8929: sub excess_filesize_warning {
 8930:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 8931:     my $current_disk_usage = 0;
 8932:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 8933:     if ($context eq 'author') {
 8934:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 8935:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 8936:     } else {
 8937:         foreach my $subdir ('docs','supplemental') {
 8938:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 8939:         }
 8940:     }
 8941:     $disk_quota = int($disk_quota * 1000);
 8942:     if (($current_disk_usage + $filesize) > $disk_quota) {
 8943:         return '<p><span class="LC_warning">'.
 8944:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 8945:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
 8946:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 8947:                             $disk_quota,$current_disk_usage).
 8948:                '</p>';
 8949:     }
 8950:     return;
 8951: }
 8952: 
 8953: ###############################################
 8954: 
 8955: 
 8956: sub get_secgrprole_info {
 8957:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8958:     my %sections_count = &get_sections($cdom,$cnum);
 8959:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8960:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8961:     my @groups = sort(keys(%curr_groups));
 8962:     my $allroles = [];
 8963:     my $rolehash;
 8964:     my $accesshash = {
 8965:                      active => 'Currently has access',
 8966:                      future => 'Will have future access',
 8967:                      previous => 'Previously had access',
 8968:                   };
 8969:     if ($needroles) {
 8970:         $rolehash = {'all' => 'all'};
 8971:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8972: 	if (&Apache::lonnet::error(%user_roles)) {
 8973: 	    undef(%user_roles);
 8974: 	}
 8975:         foreach my $item (keys(%user_roles)) {
 8976:             my ($role)=split(/\:/,$item,2);
 8977:             if ($role eq 'cr') { next; }
 8978:             if ($role =~ /^cr/) {
 8979:                 $$rolehash{$role} = (split('/',$role))[3];
 8980:             } else {
 8981:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8982:             }
 8983:         }
 8984:         foreach my $key (sort(keys(%{$rolehash}))) {
 8985:             push(@{$allroles},$key);
 8986:         }
 8987:         push (@{$allroles},'st');
 8988:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8989:     }
 8990:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8991: }
 8992: 
 8993: sub user_picker {
 8994:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8995:     my $currdom = $dom;
 8996:     my %curr_selected = (
 8997:                         srchin => 'dom',
 8998:                         srchby => 'lastname',
 8999:                       );
 9000:     my $srchterm;
 9001:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9002:         if ($srch->{'srchby'} ne '') {
 9003:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9004:         }
 9005:         if ($srch->{'srchin'} ne '') {
 9006:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9007:         }
 9008:         if ($srch->{'srchtype'} ne '') {
 9009:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9010:         }
 9011:         if ($srch->{'srchdomain'} ne '') {
 9012:             $currdom = $srch->{'srchdomain'};
 9013:         }
 9014:         $srchterm = $srch->{'srchterm'};
 9015:     }
 9016:     my %lt=&Apache::lonlocal::texthash(
 9017:                     'usr'       => 'Search criteria',
 9018:                     'doma'      => 'Domain/institution to search',
 9019:                     'uname'     => 'username',
 9020:                     'lastname'  => 'last name',
 9021:                     'lastfirst' => 'last name, first name',
 9022:                     'crs'       => 'in this course',
 9023:                     'dom'       => 'in selected LON-CAPA domain', 
 9024:                     'alc'       => 'all LON-CAPA',
 9025:                     'instd'     => 'in institutional directory for selected domain',
 9026:                     'exact'     => 'is',
 9027:                     'contains'  => 'contains',
 9028:                     'begins'    => 'begins with',
 9029:                     'youm'      => "You must include some text to search for.",
 9030:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9031:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9032:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9033:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9034:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9035:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9036:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9037:                                        );
 9038:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9039:     my $srchinsel = ' <select name="srchin">';
 9040: 
 9041:     my @srchins = ('crs','dom','alc','instd');
 9042: 
 9043:     foreach my $option (@srchins) {
 9044:         # FIXME 'alc' option unavailable until 
 9045:         #       loncreateuser::print_user_query_page()
 9046:         #       has been completed.
 9047:         next if ($option eq 'alc');
 9048:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9049:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9050:         if ($curr_selected{'srchin'} eq $option) {
 9051:             $srchinsel .= ' 
 9052:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9053:         } else {
 9054:             $srchinsel .= '
 9055:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9056:         }
 9057:     }
 9058:     $srchinsel .= "\n  </select>\n";
 9059: 
 9060:     my $srchbysel =  ' <select name="srchby">';
 9061:     foreach my $option ('lastname','lastfirst','uname') {
 9062:         if ($curr_selected{'srchby'} eq $option) {
 9063:             $srchbysel .= '
 9064:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9065:         } else {
 9066:             $srchbysel .= '
 9067:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9068:          }
 9069:     }
 9070:     $srchbysel .= "\n  </select>\n";
 9071: 
 9072:     my $srchtypesel = ' <select name="srchtype">';
 9073:     foreach my $option ('begins','contains','exact') {
 9074:         if ($curr_selected{'srchtype'} eq $option) {
 9075:             $srchtypesel .= '
 9076:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9077:         } else {
 9078:             $srchtypesel .= '
 9079:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9080:         }
 9081:     }
 9082:     $srchtypesel .= "\n  </select>\n";
 9083: 
 9084:     my ($newuserscript,$new_user_create);
 9085:     my $context_dom = $env{'request.role.domain'};
 9086:     if ($context eq 'requestcrs') {
 9087:         if ($env{'form.coursedom'} ne '') { 
 9088:             $context_dom = $env{'form.coursedom'};
 9089:         }
 9090:     }
 9091:     if ($forcenewuser) {
 9092:         if (ref($srch) eq 'HASH') {
 9093:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9094:                 if ($cancreate) {
 9095:                     $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>';
 9096:                 } else {
 9097:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9098:                     my %usertypetext = (
 9099:                         official   => 'institutional',
 9100:                         unofficial => 'non-institutional',
 9101:                     );
 9102:                     $new_user_create = '<p class="LC_warning">'
 9103:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9104:                                       .' '
 9105:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9106:                                           ,'<a href="'.$helplink.'">','</a>')
 9107:                                       .'</p><br />';
 9108:                 }
 9109:             }
 9110:         }
 9111: 
 9112:         $newuserscript = <<"ENDSCRIPT";
 9113: 
 9114: function setSearch(createnew,callingForm) {
 9115:     if (createnew == 1) {
 9116:         for (var i=0; i<callingForm.srchby.length; i++) {
 9117:             if (callingForm.srchby.options[i].value == 'uname') {
 9118:                 callingForm.srchby.selectedIndex = i;
 9119:             }
 9120:         }
 9121:         for (var i=0; i<callingForm.srchin.length; i++) {
 9122:             if ( callingForm.srchin.options[i].value == 'dom') {
 9123: 		callingForm.srchin.selectedIndex = i;
 9124:             }
 9125:         }
 9126:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9127:             if (callingForm.srchtype.options[i].value == 'exact') {
 9128:                 callingForm.srchtype.selectedIndex = i;
 9129:             }
 9130:         }
 9131:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9132:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9133:                 callingForm.srchdomain.selectedIndex = i;
 9134:             }
 9135:         }
 9136:     }
 9137: }
 9138: ENDSCRIPT
 9139: 
 9140:     }
 9141: 
 9142:     my $output = <<"END_BLOCK";
 9143: <script type="text/javascript">
 9144: // <![CDATA[
 9145: function validateEntry(callingForm) {
 9146: 
 9147:     var checkok = 1;
 9148:     var srchin;
 9149:     for (var i=0; i<callingForm.srchin.length; i++) {
 9150: 	if ( callingForm.srchin[i].checked ) {
 9151: 	    srchin = callingForm.srchin[i].value;
 9152: 	}
 9153:     }
 9154: 
 9155:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9156:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9157:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9158:     var srchterm =  callingForm.srchterm.value;
 9159:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9160:     var msg = "";
 9161: 
 9162:     if (srchterm == "") {
 9163:         checkok = 0;
 9164:         msg += "$lt{'youm'}\\n";
 9165:     }
 9166: 
 9167:     if (srchtype== 'begins') {
 9168:         if (srchterm.length < 2) {
 9169:             checkok = 0;
 9170:             msg += "$lt{'thte'}\\n";
 9171:         }
 9172:     }
 9173: 
 9174:     if (srchtype== 'contains') {
 9175:         if (srchterm.length < 3) {
 9176:             checkok = 0;
 9177:             msg += "$lt{'thet'}\\n";
 9178:         }
 9179:     }
 9180:     if (srchin == 'instd') {
 9181:         if (srchdomain == '') {
 9182:             checkok = 0;
 9183:             msg += "$lt{'yomc'}\\n";
 9184:         }
 9185:     }
 9186:     if (srchin == 'dom') {
 9187:         if (srchdomain == '') {
 9188:             checkok = 0;
 9189:             msg += "$lt{'ymcd'}\\n";
 9190:         }
 9191:     }
 9192:     if (srchby == 'lastfirst') {
 9193:         if (srchterm.indexOf(",") == -1) {
 9194:             checkok = 0;
 9195:             msg += "$lt{'whus'}\\n";
 9196:         }
 9197:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9198:             checkok = 0;
 9199:             msg += "$lt{'whse'}\\n";
 9200:         }
 9201:     }
 9202:     if (checkok == 0) {
 9203:         alert("$lt{'thfo'}\\n"+msg);
 9204:         return;
 9205:     }
 9206:     if (checkok == 1) {
 9207:         callingForm.submit();
 9208:     }
 9209: }
 9210: 
 9211: $newuserscript
 9212: 
 9213: // ]]>
 9214: </script>
 9215: 
 9216: $new_user_create
 9217: 
 9218: END_BLOCK
 9219: 
 9220:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9221:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9222:                $domform.
 9223:                &Apache::lonhtmlcommon::row_closure().
 9224:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9225:                $srchbysel.
 9226:                $srchtypesel. 
 9227:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9228:                $srchinsel.
 9229:                &Apache::lonhtmlcommon::row_closure(1). 
 9230:                &Apache::lonhtmlcommon::end_pick_box().
 9231:                '<br />';
 9232:     return $output;
 9233: }
 9234: 
 9235: sub user_rule_check {
 9236:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9237:     my $response;
 9238:     if (ref($usershash) eq 'HASH') {
 9239:         foreach my $user (keys(%{$usershash})) {
 9240:             my ($uname,$udom) = split(/:/,$user);
 9241:             next if ($udom eq '' || $uname eq '');
 9242:             my ($id,$newuser);
 9243:             if (ref($usershash->{$user}) eq 'HASH') {
 9244:                 $newuser = $usershash->{$user}->{'newuser'};
 9245:                 $id = $usershash->{$user}->{'id'};
 9246:             }
 9247:             my $inst_response;
 9248:             if (ref($checks) eq 'HASH') {
 9249:                 if (defined($checks->{'username'})) {
 9250:                     ($inst_response,%{$inst_results->{$user}}) = 
 9251:                         &Apache::lonnet::get_instuser($udom,$uname);
 9252:                 } elsif (defined($checks->{'id'})) {
 9253:                     ($inst_response,%{$inst_results->{$user}}) =
 9254:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9255:                 }
 9256:             } else {
 9257:                 ($inst_response,%{$inst_results->{$user}}) =
 9258:                     &Apache::lonnet::get_instuser($udom,$uname);
 9259:                 return;
 9260:             }
 9261:             if (!$got_rules->{$udom}) {
 9262:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9263:                                                   ['usercreation'],$udom);
 9264:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9265:                     foreach my $item ('username','id') {
 9266:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9267:                             $$curr_rules{$udom}{$item} = 
 9268:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9269:                         }
 9270:                     }
 9271:                 }
 9272:                 $got_rules->{$udom} = 1;  
 9273:             }
 9274:             foreach my $item (keys(%{$checks})) {
 9275:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9276:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9277:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9278:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9279:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9280:                                 if ($rule_check{$rule}) {
 9281:                                     $$rulematch{$user}{$item} = $rule;
 9282:                                     if ($inst_response eq 'ok') {
 9283:                                         if (ref($inst_results) eq 'HASH') {
 9284:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9285:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9286:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9287:                                                 }
 9288:                                             }
 9289:                                         }
 9290:                                     }
 9291:                                     last;
 9292:                                 }
 9293:                             }
 9294:                         }
 9295:                     }
 9296:                 }
 9297:             }
 9298:         }
 9299:     }
 9300:     return;
 9301: }
 9302: 
 9303: sub user_rule_formats {
 9304:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9305:     my %text = ( 
 9306:                  'username' => 'Usernames',
 9307:                  'id'       => 'IDs',
 9308:                );
 9309:     my $output;
 9310:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9311:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9312:         if (@{$ruleorder} > 0) {
 9313:             $output = '<br />'.
 9314:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9315:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9316:                       ' <ul>';
 9317:             foreach my $rule (@{$ruleorder}) {
 9318:                 if (ref($curr_rules) eq 'ARRAY') {
 9319:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9320:                         if (ref($rules->{$rule}) eq 'HASH') {
 9321:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9322:                                         $rules->{$rule}{'desc'}.'</li>';
 9323:                         }
 9324:                     }
 9325:                 }
 9326:             }
 9327:             $output .= '</ul>';
 9328:         }
 9329:     }
 9330:     return $output;
 9331: }
 9332: 
 9333: sub instrule_disallow_msg {
 9334:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9335:     my $response;
 9336:     my %text = (
 9337:                   item   => 'username',
 9338:                   items  => 'usernames',
 9339:                   match  => 'matches',
 9340:                   do     => 'does',
 9341:                   action => 'a username',
 9342:                   one    => 'one',
 9343:                );
 9344:     if ($count > 1) {
 9345:         $text{'item'} = 'usernames';
 9346:         $text{'match'} ='match';
 9347:         $text{'do'} = 'do';
 9348:         $text{'action'} = 'usernames',
 9349:         $text{'one'} = 'ones';
 9350:     }
 9351:     if ($checkitem eq 'id') {
 9352:         $text{'items'} = 'IDs';
 9353:         $text{'item'} = 'ID';
 9354:         $text{'action'} = 'an ID';
 9355:         if ($count > 1) {
 9356:             $text{'item'} = 'IDs';
 9357:             $text{'action'} = 'IDs';
 9358:         }
 9359:     }
 9360:     $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 />';
 9361:     if ($mode eq 'upload') {
 9362:         if ($checkitem eq 'username') {
 9363:             $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'}.");
 9364:         } elsif ($checkitem eq 'id') {
 9365:             $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.");
 9366:         }
 9367:     } elsif ($mode eq 'selfcreate') {
 9368:         if ($checkitem eq 'id') {
 9369:             $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.");
 9370:         }
 9371:     } else {
 9372:         if ($checkitem eq 'username') {
 9373:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9374:         } elsif ($checkitem eq 'id') {
 9375:             $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.");
 9376:         }
 9377:     }
 9378:     return $response;
 9379: }
 9380: 
 9381: sub personal_data_fieldtitles {
 9382:     my %fieldtitles = &Apache::lonlocal::texthash (
 9383:                         id => 'Student/Employee ID',
 9384:                         permanentemail => 'E-mail address',
 9385:                         lastname => 'Last Name',
 9386:                         firstname => 'First Name',
 9387:                         middlename => 'Middle Name',
 9388:                         generation => 'Generation',
 9389:                         gen => 'Generation',
 9390:                         inststatus => 'Affiliation',
 9391:                    );
 9392:     return %fieldtitles;
 9393: }
 9394: 
 9395: sub sorted_inst_types {
 9396:     my ($dom) = @_;
 9397:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9398:     my $othertitle = &mt('All users');
 9399:     if ($env{'request.course.id'}) {
 9400:         $othertitle  = &mt('Any users');
 9401:     }
 9402:     my @types;
 9403:     if (ref($order) eq 'ARRAY') {
 9404:         @types = @{$order};
 9405:     }
 9406:     if (@types == 0) {
 9407:         if (ref($usertypes) eq 'HASH') {
 9408:             @types = sort(keys(%{$usertypes}));
 9409:         }
 9410:     }
 9411:     if (keys(%{$usertypes}) > 0) {
 9412:         $othertitle = &mt('Other users');
 9413:     }
 9414:     return ($othertitle,$usertypes,\@types);
 9415: }
 9416: 
 9417: sub get_institutional_codes {
 9418:     my ($settings,$allcourses,$LC_code) = @_;
 9419: # Get complete list of course sections to update
 9420:     my @currsections = ();
 9421:     my @currxlists = ();
 9422:     my $coursecode = $$settings{'internal.coursecode'};
 9423: 
 9424:     if ($$settings{'internal.sectionnums'} ne '') {
 9425:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9426:     }
 9427: 
 9428:     if ($$settings{'internal.crosslistings'} ne '') {
 9429:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9430:     }
 9431: 
 9432:     if (@currxlists > 0) {
 9433:         foreach (@currxlists) {
 9434:             if (m/^([^:]+):(\w*)$/) {
 9435:                 unless (grep/^$1$/,@{$allcourses}) {
 9436:                     push @{$allcourses},$1;
 9437:                     $$LC_code{$1} = $2;
 9438:                 }
 9439:             }
 9440:         }
 9441:     }
 9442:  
 9443:     if (@currsections > 0) {
 9444:         foreach (@currsections) {
 9445:             if (m/^(\w+):(\w*)$/) {
 9446:                 my $sec = $coursecode.$1;
 9447:                 my $lc_sec = $2;
 9448:                 unless (grep/^$sec$/,@{$allcourses}) {
 9449:                     push @{$allcourses},$sec;
 9450:                     $$LC_code{$sec} = $lc_sec;
 9451:                 }
 9452:             }
 9453:         }
 9454:     }
 9455:     return;
 9456: }
 9457: 
 9458: sub get_standard_codeitems {
 9459:     return ('Year','Semester','Department','Number','Section');
 9460: }
 9461: 
 9462: =pod
 9463: 
 9464: =head1 Slot Helpers
 9465: 
 9466: =over 4
 9467: 
 9468: =item * sorted_slots()
 9469: 
 9470: Sorts an array of slot names in order of an optional sort key,
 9471: default sort is by slot start time (earliest first). 
 9472: 
 9473: Inputs:
 9474: 
 9475: =over 4
 9476: 
 9477: slotsarr  - Reference to array of unsorted slot names.
 9478: 
 9479: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9480: 
 9481: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9482: 
 9483: =back
 9484: 
 9485: Returns:
 9486: 
 9487: =over 4
 9488: 
 9489: sorted   - An array of slot names sorted by a specified sort key 
 9490:            (default sort key is start time of the slot).
 9491: 
 9492: =back
 9493: 
 9494: =cut
 9495: 
 9496: 
 9497: sub sorted_slots {
 9498:     my ($slotsarr,$slots,$sortkey) = @_;
 9499:     if ($sortkey eq '') {
 9500:         $sortkey = 'starttime';
 9501:     }
 9502:     my @sorted;
 9503:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9504:         @sorted =
 9505:             sort {
 9506:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9507:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9508:                      }
 9509:                      if (ref($slots->{$a})) { return -1;}
 9510:                      if (ref($slots->{$b})) { return 1;}
 9511:                      return 0;
 9512:                  } @{$slotsarr};
 9513:     }
 9514:     return @sorted;
 9515: }
 9516: 
 9517: =pod
 9518: 
 9519: =item * get_future_slots()
 9520: 
 9521: Inputs:
 9522: 
 9523: =over 4
 9524: 
 9525: cnum - course number
 9526: 
 9527: cdom - course domain
 9528: 
 9529: now - current UNIX time
 9530: 
 9531: symb - optional symb
 9532: 
 9533: =back
 9534: 
 9535: Returns:
 9536: 
 9537: =over 4
 9538: 
 9539: sorted_reservable - ref to array of student_schedulable slots currently 
 9540:                     reservable, ordered by end date of reservation period.
 9541: 
 9542: reservable_now - ref to hash of student_schedulable slots currently
 9543:                  reservable.
 9544: 
 9545:     Keys in inner hash are:
 9546:     (a) symb: either blank or symb to which slot use is restricted.
 9547:     (b) endreserve: end date of reservation period. 
 9548: 
 9549: sorted_future - ref to array of student_schedulable slots reservable in
 9550:                 the future, ordered by start date of reservation period.
 9551: 
 9552: future_reservable - ref to hash of student_schedulable slots reservable
 9553:                     in the future.
 9554: 
 9555:     Keys in inner hash are:
 9556:     (a) symb: either blank or symb to which slot use is restricted.
 9557:     (b) startreserve:  start date of reservation period.
 9558: 
 9559: =back
 9560: 
 9561: =cut
 9562: 
 9563: sub get_future_slots {
 9564:     my ($cnum,$cdom,$now,$symb) = @_;
 9565:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9566:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9567:     foreach my $slot (keys(%slots)) {
 9568:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9569:         if ($symb) {
 9570:             next if (($slots{$slot}->{'symb'} ne '') && 
 9571:                      ($slots{$slot}->{'symb'} ne $symb));
 9572:         }
 9573:         if (($slots{$slot}->{'starttime'} > $now) &&
 9574:             ($slots{$slot}->{'endtime'} > $now)) {
 9575:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9576:                 my $userallowed = 0;
 9577:                 if ($slots{$slot}->{'allowedsections'}) {
 9578:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9579:                     if (!defined($env{'request.role.sec'})
 9580:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9581:                         $userallowed=1;
 9582:                     } else {
 9583:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9584:                             $userallowed=1;
 9585:                         }
 9586:                     }
 9587:                     unless ($userallowed) {
 9588:                         if (defined($env{'request.course.groups'})) {
 9589:                             my @groups = split(/:/,$env{'request.course.groups'});
 9590:                             foreach my $group (@groups) {
 9591:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9592:                                     $userallowed=1;
 9593:                                     last;
 9594:                                 }
 9595:                             }
 9596:                         }
 9597:                     }
 9598:                 }
 9599:                 if ($slots{$slot}->{'allowedusers'}) {
 9600:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9601:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9602:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9603:                         $userallowed = 1;
 9604:                     }
 9605:                 }
 9606:                 next unless($userallowed);
 9607:             }
 9608:             my $startreserve = $slots{$slot}->{'startreserve'};
 9609:             my $endreserve = $slots{$slot}->{'endreserve'};
 9610:             my $symb = $slots{$slot}->{'symb'};
 9611:             if (($startreserve < $now) &&
 9612:                 (!$endreserve || $endreserve > $now)) {
 9613:                 my $lastres = $endreserve;
 9614:                 if (!$lastres) {
 9615:                     $lastres = $slots{$slot}->{'starttime'};
 9616:                 }
 9617:                 $reservable_now{$slot} = {
 9618:                                            symb       => $symb,
 9619:                                            endreserve => $lastres
 9620:                                          };
 9621:             } elsif (($startreserve > $now) &&
 9622:                      (!$endreserve || $endreserve > $startreserve)) {
 9623:                 $future_reservable{$slot} = {
 9624:                                               symb         => $symb,
 9625:                                               startreserve => $startreserve
 9626:                                             };
 9627:             }
 9628:         }
 9629:     }
 9630:     my @unsorted_reservable = keys(%reservable_now);
 9631:     if (@unsorted_reservable > 0) {
 9632:         @sorted_reservable = 
 9633:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9634:     }
 9635:     my @unsorted_future = keys(%future_reservable);
 9636:     if (@unsorted_future > 0) {
 9637:         @sorted_future =
 9638:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9639:     }
 9640:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9641: }
 9642: 
 9643: =pod
 9644: 
 9645: =back
 9646: 
 9647: =head1 HTTP Helpers
 9648: 
 9649: =over 4
 9650: 
 9651: =item * &get_unprocessed_cgi($query,$possible_names)
 9652: 
 9653: Modify the %env hash to contain unprocessed CGI form parameters held in
 9654: $query.  The parameters listed in $possible_names (an array reference),
 9655: will be set in $env{'form.name'} if they do not already exist.
 9656: 
 9657: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9658: $possible_names is an ref to an array of form element names.  As an example:
 9659: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9660: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9661: 
 9662: =cut
 9663: 
 9664: sub get_unprocessed_cgi {
 9665:   my ($query,$possible_names)= @_;
 9666:   # $Apache::lonxml::debug=1;
 9667:   foreach my $pair (split(/&/,$query)) {
 9668:     my ($name, $value) = split(/=/,$pair);
 9669:     $name = &unescape($name);
 9670:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9671:       $value =~ tr/+/ /;
 9672:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9673:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9674:     }
 9675:   }
 9676: }
 9677: 
 9678: =pod
 9679: 
 9680: =item * &cacheheader() 
 9681: 
 9682: returns cache-controlling header code
 9683: 
 9684: =cut
 9685: 
 9686: sub cacheheader {
 9687:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9688:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9689:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9690:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9691:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9692:     return $output;
 9693: }
 9694: 
 9695: =pod
 9696: 
 9697: =item * &no_cache($r) 
 9698: 
 9699: specifies header code to not have cache
 9700: 
 9701: =cut
 9702: 
 9703: sub no_cache {
 9704:     my ($r) = @_;
 9705:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9706: 	$env{'request.method'} ne 'GET') { return ''; }
 9707:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9708:     $r->no_cache(1);
 9709:     $r->header_out("Expires" => $date);
 9710:     $r->header_out("Pragma" => "no-cache");
 9711: }
 9712: 
 9713: sub content_type {
 9714:     my ($r,$type,$charset) = @_;
 9715:     if ($r) {
 9716: 	#  Note that printout.pl calls this with undef for $r.
 9717: 	&no_cache($r);
 9718:     }
 9719:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9720:     unless ($charset) {
 9721: 	$charset=&Apache::lonlocal::current_encoding;
 9722:     }
 9723:     if ($charset) { $type.='; charset='.$charset; }
 9724:     if ($r) {
 9725: 	$r->content_type($type);
 9726:     } else {
 9727: 	print("Content-type: $type\n\n");
 9728:     }
 9729: }
 9730: 
 9731: =pod
 9732: 
 9733: =item * &add_to_env($name,$value) 
 9734: 
 9735: adds $name to the %env hash with value
 9736: $value, if $name already exists, the entry is converted to an array
 9737: reference and $value is added to the array.
 9738: 
 9739: =cut
 9740: 
 9741: sub add_to_env {
 9742:   my ($name,$value)=@_;
 9743:   if (defined($env{$name})) {
 9744:     if (ref($env{$name})) {
 9745:       #already have multiple values
 9746:       push(@{ $env{$name} },$value);
 9747:     } else {
 9748:       #first time seeing multiple values, convert hash entry to an arrayref
 9749:       my $first=$env{$name};
 9750:       undef($env{$name});
 9751:       push(@{ $env{$name} },$first,$value);
 9752:     }
 9753:   } else {
 9754:     $env{$name}=$value;
 9755:   }
 9756: }
 9757: 
 9758: =pod
 9759: 
 9760: =item * &get_env_multiple($name) 
 9761: 
 9762: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9763: values may be defined and end up as an array ref.
 9764: 
 9765: returns an array of values
 9766: 
 9767: =cut
 9768: 
 9769: sub get_env_multiple {
 9770:     my ($name) = @_;
 9771:     my @values;
 9772:     if (defined($env{$name})) {
 9773:         # exists is it an array
 9774:         if (ref($env{$name})) {
 9775:             @values=@{ $env{$name} };
 9776:         } else {
 9777:             $values[0]=$env{$name};
 9778:         }
 9779:     }
 9780:     return(@values);
 9781: }
 9782: 
 9783: sub ask_for_embedded_content {
 9784:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9785:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9786:         %currsubfile,%unused,$rem);
 9787:     my $counter = 0;
 9788:     my $numnew = 0;
 9789:     my $numremref = 0;
 9790:     my $numinvalid = 0;
 9791:     my $numpathchg = 0;
 9792:     my $numexisting = 0;
 9793:     my $numunused = 0;
 9794:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9795:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
 9796:     my $heading = &mt('Upload embedded files');
 9797:     my $buttontext = &mt('Upload');
 9798: 
 9799:     if ($env{'request.course.id'}) {
 9800:         if ($actionurl eq '/adm/dependencies') {
 9801:             $navmap = Apache::lonnavmaps::navmap->new();
 9802:         }
 9803:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9804:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9805:     }
 9806:     if (($actionurl eq '/adm/portfolio') ||
 9807:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9808:         my $current_path='/';
 9809:         if ($env{'form.currentpath'}) {
 9810:             $current_path = $env{'form.currentpath'};
 9811:         }
 9812:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9813:             $udom = $cdom;
 9814:             $uname = $cnum;
 9815:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9816:         } else {
 9817:             $udom = $env{'user.domain'};
 9818:             $uname = $env{'user.name'};
 9819:             $url = '/userfiles/portfolio';
 9820:         }
 9821:         $toplevel = $url.'/';
 9822:         $url .= $current_path;
 9823:         $getpropath = 1;
 9824:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9825:              ($actionurl eq '/adm/imsimport')) { 
 9826:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9827:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9828:         $toplevel = $url;
 9829:         if ($rest ne '') {
 9830:             $url .= $rest;
 9831:         }
 9832:     } elsif ($actionurl eq '/adm/coursedocs') {
 9833:         if (ref($args) eq 'HASH') {
 9834:             $url = $args->{'docs_url'};
 9835:             $toplevel = $url;
 9836:             if ($args->{'context'} eq 'paste') {
 9837:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9838:                 ($path) =
 9839:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9840:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9841:                 $fileloc =~ s{^/}{};
 9842:             }
 9843:         }
 9844:     } elsif ($actionurl eq '/adm/dependencies') {
 9845:         if ($env{'request.course.id'} ne '') {
 9846:             if (ref($args) eq 'HASH') {
 9847:                 $url = $args->{'docs_url'};
 9848:                 $title = $args->{'docs_title'};
 9849:                 $toplevel = $url;
 9850:                 unless ($toplevel =~ m{^/}) {
 9851:                     $toplevel = "/$url";
 9852:                 }
 9853:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9854:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
 9855:                     $path = $1;
 9856:                 } else {
 9857:                     ($path) =
 9858:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9859:                 }
 9860:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9861:                 $fileloc =~ s{^/}{};
 9862:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9863:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9864:             }
 9865:         }
 9866:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9867:         $udom = $cdom;
 9868:         $uname = $cnum;
 9869:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
 9870:         $toplevel = $url;
 9871:         $path = $url;
 9872:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
 9873:         $fileloc =~ s{^/}{};
 9874:     }
 9875:     foreach my $file (keys(%{$allfiles})) {
 9876:         my $embed_file;
 9877:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
 9878:             $embed_file = $1;
 9879:         } else {
 9880:             $embed_file = $file;
 9881:         }
 9882:         my ($absolutepath,$cleaned_file);
 9883:         if ($embed_file =~ m{^\w+://}) {
 9884:             $cleaned_file = $embed_file;
 9885:             $newfiles{$cleaned_file} = 1;
 9886:             $mapping{$cleaned_file} = $embed_file;
 9887:         } else {
 9888:             $cleaned_file = &clean_path($embed_file);
 9889:             if ($embed_file =~ m{^/}) {
 9890:                 $absolutepath = $embed_file;
 9891:             }
 9892:             if ($cleaned_file =~ m{/}) {
 9893:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
 9894:                 $path = &check_for_traversal($path,$url,$toplevel);
 9895:                 my $item = $fname;
 9896:                 if ($path ne '') {
 9897:                     $item = $path.'/'.$fname;
 9898:                     $subdependencies{$path}{$fname} = 1;
 9899:                 } else {
 9900:                     $dependencies{$item} = 1;
 9901:                 }
 9902:                 if ($absolutepath) {
 9903:                     $mapping{$item} = $absolutepath;
 9904:                 } else {
 9905:                     $mapping{$item} = $embed_file;
 9906:                 }
 9907:             } else {
 9908:                 $dependencies{$embed_file} = 1;
 9909:                 if ($absolutepath) {
 9910:                     $mapping{$cleaned_file} = $absolutepath;
 9911:                 } else {
 9912:                     $mapping{$cleaned_file} = $embed_file;
 9913:                 }
 9914:             }
 9915:         }
 9916:     }
 9917:     my $dirptr = 16384;
 9918:     foreach my $path (keys(%subdependencies)) {
 9919:         $currsubfile{$path} = {};
 9920:         if (($actionurl eq '/adm/portfolio') ||
 9921:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9922:             my ($sublistref,$listerror) =
 9923:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9924:             if (ref($sublistref) eq 'ARRAY') {
 9925:                 foreach my $line (@{$sublistref}) {
 9926:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9927:                     $currsubfile{$path}{$file_name} = 1;
 9928:                 }
 9929:             }
 9930:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9931:             if (opendir(my $dir,$url.'/'.$path)) {
 9932:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9933:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9934:             }
 9935:         } elsif (($actionurl eq '/adm/dependencies') ||
 9936:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9937:                   ($args->{'context'} eq 'paste')) ||
 9938:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9939:             if ($env{'request.course.id'} ne '') {
 9940:                 my $dir;
 9941:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9942:                     $dir = $fileloc;
 9943:                 } else {
 9944:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9945:                 }
 9946:                 if ($dir ne '') {
 9947:                     my ($sublistref,$listerror) =
 9948:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9949:                     if (ref($sublistref) eq 'ARRAY') {
 9950:                         foreach my $line (@{$sublistref}) {
 9951:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9952:                                 undef,$mtime)=split(/\&/,$line,12);
 9953:                             unless (($testdir&$dirptr) ||
 9954:                                     ($file_name =~ /^\.\.?$/)) {
 9955:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9956:                             }
 9957:                         }
 9958:                     }
 9959:                 }
 9960:             }
 9961:         }
 9962:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9963:             if (exists($currsubfile{$path}{$file})) {
 9964:                 my $item = $path.'/'.$file;
 9965:                 unless ($mapping{$item} eq $item) {
 9966:                     $pathchanges{$item} = 1;
 9967:                 }
 9968:                 $existing{$item} = 1;
 9969:                 $numexisting ++;
 9970:             } else {
 9971:                 $newfiles{$path.'/'.$file} = 1;
 9972:             }
 9973:         }
 9974:         if ($actionurl eq '/adm/dependencies') {
 9975:             foreach my $path (keys(%currsubfile)) {
 9976:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9977:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9978:                          unless ($subdependencies{$path}{$file}) {
 9979:                              next if (($rem ne '') &&
 9980:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9981:                                        (ref($navmap) &&
 9982:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9983:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9984:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9985:                              $unused{$path.'/'.$file} = 1; 
 9986:                          }
 9987:                     }
 9988:                 }
 9989:             }
 9990:         }
 9991:     }
 9992:     my %currfile;
 9993:     if (($actionurl eq '/adm/portfolio') ||
 9994:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9995:         my ($dirlistref,$listerror) =
 9996:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9997:         if (ref($dirlistref) eq 'ARRAY') {
 9998:             foreach my $line (@{$dirlistref}) {
 9999:                 my ($file_name,$rest) = split(/\&/,$line,2);
10000:                 $currfile{$file_name} = 1;
10001:             }
10002:         }
10003:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10004:         if (opendir(my $dir,$url)) {
10005:             my @dir_list = grep(!/^\./,readdir($dir));
10006:             map {$currfile{$_} = 1;} @dir_list;
10007:         }
10008:     } elsif (($actionurl eq '/adm/dependencies') ||
10009:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10010:               ($args->{'context'} eq 'paste')) ||
10011:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10012:         if ($env{'request.course.id'} ne '') {
10013:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10014:             if ($dir ne '') {
10015:                 my ($dirlistref,$listerror) =
10016:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10017:                 if (ref($dirlistref) eq 'ARRAY') {
10018:                     foreach my $line (@{$dirlistref}) {
10019:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10020:                             $size,undef,$mtime)=split(/\&/,$line,12);
10021:                         unless (($testdir&$dirptr) ||
10022:                                 ($file_name =~ /^\.\.?$/)) {
10023:                             $currfile{$file_name} = [$size,$mtime];
10024:                         }
10025:                     }
10026:                 }
10027:             }
10028:         }
10029:     }
10030:     foreach my $file (keys(%dependencies)) {
10031:         if (exists($currfile{$file})) {
10032:             unless ($mapping{$file} eq $file) {
10033:                 $pathchanges{$file} = 1;
10034:             }
10035:             $existing{$file} = 1;
10036:             $numexisting ++;
10037:         } else {
10038:             $newfiles{$file} = 1;
10039:         }
10040:     }
10041:     foreach my $file (keys(%currfile)) {
10042:         unless (($file eq $filename) ||
10043:                 ($file eq $filename.'.bak') ||
10044:                 ($dependencies{$file})) {
10045:             if ($actionurl eq '/adm/dependencies') {
10046:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10047:                     next if (($rem ne '') &&
10048:                              (($env{"httpref.$rem".$file} ne '') ||
10049:                               (ref($navmap) &&
10050:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10051:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10052:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10053:                 }
10054:             }
10055:             $unused{$file} = 1;
10056:         }
10057:     }
10058:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10059:         ($args->{'context'} eq 'paste')) {
10060:         $counter = scalar(keys(%existing));
10061:         $numpathchg = scalar(keys(%pathchanges));
10062:         return ($output,$counter,$numpathchg,\%existing);
10063:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10064:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10065:         $counter = scalar(keys(%existing));
10066:         $numpathchg = scalar(keys(%pathchanges));
10067:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10068:     }
10069:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10070:         if ($actionurl eq '/adm/dependencies') {
10071:             next if ($embed_file =~ m{^\w+://});
10072:         }
10073:         $upload_output .= &start_data_table_row().
10074:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10075:                           '<span class="LC_filename">'.$embed_file.'</span>';
10076:         unless ($mapping{$embed_file} eq $embed_file) {
10077:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10078:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10079:         }
10080:         $upload_output .= '</td>';
10081:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10082:             $upload_output.='<td align="right">'.
10083:                             '<span class="LC_info LC_fontsize_medium">'.
10084:                             &mt("URL points to web address").'</span>';
10085:             $numremref++;
10086:         } elsif ($args->{'error_on_invalid_names'}
10087:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10088:             $upload_output.='<td align="right"><span class="LC_warning">'.
10089:                             &mt('Invalid characters').'</span>';
10090:             $numinvalid++;
10091:         } else {
10092:             $upload_output .= '<td>'.
10093:                               &embedded_file_element('upload_embedded',$counter,
10094:                                                      $embed_file,\%mapping,
10095:                                                      $allfiles,$codebase,'upload');
10096:             $counter ++;
10097:             $numnew ++;
10098:         }
10099:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10100:     }
10101:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10102:         if ($actionurl eq '/adm/dependencies') {
10103:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10104:             $modify_output .= &start_data_table_row().
10105:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10106:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10107:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10108:                               '<td>'.$size.'</td>'.
10109:                               '<td>'.$mtime.'</td>'.
10110:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10111:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10112:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10113:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10114:                               &embedded_file_element('upload_embedded',$counter,
10115:                                                      $embed_file,\%mapping,
10116:                                                      $allfiles,$codebase,'modify').
10117:                               '</div></td>'.
10118:                               &end_data_table_row()."\n";
10119:             $counter ++;
10120:         } else {
10121:             $upload_output .= &start_data_table_row().
10122:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10123:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10124:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10125:                               &Apache::loncommon::end_data_table_row()."\n";
10126:         }
10127:     }
10128:     my $delidx = $counter;
10129:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10130:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10131:         $delete_output .= &start_data_table_row().
10132:                           '<td><img src="'.&icon($oldfile).'" />'.
10133:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10134:                           '<td>'.$size.'</td>'.
10135:                           '<td>'.$mtime.'</td>'.
10136:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10137:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10138:                           &embedded_file_element('upload_embedded',$delidx,
10139:                                                  $oldfile,\%mapping,$allfiles,
10140:                                                  $codebase,'delete').'</td>'.
10141:                           &end_data_table_row()."\n"; 
10142:         $numunused ++;
10143:         $delidx ++;
10144:     }
10145:     if ($upload_output) {
10146:         $upload_output = &start_data_table().
10147:                          $upload_output.
10148:                          &end_data_table()."\n";
10149:     }
10150:     if ($modify_output) {
10151:         $modify_output = &start_data_table().
10152:                          &start_data_table_header_row().
10153:                          '<th>'.&mt('File').'</th>'.
10154:                          '<th>'.&mt('Size (KB)').'</th>'.
10155:                          '<th>'.&mt('Modified').'</th>'.
10156:                          '<th>'.&mt('Upload replacement?').'</th>'.
10157:                          &end_data_table_header_row().
10158:                          $modify_output.
10159:                          &end_data_table()."\n";
10160:     }
10161:     if ($delete_output) {
10162:         $delete_output = &start_data_table().
10163:                          &start_data_table_header_row().
10164:                          '<th>'.&mt('File').'</th>'.
10165:                          '<th>'.&mt('Size (KB)').'</th>'.
10166:                          '<th>'.&mt('Modified').'</th>'.
10167:                          '<th>'.&mt('Delete?').'</th>'.
10168:                          &end_data_table_header_row().
10169:                          $delete_output.
10170:                          &end_data_table()."\n";
10171:     }
10172:     my $applies = 0;
10173:     if ($numremref) {
10174:         $applies ++;
10175:     }
10176:     if ($numinvalid) {
10177:         $applies ++;
10178:     }
10179:     if ($numexisting) {
10180:         $applies ++;
10181:     }
10182:     if ($counter || $numunused) {
10183:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10184:                   ' method="post" enctype="multipart/form-data">'."\n".
10185:                   $state.'<h3>'.$heading.'</h3>'; 
10186:         if ($actionurl eq '/adm/dependencies') {
10187:             if ($numnew) {
10188:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10189:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10190:                            $upload_output.'<br />'."\n";
10191:             }
10192:             if ($numexisting) {
10193:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10194:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10195:                            $modify_output.'<br />'."\n";
10196:                            $buttontext = &mt('Save changes');
10197:             }
10198:             if ($numunused) {
10199:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10200:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10201:                            $delete_output.'<br />'."\n";
10202:                            $buttontext = &mt('Save changes');
10203:             }
10204:         } else {
10205:             $output .= $upload_output.'<br />'."\n";
10206:         }
10207:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10208:                    $counter.'" />'."\n";
10209:         if ($actionurl eq '/adm/dependencies') { 
10210:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10211:                        $numnew.'" />'."\n";
10212:         } elsif ($actionurl eq '') {
10213:             $output .=  '<input type="hidden" name="phase" value="three" />';
10214:         }
10215:     } elsif ($applies) {
10216:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10217:         if ($applies > 1) {
10218:             $output .=  
10219:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10220:             if ($numremref) {
10221:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10222:             }
10223:             if ($numinvalid) {
10224:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10225:             }
10226:             if ($numexisting) {
10227:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10228:             }
10229:             $output .= '</ul><br />';
10230:         } elsif ($numremref) {
10231:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10232:         } elsif ($numinvalid) {
10233:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10234:         } elsif ($numexisting) {
10235:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10236:         }
10237:         $output .= $upload_output.'<br />';
10238:     }
10239:     my ($pathchange_output,$chgcount);
10240:     $chgcount = $counter;
10241:     if (keys(%pathchanges) > 0) {
10242:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10243:             if ($counter) {
10244:                 $output .= &embedded_file_element('pathchange',$chgcount,
10245:                                                   $embed_file,\%mapping,
10246:                                                   $allfiles,$codebase,'change');
10247:             } else {
10248:                 $pathchange_output .= 
10249:                     &start_data_table_row().
10250:                     '<td><input type ="checkbox" name="namechange" value="'.
10251:                     $chgcount.'" checked="checked" /></td>'.
10252:                     '<td>'.$mapping{$embed_file}.'</td>'.
10253:                     '<td>'.$embed_file.
10254:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10255:                                            \%mapping,$allfiles,$codebase,'change').
10256:                     '</td>'.&end_data_table_row();
10257:             }
10258:             $numpathchg ++;
10259:             $chgcount ++;
10260:         }
10261:     }
10262:     if (($counter) || ($numunused)) {
10263:         if ($numpathchg) {
10264:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10265:                        $numpathchg.'" />'."\n";
10266:         }
10267:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10268:             ($actionurl eq '/adm/imsimport')) {
10269:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10270:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10271:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10272:         } elsif ($actionurl eq '/adm/dependencies') {
10273:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10274:         }
10275:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10276:     } elsif ($numpathchg) {
10277:         my %pathchange = ();
10278:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10279:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10280:             $output .= '<p>'.&mt('or').'</p>'; 
10281:         }
10282:     }
10283:     return ($output,$counter,$numpathchg);
10284: }
10285: 
10286: =pod
10287: 
10288: =item * clean_path($name)
10289: 
10290: Performs clean-up of directories, subdirectories and filename in an
10291: embedded object, referenced in an HTML file which is being uploaded
10292: to a course or portfolio, where
10293: "Upload embedded images/multimedia files if HTML file" checkbox was
10294: checked.
10295: 
10296: Clean-up is similar to replacements in lonnet::clean_filename()
10297: except each / between sub-directory and next level is preserved.
10298: 
10299: =cut
10300: 
10301: sub clean_path {
10302:     my ($embed_file) = @_;
10303:     $embed_file =~s{^/+}{};
10304:     my @contents;
10305:     if ($embed_file =~ m{/}) {
10306:         @contents = split(/\//,$embed_file);
10307:     } else {
10308:         @contents = ($embed_file);
10309:     }
10310:     my $lastidx = scalar(@contents)-1;
10311:     for (my $i=0; $i<=$lastidx; $i++) {
10312:         $contents[$i]=~s{\\}{/}g;
10313:         $contents[$i]=~s/\s+/\_/g;
10314:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10315:         if ($i == $lastidx) {
10316:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10317:         }
10318:     }
10319:     if ($lastidx > 0) {
10320:         return join('/',@contents);
10321:     } else {
10322:         return $contents[0];
10323:     }
10324: }
10325: 
10326: sub embedded_file_element {
10327:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10328:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10329:                    (ref($codebase) eq 'HASH'));
10330:     my $output;
10331:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10332:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10333:     }
10334:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10335:                &escape($embed_file).'" />';
10336:     unless (($context eq 'upload_embedded') && 
10337:             ($mapping->{$embed_file} eq $embed_file)) {
10338:         $output .='
10339:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10340:     }
10341:     my $attrib;
10342:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10343:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10344:     }
10345:     $output .=
10346:         "\n\t\t".
10347:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10348:         $attrib.'" />';
10349:     if (exists($codebase->{$mapping->{$embed_file}})) {
10350:         $output .=
10351:             "\n\t\t".
10352:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10353:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10354:     }
10355:     return $output;
10356: }
10357: 
10358: sub get_dependency_details {
10359:     my ($currfile,$currsubfile,$embed_file) = @_;
10360:     my ($size,$mtime,$showsize,$showmtime);
10361:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10362:         if ($embed_file =~ m{/}) {
10363:             my ($path,$fname) = split(/\//,$embed_file);
10364:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10365:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10366:             }
10367:         } else {
10368:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10369:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10370:             }
10371:         }
10372:         $showsize = $size/1024.0;
10373:         $showsize = sprintf("%.1f",$showsize);
10374:         if ($mtime > 0) {
10375:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10376:         }
10377:     }
10378:     return ($showsize,$showmtime);
10379: }
10380: 
10381: sub ask_embedded_js {
10382:     return <<"END";
10383: <script type="text/javascript"">
10384: // <![CDATA[
10385: function toggleBrowse(counter) {
10386:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10387:     var fileid = document.getElementById('embedded_item_'+counter);
10388:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10389:     if (chkboxid.checked == true) {
10390:         uploaddivid.style.display='block';
10391:     } else {
10392:         uploaddivid.style.display='none';
10393:         fileid.value = '';
10394:     }
10395: }
10396: // ]]>
10397: </script>
10398: 
10399: END
10400: }
10401: 
10402: sub upload_embedded {
10403:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10404:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10405:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10406:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10407:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10408:         my $orig_uploaded_filename =
10409:             $env{'form.embedded_item_'.$i.'.filename'};
10410:         foreach my $type ('orig','ref','attrib','codebase') {
10411:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10412:                 $env{'form.embedded_'.$type.'_'.$i} =
10413:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10414:             }
10415:         }
10416:         my ($path,$fname) =
10417:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10418:         # no path, whole string is fname
10419:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10420:         $fname = &Apache::lonnet::clean_filename($fname);
10421:         # See if there is anything left
10422:         next if ($fname eq '');
10423: 
10424:         # Check if file already exists as a file or directory.
10425:         my ($state,$msg);
10426:         if ($context eq 'portfolio') {
10427:             my $port_path = $dirpath;
10428:             if ($group ne '') {
10429:                 $port_path = "groups/$group/$port_path";
10430:             }
10431:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10432:                                               $fname,$group,'embedded_item_'.$i,
10433:                                               $dir_root,$port_path,$disk_quota,
10434:                                               $current_disk_usage,$uname,$udom);
10435:             if ($state eq 'will_exceed_quota'
10436:                 || $state eq 'file_locked') {
10437:                 $output .= $msg;
10438:                 next;
10439:             }
10440:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10441:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10442:             if ($state eq 'exists') {
10443:                 $output .= $msg;
10444:                 next;
10445:             }
10446:         }
10447:         # Check if extension is valid
10448:         if (($fname =~ /\.(\w+)$/) &&
10449:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10450:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10451:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10452:             next;
10453:         } elsif (($fname =~ /\.(\w+)$/) &&
10454:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10455:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10456:             next;
10457:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10458:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10459:             next;
10460:         }
10461:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10462:         my $subdir = $path;
10463:         $subdir =~ s{/+$}{};
10464:         if ($context eq 'portfolio') {
10465:             my $result;
10466:             if ($state eq 'existingfile') {
10467:                 $result=
10468:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10469:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10470:             } else {
10471:                 $result=
10472:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10473:                                                     $dirpath.
10474:                                                     $env{'form.currentpath'}.$subdir);
10475:                 if ($result !~ m|^/uploaded/|) {
10476:                     $output .= '<span class="LC_error">'
10477:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10478:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10479:                                .'</span><br />';
10480:                     next;
10481:                 } else {
10482:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10483:                                $path.$fname.'</span>').'<br />';     
10484:                 }
10485:             }
10486:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10487:             my $extendedsubdir = $dirpath.'/'.$subdir;
10488:             $extendedsubdir =~ s{/+$}{};
10489:             my $result =
10490:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10491:             if ($result !~ m|^/uploaded/|) {
10492:                 $output .= '<span class="LC_error">'
10493:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10494:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10495:                            .'</span><br />';
10496:                     next;
10497:             } else {
10498:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10499:                            $path.$fname.'</span>').'<br />';
10500:                 if ($context eq 'syllabus') {
10501:                     &Apache::lonnet::make_public_indefinitely($result);
10502:                 }
10503:             }
10504:         } else {
10505: # Save the file
10506:             my $target = $env{'form.embedded_item_'.$i};
10507:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10508:             my $dest = $fullpath.$fname;
10509:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10510:             my @parts=split(/\//,"$dirpath/$path");
10511:             my $count;
10512:             my $filepath = $dir_root;
10513:             foreach my $subdir (@parts) {
10514:                 $filepath .= "/$subdir";
10515:                 if (!-e $filepath) {
10516:                     mkdir($filepath,0770);
10517:                 }
10518:             }
10519:             my $fh;
10520:             if (!open($fh,'>'.$dest)) {
10521:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10522:                 $output .= '<span class="LC_error">'.
10523:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10524:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10525:                            '</span><br />';
10526:             } else {
10527:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10528:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10529:                     $output .= '<span class="LC_error">'.
10530:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10531:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10532:                               '</span><br />';
10533:                 } else {
10534:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10535:                                $url.'</span>').'<br />';
10536:                     unless ($context eq 'testbank') {
10537:                         $footer .= &mt('View embedded file: [_1]',
10538:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10539:                     }
10540:                 }
10541:                 close($fh);
10542:             }
10543:         }
10544:         if ($env{'form.embedded_ref_'.$i}) {
10545:             $pathchange{$i} = 1;
10546:         }
10547:     }
10548:     if ($output) {
10549:         $output = '<p>'.$output.'</p>';
10550:     }
10551:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10552:     $returnflag = 'ok';
10553:     my $numpathchgs = scalar(keys(%pathchange));
10554:     if ($numpathchgs > 0) {
10555:         if ($context eq 'portfolio') {
10556:             $output .= '<p>'.&mt('or').'</p>';
10557:         } elsif ($context eq 'testbank') {
10558:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10559:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10560:             $returnflag = 'modify_orightml';
10561:         }
10562:     }
10563:     return ($output.$footer,$returnflag,$numpathchgs);
10564: }
10565: 
10566: sub modify_html_form {
10567:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10568:     my $end = 0;
10569:     my $modifyform;
10570:     if ($context eq 'upload_embedded') {
10571:         return unless (ref($pathchange) eq 'HASH');
10572:         if ($env{'form.number_embedded_items'}) {
10573:             $end += $env{'form.number_embedded_items'};
10574:         }
10575:         if ($env{'form.number_pathchange_items'}) {
10576:             $end += $env{'form.number_pathchange_items'};
10577:         }
10578:         if ($end) {
10579:             for (my $i=0; $i<$end; $i++) {
10580:                 if ($i < $env{'form.number_embedded_items'}) {
10581:                     next unless($pathchange->{$i});
10582:                 }
10583:                 $modifyform .=
10584:                     &start_data_table_row().
10585:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10586:                     'checked="checked" /></td>'.
10587:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10588:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10589:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10590:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10591:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10592:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10593:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10594:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10595:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10596:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10597:                     &end_data_table_row();
10598:             }
10599:         }
10600:     } else {
10601:         $modifyform = $pathchgtable;
10602:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10603:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10604:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10605:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10606:         }
10607:     }
10608:     if ($modifyform) {
10609:         if ($actionurl eq '/adm/dependencies') {
10610:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10611:         }
10612:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10613:                '<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".
10614:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10615:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10616:                '</ol></p>'."\n".'<p>'.
10617:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10618:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10619:                &start_data_table()."\n".
10620:                &start_data_table_header_row().
10621:                '<th>'.&mt('Change?').'</th>'.
10622:                '<th>'.&mt('Current reference').'</th>'.
10623:                '<th>'.&mt('Required reference').'</th>'.
10624:                &end_data_table_header_row()."\n".
10625:                $modifyform.
10626:                &end_data_table().'<br />'."\n".$hiddenstate.
10627:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10628:                '</form>'."\n";
10629:     }
10630:     return;
10631: }
10632: 
10633: sub modify_html_refs {
10634:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10635:     my $container;
10636:     if ($context eq 'portfolio') {
10637:         $container = $env{'form.container'};
10638:     } elsif ($context eq 'coursedoc') {
10639:         $container = $env{'form.primaryurl'};
10640:     } elsif ($context eq 'manage_dependencies') {
10641:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10642:         $container = "/$container";
10643:     } elsif ($context eq 'syllabus') {
10644:         $container = $url;
10645:     } else {
10646:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10647:     }
10648:     my (%allfiles,%codebase,$output,$content);
10649:     my @changes = &get_env_multiple('form.namechange');
10650:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
10651:         if (wantarray) {
10652:             return ('',0,0); 
10653:         } else {
10654:             return;
10655:         }
10656:     }
10657:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10658:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10659:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10660:             if (wantarray) {
10661:                 return ('',0,0);
10662:             } else {
10663:                 return;
10664:             }
10665:         } 
10666:         $content = &Apache::lonnet::getfile($container);
10667:         if ($content eq '-1') {
10668:             if (wantarray) {
10669:                 return ('',0,0);
10670:             } else {
10671:                 return;
10672:             }
10673:         }
10674:     } else {
10675:         unless ($container =~ /^\Q$dir_root\E/) {
10676:             if (wantarray) {
10677:                 return ('',0,0);
10678:             } else {
10679:                 return;
10680:             }
10681:         } 
10682:         if (open(my $fh,"<$container")) {
10683:             $content = join('', <$fh>);
10684:             close($fh);
10685:         } else {
10686:             if (wantarray) {
10687:                 return ('',0,0);
10688:             } else {
10689:                 return;
10690:             }
10691:         }
10692:     }
10693:     my ($count,$codebasecount) = (0,0);
10694:     my $mm = new File::MMagic;
10695:     my $mime_type = $mm->checktype_contents($content);
10696:     if ($mime_type eq 'text/html') {
10697:         my $parse_result = 
10698:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10699:                                                     \%codebase,\$content);
10700:         if ($parse_result eq 'ok') {
10701:             foreach my $i (@changes) {
10702:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10703:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10704:                 if ($allfiles{$ref}) {
10705:                     my $newname =  $orig;
10706:                     my ($attrib_regexp,$codebase);
10707:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10708:                     if ($attrib_regexp =~ /:/) {
10709:                         $attrib_regexp =~ s/\:/|/g;
10710:                     }
10711:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10712:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10713:                         $count += $numchg;
10714:                         $allfiles{$newname} = $allfiles{$ref};
10715:                         delete($allfiles{$ref});
10716:                     }
10717:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10718:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10719:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10720:                         $codebasecount ++;
10721:                     }
10722:                 }
10723:             }
10724:             my $skiprewrites;
10725:             if ($count || $codebasecount) {
10726:                 my $saveresult;
10727:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10728:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10729:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10730:                     if ($url eq $container) {
10731:                         my ($fname) = ($container =~ m{/([^/]+)$});
10732:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10733:                                             $count,'<span class="LC_filename">'.
10734:                                             $fname.'</span>').'</p>';
10735:                     } else {
10736:                          $output = '<p class="LC_error">'.
10737:                                    &mt('Error: update failed for: [_1].',
10738:                                    '<span class="LC_filename">'.
10739:                                    $container.'</span>').'</p>';
10740:                     }
10741:                     if ($context eq 'syllabus') {
10742:                         unless ($saveresult eq 'ok') {
10743:                             $skiprewrites = 1;
10744:                         }
10745:                     }
10746:                 } else {
10747:                     if (open(my $fh,">$container")) {
10748:                         print $fh $content;
10749:                         close($fh);
10750:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10751:                                   $count,'<span class="LC_filename">'.
10752:                                   $container.'</span>').'</p>';
10753:                     } else {
10754:                          $output = '<p class="LC_error">'.
10755:                                    &mt('Error: could not update [_1].',
10756:                                    '<span class="LC_filename">'.
10757:                                    $container.'</span>').'</p>';
10758:                     }
10759:                 }
10760:             }
10761:             if (($context eq 'syllabus') && (!$skiprewrites)) {
10762:                 my ($actionurl,$state);
10763:                 $actionurl = "/public/$udom/$uname/syllabus";
10764:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10765:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
10766:                                               \%codebase,
10767:                                               {'context' => 'rewrites',
10768:                                                'ignore_remote_references' => 1,});
10769:                 if (ref($mapping) eq 'HASH') {
10770:                     my $rewrites = 0;
10771:                     foreach my $key (keys(%{$mapping})) {
10772:                         next if ($key =~ m{^https?://});
10773:                         my $ref = $mapping->{$key};
10774:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10775:                         my $attrib;
10776:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10777:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10778:                         }
10779:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10780:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10781:                             $rewrites += $numchg;
10782:                         }
10783:                     }
10784:                     if ($rewrites) {
10785:                         my $saveresult;
10786:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10787:                         if ($url eq $container) {
10788:                             my ($fname) = ($container =~ m{/([^/]+)$});
10789:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10790:                                             $count,'<span class="LC_filename">'.
10791:                                             $fname.'</span>').'</p>';
10792:                         } else {
10793:                             $output .= '<p class="LC_error">'.
10794:                                        &mt('Error: could not update links in [_1].',
10795:                                        '<span class="LC_filename">'.
10796:                                        $container.'</span>').'</p>';
10797: 
10798:                         }
10799:                     }
10800:                 }
10801:             }
10802:         } else {
10803:             &logthis('Failed to parse '.$container.
10804:                      ' to modify references: '.$parse_result);
10805:         }
10806:     }
10807:     if (wantarray) {
10808:         return ($output,$count,$codebasecount);
10809:     } else {
10810:         return $output;
10811:     }
10812: }
10813: 
10814: sub check_for_existing {
10815:     my ($path,$fname,$element) = @_;
10816:     my ($state,$msg);
10817:     if (-d $path.'/'.$fname) {
10818:         $state = 'exists';
10819:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10820:     } elsif (-e $path.'/'.$fname) {
10821:         $state = 'exists';
10822:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10823:     }
10824:     if ($state eq 'exists') {
10825:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10826:     }
10827:     return ($state,$msg);
10828: }
10829: 
10830: sub check_for_upload {
10831:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10832:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10833:     my $filesize = length($env{'form.'.$element});
10834:     if (!$filesize) {
10835:         my $msg = '<span class="LC_error">'.
10836:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10837:                       '<span class="LC_filename">'.$fname.'</span>',
10838:                       $filesize).'<br />'.
10839:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10840:                   '</span>';
10841:         return ('zero_bytes',$msg);
10842:     }
10843:     $filesize =  $filesize/1000; #express in k (1024?)
10844:     my $getpropath = 1;
10845:     my ($dirlistref,$listerror) =
10846:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10847:     my $found_file = 0;
10848:     my $locked_file = 0;
10849:     my @lockers;
10850:     my $navmap;
10851:     if ($env{'request.course.id'}) {
10852:         $navmap = Apache::lonnavmaps::navmap->new();
10853:     }
10854:     if (ref($dirlistref) eq 'ARRAY') {
10855:         foreach my $line (@{$dirlistref}) {
10856:             my ($file_name,$rest)=split(/\&/,$line,2);
10857:             if ($file_name eq $fname){
10858:                 $file_name = $path.$file_name;
10859:                 if ($group ne '') {
10860:                     $file_name = $group.$file_name;
10861:                 }
10862:                 $found_file = 1;
10863:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10864:                     foreach my $lock (@lockers) {
10865:                         if (ref($lock) eq 'ARRAY') {
10866:                             my ($symb,$crsid) = @{$lock};
10867:                             if ($crsid eq $env{'request.course.id'}) {
10868:                                 if (ref($navmap)) {
10869:                                     my $res = $navmap->getBySymb($symb);
10870:                                     foreach my $part (@{$res->parts()}) { 
10871:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10872:                                         unless (($slot_status == $res->RESERVED) ||
10873:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10874:                                             $locked_file = 1;
10875:                                         }
10876:                                     }
10877:                                 } else {
10878:                                     $locked_file = 1;
10879:                                 }
10880:                             } else {
10881:                                 $locked_file = 1;
10882:                             }
10883:                         }
10884:                    }
10885:                 } else {
10886:                     my @info = split(/\&/,$rest);
10887:                     my $currsize = $info[6]/1000;
10888:                     if ($currsize < $filesize) {
10889:                         my $extra = $filesize - $currsize;
10890:                         if (($current_disk_usage + $extra) > $disk_quota) {
10891:                             my $msg = '<span class="LC_error">'.
10892:                                       &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.',
10893:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10894:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10895:                                                    $disk_quota,$current_disk_usage);
10896:                             return ('will_exceed_quota',$msg);
10897:                         }
10898:                     }
10899:                 }
10900:             }
10901:         }
10902:     }
10903:     if (($current_disk_usage + $filesize) > $disk_quota){
10904:         my $msg = '<span class="LC_error">'.
10905:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10906:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10907:         return ('will_exceed_quota',$msg);
10908:     } elsif ($found_file) {
10909:         if ($locked_file) {
10910:             my $msg = '<span class="LC_error">';
10911:             $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>');
10912:             $msg .= '</span><br />';
10913:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10914:             return ('file_locked',$msg);
10915:         } else {
10916:             my $msg = '<span class="LC_error">';
10917:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10918:             $msg .= '</span>';
10919:             return ('existingfile',$msg);
10920:         }
10921:     }
10922: }
10923: 
10924: sub check_for_traversal {
10925:     my ($path,$url,$toplevel) = @_;
10926:     my @parts=split(/\//,$path);
10927:     my $cleanpath;
10928:     my $fullpath = $url;
10929:     for (my $i=0;$i<@parts;$i++) {
10930:         next if ($parts[$i] eq '.');
10931:         if ($parts[$i] eq '..') {
10932:             $fullpath =~ s{([^/]+/)$}{};
10933:         } else {
10934:             $fullpath .= $parts[$i].'/';
10935:         }
10936:     }
10937:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10938:         $cleanpath = $1;
10939:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10940:         my $curr_toprel = $1;
10941:         my @parts = split(/\//,$curr_toprel);
10942:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10943:         my @urlparts = split(/\//,$url_toprel);
10944:         my $doubledots;
10945:         my $startdiff = -1;
10946:         for (my $i=0; $i<@urlparts; $i++) {
10947:             if ($startdiff == -1) {
10948:                 unless ($urlparts[$i] eq $parts[$i]) {
10949:                     $startdiff = $i;
10950:                     $doubledots .= '../';
10951:                 }
10952:             } else {
10953:                 $doubledots .= '../';
10954:             }
10955:         }
10956:         if ($startdiff > -1) {
10957:             $cleanpath = $doubledots;
10958:             for (my $i=$startdiff; $i<@parts; $i++) {
10959:                 $cleanpath .= $parts[$i].'/';
10960:             }
10961:         }
10962:     }
10963:     $cleanpath =~ s{(/)$}{};
10964:     return $cleanpath;
10965: }
10966: 
10967: sub is_archive_file {
10968:     my ($mimetype) = @_;
10969:     if (($mimetype eq 'application/octet-stream') ||
10970:         ($mimetype eq 'application/x-stuffit') ||
10971:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10972:         return 1;
10973:     }
10974:     return;
10975: }
10976: 
10977: sub decompress_form {
10978:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10979:     my %lt = &Apache::lonlocal::texthash (
10980:         this => 'This file is an archive file.',
10981:         camt => 'This file is a Camtasia archive file.',
10982:         itsc => 'Its contents are as follows:',
10983:         youm => 'You may wish to extract its contents.',
10984:         extr => 'Extract contents',
10985:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10986:         proa => 'Process automatically?',
10987:         yes  => 'Yes',
10988:         no   => 'No',
10989:         fold => 'Title for folder containing movie',
10990:         movi => 'Title for page containing embedded movie', 
10991:     );
10992:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10993:     my ($is_camtasia,$topdir,%toplevel,@paths);
10994:     my $info = &list_archive_contents($fileloc,\@paths);
10995:     if (@paths) {
10996:         foreach my $path (@paths) {
10997:             $path =~ s{^/}{};
10998:             if ($path =~ m{^([^/]+)/$}) {
10999:                 $topdir = $1;
11000:             }
11001:             if ($path =~ m{^([^/]+)/}) {
11002:                 $toplevel{$1} = $path;
11003:             } else {
11004:                 $toplevel{$path} = $path;
11005:             }
11006:         }
11007:     }
11008:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11009:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11010:                         "$topdir/media/",
11011:                         "$topdir/media/$topdir.mp4",
11012:                         "$topdir/media/FirstFrame.png",
11013:                         "$topdir/media/player.swf",
11014:                         "$topdir/media/swfobject.js",
11015:                         "$topdir/media/expressInstall.swf");
11016:         my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
11017:                          "$topdir/$topdir.mp4",
11018:                          "$topdir/$topdir\_config.xml",
11019:                          "$topdir/$topdir\_controller.swf",
11020:                          "$topdir/$topdir\_embed.css",
11021:                          "$topdir/$topdir\_First_Frame.png",
11022:                          "$topdir/$topdir\_player.html",
11023:                          "$topdir/$topdir\_Thumbnails.png",
11024:                          "$topdir/playerProductInstall.swf",
11025:                          "$topdir/scripts/",
11026:                          "$topdir/scripts/config_xml.js",
11027:                          "$topdir/scripts/handlebars.js",
11028:                          "$topdir/scripts/jquery-1.7.1.min.js",
11029:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11030:                          "$topdir/scripts/modernizr.js",
11031:                          "$topdir/scripts/player-min.js",
11032:                          "$topdir/scripts/swfobject.js",
11033:                          "$topdir/skins/",
11034:                          "$topdir/skins/configuration_express.xml",
11035:                          "$topdir/skins/express_show/",
11036:                          "$topdir/skins/express_show/player-min.css",
11037:                          "$topdir/skins/express_show/spritesheet.png");
11038:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11039:         if (@diffs == 0) {
11040:             $is_camtasia = 6;
11041:         } else {
11042:             @diffs = &compare_arrays(\@paths,\@camtasia8);
11043:             if (@diffs == 0) {
11044:                 $is_camtasia = 8;
11045:             }
11046:         }
11047:     }
11048:     my $output;
11049:     if ($is_camtasia) {
11050:         $output = <<"ENDCAM";
11051: <script type="text/javascript" language="Javascript">
11052: // <![CDATA[
11053: 
11054: function camtasiaToggle() {
11055:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11056:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11057:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11058:                 document.getElementById('camtasia_titles').style.display='block';
11059:             } else {
11060:                 document.getElementById('camtasia_titles').style.display='none';
11061:             }
11062:         }
11063:     }
11064:     return;
11065: }
11066: 
11067: // ]]>
11068: </script>
11069: <p>$lt{'camt'}</p>
11070: ENDCAM
11071:     } else {
11072:         $output = '<p>'.$lt{'this'};
11073:         if ($info eq '') {
11074:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11075:         } else {
11076:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11077:                        '<div><pre>'.$info.'</pre></div>';
11078:         }
11079:     }
11080:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11081:     my $duplicates;
11082:     my $num = 0;
11083:     if (ref($dirlist) eq 'ARRAY') {
11084:         foreach my $item (@{$dirlist}) {
11085:             if (ref($item) eq 'ARRAY') {
11086:                 if (exists($toplevel{$item->[0]})) {
11087:                     $duplicates .= 
11088:                         &start_data_table_row().
11089:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11090:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11091:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11092:                         'value="1" />'.&mt('Yes').'</label>'.
11093:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11094:                         '<td>'.$item->[0].'</td>';
11095:                     if ($item->[2]) {
11096:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11097:                     } else {
11098:                         $duplicates .= '<td>'.&mt('File').'</td>';
11099:                     }
11100:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11101:                                    '<td>'.
11102:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11103:                                    '</td>'.
11104:                                    &end_data_table_row();
11105:                     $num ++;
11106:                 }
11107:             }
11108:         }
11109:     }
11110:     my $itemcount;
11111:     if (@paths > 0) {
11112:         $itemcount = scalar(@paths);
11113:     } else {
11114:         $itemcount = 1;
11115:     }
11116:     if ($is_camtasia) {
11117:         $output .= $lt{'auto'}.'<br />'.
11118:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11119:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11120:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11121:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11122:                    $lt{'no'}.'</label></span><br />'.
11123:                    '<div id="camtasia_titles" style="display:block">'.
11124:                    &Apache::lonhtmlcommon::start_pick_box().
11125:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11126:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11127:                    &Apache::lonhtmlcommon::row_closure().
11128:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11129:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11130:                    &Apache::lonhtmlcommon::row_closure(1).
11131:                    &Apache::lonhtmlcommon::end_pick_box().
11132:                    '</div>';
11133:     }
11134:     $output .= 
11135:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11136:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11137:         "\n";
11138:     if ($duplicates ne '') {
11139:         $output .= '<p><span class="LC_warning">'.
11140:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11141:                    &start_data_table().
11142:                    &start_data_table_header_row().
11143:                    '<th>'.&mt('Overwrite?').'</th>'.
11144:                    '<th>'.&mt('Name').'</th>'.
11145:                    '<th>'.&mt('Type').'</th>'.
11146:                    '<th>'.&mt('Size').'</th>'.
11147:                    '<th>'.&mt('Last modified').'</th>'.
11148:                    &end_data_table_header_row().
11149:                    $duplicates.
11150:                    &end_data_table().
11151:                    '</p>';
11152:     }
11153:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11154:     if (ref($hiddenelements) eq 'HASH') {
11155:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11156:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11157:         }
11158:     }
11159:     $output .= <<"END";
11160: <br />
11161: <input type="submit" name="decompress" value="$lt{'extr'}" />
11162: </form>
11163: $noextract
11164: END
11165:     return $output;
11166: }
11167: 
11168: sub decompression_utility {
11169:     my ($program) = @_;
11170:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11171:     my $location;
11172:     if (grep(/^\Q$program\E$/,@utilities)) { 
11173:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11174:                          '/usr/sbin/') {
11175:             if (-x $dir.$program) {
11176:                 $location = $dir.$program;
11177:                 last;
11178:             }
11179:         }
11180:     }
11181:     return $location;
11182: }
11183: 
11184: sub list_archive_contents {
11185:     my ($file,$pathsref) = @_;
11186:     my (@cmd,$output);
11187:     my $needsregexp;
11188:     if ($file =~ /\.zip$/) {
11189:         @cmd = (&decompression_utility('unzip'),"-l");
11190:         $needsregexp = 1;
11191:     } elsif (($file =~ m/\.tar\.gz$/) ||
11192:              ($file =~ /\.tgz$/)) {
11193:         @cmd = (&decompression_utility('tar'),"-ztf");
11194:     } elsif ($file =~ /\.tar\.bz2$/) {
11195:         @cmd = (&decompression_utility('tar'),"-jtf");
11196:     } elsif ($file =~ m|\.tar$|) {
11197:         @cmd = (&decompression_utility('tar'),"-tf");
11198:     }
11199:     if (@cmd) {
11200:         undef($!);
11201:         undef($@);
11202:         if (open(my $fh,"-|", @cmd, $file)) {
11203:             while (my $line = <$fh>) {
11204:                 $output .= $line;
11205:                 chomp($line);
11206:                 my $item;
11207:                 if ($needsregexp) {
11208:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11209:                 } else {
11210:                     $item = $line;
11211:                 }
11212:                 if ($item ne '') {
11213:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11214:                         push(@{$pathsref},$item);
11215:                     } 
11216:                 }
11217:             }
11218:             close($fh);
11219:         }
11220:     }
11221:     return $output;
11222: }
11223: 
11224: sub decompress_uploaded_file {
11225:     my ($file,$dir) = @_;
11226:     &Apache::lonnet::appenv({'cgi.file' => $file});
11227:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11228:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11229:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11230:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11231:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11232:     my $decompressed = $env{'cgi.decompressed'};
11233:     &Apache::lonnet::delenv('cgi.file');
11234:     &Apache::lonnet::delenv('cgi.dir');
11235:     &Apache::lonnet::delenv('cgi.decompressed');
11236:     return ($decompressed,$result);
11237: }
11238: 
11239: sub process_decompression {
11240:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11241:     my ($dir,$error,$warning,$output);
11242:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
11243:         $error = &mt('Filename not a supported archive file type.').
11244:                  '<br />'.&mt('Filename should end with one of: [_1].',
11245:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11246:     } else {
11247:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11248:         if ($docuhome eq 'no_host') {
11249:             $error = &mt('Could not determine home server for course.');
11250:         } else {
11251:             my @ids=&Apache::lonnet::current_machine_ids();
11252:             my $currdir = "$dir_root/$destination";
11253:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11254:                 $dir = &LONCAPA::propath($docudom,$docuname).
11255:                        "$dir_root/$destination";
11256:             } else {
11257:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11258:                        "$dir_root/$docudom/$docuname/$destination";
11259:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11260:                     $error = &mt('Archive file not found.');
11261:                 }
11262:             }
11263:             my (@to_overwrite,@to_skip);
11264:             if ($env{'form.archive_overwrite_total'} > 0) {
11265:                 my $total = $env{'form.archive_overwrite_total'};
11266:                 for (my $i=0; $i<$total; $i++) {
11267:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11268:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11269:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11270:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11271:                     }
11272:                 }
11273:             }
11274:             my $numskip = scalar(@to_skip);
11275:             if (($numskip > 0) && 
11276:                 ($numskip == $env{'form.archive_itemcount'})) {
11277:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11278:             } elsif ($dir eq '') {
11279:                 $error = &mt('Directory containing archive file unavailable.');
11280:             } elsif (!$error) {
11281:                 my ($decompressed,$display);
11282:                 if ($numskip > 0) {
11283:                     my $tempdir = time.'_'.$$.int(rand(10000));
11284:                     mkdir("$dir/$tempdir",0755);
11285:                     system("mv $dir/$file $dir/$tempdir/$file");
11286:                     ($decompressed,$display) = 
11287:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11288:                     foreach my $item (@to_skip) {
11289:                         if (($item ne '') && ($item !~ /\.\./)) {
11290:                             if (-f "$dir/$tempdir/$item") { 
11291:                                 unlink("$dir/$tempdir/$item");
11292:                             } elsif (-d "$dir/$tempdir/$item") {
11293:                                 system("rm -rf $dir/$tempdir/$item");
11294:                             }
11295:                         }
11296:                     }
11297:                     system("mv $dir/$tempdir/* $dir");
11298:                     rmdir("$dir/$tempdir");   
11299:                 } else {
11300:                     ($decompressed,$display) = 
11301:                         &decompress_uploaded_file($file,$dir);
11302:                 }
11303:                 if ($decompressed eq 'ok') {
11304:                     $output = '<p class="LC_info">'.
11305:                               &mt('Files extracted successfully from archive.').
11306:                               '</p>'."\n";
11307:                     my ($warning,$result,@contents);
11308:                     my ($newdirlistref,$newlisterror) =
11309:                         &Apache::lonnet::dirlist($currdir,$docudom,
11310:                                                  $docuname,1);
11311:                     my (%is_dir,%changes,@newitems);
11312:                     my $dirptr = 16384;
11313:                     if (ref($newdirlistref) eq 'ARRAY') {
11314:                         foreach my $dir_line (@{$newdirlistref}) {
11315:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11316:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11317:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11318:                                 push(@newitems,$item);
11319:                                 if ($dirptr&$testdir) {
11320:                                     $is_dir{$item} = 1;
11321:                                 }
11322:                                 $changes{$item} = 1;
11323:                             }
11324:                         }
11325:                     }
11326:                     if (keys(%changes) > 0) {
11327:                         foreach my $item (sort(@newitems)) {
11328:                             if ($changes{$item}) {
11329:                                 push(@contents,$item);
11330:                             }
11331:                         }
11332:                     }
11333:                     if (@contents > 0) {
11334:                         my $wantform;
11335:                         unless ($env{'form.autoextract_camtasia'}) {
11336:                             $wantform = 1;
11337:                         }
11338:                         my (%children,%parent,%dirorder,%titles);
11339:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11340:                                                                 $currdir,\%is_dir,
11341:                                                                 \%children,\%parent,
11342:                                                                 \@contents,\%dirorder,
11343:                                                                 \%titles,$wantform);
11344:                         if ($datatable ne '') {
11345:                             $output .= &archive_options_form('decompressed',$datatable,
11346:                                                              $count,$hiddenelem);
11347:                             my $startcount = 6;
11348:                             $output .= &archive_javascript($startcount,$count,
11349:                                                            \%titles,\%children);
11350:                         }
11351:                         if ($env{'form.autoextract_camtasia'}) {
11352:                             my $version = $env{'form.autoextract_camtasia'};
11353:                             my %displayed;
11354:                             my $total = 1;
11355:                             $env{'form.archive_directory'} = [];
11356:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11357:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11358:                                 $path =~ s{/$}{};
11359:                                 my $item;
11360:                                 if ($path ne '') {
11361:                                     $item = "$path/$titles{$i}";
11362:                                 } else {
11363:                                     $item = $titles{$i};
11364:                                 }
11365:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11366:                                 if ($item eq $contents[0]) {
11367:                                     push(@{$env{'form.archive_directory'}},$i);
11368:                                     $env{'form.archive_'.$i} = 'display';
11369:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11370:                                     $displayed{'folder'} = $i;
11371:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11372:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
11373:                                     $env{'form.archive_'.$i} = 'display';
11374:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11375:                                     $displayed{'web'} = $i;
11376:                                 } else {
11377:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11378:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11379:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11380:                                         push(@{$env{'form.archive_directory'}},$i);
11381:                                     }
11382:                                     $env{'form.archive_'.$i} = 'dependency';
11383:                                 }
11384:                                 $total ++;
11385:                             }
11386:                             for (my $i=1; $i<$total; $i++) {
11387:                                 next if ($i == $displayed{'web'});
11388:                                 next if ($i == $displayed{'folder'});
11389:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11390:                             }
11391:                             $env{'form.phase'} = 'decompress_cleanup';
11392:                             $env{'form.archivedelete'} = 1;
11393:                             $env{'form.archive_count'} = $total-1;
11394:                             $output .=
11395:                                 &process_extracted_files('coursedocs',$docudom,
11396:                                                          $docuname,$destination,
11397:                                                          $dir_root,$hiddenelem);
11398:                         }
11399:                     } else {
11400:                         $warning = &mt('No new items extracted from archive file.');
11401:                     }
11402:                 } else {
11403:                     $output = $display;
11404:                     $error = &mt('An error occurred during extraction from the archive file.');
11405:                 }
11406:             }
11407:         }
11408:     }
11409:     if ($error) {
11410:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11411:                    $error.'</p>'."\n";
11412:     }
11413:     if ($warning) {
11414:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11415:     }
11416:     return $output;
11417: }
11418: 
11419: sub get_extracted {
11420:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11421:         $titles,$wantform) = @_;
11422:     my $count = 0;
11423:     my $depth = 0;
11424:     my $datatable;
11425:     my @hierarchy;
11426:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11427:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11428:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11429:     foreach my $item (@{$contents}) {
11430:         $count ++;
11431:         @{$dirorder->{$count}} = @hierarchy;
11432:         $titles->{$count} = $item;
11433:         &archive_hierarchy($depth,$count,$parent,$children);
11434:         if ($wantform) {
11435:             $datatable .= &archive_row($is_dir->{$item},$item,
11436:                                        $currdir,$depth,$count);
11437:         }
11438:         if ($is_dir->{$item}) {
11439:             $depth ++;
11440:             push(@hierarchy,$count);
11441:             $parent->{$depth} = $count;
11442:             $datatable .=
11443:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11444:                                            \$depth,\$count,\@hierarchy,$dirorder,
11445:                                            $children,$parent,$titles,$wantform);
11446:             $depth --;
11447:             pop(@hierarchy);
11448:         }
11449:     }
11450:     return ($count,$datatable);
11451: }
11452: 
11453: sub recurse_extracted_archive {
11454:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11455:         $children,$parent,$titles,$wantform) = @_;
11456:     my $result='';
11457:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11458:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11459:             (ref($dirorder) eq 'HASH')) {
11460:         return $result;
11461:     }
11462:     my $dirptr = 16384;
11463:     my ($newdirlistref,$newlisterror) =
11464:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11465:     if (ref($newdirlistref) eq 'ARRAY') {
11466:         foreach my $dir_line (@{$newdirlistref}) {
11467:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11468:             unless ($item =~ /^\.+$/) {
11469:                 $$count ++;
11470:                 @{$dirorder->{$$count}} = @{$hierarchy};
11471:                 $titles->{$$count} = $item;
11472:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11473: 
11474:                 my $is_dir;
11475:                 if ($dirptr&$testdir) {
11476:                     $is_dir = 1;
11477:                 }
11478:                 if ($wantform) {
11479:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11480:                 }
11481:                 if ($is_dir) {
11482:                     $$depth ++;
11483:                     push(@{$hierarchy},$$count);
11484:                     $parent->{$$depth} = $$count;
11485:                     $result .=
11486:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11487:                                                    $docuname,$depth,$count,
11488:                                                    $hierarchy,$dirorder,$children,
11489:                                                    $parent,$titles,$wantform);
11490:                     $$depth --;
11491:                     pop(@{$hierarchy});
11492:                 }
11493:             }
11494:         }
11495:     }
11496:     return $result;
11497: }
11498: 
11499: sub archive_hierarchy {
11500:     my ($depth,$count,$parent,$children) =@_;
11501:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11502:         if (exists($parent->{$depth})) {
11503:              $children->{$parent->{$depth}} .= $count.':';
11504:         }
11505:     }
11506:     return;
11507: }
11508: 
11509: sub archive_row {
11510:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11511:     my ($name) = ($item =~ m{([^/]+)$});
11512:     my %choices = &Apache::lonlocal::texthash (
11513:                                        'display'    => 'Add as file',
11514:                                        'dependency' => 'Include as dependency',
11515:                                        'discard'    => 'Discard',
11516:                                       );
11517:     if ($is_dir) {
11518:         $choices{'display'} = &mt('Add as folder'); 
11519:     }
11520:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11521:     my $offset = 0;
11522:     foreach my $action ('display','dependency','discard') {
11523:         $offset ++;
11524:         if ($action ne 'display') {
11525:             $offset ++;
11526:         }  
11527:         $output .= '<td><span class="LC_nobreak">'.
11528:                    '<label><input type="radio" name="archive_'.$count.
11529:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11530:         my $text = $choices{$action};
11531:         if ($is_dir) {
11532:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11533:             if ($action eq 'display') {
11534:                 $text = &mt('Add as folder');
11535:             }
11536:         } else {
11537:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11538: 
11539:         }
11540:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11541:         if ($action eq 'dependency') {
11542:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11543:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11544:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11545:                        '<option value=""></option>'."\n".
11546:                        '</select>'."\n".
11547:                        '</div>';
11548:         } elsif ($action eq 'display') {
11549:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11550:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11551:                        '</div>';
11552:         }
11553:         $output .= '</td>';
11554:     }
11555:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11556:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11557:     for (my $i=0; $i<$depth; $i++) {
11558:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11559:     }
11560:     if ($is_dir) {
11561:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11562:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11563:     } else {
11564:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11565:     }
11566:     $output .= '&nbsp;'.$name.'</td>'."\n".
11567:                &end_data_table_row();
11568:     return $output;
11569: }
11570: 
11571: sub archive_options_form {
11572:     my ($form,$display,$count,$hiddenelem) = @_;
11573:     my %lt = &Apache::lonlocal::texthash(
11574:                perm => 'Permanently remove archive file?',
11575:                hows => 'How should each extracted item be incorporated in the course?',
11576:                cont => 'Content actions for all',
11577:                addf => 'Add as folder/file',
11578:                incd => 'Include as dependency for a displayed file',
11579:                disc => 'Discard',
11580:                no   => 'No',
11581:                yes  => 'Yes',
11582:                save => 'Save',
11583:     );
11584:     my $output = <<"END";
11585: <form name="$form" method="post" action="">
11586: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11587: <label>
11588:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11589: </label>
11590: &nbsp;
11591: <label>
11592:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11593: </span>
11594: </p>
11595: <input type="hidden" name="phase" value="decompress_cleanup" />
11596: <br />$lt{'hows'}
11597: <div class="LC_columnSection">
11598:   <fieldset>
11599:     <legend>$lt{'cont'}</legend>
11600:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11601:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11602:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11603:   </fieldset>
11604: </div>
11605: END
11606:     return $output.
11607:            &start_data_table()."\n".
11608:            $display."\n".
11609:            &end_data_table()."\n".
11610:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11611:            $hiddenelem.
11612:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11613:            '</form>';
11614: }
11615: 
11616: sub archive_javascript {
11617:     my ($startcount,$numitems,$titles,$children) = @_;
11618:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11619:     my $maintitle = $env{'form.comment'};
11620:     my $scripttag = <<START;
11621: <script type="text/javascript">
11622: // <![CDATA[
11623: 
11624: function checkAll(form,prefix) {
11625:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11626:     for (var i=0; i < form.elements.length; i++) {
11627:         var id = form.elements[i].id;
11628:         if ((id != '') && (id != undefined)) {
11629:             if (idstr.test(id)) {
11630:                 if (form.elements[i].type == 'radio') {
11631:                     form.elements[i].checked = true;
11632:                     var nostart = i-$startcount;
11633:                     var offset = nostart%7;
11634:                     var count = (nostart-offset)/7;    
11635:                     dependencyCheck(form,count,offset);
11636:                 }
11637:             }
11638:         }
11639:     }
11640: }
11641: 
11642: function propagateCheck(form,count) {
11643:     if (count > 0) {
11644:         var startelement = $startcount + ((count-1) * 7);
11645:         for (var j=1; j<6; j++) {
11646:             if ((j != 2) && (j != 4)) {
11647:                 var item = startelement + j; 
11648:                 if (form.elements[item].type == 'radio') {
11649:                     if (form.elements[item].checked) {
11650:                         containerCheck(form,count,j);
11651:                         break;
11652:                     }
11653:                 }
11654:             }
11655:         }
11656:     }
11657: }
11658: 
11659: numitems = $numitems
11660: var titles = new Array(numitems);
11661: var parents = new Array(numitems);
11662: for (var i=0; i<numitems; i++) {
11663:     parents[i] = new Array;
11664: }
11665: var maintitle = '$maintitle';
11666: 
11667: START
11668: 
11669:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11670:         my @contents = split(/:/,$children->{$container});
11671:         for (my $i=0; $i<@contents; $i ++) {
11672:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11673:         }
11674:     }
11675: 
11676:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11677:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11678:     }
11679: 
11680:     $scripttag .= <<END;
11681: 
11682: function containerCheck(form,count,offset) {
11683:     if (count > 0) {
11684:         dependencyCheck(form,count,offset);
11685:         var item = (offset+$startcount)+7*(count-1);
11686:         form.elements[item].checked = true;
11687:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11688:             if (parents[count].length > 0) {
11689:                 for (var j=0; j<parents[count].length; j++) {
11690:                     containerCheck(form,parents[count][j],offset);
11691:                 }
11692:             }
11693:         }
11694:     }
11695: }
11696: 
11697: function dependencyCheck(form,count,offset) {
11698:     if (count > 0) {
11699:         var chosen = (offset+$startcount)+7*(count-1);
11700:         var depitem = $startcount + ((count-1) * 7) + 4;
11701:         var currtype = form.elements[depitem].type;
11702:         if (form.elements[chosen].value == 'dependency') {
11703:             document.getElementById('arc_depon_'+count).style.display='block'; 
11704:             form.elements[depitem].options.length = 0;
11705:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11706:             for (var i=1; i<=numitems; i++) {
11707:                 if (i == count) {
11708:                     continue;
11709:                 }
11710:                 var startelement = $startcount + (i-1) * 7;
11711:                 for (var j=1; j<6; j++) {
11712:                     if ((j != 2) && (j!= 4)) {
11713:                         var item = startelement + j;
11714:                         if (form.elements[item].type == 'radio') {
11715:                             if (form.elements[item].checked) {
11716:                                 if (form.elements[item].value == 'display') {
11717:                                     var n = form.elements[depitem].options.length;
11718:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11719:                                 }
11720:                             }
11721:                         }
11722:                     }
11723:                 }
11724:             }
11725:         } else {
11726:             document.getElementById('arc_depon_'+count).style.display='none';
11727:             form.elements[depitem].options.length = 0;
11728:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11729:         }
11730:         titleCheck(form,count,offset);
11731:     }
11732: }
11733: 
11734: function propagateSelect(form,count,offset) {
11735:     if (count > 0) {
11736:         var item = (1+offset+$startcount)+7*(count-1);
11737:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11738:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11739:             if (parents[count].length > 0) {
11740:                 for (var j=0; j<parents[count].length; j++) {
11741:                     containerSelect(form,parents[count][j],offset,picked);
11742:                 }
11743:             }
11744:         }
11745:     }
11746: }
11747: 
11748: function containerSelect(form,count,offset,picked) {
11749:     if (count > 0) {
11750:         var item = (offset+$startcount)+7*(count-1);
11751:         if (form.elements[item].type == 'radio') {
11752:             if (form.elements[item].value == 'dependency') {
11753:                 if (form.elements[item+1].type == 'select-one') {
11754:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11755:                         if (form.elements[item+1].options[i].value == picked) {
11756:                             form.elements[item+1].selectedIndex = i;
11757:                             break;
11758:                         }
11759:                     }
11760:                 }
11761:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11762:                     if (parents[count].length > 0) {
11763:                         for (var j=0; j<parents[count].length; j++) {
11764:                             containerSelect(form,parents[count][j],offset,picked);
11765:                         }
11766:                     }
11767:                 }
11768:             }
11769:         }
11770:     }
11771: }
11772: 
11773: function titleCheck(form,count,offset) {
11774:     if (count > 0) {
11775:         var chosen = (offset+$startcount)+7*(count-1);
11776:         var depitem = $startcount + ((count-1) * 7) + 2;
11777:         var currtype = form.elements[depitem].type;
11778:         if (form.elements[chosen].value == 'display') {
11779:             document.getElementById('arc_title_'+count).style.display='block';
11780:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11781:                 document.getElementById('archive_title_'+count).value=maintitle;
11782:             }
11783:         } else {
11784:             document.getElementById('arc_title_'+count).style.display='none';
11785:             if (currtype == 'text') { 
11786:                 document.getElementById('archive_title_'+count).value='';
11787:             }
11788:         }
11789:     }
11790:     return;
11791: }
11792: 
11793: // ]]>
11794: </script>
11795: END
11796:     return $scripttag;
11797: }
11798: 
11799: sub process_extracted_files {
11800:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11801:     my $numitems = $env{'form.archive_count'};
11802:     return unless ($numitems);
11803:     my @ids=&Apache::lonnet::current_machine_ids();
11804:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11805:         %folders,%containers,%mapinner,%prompttofetch);
11806:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11807:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11808:         $prefix = &LONCAPA::propath($docudom,$docuname);
11809:         $pathtocheck = "$dir_root/$destination";
11810:         $dir = $dir_root;
11811:         $ishome = 1;
11812:     } else {
11813:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11814:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11815:         $dir = "$dir_root/$docudom/$docuname";    
11816:     }
11817:     my $currdir = "$dir_root/$destination";
11818:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11819:     if ($env{'form.folderpath'}) {
11820:         my @items = split('&',$env{'form.folderpath'});
11821:         $folders{'0'} = $items[-2];
11822:         if ($env{'form.folderpath'} =~ /\:1$/) {
11823:             $containers{'0'}='page';
11824:         } else {
11825:             $containers{'0'}='sequence';
11826:         }
11827:     }
11828:     my @archdirs = &get_env_multiple('form.archive_directory');
11829:     if ($numitems) {
11830:         for (my $i=1; $i<=$numitems; $i++) {
11831:             my $path = $env{'form.archive_content_'.$i};
11832:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11833:                 my $item = $1;
11834:                 $toplevelitems{$item} = $i;
11835:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11836:                     $is_dir{$item} = 1;
11837:                 }
11838:             }
11839:         }
11840:     }
11841:     my ($output,%children,%parent,%titles,%dirorder,$result);
11842:     if (keys(%toplevelitems) > 0) {
11843:         my @contents = sort(keys(%toplevelitems));
11844:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11845:                                            \%parent,\@contents,\%dirorder,\%titles);
11846:     }
11847:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11848:     if ($numitems) {
11849:         for (my $i=1; $i<=$numitems; $i++) {
11850:             next if ($env{'form.archive_'.$i} eq 'dependency');
11851:             my $path = $env{'form.archive_content_'.$i};
11852:             if ($path =~ /^\Q$pathtocheck\E/) {
11853:                 if ($env{'form.archive_'.$i} eq 'discard') {
11854:                     if ($prefix ne '' && $path ne '') {
11855:                         if (-e $prefix.$path) {
11856:                             if ((@archdirs > 0) && 
11857:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11858:                                 $todeletedir{$prefix.$path} = 1;
11859:                             } else {
11860:                                 $todelete{$prefix.$path} = 1;
11861:                             }
11862:                         }
11863:                     }
11864:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11865:                     my ($docstitle,$title,$url,$outer);
11866:                     ($title) = ($path =~ m{/([^/]+)$});
11867:                     $docstitle = $env{'form.archive_title_'.$i};
11868:                     if ($docstitle eq '') {
11869:                         $docstitle = $title;
11870:                     }
11871:                     $outer = 0;
11872:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11873:                         if (@{$dirorder{$i}} > 0) {
11874:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11875:                                 if ($env{'form.archive_'.$item} eq 'display') {
11876:                                     $outer = $item;
11877:                                     last;
11878:                                 }
11879:                             }
11880:                         }
11881:                     }
11882:                     my ($errtext,$fatal) = 
11883:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11884:                                                '/'.$folders{$outer}.'.'.
11885:                                                $containers{$outer});
11886:                     next if ($fatal);
11887:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11888:                         if ($context eq 'coursedocs') {
11889:                             $mapinner{$i} = time;
11890:                             $folders{$i} = 'default_'.$mapinner{$i};
11891:                             $containers{$i} = 'sequence';
11892:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11893:                                       $folders{$i}.'.'.$containers{$i};
11894:                             my $newidx = &LONCAPA::map::getresidx();
11895:                             $LONCAPA::map::resources[$newidx]=
11896:                                 $docstitle.':'.$url.':false:normal:res';
11897:                             push(@LONCAPA::map::order,$newidx);
11898:                             my ($outtext,$errtext) =
11899:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11900:                                                         $docuname.'/'.$folders{$outer}.
11901:                                                         '.'.$containers{$outer},1,1);
11902:                             $newseqid{$i} = $newidx;
11903:                             unless ($errtext) {
11904:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11905:                             }
11906:                         }
11907:                     } else {
11908:                         if ($context eq 'coursedocs') {
11909:                             my $newidx=&LONCAPA::map::getresidx();
11910:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11911:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11912:                                       $title;
11913:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11914:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11915:                             }
11916:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11917:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11918:                             }
11919:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11920:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11921:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11922:                                 unless ($ishome) {
11923:                                     my $fetch = "$newdest{$i}/$title";
11924:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11925:                                     $prompttofetch{$fetch} = 1;
11926:                                 }
11927:                             }
11928:                             $LONCAPA::map::resources[$newidx]=
11929:                                 $docstitle.':'.$url.':false:normal:res';
11930:                             push(@LONCAPA::map::order, $newidx);
11931:                             my ($outtext,$errtext)=
11932:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11933:                                                         $docuname.'/'.$folders{$outer}.
11934:                                                         '.'.$containers{$outer},1,1);
11935:                             unless ($errtext) {
11936:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11937:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11938:                                 }
11939:                             }
11940:                         }
11941:                     }
11942:                 }
11943:             } else {
11944:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11945:             }
11946:         }
11947:         for (my $i=1; $i<=$numitems; $i++) {
11948:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11949:             my $path = $env{'form.archive_content_'.$i};
11950:             if ($path =~ /^\Q$pathtocheck\E/) {
11951:                 my ($title) = ($path =~ m{/([^/]+)$});
11952:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11953:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11954:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11955:                         my ($itemidx,$fullpath,$relpath);
11956:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11957:                             my $container = $dirorder{$referrer{$i}}->[-1];
11958:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11959:                                 if ($dirorder{$i}->[$j] eq $container) {
11960:                                     $itemidx = $j;
11961:                                 }
11962:                             }
11963:                         }
11964:                         if ($itemidx eq '') {
11965:                             $itemidx =  0;
11966:                         }
11967:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11968:                             if ($mapinner{$referrer{$i}}) {
11969:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11970:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11971:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11972:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11973:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11974:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11975:                                             if (!-e $fullpath) {
11976:                                                 mkdir($fullpath,0755);
11977:                                             }
11978:                                         }
11979:                                     } else {
11980:                                         last;
11981:                                     }
11982:                                 }
11983:                             }
11984:                         } elsif ($newdest{$referrer{$i}}) {
11985:                             $fullpath = $newdest{$referrer{$i}};
11986:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11987:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11988:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11989:                                     last;
11990:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11991:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11992:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11993:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11994:                                         if (!-e $fullpath) {
11995:                                             mkdir($fullpath,0755);
11996:                                         }
11997:                                     }
11998:                                 } else {
11999:                                     last;
12000:                                 }
12001:                             }
12002:                         }
12003:                         if ($fullpath ne '') {
12004:                             if (-e "$prefix$path") {
12005:                                 system("mv $prefix$path $fullpath/$title");
12006:                             }
12007:                             if (-e "$fullpath/$title") {
12008:                                 my $showpath;
12009:                                 if ($relpath ne '') {
12010:                                     $showpath = "$relpath/$title";
12011:                                 } else {
12012:                                     $showpath = "/$title";
12013:                                 }
12014:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12015:                             }
12016:                             unless ($ishome) {
12017:                                 my $fetch = "$fullpath/$title";
12018:                                 $fetch =~ s/^\Q$prefix$dir\E//;
12019:                                 $prompttofetch{$fetch} = 1;
12020:                             }
12021:                         }
12022:                     }
12023:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12024:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12025:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12026:                 }
12027:             } else {
12028:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12029:             }
12030:         }
12031:         if (keys(%todelete)) {
12032:             foreach my $key (keys(%todelete)) {
12033:                 unlink($key);
12034:             }
12035:         }
12036:         if (keys(%todeletedir)) {
12037:             foreach my $key (keys(%todeletedir)) {
12038:                 rmdir($key);
12039:             }
12040:         }
12041:         foreach my $dir (sort(keys(%is_dir))) {
12042:             if (($pathtocheck ne '') && ($dir ne ''))  {
12043:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12044:             }
12045:         }
12046:         if ($result ne '') {
12047:             $output .= '<ul>'."\n".
12048:                        $result."\n".
12049:                        '</ul>';
12050:         }
12051:         unless ($ishome) {
12052:             my $replicationfail;
12053:             foreach my $item (keys(%prompttofetch)) {
12054:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12055:                 unless ($fetchresult eq 'ok') {
12056:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12057:                 }
12058:             }
12059:             if ($replicationfail) {
12060:                 $output .= '<p class="LC_error">'.
12061:                            &mt('Course home server failed to retrieve:').'<ul>'.
12062:                            $replicationfail.
12063:                            '</ul></p>';
12064:             }
12065:         }
12066:     } else {
12067:         $warning = &mt('No items found in archive.');
12068:     }
12069:     if ($error) {
12070:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12071:                    $error.'</p>'."\n";
12072:     }
12073:     if ($warning) {
12074:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12075:     }
12076:     return $output;
12077: }
12078: 
12079: sub cleanup_empty_dirs {
12080:     my ($path) = @_;
12081:     if (($path ne '') && (-d $path)) {
12082:         if (opendir(my $dirh,$path)) {
12083:             my @dircontents = grep(!/^\./,readdir($dirh));
12084:             my $numitems = 0;
12085:             foreach my $item (@dircontents) {
12086:                 if (-d "$path/$item") {
12087:                     &cleanup_empty_dirs("$path/$item");
12088:                     if (-e "$path/$item") {
12089:                         $numitems ++;
12090:                     }
12091:                 } else {
12092:                     $numitems ++;
12093:                 }
12094:             }
12095:             if ($numitems == 0) {
12096:                 rmdir($path);
12097:             }
12098:             closedir($dirh);
12099:         }
12100:     }
12101:     return;
12102: }
12103: 
12104: =pod
12105: 
12106: =item * &get_folder_hierarchy()
12107: 
12108: Provides hierarchy of names of folders/sub-folders containing the current
12109: item,
12110: 
12111: Inputs: 3
12112:      - $navmap - navmaps object
12113: 
12114:      - $map - url for map (either the trigger itself, or map containing
12115:                            the resource, which is the trigger).
12116: 
12117:      - $showitem - 1 => show title for map itself; 0 => do not show.
12118: 
12119: Outputs: 1 @pathitems - array of folder/subfolder names.
12120: 
12121: =cut
12122: 
12123: sub get_folder_hierarchy {
12124:     my ($navmap,$map,$showitem) = @_;
12125:     my @pathitems;
12126:     if (ref($navmap)) {
12127:         my $mapres = $navmap->getResourceByUrl($map);
12128:         if (ref($mapres)) {
12129:             my $pcslist = $mapres->map_hierarchy();
12130:             if ($pcslist ne '') {
12131:                 my @pcs = split(/,/,$pcslist);
12132:                 foreach my $pc (@pcs) {
12133:                     if ($pc == 1) {
12134:                         push(@pathitems,&mt('Main Content'));
12135:                     } else {
12136:                         my $res = $navmap->getByMapPc($pc);
12137:                         if (ref($res)) {
12138:                             my $title = $res->compTitle();
12139:                             $title =~ s/\W+/_/g;
12140:                             if ($title ne '') {
12141:                                 push(@pathitems,$title);
12142:                             }
12143:                         }
12144:                     }
12145:                 }
12146:             }
12147:             if ($showitem) {
12148:                 if ($mapres->{ID} eq '0.0') {
12149:                     push(@pathitems,&mt('Main Content'));
12150:                 } else {
12151:                     my $maptitle = $mapres->compTitle();
12152:                     $maptitle =~ s/\W+/_/g;
12153:                     if ($maptitle ne '') {
12154:                         push(@pathitems,$maptitle);
12155:                     }
12156:                 }
12157:             }
12158:         }
12159:     }
12160:     return @pathitems;
12161: }
12162: 
12163: =pod
12164: 
12165: =item * &get_turnedin_filepath()
12166: 
12167: Determines path in a user's portfolio file for storage of files uploaded
12168: to a specific essayresponse or dropbox item.
12169: 
12170: Inputs: 3 required + 1 optional.
12171: $symb is symb for resource, $uname and $udom are for current user (required).
12172: $caller is optional (can be "submission", if routine is called when storing
12173: an upoaded file when "Submit Answer" button was pressed).
12174: 
12175: Returns array containing $path and $multiresp. 
12176: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12177: than one file upload item.  Callers of routine should append partid as a 
12178: subdirectory to $path in cases where $multiresp is 1.
12179: 
12180: Called by: homework/essayresponse.pm and homework/structuretags.pm
12181: 
12182: =cut
12183: 
12184: sub get_turnedin_filepath {
12185:     my ($symb,$uname,$udom,$caller) = @_;
12186:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12187:     my $turnindir;
12188:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12189:     $turnindir = $userhash{'turnindir'};
12190:     my ($path,$multiresp);
12191:     if ($turnindir eq '') {
12192:         if ($caller eq 'submission') {
12193:             $turnindir = &mt('turned in');
12194:             $turnindir =~ s/\W+/_/g;
12195:             my %newhash = (
12196:                             'turnindir' => $turnindir,
12197:                           );
12198:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12199:         }
12200:     }
12201:     if ($turnindir ne '') {
12202:         $path = '/'.$turnindir.'/';
12203:         my ($multipart,$turnin,@pathitems);
12204:         my $navmap = Apache::lonnavmaps::navmap->new();
12205:         if (defined($navmap)) {
12206:             my $mapres = $navmap->getResourceByUrl($map);
12207:             if (ref($mapres)) {
12208:                 my $pcslist = $mapres->map_hierarchy();
12209:                 if ($pcslist ne '') {
12210:                     foreach my $pc (split(/,/,$pcslist)) {
12211:                         my $res = $navmap->getByMapPc($pc);
12212:                         if (ref($res)) {
12213:                             my $title = $res->compTitle();
12214:                             $title =~ s/\W+/_/g;
12215:                             if ($title ne '') {
12216:                                 if (($pc > 1) && (length($title) > 12)) {
12217:                                     $title = substr($title,0,12);
12218:                                 }
12219:                                 push(@pathitems,$title);
12220:                             }
12221:                         }
12222:                     }
12223:                 }
12224:                 my $maptitle = $mapres->compTitle();
12225:                 $maptitle =~ s/\W+/_/g;
12226:                 if ($maptitle ne '') {
12227:                     if (length($maptitle) > 12) {
12228:                         $maptitle = substr($maptitle,0,12);
12229:                     }
12230:                     push(@pathitems,$maptitle);
12231:                 }
12232:                 unless ($env{'request.state'} eq 'construct') {
12233:                     my $res = $navmap->getBySymb($symb);
12234:                     if (ref($res)) {
12235:                         my $partlist = $res->parts();
12236:                         my $totaluploads = 0;
12237:                         if (ref($partlist) eq 'ARRAY') {
12238:                             foreach my $part (@{$partlist}) {
12239:                                 my @types = $res->responseType($part);
12240:                                 my @ids = $res->responseIds($part);
12241:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12242:                                     if ($types[$i] eq 'essay') {
12243:                                         my $partid = $part.'_'.$ids[$i];
12244:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12245:                                             $totaluploads ++;
12246:                                         }
12247:                                     }
12248:                                 }
12249:                             }
12250:                             if ($totaluploads > 1) {
12251:                                 $multiresp = 1;
12252:                             }
12253:                         }
12254:                     }
12255:                 }
12256:             } else {
12257:                 return;
12258:             }
12259:         } else {
12260:             return;
12261:         }
12262:         my $restitle=&Apache::lonnet::gettitle($symb);
12263:         $restitle =~ s/\W+/_/g;
12264:         if ($restitle eq '') {
12265:             $restitle = ($resurl =~ m{/[^/]+$});
12266:             if ($restitle eq '') {
12267:                 $restitle = time;
12268:             }
12269:         }
12270:         if (length($restitle) > 12) {
12271:             $restitle = substr($restitle,0,12);
12272:         }
12273:         push(@pathitems,$restitle);
12274:         $path .= join('/',@pathitems);
12275:     }
12276:     return ($path,$multiresp);
12277: }
12278: 
12279: =pod
12280: 
12281: =back
12282: 
12283: =head1 CSV Upload/Handling functions
12284: 
12285: =over 4
12286: 
12287: =item * &upfile_store($r)
12288: 
12289: Store uploaded file, $r should be the HTTP Request object,
12290: needs $env{'form.upfile'}
12291: returns $datatoken to be put into hidden field
12292: 
12293: =cut
12294: 
12295: sub upfile_store {
12296:     my $r=shift;
12297:     $env{'form.upfile'}=~s/\r/\n/gs;
12298:     $env{'form.upfile'}=~s/\f/\n/gs;
12299:     $env{'form.upfile'}=~s/\n+/\n/gs;
12300:     $env{'form.upfile'}=~s/\n+$//gs;
12301: 
12302:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12303: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12304:     {
12305:         my $datafile = $r->dir_config('lonDaemons').
12306:                            '/tmp/'.$datatoken.'.tmp';
12307:         if ( open(my $fh,">$datafile") ) {
12308:             print $fh $env{'form.upfile'};
12309:             close($fh);
12310:         }
12311:     }
12312:     return $datatoken;
12313: }
12314: 
12315: =pod
12316: 
12317: =item * &load_tmp_file($r)
12318: 
12319: Load uploaded file from tmp, $r should be the HTTP Request object,
12320: needs $env{'form.datatoken'},
12321: sets $env{'form.upfile'} to the contents of the file
12322: 
12323: =cut
12324: 
12325: sub load_tmp_file {
12326:     my $r=shift;
12327:     my @studentdata=();
12328:     {
12329:         my $studentfile = $r->dir_config('lonDaemons').
12330:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12331:         if ( open(my $fh,"<$studentfile") ) {
12332:             @studentdata=<$fh>;
12333:             close($fh);
12334:         }
12335:     }
12336:     $env{'form.upfile'}=join('',@studentdata);
12337: }
12338: 
12339: =pod
12340: 
12341: =item * &upfile_record_sep()
12342: 
12343: Separate uploaded file into records
12344: returns array of records,
12345: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12346: 
12347: =cut
12348: 
12349: sub upfile_record_sep {
12350:     if ($env{'form.upfiletype'} eq 'xml') {
12351:     } else {
12352: 	my @records;
12353: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12354: 	    if ($line=~/^\s*$/) { next; }
12355: 	    push(@records,$line);
12356: 	}
12357: 	return @records;
12358:     }
12359: }
12360: 
12361: =pod
12362: 
12363: =item * &record_sep($record)
12364: 
12365: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12366: 
12367: =cut
12368: 
12369: sub takeleft {
12370:     my $index=shift;
12371:     return substr('0000'.$index,-4,4);
12372: }
12373: 
12374: sub record_sep {
12375:     my $record=shift;
12376:     my %components=();
12377:     if ($env{'form.upfiletype'} eq 'xml') {
12378:     } elsif ($env{'form.upfiletype'} eq 'space') {
12379:         my $i=0;
12380:         foreach my $field (split(/\s+/,$record)) {
12381:             $field=~s/^(\"|\')//;
12382:             $field=~s/(\"|\')$//;
12383:             $components{&takeleft($i)}=$field;
12384:             $i++;
12385:         }
12386:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12387:         my $i=0;
12388:         foreach my $field (split(/\t/,$record)) {
12389:             $field=~s/^(\"|\')//;
12390:             $field=~s/(\"|\')$//;
12391:             $components{&takeleft($i)}=$field;
12392:             $i++;
12393:         }
12394:     } else {
12395:         my $separator=',';
12396:         if ($env{'form.upfiletype'} eq 'semisv') {
12397:             $separator=';';
12398:         }
12399:         my $i=0;
12400: # the character we are looking for to indicate the end of a quote or a record 
12401:         my $looking_for=$separator;
12402: # do not add the characters to the fields
12403:         my $ignore=0;
12404: # we just encountered a separator (or the beginning of the record)
12405:         my $just_found_separator=1;
12406: # store the field we are working on here
12407:         my $field='';
12408: # work our way through all characters in record
12409:         foreach my $character ($record=~/(.)/g) {
12410:             if ($character eq $looking_for) {
12411:                if ($character ne $separator) {
12412: # Found the end of a quote, again looking for separator
12413:                   $looking_for=$separator;
12414:                   $ignore=1;
12415:                } else {
12416: # Found a separator, store away what we got
12417:                   $components{&takeleft($i)}=$field;
12418: 	          $i++;
12419:                   $just_found_separator=1;
12420:                   $ignore=0;
12421:                   $field='';
12422:                }
12423:                next;
12424:             }
12425: # single or double quotation marks after a separator indicate beginning of a quote
12426: # we are now looking for the end of the quote and need to ignore separators
12427:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12428:                $looking_for=$character;
12429:                next;
12430:             }
12431: # ignore would be true after we reached the end of a quote
12432:             if ($ignore) { next; }
12433:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12434:             $field.=$character;
12435:             $just_found_separator=0; 
12436:         }
12437: # catch the very last entry, since we never encountered the separator
12438:         $components{&takeleft($i)}=$field;
12439:     }
12440:     return %components;
12441: }
12442: 
12443: ######################################################
12444: ######################################################
12445: 
12446: =pod
12447: 
12448: =item * &upfile_select_html()
12449: 
12450: Return HTML code to select a file from the users machine and specify 
12451: the file type.
12452: 
12453: =cut
12454: 
12455: ######################################################
12456: ######################################################
12457: sub upfile_select_html {
12458:     my %Types = (
12459:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12460:                  semisv => &mt('Semicolon separated values'),
12461:                  space => &mt('Space separated'),
12462:                  tab   => &mt('Tabulator separated'),
12463: #                 xml   => &mt('HTML/XML'),
12464:                  );
12465:     my $Str = '<input type="file" name="upfile" size="50" />'.
12466:         '<br />'.&mt('Type').': <select name="upfiletype">';
12467:     foreach my $type (sort(keys(%Types))) {
12468:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12469:     }
12470:     $Str .= "</select>\n";
12471:     return $Str;
12472: }
12473: 
12474: sub get_samples {
12475:     my ($records,$toget) = @_;
12476:     my @samples=({});
12477:     my $got=0;
12478:     foreach my $rec (@$records) {
12479: 	my %temp = &record_sep($rec);
12480: 	if (! grep(/\S/, values(%temp))) { next; }
12481: 	if (%temp) {
12482: 	    $samples[$got]=\%temp;
12483: 	    $got++;
12484: 	    if ($got == $toget) { last; }
12485: 	}
12486:     }
12487:     return \@samples;
12488: }
12489: 
12490: ######################################################
12491: ######################################################
12492: 
12493: =pod
12494: 
12495: =item * &csv_print_samples($r,$records)
12496: 
12497: Prints a table of sample values from each column uploaded $r is an
12498: Apache Request ref, $records is an arrayref from
12499: &Apache::loncommon::upfile_record_sep
12500: 
12501: =cut
12502: 
12503: ######################################################
12504: ######################################################
12505: sub csv_print_samples {
12506:     my ($r,$records) = @_;
12507:     my $samples = &get_samples($records,5);
12508: 
12509:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12510:               &start_data_table_header_row());
12511:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12512:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12513:     $r->print(&end_data_table_header_row());
12514:     foreach my $hash (@$samples) {
12515: 	$r->print(&start_data_table_row());
12516: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12517: 	    $r->print('<td>');
12518: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12519: 	    $r->print('</td>');
12520: 	}
12521: 	$r->print(&end_data_table_row());
12522:     }
12523:     $r->print(&end_data_table().'<br />'."\n");
12524: }
12525: 
12526: ######################################################
12527: ######################################################
12528: 
12529: =pod
12530: 
12531: =item * &csv_print_select_table($r,$records,$d)
12532: 
12533: Prints a table to create associations between values and table columns.
12534: 
12535: $r is an Apache Request ref,
12536: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12537: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12538: 
12539: =cut
12540: 
12541: ######################################################
12542: ######################################################
12543: sub csv_print_select_table {
12544:     my ($r,$records,$d) = @_;
12545:     my $i=0;
12546:     my $samples = &get_samples($records,1);
12547:     $r->print(&mt('Associate columns with student attributes.')."\n".
12548: 	      &start_data_table().&start_data_table_header_row().
12549:               '<th>'.&mt('Attribute').'</th>'.
12550:               '<th>'.&mt('Column').'</th>'.
12551:               &end_data_table_header_row()."\n");
12552:     foreach my $array_ref (@$d) {
12553: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12554: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12555: 
12556: 	$r->print('<td><select name="f'.$i.'"'.
12557: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12558: 	$r->print('<option value="none"></option>');
12559: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12560: 	    $r->print('<option value="'.$sample.'"'.
12561:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12562:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12563: 	}
12564: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12565: 	$i++;
12566:     }
12567:     $r->print(&end_data_table());
12568:     $i--;
12569:     return $i;
12570: }
12571: 
12572: ######################################################
12573: ######################################################
12574: 
12575: =pod
12576: 
12577: =item * &csv_samples_select_table($r,$records,$d)
12578: 
12579: Prints a table of sample values from the upload and can make associate samples to internal names.
12580: 
12581: $r is an Apache Request ref,
12582: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12583: $d is an array of 2 element arrays (internal name, displayed name)
12584: 
12585: =cut
12586: 
12587: ######################################################
12588: ######################################################
12589: sub csv_samples_select_table {
12590:     my ($r,$records,$d) = @_;
12591:     my $i=0;
12592:     #
12593:     my $max_samples = 5;
12594:     my $samples = &get_samples($records,$max_samples);
12595:     $r->print(&start_data_table().
12596:               &start_data_table_header_row().'<th>'.
12597:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12598:               &end_data_table_header_row());
12599: 
12600:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12601: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12602: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12603: 	foreach my $option (@$d) {
12604: 	    my ($value,$display,$defaultcol)=@{ $option };
12605: 	    $r->print('<option value="'.$value.'"'.
12606:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12607:                       $display.'</option>');
12608: 	}
12609: 	$r->print('</select></td><td>');
12610: 	foreach my $line (0..($max_samples-1)) {
12611: 	    if (defined($samples->[$line]{$key})) { 
12612: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12613: 	    }
12614: 	}
12615: 	$r->print('</td>'.&end_data_table_row());
12616: 	$i++;
12617:     }
12618:     $r->print(&end_data_table());
12619:     $i--;
12620:     return($i);
12621: }
12622: 
12623: ######################################################
12624: ######################################################
12625: 
12626: =pod
12627: 
12628: =item * &clean_excel_name($name)
12629: 
12630: Returns a replacement for $name which does not contain any illegal characters.
12631: 
12632: =cut
12633: 
12634: ######################################################
12635: ######################################################
12636: sub clean_excel_name {
12637:     my ($name) = @_;
12638:     $name =~ s/[:\*\?\/\\]//g;
12639:     if (length($name) > 31) {
12640:         $name = substr($name,0,31);
12641:     }
12642:     return $name;
12643: }
12644: 
12645: =pod
12646: 
12647: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12648: 
12649: Returns either 1 or undef
12650: 
12651: 1 if the part is to be hidden, undef if it is to be shown
12652: 
12653: Arguments are:
12654: 
12655: $id the id of the part to be checked
12656: $symb, optional the symb of the resource to check
12657: $udom, optional the domain of the user to check for
12658: $uname, optional the username of the user to check for
12659: 
12660: =cut
12661: 
12662: sub check_if_partid_hidden {
12663:     my ($id,$symb,$udom,$uname) = @_;
12664:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12665: 					 $symb,$udom,$uname);
12666:     my $truth=1;
12667:     #if the string starts with !, then the list is the list to show not hide
12668:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12669:     my @hiddenlist=split(/,/,$hiddenparts);
12670:     foreach my $checkid (@hiddenlist) {
12671: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12672:     }
12673:     return !$truth;
12674: }
12675: 
12676: 
12677: ############################################################
12678: ############################################################
12679: 
12680: =pod
12681: 
12682: =back 
12683: 
12684: =head1 cgi-bin script and graphing routines
12685: 
12686: =over 4
12687: 
12688: =item * &get_cgi_id()
12689: 
12690: Inputs: none
12691: 
12692: Returns an id which can be used to pass environment variables
12693: to various cgi-bin scripts.  These environment variables will
12694: be removed from the users environment after a given time by
12695: the routine &Apache::lonnet::transfer_profile_to_env.
12696: 
12697: =cut
12698: 
12699: ############################################################
12700: ############################################################
12701: my $uniq=0;
12702: sub get_cgi_id {
12703:     $uniq=($uniq+1)%100000;
12704:     return (time.'_'.$$.'_'.$uniq);
12705: }
12706: 
12707: ############################################################
12708: ############################################################
12709: 
12710: =pod
12711: 
12712: =item * &DrawBarGraph()
12713: 
12714: Facilitates the plotting of data in a (stacked) bar graph.
12715: Puts plot definition data into the users environment in order for 
12716: graph.png to plot it.  Returns an <img> tag for the plot.
12717: The bars on the plot are labeled '1','2',...,'n'.
12718: 
12719: Inputs:
12720: 
12721: =over 4
12722: 
12723: =item $Title: string, the title of the plot
12724: 
12725: =item $xlabel: string, text describing the X-axis of the plot
12726: 
12727: =item $ylabel: string, text describing the Y-axis of the plot
12728: 
12729: =item $Max: scalar, the maximum Y value to use in the plot
12730: If $Max is < any data point, the graph will not be rendered.
12731: 
12732: =item $colors: array ref holding the colors to be used for the data sets when
12733: they are plotted.  If undefined, default values will be used.
12734: 
12735: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12736: 
12737: =item @Values: An array of array references.  Each array reference holds data
12738: to be plotted in a stacked bar chart.
12739: 
12740: =item If the final element of @Values is a hash reference the key/value
12741: pairs will be added to the graph definition.
12742: 
12743: =back
12744: 
12745: Returns:
12746: 
12747: An <img> tag which references graph.png and the appropriate identifying
12748: information for the plot.
12749: 
12750: =cut
12751: 
12752: ############################################################
12753: ############################################################
12754: sub DrawBarGraph {
12755:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12756:     #
12757:     if (! defined($colors)) {
12758:         $colors = ['#33ff00', 
12759:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12760:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12761:                   ]; 
12762:     }
12763:     my $extra_settings = {};
12764:     if (ref($Values[-1]) eq 'HASH') {
12765:         $extra_settings = pop(@Values);
12766:     }
12767:     #
12768:     my $identifier = &get_cgi_id();
12769:     my $id = 'cgi.'.$identifier;        
12770:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12771:         return '';
12772:     }
12773:     #
12774:     my @Labels;
12775:     if (defined($labels)) {
12776:         @Labels = @$labels;
12777:     } else {
12778:         for (my $i=0;$i<@{$Values[0]};$i++) {
12779:             push (@Labels,$i+1);
12780:         }
12781:     }
12782:     #
12783:     my $NumBars = scalar(@{$Values[0]});
12784:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12785:     my %ValuesHash;
12786:     my $NumSets=1;
12787:     foreach my $array (@Values) {
12788:         next if (! ref($array));
12789:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12790:             join(',',@$array);
12791:     }
12792:     #
12793:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12794:     if ($NumBars < 3) {
12795:         $width = 120+$NumBars*32;
12796:         $xskip = 1;
12797:         $bar_width = 30;
12798:     } elsif ($NumBars < 5) {
12799:         $width = 120+$NumBars*20;
12800:         $xskip = 1;
12801:         $bar_width = 20;
12802:     } elsif ($NumBars < 10) {
12803:         $width = 120+$NumBars*15;
12804:         $xskip = 1;
12805:         $bar_width = 15;
12806:     } elsif ($NumBars <= 25) {
12807:         $width = 120+$NumBars*11;
12808:         $xskip = 5;
12809:         $bar_width = 8;
12810:     } elsif ($NumBars <= 50) {
12811:         $width = 120+$NumBars*8;
12812:         $xskip = 5;
12813:         $bar_width = 4;
12814:     } else {
12815:         $width = 120+$NumBars*8;
12816:         $xskip = 5;
12817:         $bar_width = 4;
12818:     }
12819:     #
12820:     $Max = 1 if ($Max < 1);
12821:     if ( int($Max) < $Max ) {
12822:         $Max++;
12823:         $Max = int($Max);
12824:     }
12825:     $Title  = '' if (! defined($Title));
12826:     $xlabel = '' if (! defined($xlabel));
12827:     $ylabel = '' if (! defined($ylabel));
12828:     $ValuesHash{$id.'.title'}    = &escape($Title);
12829:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12830:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12831:     $ValuesHash{$id.'.y_max_value'} = $Max;
12832:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12833:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12834:     $ValuesHash{$id.'.PlotType'} = 'bar';
12835:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12836:     $ValuesHash{$id.'.height'}   = $height;
12837:     $ValuesHash{$id.'.width'}    = $width;
12838:     $ValuesHash{$id.'.xskip'}    = $xskip;
12839:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12840:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12841:     #
12842:     # Deal with other parameters
12843:     while (my ($key,$value) = each(%$extra_settings)) {
12844:         $ValuesHash{$id.'.'.$key} = $value;
12845:     }
12846:     #
12847:     &Apache::lonnet::appenv(\%ValuesHash);
12848:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12849: }
12850: 
12851: ############################################################
12852: ############################################################
12853: 
12854: =pod
12855: 
12856: =item * &DrawXYGraph()
12857: 
12858: Facilitates the plotting of data in an XY graph.
12859: Puts plot definition data into the users environment in order for 
12860: graph.png to plot it.  Returns an <img> tag for the plot.
12861: 
12862: Inputs:
12863: 
12864: =over 4
12865: 
12866: =item $Title: string, the title of the plot
12867: 
12868: =item $xlabel: string, text describing the X-axis of the plot
12869: 
12870: =item $ylabel: string, text describing the Y-axis of the plot
12871: 
12872: =item $Max: scalar, the maximum Y value to use in the plot
12873: If $Max is < any data point, the graph will not be rendered.
12874: 
12875: =item $colors: Array ref containing the hex color codes for the data to be 
12876: plotted in.  If undefined, default values will be used.
12877: 
12878: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12879: 
12880: =item $Ydata: Array ref containing Array refs.  
12881: Each of the contained arrays will be plotted as a separate curve.
12882: 
12883: =item %Values: hash indicating or overriding any default values which are 
12884: passed to graph.png.  
12885: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12886: 
12887: =back
12888: 
12889: Returns:
12890: 
12891: An <img> tag which references graph.png and the appropriate identifying
12892: information for the plot.
12893: 
12894: =cut
12895: 
12896: ############################################################
12897: ############################################################
12898: sub DrawXYGraph {
12899:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12900:     #
12901:     # Create the identifier for the graph
12902:     my $identifier = &get_cgi_id();
12903:     my $id = 'cgi.'.$identifier;
12904:     #
12905:     $Title  = '' if (! defined($Title));
12906:     $xlabel = '' if (! defined($xlabel));
12907:     $ylabel = '' if (! defined($ylabel));
12908:     my %ValuesHash = 
12909:         (
12910:          $id.'.title'  => &escape($Title),
12911:          $id.'.xlabel' => &escape($xlabel),
12912:          $id.'.ylabel' => &escape($ylabel),
12913:          $id.'.y_max_value'=> $Max,
12914:          $id.'.labels'     => join(',',@$Xlabels),
12915:          $id.'.PlotType'   => 'XY',
12916:          );
12917:     #
12918:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12919:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12920:     }
12921:     #
12922:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12923:         return '';
12924:     }
12925:     my $NumSets=1;
12926:     foreach my $array (@{$Ydata}){
12927:         next if (! ref($array));
12928:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12929:     }
12930:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12931:     #
12932:     # Deal with other parameters
12933:     while (my ($key,$value) = each(%Values)) {
12934:         $ValuesHash{$id.'.'.$key} = $value;
12935:     }
12936:     #
12937:     &Apache::lonnet::appenv(\%ValuesHash);
12938:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12939: }
12940: 
12941: ############################################################
12942: ############################################################
12943: 
12944: =pod
12945: 
12946: =item * &DrawXYYGraph()
12947: 
12948: Facilitates the plotting of data in an XY graph with two Y axes.
12949: Puts plot definition data into the users environment in order for 
12950: graph.png to plot it.  Returns an <img> tag for the plot.
12951: 
12952: Inputs:
12953: 
12954: =over 4
12955: 
12956: =item $Title: string, the title of the plot
12957: 
12958: =item $xlabel: string, text describing the X-axis of the plot
12959: 
12960: =item $ylabel: string, text describing the Y-axis of the plot
12961: 
12962: =item $colors: Array ref containing the hex color codes for the data to be 
12963: plotted in.  If undefined, default values will be used.
12964: 
12965: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12966: 
12967: =item $Ydata1: The first data set
12968: 
12969: =item $Min1: The minimum value of the left Y-axis
12970: 
12971: =item $Max1: The maximum value of the left Y-axis
12972: 
12973: =item $Ydata2: The second data set
12974: 
12975: =item $Min2: The minimum value of the right Y-axis
12976: 
12977: =item $Max2: The maximum value of the left Y-axis
12978: 
12979: =item %Values: hash indicating or overriding any default values which are 
12980: passed to graph.png.  
12981: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12982: 
12983: =back
12984: 
12985: Returns:
12986: 
12987: An <img> tag which references graph.png and the appropriate identifying
12988: information for the plot.
12989: 
12990: =cut
12991: 
12992: ############################################################
12993: ############################################################
12994: sub DrawXYYGraph {
12995:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12996:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12997:     #
12998:     # Create the identifier for the graph
12999:     my $identifier = &get_cgi_id();
13000:     my $id = 'cgi.'.$identifier;
13001:     #
13002:     $Title  = '' if (! defined($Title));
13003:     $xlabel = '' if (! defined($xlabel));
13004:     $ylabel = '' if (! defined($ylabel));
13005:     my %ValuesHash = 
13006:         (
13007:          $id.'.title'  => &escape($Title),
13008:          $id.'.xlabel' => &escape($xlabel),
13009:          $id.'.ylabel' => &escape($ylabel),
13010:          $id.'.labels' => join(',',@$Xlabels),
13011:          $id.'.PlotType' => 'XY',
13012:          $id.'.NumSets' => 2,
13013:          $id.'.two_axes' => 1,
13014:          $id.'.y1_max_value' => $Max1,
13015:          $id.'.y1_min_value' => $Min1,
13016:          $id.'.y2_max_value' => $Max2,
13017:          $id.'.y2_min_value' => $Min2,
13018:          );
13019:     #
13020:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13021:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13022:     }
13023:     #
13024:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13025:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13026:         return '';
13027:     }
13028:     my $NumSets=1;
13029:     foreach my $array ($Ydata1,$Ydata2){
13030:         next if (! ref($array));
13031:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13032:     }
13033:     #
13034:     # Deal with other parameters
13035:     while (my ($key,$value) = each(%Values)) {
13036:         $ValuesHash{$id.'.'.$key} = $value;
13037:     }
13038:     #
13039:     &Apache::lonnet::appenv(\%ValuesHash);
13040:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13041: }
13042: 
13043: ############################################################
13044: ############################################################
13045: 
13046: =pod
13047: 
13048: =back 
13049: 
13050: =head1 Statistics helper routines?  
13051: 
13052: Bad place for them but what the hell.
13053: 
13054: =over 4
13055: 
13056: =item * &chartlink()
13057: 
13058: Returns a link to the chart for a specific student.  
13059: 
13060: Inputs:
13061: 
13062: =over 4
13063: 
13064: =item $linktext: The text of the link
13065: 
13066: =item $sname: The students username
13067: 
13068: =item $sdomain: The students domain
13069: 
13070: =back
13071: 
13072: =back
13073: 
13074: =cut
13075: 
13076: ############################################################
13077: ############################################################
13078: sub chartlink {
13079:     my ($linktext, $sname, $sdomain) = @_;
13080:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13081:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13082:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13083:        '">'.$linktext.'</a>';
13084: }
13085: 
13086: #######################################################
13087: #######################################################
13088: 
13089: =pod
13090: 
13091: =head1 Course Environment Routines
13092: 
13093: =over 4
13094: 
13095: =item * &restore_course_settings()
13096: 
13097: =item * &store_course_settings()
13098: 
13099: Restores/Store indicated form parameters from the course environment.
13100: Will not overwrite existing values of the form parameters.
13101: 
13102: Inputs: 
13103: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13104: 
13105: a hash ref describing the data to be stored.  For example:
13106:    
13107: %Save_Parameters = ('Status' => 'scalar',
13108:     'chartoutputmode' => 'scalar',
13109:     'chartoutputdata' => 'scalar',
13110:     'Section' => 'array',
13111:     'Group' => 'array',
13112:     'StudentData' => 'array',
13113:     'Maps' => 'array');
13114: 
13115: Returns: both routines return nothing
13116: 
13117: =back
13118: 
13119: =cut
13120: 
13121: #######################################################
13122: #######################################################
13123: sub store_course_settings {
13124:     return &store_settings($env{'request.course.id'},@_);
13125: }
13126: 
13127: sub store_settings {
13128:     # save to the environment
13129:     # appenv the same items, just to be safe
13130:     my $udom  = $env{'user.domain'};
13131:     my $uname = $env{'user.name'};
13132:     my ($context,$prefix,$Settings) = @_;
13133:     my %SaveHash;
13134:     my %AppHash;
13135:     while (my ($setting,$type) = each(%$Settings)) {
13136:         my $basename = join('.','internal',$context,$prefix,$setting);
13137:         my $envname = 'environment.'.$basename;
13138:         if (exists($env{'form.'.$setting})) {
13139:             # Save this value away
13140:             if ($type eq 'scalar' &&
13141:                 (! exists($env{$envname}) || 
13142:                  $env{$envname} ne $env{'form.'.$setting})) {
13143:                 $SaveHash{$basename} = $env{'form.'.$setting};
13144:                 $AppHash{$envname}   = $env{'form.'.$setting};
13145:             } elsif ($type eq 'array') {
13146:                 my $stored_form;
13147:                 if (ref($env{'form.'.$setting})) {
13148:                     $stored_form = join(',',
13149:                                         map {
13150:                                             &escape($_);
13151:                                         } sort(@{$env{'form.'.$setting}}));
13152:                 } else {
13153:                     $stored_form = 
13154:                         &escape($env{'form.'.$setting});
13155:                 }
13156:                 # Determine if the array contents are the same.
13157:                 if ($stored_form ne $env{$envname}) {
13158:                     $SaveHash{$basename} = $stored_form;
13159:                     $AppHash{$envname}   = $stored_form;
13160:                 }
13161:             }
13162:         }
13163:     }
13164:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13165:                                           $udom,$uname);
13166:     if ($put_result !~ /^(ok|delayed)/) {
13167:         &Apache::lonnet::logthis('unable to save form parameters, '.
13168:                                  'got error:'.$put_result);
13169:     }
13170:     # Make sure these settings stick around in this session, too
13171:     &Apache::lonnet::appenv(\%AppHash);
13172:     return;
13173: }
13174: 
13175: sub restore_course_settings {
13176:     return &restore_settings($env{'request.course.id'},@_);
13177: }
13178: 
13179: sub restore_settings {
13180:     my ($context,$prefix,$Settings) = @_;
13181:     while (my ($setting,$type) = each(%$Settings)) {
13182:         next if (exists($env{'form.'.$setting}));
13183:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13184:             '.'.$setting;
13185:         if (exists($env{$envname})) {
13186:             if ($type eq 'scalar') {
13187:                 $env{'form.'.$setting} = $env{$envname};
13188:             } elsif ($type eq 'array') {
13189:                 $env{'form.'.$setting} = [ 
13190:                                            map { 
13191:                                                &unescape($_); 
13192:                                            } split(',',$env{$envname})
13193:                                            ];
13194:             }
13195:         }
13196:     }
13197: }
13198: 
13199: #######################################################
13200: #######################################################
13201: 
13202: =pod
13203: 
13204: =head1 Domain E-mail Routines  
13205: 
13206: =over 4
13207: 
13208: =item * &build_recipient_list()
13209: 
13210: Build recipient lists for following types of e-mail:
13211: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13212: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13213: module change checking, student/employee ID conflict checks, as
13214: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13215: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13216: 
13217: Inputs:
13218: defmail (scalar - email address of default recipient),
13219: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13220: requestsmail, updatesmail, or idconflictsmail).
13221: 
13222: defdom (domain for which to retrieve configuration settings),
13223: 
13224: origmail (scalar - email address of recipient from loncapa.conf,
13225: i.e., predates configuration by DC via domainprefs.pm
13226: 
13227: Returns: comma separated list of addresses to which to send e-mail.
13228: 
13229: =back
13230: 
13231: =cut
13232: 
13233: ############################################################
13234: ############################################################
13235: sub build_recipient_list {
13236:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13237:     my @recipients;
13238:     my $otheremails;
13239:     my %domconfig =
13240:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13241:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13242:         if (exists($domconfig{'contacts'}{$mailing})) {
13243:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13244:                 my @contacts = ('adminemail','supportemail');
13245:                 foreach my $item (@contacts) {
13246:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13247:                         my $addr = $domconfig{'contacts'}{$item}; 
13248:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13249:                             push(@recipients,$addr);
13250:                         }
13251:                     }
13252:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13253:                 }
13254:             }
13255:         } elsif ($origmail ne '') {
13256:             push(@recipients,$origmail);
13257:         }
13258:     } elsif ($origmail ne '') {
13259:         push(@recipients,$origmail);
13260:     }
13261:     if (defined($defmail)) {
13262:         if ($defmail ne '') {
13263:             push(@recipients,$defmail);
13264:         }
13265:     }
13266:     if ($otheremails) {
13267:         my @others;
13268:         if ($otheremails =~ /,/) {
13269:             @others = split(/,/,$otheremails);
13270:         } else {
13271:             push(@others,$otheremails);
13272:         }
13273:         foreach my $addr (@others) {
13274:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13275:                 push(@recipients,$addr);
13276:             }
13277:         }
13278:     }
13279:     my $recipientlist = join(',',@recipients); 
13280:     return $recipientlist;
13281: }
13282: 
13283: ############################################################
13284: ############################################################
13285: 
13286: =pod
13287: 
13288: =head1 Course Catalog Routines
13289: 
13290: =over 4
13291: 
13292: =item * &gather_categories()
13293: 
13294: Converts category definitions - keys of categories hash stored in  
13295: coursecategories in configuration.db on the primary library server in a 
13296: domain - to an array.  Also generates javascript and idx hash used to 
13297: generate Domain Coordinator interface for editing Course Categories.
13298: 
13299: Inputs:
13300: 
13301: categories (reference to hash of category definitions).
13302: 
13303: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13304:       categories and subcategories).
13305: 
13306: idx (reference to hash of counters used in Domain Coordinator interface for 
13307:       editing Course Categories).
13308: 
13309: jsarray (reference to array of categories used to create Javascript arrays for
13310:          Domain Coordinator interface for editing Course Categories).
13311: 
13312: Returns: nothing
13313: 
13314: Side effects: populates cats, idx and jsarray. 
13315: 
13316: =cut
13317: 
13318: sub gather_categories {
13319:     my ($categories,$cats,$idx,$jsarray) = @_;
13320:     my %counters;
13321:     my $num = 0;
13322:     foreach my $item (keys(%{$categories})) {
13323:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13324:         if ($container eq '' && $depth == 0) {
13325:             $cats->[$depth][$categories->{$item}] = $cat;
13326:         } else {
13327:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13328:         }
13329:         my ($escitem,$tail) = split(/:/,$item,2);
13330:         if ($counters{$tail} eq '') {
13331:             $counters{$tail} = $num;
13332:             $num ++;
13333:         }
13334:         if (ref($idx) eq 'HASH') {
13335:             $idx->{$item} = $counters{$tail};
13336:         }
13337:         if (ref($jsarray) eq 'ARRAY') {
13338:             push(@{$jsarray->[$counters{$tail}]},$item);
13339:         }
13340:     }
13341:     return;
13342: }
13343: 
13344: =pod
13345: 
13346: =item * &extract_categories()
13347: 
13348: Used to generate breadcrumb trails for course categories.
13349: 
13350: Inputs:
13351: 
13352: categories (reference to hash of category definitions).
13353: 
13354: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13355:       categories and subcategories).
13356: 
13357: trails (reference to array of breacrumb trails for each category).
13358: 
13359: allitems (reference to hash - key is category key 
13360:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13361: 
13362: idx (reference to hash of counters used in Domain Coordinator interface for
13363:       editing Course Categories).
13364: 
13365: jsarray (reference to array of categories used to create Javascript arrays for
13366:          Domain Coordinator interface for editing Course Categories).
13367: 
13368: subcats (reference to hash of arrays containing all subcategories within each 
13369:          category, -recursive)
13370: 
13371: Returns: nothing
13372: 
13373: Side effects: populates trails and allitems hash references.
13374: 
13375: =cut
13376: 
13377: sub extract_categories {
13378:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13379:     if (ref($categories) eq 'HASH') {
13380:         &gather_categories($categories,$cats,$idx,$jsarray);
13381:         if (ref($cats->[0]) eq 'ARRAY') {
13382:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13383:                 my $name = $cats->[0][$i];
13384:                 my $item = &escape($name).'::0';
13385:                 my $trailstr;
13386:                 if ($name eq 'instcode') {
13387:                     $trailstr = &mt('Official courses (with institutional codes)');
13388:                 } elsif ($name eq 'communities') {
13389:                     $trailstr = &mt('Communities');
13390:                 } else {
13391:                     $trailstr = $name;
13392:                 }
13393:                 if ($allitems->{$item} eq '') {
13394:                     push(@{$trails},$trailstr);
13395:                     $allitems->{$item} = scalar(@{$trails})-1;
13396:                 }
13397:                 my @parents = ($name);
13398:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13399:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13400:                         my $category = $cats->[1]{$name}[$j];
13401:                         if (ref($subcats) eq 'HASH') {
13402:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13403:                         }
13404:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13405:                     }
13406:                 } else {
13407:                     if (ref($subcats) eq 'HASH') {
13408:                         $subcats->{$item} = [];
13409:                     }
13410:                 }
13411:             }
13412:         }
13413:     }
13414:     return;
13415: }
13416: 
13417: =pod
13418: 
13419: =item * &recurse_categories()
13420: 
13421: Recursively used to generate breadcrumb trails for course categories.
13422: 
13423: Inputs:
13424: 
13425: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13426:       categories and subcategories).
13427: 
13428: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13429: 
13430: category (current course category, for which breadcrumb trail is being generated).
13431: 
13432: trails (reference to array of breadcrumb trails for each category).
13433: 
13434: allitems (reference to hash - key is category key
13435:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13436: 
13437: parents (array containing containers directories for current category, 
13438:          back to top level). 
13439: 
13440: Returns: nothing
13441: 
13442: Side effects: populates trails and allitems hash references
13443: 
13444: =cut
13445: 
13446: sub recurse_categories {
13447:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13448:     my $shallower = $depth - 1;
13449:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13450:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13451:             my $name = $cats->[$depth]{$category}[$k];
13452:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13453:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13454:             if ($allitems->{$item} eq '') {
13455:                 push(@{$trails},$trailstr);
13456:                 $allitems->{$item} = scalar(@{$trails})-1;
13457:             }
13458:             my $deeper = $depth+1;
13459:             push(@{$parents},$category);
13460:             if (ref($subcats) eq 'HASH') {
13461:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13462:                 for (my $j=@{$parents}; $j>=0; $j--) {
13463:                     my $higher;
13464:                     if ($j > 0) {
13465:                         $higher = &escape($parents->[$j]).':'.
13466:                                   &escape($parents->[$j-1]).':'.$j;
13467:                     } else {
13468:                         $higher = &escape($parents->[$j]).'::'.$j;
13469:                     }
13470:                     push(@{$subcats->{$higher}},$subcat);
13471:                 }
13472:             }
13473:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13474:                                 $subcats);
13475:             pop(@{$parents});
13476:         }
13477:     } else {
13478:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13479:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13480:         if ($allitems->{$item} eq '') {
13481:             push(@{$trails},$trailstr);
13482:             $allitems->{$item} = scalar(@{$trails})-1;
13483:         }
13484:     }
13485:     return;
13486: }
13487: 
13488: =pod
13489: 
13490: =item * &assign_categories_table()
13491: 
13492: Create a datatable for display of hierarchical categories in a domain,
13493: with checkboxes to allow a course to be categorized. 
13494: 
13495: Inputs:
13496: 
13497: cathash - reference to hash of categories defined for the domain (from
13498:           configuration.db)
13499: 
13500: currcat - scalar with an & separated list of categories assigned to a course. 
13501: 
13502: type    - scalar contains course type (Course or Community).
13503: 
13504: Returns: $output (markup to be displayed) 
13505: 
13506: =cut
13507: 
13508: sub assign_categories_table {
13509:     my ($cathash,$currcat,$type) = @_;
13510:     my $output;
13511:     if (ref($cathash) eq 'HASH') {
13512:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13513:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13514:         $maxdepth = scalar(@cats);
13515:         if (@cats > 0) {
13516:             my $itemcount = 0;
13517:             if (ref($cats[0]) eq 'ARRAY') {
13518:                 my @currcategories;
13519:                 if ($currcat ne '') {
13520:                     @currcategories = split('&',$currcat);
13521:                 }
13522:                 my $table;
13523:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13524:                     my $parent = $cats[0][$i];
13525:                     next if ($parent eq 'instcode');
13526:                     if ($type eq 'Community') {
13527:                         next unless ($parent eq 'communities');
13528:                     } else {
13529:                         next if ($parent eq 'communities');
13530:                     }
13531:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13532:                     my $item = &escape($parent).'::0';
13533:                     my $checked = '';
13534:                     if (@currcategories > 0) {
13535:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13536:                             $checked = ' checked="checked"';
13537:                         }
13538:                     }
13539:                     my $parent_title = $parent;
13540:                     if ($parent eq 'communities') {
13541:                         $parent_title = &mt('Communities');
13542:                     }
13543:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13544:                               '<input type="checkbox" name="usecategory" value="'.
13545:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13546:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13547:                     my $depth = 1;
13548:                     push(@path,$parent);
13549:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13550:                     pop(@path);
13551:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13552:                     $itemcount ++;
13553:                 }
13554:                 if ($itemcount) {
13555:                     $output = &Apache::loncommon::start_data_table().
13556:                               $table.
13557:                               &Apache::loncommon::end_data_table();
13558:                 }
13559:             }
13560:         }
13561:     }
13562:     return $output;
13563: }
13564: 
13565: =pod
13566: 
13567: =item * &assign_category_rows()
13568: 
13569: Create a datatable row for display of nested categories in a domain,
13570: with checkboxes to allow a course to be categorized,called recursively.
13571: 
13572: Inputs:
13573: 
13574: itemcount - track row number for alternating colors
13575: 
13576: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13577:       categories and subcategories.
13578: 
13579: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13580: 
13581: parent - parent of current category item
13582: 
13583: path - Array containing all categories back up through the hierarchy from the
13584:        current category to the top level.
13585: 
13586: currcategories - reference to array of current categories assigned to the course
13587: 
13588: Returns: $output (markup to be displayed).
13589: 
13590: =cut
13591: 
13592: sub assign_category_rows {
13593:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13594:     my ($text,$name,$item,$chgstr);
13595:     if (ref($cats) eq 'ARRAY') {
13596:         my $maxdepth = scalar(@{$cats});
13597:         if (ref($cats->[$depth]) eq 'HASH') {
13598:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13599:                 my $numchildren = @{$cats->[$depth]{$parent}};
13600:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13601:                 $text .= '<td><table class="LC_data_table">';
13602:                 for (my $j=0; $j<$numchildren; $j++) {
13603:                     $name = $cats->[$depth]{$parent}[$j];
13604:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13605:                     my $deeper = $depth+1;
13606:                     my $checked = '';
13607:                     if (ref($currcategories) eq 'ARRAY') {
13608:                         if (@{$currcategories} > 0) {
13609:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13610:                                 $checked = ' checked="checked"';
13611:                             }
13612:                         }
13613:                     }
13614:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13615:                              '<input type="checkbox" name="usecategory" value="'.
13616:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13617:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13618:                              '</td><td>';
13619:                     if (ref($path) eq 'ARRAY') {
13620:                         push(@{$path},$name);
13621:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13622:                         pop(@{$path});
13623:                     }
13624:                     $text .= '</td></tr>';
13625:                 }
13626:                 $text .= '</table></td>';
13627:             }
13628:         }
13629:     }
13630:     return $text;
13631: }
13632: 
13633: ############################################################
13634: ############################################################
13635: 
13636: 
13637: sub commit_customrole {
13638:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13639:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13640:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13641:                          ($end?', ending '.localtime($end):'').': <b>'.
13642:               &Apache::lonnet::assigncustomrole(
13643:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13644:                  '</b><br />';
13645:     return $output;
13646: }
13647: 
13648: sub commit_standardrole {
13649:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13650:     my ($output,$logmsg,$linefeed);
13651:     if ($context eq 'auto') {
13652:         $linefeed = "\n";
13653:     } else {
13654:         $linefeed = "<br />\n";
13655:     }  
13656:     if ($three eq 'st') {
13657:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13658:                                          $one,$two,$sec,$context,$credits);
13659:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13660:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13661:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13662:         } else {
13663:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13664:                ($start?', '.&mt('starting').' '.localtime($start):'').
13665:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13666:             if ($context eq 'auto') {
13667:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13668:             } else {
13669:                $output .= '<b>'.$result.'</b>'.$linefeed.
13670:                &mt('Add to classlist').': <b>ok</b>';
13671:             }
13672:             $output .= $linefeed;
13673:         }
13674:     } else {
13675:         $output = &mt('Assigning').' '.$three.' in '.$url.
13676:                ($start?', '.&mt('starting').' '.localtime($start):'').
13677:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13678:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13679:         if ($context eq 'auto') {
13680:             $output .= $result.$linefeed;
13681:         } else {
13682:             $output .= '<b>'.$result.'</b>'.$linefeed;
13683:         }
13684:     }
13685:     return $output;
13686: }
13687: 
13688: sub commit_studentrole {
13689:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13690:         $credits) = @_;
13691:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13692:     if ($context eq 'auto') {
13693:         $linefeed = "\n";
13694:     } else {
13695:         $linefeed = '<br />'."\n";
13696:     }
13697:     if (defined($one) && defined($two)) {
13698:         my $cid=$one.'_'.$two;
13699:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13700:         my $secchange = 0;
13701:         my $expire_role_result;
13702:         my $modify_section_result;
13703:         if ($oldsec ne '-1') { 
13704:             if ($oldsec ne $sec) {
13705:                 $secchange = 1;
13706:                 my $now = time;
13707:                 my $uurl='/'.$cid;
13708:                 $uurl=~s/\_/\//g;
13709:                 if ($oldsec) {
13710:                     $uurl.='/'.$oldsec;
13711:                 }
13712:                 $oldsecurl = $uurl;
13713:                 $expire_role_result = 
13714:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13715:                 if ($env{'request.course.sec'} ne '') { 
13716:                     if ($expire_role_result eq 'refused') {
13717:                         my @roles = ('st');
13718:                         my @statuses = ('previous');
13719:                         my @roledoms = ($one);
13720:                         my $withsec = 1;
13721:                         my %roleshash = 
13722:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13723:                                               \@statuses,\@roles,\@roledoms,$withsec);
13724:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13725:                             my ($oldstart,$oldend) = 
13726:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13727:                             if ($oldend > 0 && $oldend <= $now) {
13728:                                 $expire_role_result = 'ok';
13729:                             }
13730:                         }
13731:                     }
13732:                 }
13733:                 $result = $expire_role_result;
13734:             }
13735:         }
13736:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13737:             $modify_section_result = 
13738:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13739:                                                            undef,undef,undef,$sec,
13740:                                                            $end,$start,'','',$cid,
13741:                                                            '',$context,$credits);
13742:             if ($modify_section_result =~ /^ok/) {
13743:                 if ($secchange == 1) {
13744:                     if ($sec eq '') {
13745:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13746:                     } else {
13747:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13748:                     }
13749:                 } elsif ($oldsec eq '-1') {
13750:                     if ($sec eq '') {
13751:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13752:                     } else {
13753:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13754:                     }
13755:                 } else {
13756:                     if ($sec eq '') {
13757:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13758:                     } else {
13759:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13760:                     }
13761:                 }
13762:             } else {
13763:                 if ($secchange) {       
13764:                     $$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;
13765:                 } else {
13766:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13767:                 }
13768:             }
13769:             $result = $modify_section_result;
13770:         } elsif ($secchange == 1) {
13771:             if ($oldsec eq '') {
13772:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13773:             } else {
13774:                 $$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;
13775:             }
13776:             if ($expire_role_result eq 'refused') {
13777:                 my $newsecurl = '/'.$cid;
13778:                 $newsecurl =~ s/\_/\//g;
13779:                 if ($sec ne '') {
13780:                     $newsecurl.='/'.$sec;
13781:                 }
13782:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13783:                     if ($sec eq '') {
13784:                         $$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;
13785:                     } else {
13786:                         $$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;
13787:                     }
13788:                 }
13789:             }
13790:         }
13791:     } else {
13792:         $$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;
13793:         $result = "error: incomplete course id\n";
13794:     }
13795:     return $result;
13796: }
13797: 
13798: sub show_role_extent {
13799:     my ($scope,$context,$role) = @_;
13800:     $scope =~ s{^/}{};
13801:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13802:     push(@courseroles,'co');
13803:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13804:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13805:         $scope =~ s{/}{_};
13806:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13807:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13808:         my ($audom,$auname) = split(/\//,$scope);
13809:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13810:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13811:     } else {
13812:         $scope =~ s{/$}{};
13813:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13814:                    &Apache::lonnet::domain($scope,'description').'</span>');
13815:     }
13816: }
13817: 
13818: ############################################################
13819: ############################################################
13820: 
13821: sub check_clone {
13822:     my ($args,$linefeed) = @_;
13823:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13824:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13825:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13826:     my $clonemsg;
13827:     my $can_clone = 0;
13828:     my $lctype = lc($args->{'crstype'});
13829:     if ($lctype ne 'community') {
13830:         $lctype = 'course';
13831:     }
13832:     if ($clonehome eq 'no_host') {
13833:         if ($args->{'crstype'} eq 'Community') {
13834:             $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'});
13835:         } else {
13836:             $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'});
13837:         }     
13838:     } else {
13839: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13840:         if ($args->{'crstype'} eq 'Community') {
13841:             if ($clonedesc{'type'} ne 'Community') {
13842:                  $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'});
13843:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13844:             }
13845:         }
13846: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13847:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13848: 	    $can_clone = 1;
13849: 	} else {
13850: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13851: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13852: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13853:             if (grep(/^\*$/,@cloners)) {
13854:                 $can_clone = 1;
13855:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13856:                 $can_clone = 1;
13857:             } else {
13858:                 my $ccrole = 'cc';
13859:                 if ($args->{'crstype'} eq 'Community') {
13860:                     $ccrole = 'co';
13861:                 }
13862: 	        my %roleshash =
13863: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13864: 					 $args->{'ccdomain'},
13865:                                          'userroles',['active'],[$ccrole],
13866: 					 [$args->{'clonedomain'}]);
13867: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13868:                     $can_clone = 1;
13869:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13870:                     $can_clone = 1;
13871:                 } else {
13872:                     if ($args->{'crstype'} eq 'Community') {
13873:                         $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'});
13874:                     } else {
13875:                         $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'});
13876:                     }
13877: 	        }
13878: 	    }
13879:         }
13880:     }
13881:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13882: }
13883: 
13884: sub construct_course {
13885:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
13886:     my $outcome;
13887:     my $linefeed =  '<br />'."\n";
13888:     if ($context eq 'auto') {
13889:         $linefeed = "\n";
13890:     }
13891: 
13892: #
13893: # Are we cloning?
13894: #
13895:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13896:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13897: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13898: 	if ($context ne 'auto') {
13899:             if ($clonemsg ne '') {
13900: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13901:             }
13902: 	}
13903: 	$outcome .= $clonemsg.$linefeed;
13904: 
13905:         if (!$can_clone) {
13906: 	    return (0,$outcome);
13907: 	}
13908:     }
13909: 
13910: #
13911: # Open course
13912: #
13913:     my $crstype = lc($args->{'crstype'});
13914:     my %cenv=();
13915:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13916:                                              $args->{'cdescr'},
13917:                                              $args->{'curl'},
13918:                                              $args->{'course_home'},
13919:                                              $args->{'nonstandard'},
13920:                                              $args->{'crscode'},
13921:                                              $args->{'ccuname'}.':'.
13922:                                              $args->{'ccdomain'},
13923:                                              $args->{'crstype'},
13924:                                              $cnum,$context,$category);
13925: 
13926:     # Note: The testing routines depend on this being output; see 
13927:     # Utils::Course. This needs to at least be output as a comment
13928:     # if anyone ever decides to not show this, and Utils::Course::new
13929:     # will need to be suitably modified.
13930:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13931:     if ($$courseid =~ /^error:/) {
13932:         return (0,$outcome);
13933:     }
13934: 
13935: #
13936: # Check if created correctly
13937: #
13938:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13939:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13940:     if ($crsuhome eq 'no_host') {
13941:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13942:         return (0,$outcome);
13943:     }
13944:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13945: 
13946: #
13947: # Do the cloning
13948: #   
13949:     if ($can_clone && $cloneid) {
13950: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13951: 	if ($context ne 'auto') {
13952: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13953: 	}
13954: 	$outcome .= $clonemsg.$linefeed;
13955: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13956: # Copy all files
13957: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13958: # Restore URL
13959: 	$cenv{'url'}=$oldcenv{'url'};
13960: # Restore title
13961: 	$cenv{'description'}=$oldcenv{'description'};
13962: # Restore creation date, creator and creation context.
13963:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13964:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13965:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13966: # Mark as cloned
13967: 	$cenv{'clonedfrom'}=$cloneid;
13968: # Need to clone grading mode
13969:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13970:         $cenv{'grading'}=$newenv{'grading'};
13971: # Do not clone these environment entries
13972:         &Apache::lonnet::del('environment',
13973:                   ['default_enrollment_start_date',
13974:                    'default_enrollment_end_date',
13975:                    'question.email',
13976:                    'policy.email',
13977:                    'comment.email',
13978:                    'pch.users.denied',
13979:                    'plc.users.denied',
13980:                    'hidefromcat',
13981:                    'checkforpriv',
13982:                    'categories',
13983:                    'internal.uniquecode'],
13984:                    $$crsudom,$$crsunum);
13985:     }
13986: 
13987: #
13988: # Set environment (will override cloned, if existing)
13989: #
13990:     my @sections = ();
13991:     my @xlists = ();
13992:     if ($args->{'crstype'}) {
13993:         $cenv{'type'}=$args->{'crstype'};
13994:     }
13995:     if ($args->{'crsid'}) {
13996:         $cenv{'courseid'}=$args->{'crsid'};
13997:     }
13998:     if ($args->{'crscode'}) {
13999:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14000:     }
14001:     if ($args->{'crsquota'} ne '') {
14002:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14003:     } else {
14004:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14005:     }
14006:     if ($args->{'ccuname'}) {
14007:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14008:                                         ':'.$args->{'ccdomain'};
14009:     } else {
14010:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14011:     }
14012:     if ($args->{'defaultcredits'}) {
14013:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14014:     }
14015:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14016:     if ($args->{'crssections'}) {
14017:         $cenv{'internal.sectionnums'} = '';
14018:         if ($args->{'crssections'} =~ m/,/) {
14019:             @sections = split/,/,$args->{'crssections'};
14020:         } else {
14021:             $sections[0] = $args->{'crssections'};
14022:         }
14023:         if (@sections > 0) {
14024:             foreach my $item (@sections) {
14025:                 my ($sec,$gp) = split/:/,$item;
14026:                 my $class = $args->{'crscode'}.$sec;
14027:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14028:                 $cenv{'internal.sectionnums'} .= $item.',';
14029:                 unless ($addcheck eq 'ok') {
14030:                     push @badclasses, $class;
14031:                 }
14032:             }
14033:             $cenv{'internal.sectionnums'} =~ s/,$//;
14034:         }
14035:     }
14036: # do not hide course coordinator from staff listing, 
14037: # even if privileged
14038:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14039: # add course coordinator's domain to domains to check for privileged users
14040: # if different to course domain
14041:     if ($$crsudom ne $args->{'ccdomain'}) {
14042:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14043:     }
14044: # add crosslistings
14045:     if ($args->{'crsxlist'}) {
14046:         $cenv{'internal.crosslistings'}='';
14047:         if ($args->{'crsxlist'} =~ m/,/) {
14048:             @xlists = split/,/,$args->{'crsxlist'};
14049:         } else {
14050:             $xlists[0] = $args->{'crsxlist'};
14051:         }
14052:         if (@xlists > 0) {
14053:             foreach my $item (@xlists) {
14054:                 my ($xl,$gp) = split/:/,$item;
14055:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14056:                 $cenv{'internal.crosslistings'} .= $item.',';
14057:                 unless ($addcheck eq 'ok') {
14058:                     push @badclasses, $xl;
14059:                 }
14060:             }
14061:             $cenv{'internal.crosslistings'} =~ s/,$//;
14062:         }
14063:     }
14064:     if ($args->{'autoadds'}) {
14065:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14066:     }
14067:     if ($args->{'autodrops'}) {
14068:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14069:     }
14070: # check for notification of enrollment changes
14071:     my @notified = ();
14072:     if ($args->{'notify_owner'}) {
14073:         if ($args->{'ccuname'} ne '') {
14074:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14075:         }
14076:     }
14077:     if ($args->{'notify_dc'}) {
14078:         if ($uname ne '') { 
14079:             push(@notified,$uname.':'.$udom);
14080:         }
14081:     }
14082:     if (@notified > 0) {
14083:         my $notifylist;
14084:         if (@notified > 1) {
14085:             $notifylist = join(',',@notified);
14086:         } else {
14087:             $notifylist = $notified[0];
14088:         }
14089:         $cenv{'internal.notifylist'} = $notifylist;
14090:     }
14091:     if (@badclasses > 0) {
14092:         my %lt=&Apache::lonlocal::texthash(
14093:                 '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',
14094:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14095:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14096:         );
14097:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14098:                            ' ('.$lt{'adby'}.')';
14099:         if ($context eq 'auto') {
14100:             $outcome .= $badclass_msg.$linefeed;
14101:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14102:             foreach my $item (@badclasses) {
14103:                 if ($context eq 'auto') {
14104:                     $outcome .= " - $item\n";
14105:                 } else {
14106:                     $outcome .= "<li>$item</li>\n";
14107:                 }
14108:             }
14109:             if ($context eq 'auto') {
14110:                 $outcome .= $linefeed;
14111:             } else {
14112:                 $outcome .= "</ul><br /><br /></div>\n";
14113:             }
14114:         } 
14115:     }
14116:     if ($args->{'no_end_date'}) {
14117:         $args->{'endaccess'} = 0;
14118:     }
14119:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14120:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14121:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14122:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14123:     if ($args->{'showphotos'}) {
14124:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14125:     }
14126:     $cenv{'internal.authtype'} = $args->{'authtype'};
14127:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14128:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14129:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14130:             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'); 
14131:             if ($context eq 'auto') {
14132:                 $outcome .= $krb_msg;
14133:             } else {
14134:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14135:             }
14136:             $outcome .= $linefeed;
14137:         }
14138:     }
14139:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14140:        if ($args->{'setpolicy'}) {
14141:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14142:        }
14143:        if ($args->{'setcontent'}) {
14144:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14145:        }
14146:     }
14147:     if ($args->{'reshome'}) {
14148: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14149: 	$cenv{'reshome'}=~s/\/+$/\//;
14150:     }
14151: #
14152: # course has keyed access
14153: #
14154:     if ($args->{'setkeys'}) {
14155:        $cenv{'keyaccess'}='yes';
14156:     }
14157: # if specified, key authority is not course, but user
14158: # only active if keyaccess is yes
14159:     if ($args->{'keyauth'}) {
14160: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14161: 	$user = &LONCAPA::clean_username($user);
14162: 	$domain = &LONCAPA::clean_username($domain);
14163: 	if ($user ne '' && $domain ne '') {
14164: 	    $cenv{'keyauth'}=$user.':'.$domain;
14165: 	}
14166:     }
14167: 
14168: #
14169: #  generate and store uniquecode (available to course requester), if course should have one.
14170: #
14171:     if ($args->{'uniquecode'}) {
14172:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14173:         if ($code) {
14174:             $cenv{'internal.uniquecode'} = $code;
14175:             my %crsinfo =
14176:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14177:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14178:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14179:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14180:             }
14181:             if (ref($coderef)) {
14182:                 $$coderef = $code;
14183:             }
14184:         }
14185:     }
14186: 
14187:     if ($args->{'disresdis'}) {
14188:         $cenv{'pch.roles.denied'}='st';
14189:     }
14190:     if ($args->{'disablechat'}) {
14191:         $cenv{'plc.roles.denied'}='st';
14192:     }
14193: 
14194:     # Record we've not yet viewed the Course Initialization Helper for this 
14195:     # course
14196:     $cenv{'course.helper.not.run'} = 1;
14197:     #
14198:     # Use new Randomseed
14199:     #
14200:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14201:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14202:     #
14203:     # The encryption code and receipt prefix for this course
14204:     #
14205:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14206:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14207:     #
14208:     # By default, use standard grading
14209:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14210: 
14211:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14212:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14213: #
14214: # Open all assignments
14215: #
14216:     if ($args->{'openall'}) {
14217:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14218:        my %storecontent = ($storeunder         => time,
14219:                            $storeunder.'.type' => 'date_start');
14220:        
14221:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14222:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14223:    }
14224: #
14225: # Set first page
14226: #
14227:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14228: 	    || ($cloneid)) {
14229: 	use LONCAPA::map;
14230: 	$outcome .= &mt('Setting first resource').': ';
14231: 
14232: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14233:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14234: 
14235:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14236:         my $title; my $url;
14237:         if ($args->{'firstres'} eq 'syl') {
14238: 	    $title=&mt('Syllabus');
14239:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14240:         } else {
14241:             $title=&mt('Table of Contents');
14242:             $url='/adm/navmaps';
14243:         }
14244: 
14245:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14246: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14247: 
14248: 	if ($errtext) { $fatal=2; }
14249:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14250:     }
14251: 
14252:     return (1,$outcome);
14253: }
14254: 
14255: sub make_unique_code {
14256:     my ($cdom,$cnum) = @_;
14257:     # get lock on uniquecodes db
14258:     my $lockhash = {
14259:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
14260:                                                   ':'.$env{'user.domain'},
14261:                    };
14262:     my $tries = 0;
14263:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14264:     my ($code,$error);
14265: 
14266:     while (($gotlock ne 'ok') && ($tries<3)) {
14267:         $tries ++;
14268:         sleep 1;
14269:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14270:     }
14271:     if ($gotlock eq 'ok') {
14272:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14273:         my $gotcode;
14274:         my $attempts = 0;
14275:         while ((!$gotcode) && ($attempts < 100)) {
14276:             $code = &generate_code();
14277:             if (!exists($currcodes{$code})) {
14278:                 $gotcode = 1;
14279:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14280:                     $error = 'nostore';
14281:                 }
14282:             }
14283:             $attempts ++;
14284:         }
14285:         my @del_lock = ($cnum."\0".'uniquecodes');
14286:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14287:     } else {
14288:         $error = 'nolock';
14289:     }
14290:     return ($code,$error);
14291: }
14292: 
14293: sub generate_code {
14294:     my $code;
14295:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14296:     for (my $i=0; $i<6; $i++) {
14297:         my $lettnum = int (rand 2);
14298:         my $item = '';
14299:         if ($lettnum) {
14300:             $item = $letts[int( rand(18) )];
14301:         } else {
14302:             $item = 1+int( rand(8) );
14303:         }
14304:         $code .= $item;
14305:     }
14306:     return $code;
14307: }
14308: 
14309: ############################################################
14310: ############################################################
14311: 
14312: #SD
14313: # only Community and Course, or anything else?
14314: sub course_type {
14315:     my ($cid) = @_;
14316:     if (!defined($cid)) {
14317:         $cid = $env{'request.course.id'};
14318:     }
14319:     if (defined($env{'course.'.$cid.'.type'})) {
14320:         return $env{'course.'.$cid.'.type'};
14321:     } else {
14322:         return 'Course';
14323:     }
14324: }
14325: 
14326: sub group_term {
14327:     my $crstype = &course_type();
14328:     my %names = (
14329:                   'Course' => 'group',
14330:                   'Community' => 'group',
14331:                 );
14332:     return $names{$crstype};
14333: }
14334: 
14335: sub course_types {
14336:     my @types = ('official','unofficial','community','textbook');
14337:     my %typename = (
14338:                          official   => 'Official course',
14339:                          unofficial => 'Unofficial course',
14340:                          community  => 'Community',
14341:                          textbook   => 'Textbook course',
14342:                    );
14343:     return (\@types,\%typename);
14344: }
14345: 
14346: sub icon {
14347:     my ($file)=@_;
14348:     my $curfext = lc((split(/\./,$file))[-1]);
14349:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14350:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14351:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14352: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14353: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14354: 	            $curfext.".gif") {
14355: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14356: 		$curfext.".gif";
14357: 	}
14358:     }
14359:     return &lonhttpdurl($iconname);
14360: } 
14361: 
14362: sub lonhttpdurl {
14363: #
14364: # Had been used for "small fry" static images on separate port 8080.
14365: # Modify here if lightweight http functionality desired again.
14366: # Currently eliminated due to increasing firewall issues.
14367: #
14368:     my ($url)=@_;
14369:     return $url;
14370: }
14371: 
14372: sub connection_aborted {
14373:     my ($r)=@_;
14374:     $r->print(" ");$r->rflush();
14375:     my $c = $r->connection;
14376:     return $c->aborted();
14377: }
14378: 
14379: #    Escapes strings that may have embedded 's that will be put into
14380: #    strings as 'strings'.
14381: sub escape_single {
14382:     my ($input) = @_;
14383:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14384:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14385:     return $input;
14386: }
14387: 
14388: #  Same as escape_single, but escape's "'s  This 
14389: #  can be used for  "strings"
14390: sub escape_double {
14391:     my ($input) = @_;
14392:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14393:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14394:     return $input;
14395: }
14396:  
14397: #   Escapes the last element of a full URL.
14398: sub escape_url {
14399:     my ($url)   = @_;
14400:     my @urlslices = split(/\//, $url,-1);
14401:     my $lastitem = &escape(pop(@urlslices));
14402:     return join('/',@urlslices).'/'.$lastitem;
14403: }
14404: 
14405: sub compare_arrays {
14406:     my ($arrayref1,$arrayref2) = @_;
14407:     my (@difference,%count);
14408:     @difference = ();
14409:     %count = ();
14410:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14411:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14412:         foreach my $element (keys(%count)) {
14413:             if ($count{$element} == 1) {
14414:                 push(@difference,$element);
14415:             }
14416:         }
14417:     }
14418:     return @difference;
14419: }
14420: 
14421: # -------------------------------------------------------- Initialize user login
14422: sub init_user_environment {
14423:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14424:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14425: 
14426:     my $public=($username eq 'public' && $domain eq 'public');
14427: 
14428: # See if old ID present, if so, remove
14429: 
14430:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14431:     my $now=time;
14432: 
14433:     if ($public) {
14434: 	my $max_public=100;
14435: 	my $oldest;
14436: 	my $oldest_time=0;
14437: 	for(my $next=1;$next<=$max_public;$next++) {
14438: 	    if (-e $lonids."/publicuser_$next.id") {
14439: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14440: 		if ($mtime<$oldest_time || !$oldest_time) {
14441: 		    $oldest_time=$mtime;
14442: 		    $oldest=$next;
14443: 		}
14444: 	    } else {
14445: 		$cookie="publicuser_$next";
14446: 		last;
14447: 	    }
14448: 	}
14449: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14450:     } else {
14451: 	# if this isn't a robot, kill any existing non-robot sessions
14452: 	if (!$args->{'robot'}) {
14453: 	    opendir(DIR,$lonids);
14454: 	    while ($filename=readdir(DIR)) {
14455: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14456: 		    unlink($lonids.'/'.$filename);
14457: 		}
14458: 	    }
14459: 	    closedir(DIR);
14460: 	}
14461: # Give them a new cookie
14462: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14463: 		                   : $now.$$.int(rand(10000)));
14464: 	$cookie="$username\_$id\_$domain\_$authhost";
14465:     
14466: # Initialize roles
14467: 
14468: 	($userroles,$firstaccenv,$timerintenv) = 
14469:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14470:     }
14471: # ------------------------------------ Check browser type and MathML capability
14472: 
14473:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14474:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14475: 
14476: # ------------------------------------------------------------- Get environment
14477: 
14478:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14479:     my ($tmp) = keys(%userenv);
14480:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14481:     } else {
14482: 	undef(%userenv);
14483:     }
14484:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14485: 	$form->{'interface'}=$userenv{'interface'};
14486:     }
14487:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14488: 
14489: # --------------- Do not trust query string to be put directly into environment
14490:     foreach my $option ('interface','localpath','localres') {
14491:         $form->{$option}=~s/[\n\r\=]//gs;
14492:     }
14493: # --------------------------------------------------------- Write first profile
14494: 
14495:     {
14496: 	my %initial_env = 
14497: 	    ("user.name"          => $username,
14498: 	     "user.domain"        => $domain,
14499: 	     "user.home"          => $authhost,
14500: 	     "browser.type"       => $clientbrowser,
14501: 	     "browser.version"    => $clientversion,
14502: 	     "browser.mathml"     => $clientmathml,
14503: 	     "browser.unicode"    => $clientunicode,
14504: 	     "browser.os"         => $clientos,
14505:              "browser.mobile"     => $clientmobile,
14506:              "browser.info"       => $clientinfo,
14507: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14508: 	     "request.course.fn"  => '',
14509: 	     "request.course.uri" => '',
14510: 	     "request.course.sec" => '',
14511: 	     "request.role"       => 'cm',
14512: 	     "request.role.adv"   => $env{'user.adv'},
14513: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14514: 
14515:         if ($form->{'localpath'}) {
14516: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14517: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14518:         }
14519: 	
14520: 	if ($form->{'interface'}) {
14521: 	    $form->{'interface'}=~s/\W//gs;
14522: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14523: 	    $env{'browser.interface'}=$form->{'interface'};
14524: 	}
14525: 
14526:         if ($form->{'iptoken'}) {
14527:             my $lonhost = $r->dir_config('lonHostID');
14528:             $initial_env{"user.noloadbalance"} = $lonhost;
14529:             $env{'user.noloadbalance'} = $lonhost;
14530:         }
14531: 
14532:         my %is_adv = ( is_adv => $env{'user.adv'} );
14533:         my %domdef;
14534:         unless ($domain eq 'public') {
14535:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14536:         }
14537: 
14538:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14539:             $userenv{'availabletools.'.$tool} = 
14540:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14541:                                                   undef,\%userenv,\%domdef,\%is_adv);
14542:         }
14543: 
14544:         foreach my $crstype ('official','unofficial','community','textbook') {
14545:             $userenv{'canrequest.'.$crstype} =
14546:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14547:                                                   'reload','requestcourses',
14548:                                                   \%userenv,\%domdef,\%is_adv);
14549:         }
14550: 
14551:         $userenv{'canrequest.author'} =
14552:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14553:                                         'reload','requestauthor',
14554:                                         \%userenv,\%domdef,\%is_adv);
14555:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14556:                                              $domain,$username);
14557:         my $reqstatus = $reqauthor{'author_status'};
14558:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14559:             if (ref($reqauthor{'author'}) eq 'HASH') {
14560:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14561:                                                   $reqauthor{'author'}{'timestamp'};
14562:             }
14563:         }
14564: 
14565: 	$env{'user.environment'} = "$lonids/$cookie.id";
14566: 
14567: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14568: 		 &GDBM_WRCREAT(),0640)) {
14569: 	    &_add_to_env(\%disk_env,\%initial_env);
14570: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14571: 	    &_add_to_env(\%disk_env,$userroles);
14572:             if (ref($firstaccenv) eq 'HASH') {
14573:                 &_add_to_env(\%disk_env,$firstaccenv);
14574:             }
14575:             if (ref($timerintenv) eq 'HASH') {
14576:                 &_add_to_env(\%disk_env,$timerintenv);
14577:             }
14578: 	    if (ref($args->{'extra_env'})) {
14579: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14580: 	    }
14581: 	    untie(%disk_env);
14582: 	} else {
14583: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14584: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14585: 	    return 'error: '.$!;
14586: 	}
14587:     }
14588:     $env{'request.role'}='cm';
14589:     $env{'request.role.adv'}=$env{'user.adv'};
14590:     $env{'browser.type'}=$clientbrowser;
14591: 
14592:     return $cookie;
14593: 
14594: }
14595: 
14596: sub _add_to_env {
14597:     my ($idf,$env_data,$prefix) = @_;
14598:     if (ref($env_data) eq 'HASH') {
14599:         while (my ($key,$value) = each(%$env_data)) {
14600: 	    $idf->{$prefix.$key} = $value;
14601: 	    $env{$prefix.$key}   = $value;
14602:         }
14603:     }
14604: }
14605: 
14606: # --- Get the symbolic name of a problem and the url
14607: sub get_symb {
14608:     my ($request,$silent) = @_;
14609:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14610:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14611:     if ($symb eq '') {
14612:         if (!$silent) {
14613:             if (ref($request)) { 
14614:                 $request->print("Unable to handle ambiguous references:$url:.");
14615:             }
14616:             return ();
14617:         }
14618:     }
14619:     &Apache::lonenc::check_decrypt(\$symb);
14620:     return ($symb);
14621: }
14622: 
14623: # --------------------------------------------------------------Get annotation
14624: 
14625: sub get_annotation {
14626:     my ($symb,$enc) = @_;
14627: 
14628:     my $key = $symb;
14629:     if (!$enc) {
14630:         $key =
14631:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14632:     }
14633:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14634:     return $annotation{$key};
14635: }
14636: 
14637: sub clean_symb {
14638:     my ($symb,$delete_enc) = @_;
14639: 
14640:     &Apache::lonenc::check_decrypt(\$symb);
14641:     my $enc = $env{'request.enc'};
14642:     if ($delete_enc) {
14643:         delete($env{'request.enc'});
14644:     }
14645: 
14646:     return ($symb,$enc);
14647: }
14648: 
14649: sub build_release_hashes {
14650:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14651:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14652:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14653:                   (ref($randomizetry) eq 'HASH'));
14654:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14655:         my ($item,$name,$value) = split(/:/,$key);
14656:         if ($item eq 'parameter') {
14657:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14658:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14659:                     push(@{$checkparms->{$name}},$value);
14660:                 }
14661:             } else {
14662:                 push(@{$checkparms->{$name}},$value);
14663:             }
14664:         } elsif ($item eq 'resourcetag') {
14665:             if ($name eq 'responsetype') {
14666:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14667:             }
14668:         } elsif ($item eq 'course') {
14669:             if ($name eq 'crstype') {
14670:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14671:             }
14672:         }
14673:     }
14674:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14675:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14676:     return;
14677: }
14678: 
14679: sub update_content_constraints {
14680:     my ($cdom,$cnum,$chome,$cid) = @_;
14681:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14682:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14683:     my %checkresponsetypes;
14684:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14685:         my ($item,$name,$value) = split(/:/,$key);
14686:         if ($item eq 'resourcetag') {
14687:             if ($name eq 'responsetype') {
14688:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14689:             }
14690:         }
14691:     }
14692:     my $navmap = Apache::lonnavmaps::navmap->new();
14693:     if (defined($navmap)) {
14694:         my %allresponses;
14695:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14696:             my %responses = $res->responseTypes();
14697:             foreach my $key (keys(%responses)) {
14698:                 next unless(exists($checkresponsetypes{$key}));
14699:                 $allresponses{$key} += $responses{$key};
14700:             }
14701:         }
14702:         foreach my $key (keys(%allresponses)) {
14703:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14704:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14705:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14706:             }
14707:         }
14708:         undef($navmap);
14709:     }
14710:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14711:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14712:     }
14713:     return;
14714: }
14715: 
14716: sub allmaps_incourse {
14717:     my ($cdom,$cnum,$chome,$cid) = @_;
14718:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14719:         $cid = $env{'request.course.id'};
14720:         $cdom = $env{'course.'.$cid.'.domain'};
14721:         $cnum = $env{'course.'.$cid.'.num'};
14722:         $chome = $env{'course.'.$cid.'.home'};
14723:     }
14724:     my %allmaps = ();
14725:     my $lastchange =
14726:         &Apache::lonnet::get_coursechange($cdom,$cnum);
14727:     if ($lastchange > $env{'request.course.tied'}) {
14728:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14729:         unless ($ferr) {
14730:             &update_content_constraints($cdom,$cnum,$chome,$cid);
14731:         }
14732:     }
14733:     my $navmap = Apache::lonnavmaps::navmap->new();
14734:     if (defined($navmap)) {
14735:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14736:             $allmaps{$res->src()} = 1;
14737:         }
14738:     }
14739:     return \%allmaps;
14740: }
14741: 
14742: sub parse_supplemental_title {
14743:     my ($title) = @_;
14744: 
14745:     my ($foldertitle,$renametitle);
14746:     if ($title =~ /&amp;&amp;&amp;/) {
14747:         $title = &HTML::Entites::decode($title);
14748:     }
14749:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14750:         $renametitle=$4;
14751:         my ($time,$uname,$udom) = ($1,$2,$3);
14752:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14753:         my $name =  &plainname($uname,$udom);
14754:         $name = &HTML::Entities::encode($name,'"<>&\'');
14755:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14756:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14757:             $name.': <br />'.$foldertitle;
14758:     }
14759:     if (wantarray) {
14760:         return ($title,$foldertitle,$renametitle);
14761:     }
14762:     return $title;
14763: }
14764: 
14765: sub recurse_supplemental {
14766:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
14767:     if ($suppmap) {
14768:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
14769:         if ($fatal) {
14770:             $errors ++;
14771:         } else {
14772:             if ($#LONCAPA::map::resources > 0) {
14773:                 foreach my $res (@LONCAPA::map::resources) {
14774:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
14775:                     if (($src ne '') && ($status eq 'res')) {
14776:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
14777:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
14778:                         } else {
14779:                             $numfiles ++;
14780:                         }
14781:                     }
14782:                 }
14783:             }
14784:         }
14785:     }
14786:     return ($numfiles,$errors);
14787: }
14788: 
14789: sub symb_to_docspath {
14790:     my ($symb) = @_;
14791:     return unless ($symb);
14792:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14793:     if ($resurl=~/\.(sequence|page)$/) {
14794:         $mapurl=$resurl;
14795:     } elsif ($resurl eq 'adm/navmaps') {
14796:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14797:     }
14798:     my $mapresobj;
14799:     my $navmap = Apache::lonnavmaps::navmap->new();
14800:     if (ref($navmap)) {
14801:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14802:     }
14803:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14804:     my $type=$2;
14805:     my $path;
14806:     if (ref($mapresobj)) {
14807:         my $pcslist = $mapresobj->map_hierarchy();
14808:         if ($pcslist ne '') {
14809:             foreach my $pc (split(/,/,$pcslist)) {
14810:                 next if ($pc <= 1);
14811:                 my $res = $navmap->getByMapPc($pc);
14812:                 if (ref($res)) {
14813:                     my $thisurl = $res->src();
14814:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14815:                     my $thistitle = $res->title();
14816:                     $path .= '&'.
14817:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14818:                              &escape($thistitle).
14819:                              ':'.$res->randompick().
14820:                              ':'.$res->randomout().
14821:                              ':'.$res->encrypted().
14822:                              ':'.$res->randomorder().
14823:                              ':'.$res->is_page();
14824:                 }
14825:             }
14826:         }
14827:         $path =~ s/^\&//;
14828:         my $maptitle = $mapresobj->title();
14829:         if ($mapurl eq 'default') {
14830:             $maptitle = 'Main Content';
14831:         }
14832:         $path .= (($path ne '')? '&' : '').
14833:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14834:                  &escape($maptitle).
14835:                  ':'.$mapresobj->randompick().
14836:                  ':'.$mapresobj->randomout().
14837:                  ':'.$mapresobj->encrypted().
14838:                  ':'.$mapresobj->randomorder().
14839:                  ':'.$mapresobj->is_page();
14840:     } else {
14841:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14842:         my $ispage = (($type eq 'page')? 1 : '');
14843:         if ($mapurl eq 'default') {
14844:             $maptitle = 'Main Content';
14845:         }
14846:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14847:                 &escape($maptitle).':::::'.$ispage;
14848:     }
14849:     unless ($mapurl eq 'default') {
14850:         $path = 'default&'.
14851:                 &escape('Main Content').
14852:                 ':::::&'.$path;
14853:     }
14854:     return $path;
14855: }
14856: 
14857: sub captcha_display {
14858:     my ($context,$lonhost) = @_;
14859:     my ($output,$error);
14860:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14861:     if ($captcha eq 'original') {
14862:         $output = &create_captcha();
14863:         unless ($output) {
14864:             $error = 'captcha';
14865:         }
14866:     } elsif ($captcha eq 'recaptcha') {
14867:         $output = &create_recaptcha($pubkey);
14868:         unless ($output) {
14869:             $error = 'recaptcha';
14870:         }
14871:     }
14872:     return ($output,$error);
14873: }
14874: 
14875: sub captcha_response {
14876:     my ($context,$lonhost) = @_;
14877:     my ($captcha_chk,$captcha_error);
14878:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14879:     if ($captcha eq 'original') {
14880:         ($captcha_chk,$captcha_error) = &check_captcha();
14881:     } elsif ($captcha eq 'recaptcha') {
14882:         $captcha_chk = &check_recaptcha($privkey);
14883:     } else {
14884:         $captcha_chk = 1;
14885:     }
14886:     return ($captcha_chk,$captcha_error);
14887: }
14888: 
14889: sub get_captcha_config {
14890:     my ($context,$lonhost) = @_;
14891:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14892:     my $hostname = &Apache::lonnet::hostname($lonhost);
14893:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14894:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14895:     if ($context eq 'usercreation') {
14896:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14897:         if (ref($domconfig{$context}) eq 'HASH') {
14898:             $hashtocheck = $domconfig{$context}{'cancreate'};
14899:             if (ref($hashtocheck) eq 'HASH') {
14900:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14901:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14902:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14903:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14904:                     }
14905:                     if ($privkey && $pubkey) {
14906:                         $captcha = 'recaptcha';
14907:                     } else {
14908:                         $captcha = 'original';
14909:                     }
14910:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14911:                     $captcha = 'original';
14912:                 }
14913:             }
14914:         } else {
14915:             $captcha = 'captcha';
14916:         }
14917:     } elsif ($context eq 'login') {
14918:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14919:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14920:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14921:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14922:             if ($privkey && $pubkey) {
14923:                 $captcha = 'recaptcha';
14924:             } else {
14925:                 $captcha = 'original';
14926:             }
14927:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14928:             $captcha = 'original';
14929:         }
14930:     }
14931:     return ($captcha,$pubkey,$privkey);
14932: }
14933: 
14934: sub create_captcha {
14935:     my %captcha_params = &captcha_settings();
14936:     my ($output,$maxtries,$tries) = ('',10,0);
14937:     while ($tries < $maxtries) {
14938:         $tries ++;
14939:         my $captcha = Authen::Captcha->new (
14940:                                            output_folder => $captcha_params{'output_dir'},
14941:                                            data_folder   => $captcha_params{'db_dir'},
14942:                                           );
14943:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14944: 
14945:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14946:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14947:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14948:                      '<input type="text" size="5" name="code" value="" /><br />'.
14949:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14950:             last;
14951:         }
14952:     }
14953:     return $output;
14954: }
14955: 
14956: sub captcha_settings {
14957:     my %captcha_params = (
14958:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14959:                            www_output_dir => "/captchaspool",
14960:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14961:                            numchars       => '5',
14962:                          );
14963:     return %captcha_params;
14964: }
14965: 
14966: sub check_captcha {
14967:     my ($captcha_chk,$captcha_error);
14968:     my $code = $env{'form.code'};
14969:     my $md5sum = $env{'form.crypt'};
14970:     my %captcha_params = &captcha_settings();
14971:     my $captcha = Authen::Captcha->new(
14972:                       output_folder => $captcha_params{'output_dir'},
14973:                       data_folder   => $captcha_params{'db_dir'},
14974:                   );
14975:     $captcha_chk = $captcha->check_code($code,$md5sum);
14976:     my %captcha_hash = (
14977:                         0       => 'Code not checked (file error)',
14978:                        -1      => 'Failed: code expired',
14979:                        -2      => 'Failed: invalid code (not in database)',
14980:                        -3      => 'Failed: invalid code (code does not match crypt)',
14981:     );
14982:     if ($captcha_chk != 1) {
14983:         $captcha_error = $captcha_hash{$captcha_chk}
14984:     }
14985:     return ($captcha_chk,$captcha_error);
14986: }
14987: 
14988: sub create_recaptcha {
14989:     my ($pubkey) = @_;
14990:     my $use_ssl;
14991:     if ($ENV{'SERVER_PORT'} == 443) {
14992:         $use_ssl = 1;
14993:     }
14994:     my $captcha = Captcha::reCAPTCHA->new;
14995:     return $captcha->get_options_setter({theme => 'white'})."\n".
14996:            $captcha->get_html($pubkey,undef,$use_ssl).
14997:            &mt('If either word is hard to read, [_1] will replace them.',
14998:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14999:            '<br /><br />';
15000: }
15001: 
15002: sub check_recaptcha {
15003:     my ($privkey) = @_;
15004:     my $captcha_chk;
15005:     my $captcha = Captcha::reCAPTCHA->new;
15006:     my $captcha_result =
15007:         $captcha->check_answer(
15008:                                 $privkey,
15009:                                 $ENV{'REMOTE_ADDR'},
15010:                                 $env{'form.recaptcha_challenge_field'},
15011:                                 $env{'form.recaptcha_response_field'},
15012:                               );
15013:     if ($captcha_result->{is_valid}) {
15014:         $captcha_chk = 1;
15015:     }
15016:     return $captcha_chk;
15017: }
15018: 
15019: sub cleanup_html {
15020:     my ($incoming) = @_;
15021:     my $outgoing;
15022:     if ($incoming ne '') {
15023:         $outgoing = $incoming;
15024:         $outgoing =~ s/;/&#059;/g;
15025:         $outgoing =~ s/\#/&#035;/g;
15026:         $outgoing =~ s/\&/&#038;/g;
15027:         $outgoing =~ s/</&#060;/g;
15028:         $outgoing =~ s/>/&#062;/g;
15029:         $outgoing =~ s/\(/&#040/g;
15030:         $outgoing =~ s/\)/&#041;/g;
15031:         $outgoing =~ s/"/&#034;/g;
15032:         $outgoing =~ s/'/&#039;/g;
15033:         $outgoing =~ s/\$/&#036;/g;
15034:         $outgoing =~ s{/}{&#047;}g;
15035:         $outgoing =~ s/=/&#061;/g;
15036:         $outgoing =~ s/\\/&#092;/g
15037:     }
15038:     return $outgoing;
15039: }
15040: 
15041: =pod
15042: 
15043: =back
15044: 
15045: =cut
15046: 
15047: 1;
15048: __END__;
15049: 

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