File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1301: download - view: text, annotated - select for diffs
Sun Nov 12 13:15:25 2017 UTC (6 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Updating text in progress bar when there is no change in progress value
  requires explicit command because progressbar change action is only fired
  if value changes.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1301 2017/11/12 13:15:25 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 Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use LONCAPA::LWPReq;
   75: use DateTime::TimeZone;
   76: use DateTime::Locale;
   77: use Encode();
   78: use Text::Aspell;
   79: use Authen::Captcha;
   80: use Captcha::reCAPTCHA;
   81: use JSON::DWIW;
   82: use LWP::UserAgent;
   83: use Crypt::DES;
   84: use DynaLoader; # for Crypt::DES version
   85: use MIME::Lite;
   86: use MIME::Types;
   87: use File::Copy();
   88: use File::Path();
   89: 
   90: # ---------------------------------------------- Designs
   91: use vars qw(%defaultdesign);
   92: 
   93: my $readit;
   94: 
   95: 
   96: ##
   97: ## Global Variables
   98: ##
   99: 
  100: 
  101: # ----------------------------------------------- SSI with retries:
  102: #
  103: 
  104: =pod
  105: 
  106: =head1 Server Side include with retries:
  107: 
  108: =over 4
  109: 
  110: =item * &ssi_with_retries(resource,retries form)
  111: 
  112: Performs an ssi with some number of retries.  Retries continue either
  113: until the result is ok or until the retry count supplied by the
  114: caller is exhausted.  
  115: 
  116: Inputs:
  117: 
  118: =over 4
  119: 
  120: resource   - Identifies the resource to insert.
  121: 
  122: retries    - Count of the number of retries allowed.
  123: 
  124: form       - Hash that identifies the rendering options.
  125: 
  126: =back
  127: 
  128: Returns:
  129: 
  130: =over 4
  131: 
  132: content    - The content of the response.  If retries were exhausted this is empty.
  133: 
  134: response   - The response from the last attempt (which may or may not have been successful.
  135: 
  136: =back
  137: 
  138: =back
  139: 
  140: =cut
  141: 
  142: sub ssi_with_retries {
  143:     my ($resource, $retries, %form) = @_;
  144: 
  145: 
  146:     my $ok = 0;			# True if we got a good response.
  147:     my $content;
  148:     my $response;
  149: 
  150:     # Try to get the ssi done. within the retries count:
  151: 
  152:     do {
  153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  154: 	$ok      = $response->is_success;
  155:         if (!$ok) {
  156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  157:         }
  158: 	$retries--;
  159:     } while (!$ok && ($retries > 0));
  160: 
  161:     if (!$ok) {
  162: 	$content = '';		# On error return an empty content.
  163:     }
  164:     return ($content, $response);
  165: 
  166: }
  167: 
  168: 
  169: 
  170: # ----------------------------------------------- Filetypes/Languages/Copyright
  171: my %language;
  172: my %supported_language;
  173: my %supported_codes;
  174: my %latex_language;		# For choosing hyphenation in <transl..>
  175: my %latex_language_bykey;	# for choosing hyphenation from metadata
  176: my %cprtag;
  177: my %scprtag;
  178: my %fe; my %fd; my %fm;
  179: my %category_extensions;
  180: 
  181: # ---------------------------------------------- Thesaurus variables
  182: #
  183: # %Keywords:
  184: #      A hash used by &keyword to determine if a word is considered a keyword.
  185: # $thesaurus_db_file 
  186: #      Scalar containing the full path to the thesaurus database.
  187: 
  188: my %Keywords;
  189: my $thesaurus_db_file;
  190: 
  191: #
  192: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  193: # thesaurus.tab, and filecategories.tab.
  194: #
  195: BEGIN {
  196:     # Variable initialization
  197:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  198:     #
  199:     unless ($readit) {
  200: # ------------------------------------------------------------------- languages
  201:     {
  202:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  203:                                    '/language.tab';
  204:         if ( open(my $fh,"<$langtabfile") ) {
  205:             while (my $line = <$fh>) {
  206:                 next if ($line=~/^\#/);
  207:                 chomp($line);
  208:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  209:                 $language{$key}=$val.' - '.$enc;
  210:                 if ($sup) {
  211:                     $supported_language{$key}=$sup;
  212: 		    $supported_codes{$key}   = $code;
  213:                 }
  214: 		if ($latex) {
  215: 		    $latex_language_bykey{$key} = $latex;
  216: 		    $latex_language{$code} = $latex;
  217: 		}
  218:             }
  219:             close($fh);
  220:         }
  221:     }
  222: # ------------------------------------------------------------------ copyrights
  223:     {
  224:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  225:                                   '/copyright.tab';
  226:         if ( open (my $fh,"<$copyrightfile") ) {
  227:             while (my $line = <$fh>) {
  228:                 next if ($line=~/^\#/);
  229:                 chomp($line);
  230:                 my ($key,$val)=(split(/\s+/,$line,2));
  231:                 $cprtag{$key}=$val;
  232:             }
  233:             close($fh);
  234:         }
  235:     }
  236: # ----------------------------------------------------------- source copyrights
  237:     {
  238:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  239:                                   '/source_copyright.tab';
  240:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  241:             while (my $line = <$fh>) {
  242:                 next if ($line =~ /^\#/);
  243:                 chomp($line);
  244:                 my ($key,$val)=(split(/\s+/,$line,2));
  245:                 $scprtag{$key}=$val;
  246:             }
  247:             close($fh);
  248:         }
  249:     }
  250: 
  251: # -------------------------------------------------------------- default domain designs
  252:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  253:     my $designfile = $designdir.'/default.tab';
  254:     if ( open (my $fh,"<$designfile") ) {
  255:         while (my $line = <$fh>) {
  256:             next if ($line =~ /^\#/);
  257:             chomp($line);
  258:             my ($key,$val)=(split(/\=/,$line));
  259:             if ($val) { $defaultdesign{$key}=$val; }
  260:         }
  261:         close($fh);
  262:     }
  263: 
  264: # ------------------------------------------------------------- file categories
  265:     {
  266:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  267:                                   '/filecategories.tab';
  268:         if ( open (my $fh,"<$categoryfile") ) {
  269: 	    while (my $line = <$fh>) {
  270: 		next if ($line =~ /^\#/);
  271: 		chomp($line);
  272:                 my ($extension,$category)=(split(/\s+/,$line,2));
  273:                 push(@{$category_extensions{lc($category)}},$extension);
  274:             }
  275:             close($fh);
  276:         }
  277: 
  278:     }
  279: # ------------------------------------------------------------------ file types
  280:     {
  281:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  282:                '/filetypes.tab';
  283:         if ( open (my $fh,"<$typesfile") ) {
  284:             while (my $line = <$fh>) {
  285: 		next if ($line =~ /^\#/);
  286: 		chomp($line);
  287:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  288:                 if ($descr ne '') {
  289:                     $fe{$ending}=lc($emb);
  290:                     $fd{$ending}=$descr;
  291:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  292:                 }
  293:             }
  294:             close($fh);
  295:         }
  296:     }
  297:     &Apache::lonnet::logthis(
  298:              "<span style='color:yellow;'>INFO: Read file types</span>");
  299:     $readit=1;
  300:     }  # end of unless($readit) 
  301:     
  302: }
  303: 
  304: ###############################################################
  305: ##           HTML and Javascript Helper Functions            ##
  306: ###############################################################
  307: 
  308: =pod 
  309: 
  310: =head1 HTML and Javascript Functions
  311: 
  312: =over 4
  313: 
  314: =item * &browser_and_searcher_javascript()
  315: 
  316: X<browsing, javascript>X<searching, javascript>Returns a string
  317: containing javascript with two functions, C<openbrowser> and
  318: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  319: tags.
  320: 
  321: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  322: 
  323: inputs: formname, elementname, only, omit
  324: 
  325: formname and elementname indicate the name of the html form and name of
  326: the element that the results of the browsing selection are to be placed in. 
  327: 
  328: Specifying 'only' will restrict the browser to displaying only files
  329: with the given extension.  Can be a comma separated list.
  330: 
  331: Specifying 'omit' will restrict the browser to NOT displaying files
  332: with the given extension.  Can be a comma separated list.
  333: 
  334: =item * &opensearcher(formname,elementname) [javascript]
  335: 
  336: Inputs: formname, elementname
  337: 
  338: formname and elementname specify the name of the html form and the name
  339: of the element the selection from the search results will be placed in.
  340: 
  341: =cut
  342: 
  343: sub browser_and_searcher_javascript {
  344:     my ($mode)=@_;
  345:     if (!defined($mode)) { $mode='edit'; }
  346:     my $resurl=&escape_single(&lastresurl());
  347:     return <<END;
  348: // <!-- BEGIN LON-CAPA Internal
  349:     var editbrowser = null;
  350:     function openbrowser(formname,elementname,only,omit,titleelement) {
  351:         var url = '$resurl/?';
  352:         if (editbrowser == null) {
  353:             url += 'launch=1&';
  354:         }
  355:         url += 'catalogmode=interactive&';
  356:         url += 'mode=$mode&';
  357:         url += 'inhibitmenu=yes&';
  358:         url += 'form=' + formname + '&';
  359:         if (only != null) {
  360:             url += 'only=' + only + '&';
  361:         } else {
  362:             url += 'only=&';
  363: 	}
  364:         if (omit != null) {
  365:             url += 'omit=' + omit + '&';
  366:         } else {
  367:             url += 'omit=&';
  368: 	}
  369:         if (titleelement != null) {
  370:             url += 'titleelement=' + titleelement + '&';
  371:         } else {
  372: 	    url += 'titleelement=&';
  373: 	}
  374:         url += 'element=' + elementname + '';
  375:         var title = 'Browser';
  376:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  377:         options += ',width=700,height=600';
  378:         editbrowser = open(url,title,options,'1');
  379:         editbrowser.focus();
  380:     }
  381:     var editsearcher;
  382:     function opensearcher(formname,elementname,titleelement) {
  383:         var url = '/adm/searchcat?';
  384:         if (editsearcher == null) {
  385:             url += 'launch=1&';
  386:         }
  387:         url += 'catalogmode=interactive&';
  388:         url += 'mode=$mode&';
  389:         url += 'form=' + formname + '&';
  390:         if (titleelement != null) {
  391:             url += 'titleelement=' + titleelement + '&';
  392:         } else {
  393: 	    url += 'titleelement=&';
  394: 	}
  395:         url += 'element=' + elementname + '';
  396:         var title = 'Search';
  397:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  398:         options += ',width=700,height=600';
  399:         editsearcher = open(url,title,options,'1');
  400:         editsearcher.focus();
  401:     }
  402: // END LON-CAPA Internal -->
  403: END
  404: }
  405: 
  406: sub lastresurl {
  407:     if ($env{'environment.lastresurl'}) {
  408: 	return $env{'environment.lastresurl'}
  409:     } else {
  410: 	return '/res';
  411:     }
  412: }
  413: 
  414: sub storeresurl {
  415:     my $resurl=&Apache::lonnet::clutter(shift);
  416:     unless ($resurl=~/^\/res/) { return 0; }
  417:     $resurl=~s/\/$//;
  418:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  419:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  420:     return 1;
  421: }
  422: 
  423: sub studentbrowser_javascript {
  424:    unless (
  425:             (($env{'request.course.id'}) && 
  426:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  427: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  428: 					  '/'.$env{'request.course.sec'})
  429: 	      ))
  430:          || ($env{'request.role'}=~/^(au|dc|su)/)
  431:           ) { return ''; }  
  432:    return (<<'ENDSTDBRW');
  433: <script type="text/javascript" language="Javascript">
  434: // <![CDATA[
  435:     var stdeditbrowser;
  436:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  437:         var url = '/adm/pickstudent?';
  438:         var filter;
  439: 	if (!ignorefilter) {
  440: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  441: 	}
  442:         if (filter != null) {
  443:            if (filter != '') {
  444:                url += 'filter='+filter+'&';
  445: 	   }
  446:         }
  447:         url += 'form=' + formname + '&unameelement='+uname+
  448:                                     '&udomelement='+udom+
  449:                                     '&clicker='+clicker;
  450: 	if (roleflag) { url+="&roles=1"; }
  451:         if (courseadvonly) { url+="&courseadvonly=1"; }
  452:         var title = 'Student_Browser';
  453:         var options = 'scrollbars=1,resizable=1,menubar=0';
  454:         options += ',width=700,height=600';
  455:         stdeditbrowser = open(url,title,options,'1');
  456:         stdeditbrowser.focus();
  457:     }
  458: // ]]>
  459: </script>
  460: ENDSTDBRW
  461: }
  462: 
  463: sub resourcebrowser_javascript {
  464:    unless ($env{'request.course.id'}) { return ''; }
  465:    return (<<'ENDRESBRW');
  466: <script type="text/javascript" language="Javascript">
  467: // <![CDATA[
  468:     var reseditbrowser;
  469:     function openresbrowser(formname,reslink) {
  470:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  471:         var title = 'Resource_Browser';
  472:         var options = 'scrollbars=1,resizable=1,menubar=0';
  473:         options += ',width=700,height=500';
  474:         reseditbrowser = open(url,title,options,'1');
  475:         reseditbrowser.focus();
  476:     }
  477: // ]]>
  478: </script>
  479: ENDRESBRW
  480: }
  481: 
  482: sub selectstudent_link {
  483:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  484:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  485:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  486:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  487:    if ($env{'request.course.id'}) {  
  488:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  489: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  490: 					'/'.$env{'request.course.sec'})) {
  491: 	   return '';
  492:        }
  493:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  494:        if ($courseadvonly)  {
  495:            $callargs .= ",'',1,1";
  496:        }
  497:        return '<span class="LC_nobreak">'.
  498:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  499:               &mt('Select User').'</a></span>';
  500:    }
  501:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  502:        $callargs .= ",'',1"; 
  503:        return '<span class="LC_nobreak">'.
  504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  505:               &mt('Select User').'</a></span>';
  506:    }
  507:    return '';
  508: }
  509: 
  510: sub selectresource_link {
  511:    my ($form,$reslink,$arg)=@_;
  512:    
  513:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  514:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  515:    unless ($env{'request.course.id'}) { return $arg; }
  516:    return '<span class="LC_nobreak">'.
  517:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  518:               $arg.'</a></span>';
  519: }
  520: 
  521: 
  522: 
  523: sub authorbrowser_javascript {
  524:     return <<"ENDAUTHORBRW";
  525: <script type="text/javascript" language="JavaScript">
  526: // <![CDATA[
  527: var stdeditbrowser;
  528: 
  529: function openauthorbrowser(formname,udom) {
  530:     var url = '/adm/pickauthor?';
  531:     url += 'form='+formname+'&roledom='+udom;
  532:     var title = 'Author_Browser';
  533:     var options = 'scrollbars=1,resizable=1,menubar=0';
  534:     options += ',width=700,height=600';
  535:     stdeditbrowser = open(url,title,options,'1');
  536:     stdeditbrowser.focus();
  537: }
  538: 
  539: // ]]>
  540: </script>
  541: ENDAUTHORBRW
  542: }
  543: 
  544: sub coursebrowser_javascript {
  545:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  546:         $credits_element,$instcode) = @_;
  547:     my $wintitle = 'Course_Browser';
  548:     if ($crstype eq 'Community') {
  549:         $wintitle = 'Community_Browser';
  550:     }
  551:     my $id_functions = &javascript_index_functions();
  552:     my $output = '
  553: <script type="text/javascript" language="JavaScript">
  554: // <![CDATA[
  555:     var stdeditbrowser;'."\n";
  556: 
  557:     $output .= <<"ENDSTDBRW";
  558:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  559:         var url = '/adm/pickcourse?';
  560:         var formid = getFormIdByName(formname);
  561:         var domainfilter = getDomainFromSelectbox(formname,udom);
  562:         if (domainfilter != null) {
  563:            if (domainfilter != '') {
  564:                url += 'domainfilter='+domainfilter+'&';
  565: 	   }
  566:         }
  567:         url += 'form=' + formname + '&cnumelement='+uname+
  568: 	                            '&cdomelement='+udom+
  569:                                     '&cnameelement='+desc;
  570:         if (extra_element !=null && extra_element != '') {
  571:             if (formname == 'rolechoice' || formname == 'studentform') {
  572:                 url += '&roleelement='+extra_element;
  573:                 if (domainfilter == null || domainfilter == '') {
  574:                     url += '&domainfilter='+extra_element;
  575:                 }
  576:             }
  577:             else {
  578:                 if (formname == 'portform') {
  579:                     url += '&setroles='+extra_element;
  580:                 } else {
  581:                     if (formname == 'rules') {
  582:                         url += '&fixeddom='+extra_element; 
  583:                     }
  584:                 }
  585:             }     
  586:         }
  587:         if (type != null && type != '') {
  588:             url += '&type='+type;
  589:         }
  590:         if (type_elem != null && type_elem != '') {
  591:             url += '&typeelement='+type_elem;
  592:         }
  593:         if (formname == 'ccrs') {
  594:             var ownername = document.forms[formid].ccuname.value;
  595:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  596:             url += '&cloner='+ownername+':'+ownerdom;
  597:             if (type == 'Course') {
  598:                 url += '&crscode='+document.forms[formid].crscode.value;
  599:             }
  600:         }
  601:         if (formname == 'requestcrs') {
  602:             url += '&crsdom=$domainfilter&crscode=$instcode';
  603:         }
  604:         if (multflag !=null && multflag != '') {
  605:             url += '&multiple='+multflag;
  606:         }
  607:         var title = '$wintitle';
  608:         var options = 'scrollbars=1,resizable=1,menubar=0';
  609:         options += ',width=700,height=600';
  610:         stdeditbrowser = open(url,title,options,'1');
  611:         stdeditbrowser.focus();
  612:     }
  613: $id_functions
  614: ENDSTDBRW
  615:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  616:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  617:                                       $credits_element);
  618:     }
  619:     $output .= '
  620: // ]]>
  621: </script>';
  622:     return $output;
  623: }
  624: 
  625: sub javascript_index_functions {
  626:     return <<"ENDJS";
  627: 
  628: function getFormIdByName(formname) {
  629:     for (var i=0;i<document.forms.length;i++) {
  630:         if (document.forms[i].name == formname) {
  631:             return i;
  632:         }
  633:     }
  634:     return -1;
  635: }
  636: 
  637: function getIndexByName(formid,item) {
  638:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  639:         if (document.forms[formid].elements[i].name == item) {
  640:             return i;
  641:         }
  642:     }
  643:     return -1;
  644: }
  645: 
  646: function getDomainFromSelectbox(formname,udom) {
  647:     var userdom;
  648:     var formid = getFormIdByName(formname);
  649:     if (formid > -1) {
  650:         var domid = getIndexByName(formid,udom);
  651:         if (domid > -1) {
  652:             if (document.forms[formid].elements[domid].type == 'select-one') {
  653:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  654:             }
  655:             if (document.forms[formid].elements[domid].type == 'hidden') {
  656:                 userdom=document.forms[formid].elements[domid].value;
  657:             }
  658:         }
  659:     }
  660:     return userdom;
  661: }
  662: 
  663: ENDJS
  664: 
  665: }
  666: 
  667: sub javascript_array_indexof {
  668:     return <<ENDJS;
  669: <script type="text/javascript" language="JavaScript">
  670: // <![CDATA[
  671: 
  672: if (!Array.prototype.indexOf) {
  673:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  674:         "use strict";
  675:         if (this === void 0 || this === null) {
  676:             throw new TypeError();
  677:         }
  678:         var t = Object(this);
  679:         var len = t.length >>> 0;
  680:         if (len === 0) {
  681:             return -1;
  682:         }
  683:         var n = 0;
  684:         if (arguments.length > 0) {
  685:             n = Number(arguments[1]);
  686:             if (n !== n) { // shortcut for verifying if it is NaN
  687:                 n = 0;
  688:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  689:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  690:             }
  691:         }
  692:         if (n >= len) {
  693:             return -1;
  694:         }
  695:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  696:         for (; k < len; k++) {
  697:             if (k in t && t[k] === searchElement) {
  698:                 return k;
  699:             }
  700:         }
  701:         return -1;
  702:     }
  703: }
  704: 
  705: // ]]>
  706: </script>
  707: 
  708: ENDJS
  709: 
  710: }
  711: 
  712: sub userbrowser_javascript {
  713:     my $id_functions = &javascript_index_functions();
  714:     return <<"ENDUSERBRW";
  715: 
  716: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  717:     var url = '/adm/pickuser?';
  718:     var userdom = getDomainFromSelectbox(formname,udom);
  719:     if (userdom != null) {
  720:        if (userdom != '') {
  721:            url += 'srchdom='+userdom+'&';
  722:        }
  723:     }
  724:     url += 'form=' + formname + '&unameelement='+uname+
  725:                                 '&udomelement='+udom+
  726:                                 '&ulastelement='+ulast+
  727:                                 '&ufirstelement='+ufirst+
  728:                                 '&uemailelement='+uemail+
  729:                                 '&hideudomelement='+hideudom+
  730:                                 '&coursedom='+crsdom;
  731:     if ((caller != null) && (caller != undefined)) {
  732:         url += '&caller='+caller;
  733:     }
  734:     var title = 'User_Browser';
  735:     var options = 'scrollbars=1,resizable=1,menubar=0';
  736:     options += ',width=700,height=600';
  737:     var stdeditbrowser = open(url,title,options,'1');
  738:     stdeditbrowser.focus();
  739: }
  740: 
  741: function fix_domain (formname,udom,origdom,uname) {
  742:     var formid = getFormIdByName(formname);
  743:     if (formid > -1) {
  744:         var unameid = getIndexByName(formid,uname);
  745:         var domid = getIndexByName(formid,udom);
  746:         var hidedomid = getIndexByName(formid,origdom);
  747:         if (hidedomid > -1) {
  748:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  749:             var unameval = document.forms[formid].elements[unameid].value;
  750:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  751:                 if (domid > -1) {
  752:                     var slct = document.forms[formid].elements[domid];
  753:                     if (slct.type == 'select-one') {
  754:                         var i;
  755:                         for (i=0;i<slct.length;i++) {
  756:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  757:                         }
  758:                     }
  759:                     if (slct.type == 'hidden') {
  760:                         slct.value = fixeddom;
  761:                     }
  762:                 }
  763:             }
  764:         }
  765:     }
  766:     return;
  767: }
  768: 
  769: $id_functions
  770: ENDUSERBRW
  771: }
  772: 
  773: sub setsec_javascript {
  774:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  775:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  776:         $communityrolestr);
  777:     if ($role_element ne '') {
  778:         my @allroles = ('st','ta','ep','in','ad');
  779:         foreach my $crstype ('Course','Community') {
  780:             if ($crstype eq 'Community') {
  781:                 foreach my $role (@allroles) {
  782:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  783:                 }
  784:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  785:             } else {
  786:                 foreach my $role (@allroles) {
  787:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  788:                 }
  789:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  790:             }
  791:         }
  792:         $rolestr = '"'.join('","',@allroles).'"';
  793:         $courserolestr = '"'.join('","',@courserolenames).'"';
  794:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  795:     }
  796:     my $setsections = qq|
  797: function setSect(sectionlist) {
  798:     var sectionsArray = new Array();
  799:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  800:         sectionsArray = sectionlist.split(",");
  801:     }
  802:     var numSections = sectionsArray.length;
  803:     document.$formname.$sec_element.length = 0;
  804:     if (numSections == 0) {
  805:         document.$formname.$sec_element.multiple=false;
  806:         document.$formname.$sec_element.size=1;
  807:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  808:     } else {
  809:         if (numSections == 1) {
  810:             document.$formname.$sec_element.multiple=false;
  811:             document.$formname.$sec_element.size=1;
  812:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  813:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  814:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  815:         } else {
  816:             for (var i=0; i<numSections; i++) {
  817:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  818:             }
  819:             document.$formname.$sec_element.multiple=true
  820:             if (numSections < 3) {
  821:                 document.$formname.$sec_element.size=numSections;
  822:             } else {
  823:                 document.$formname.$sec_element.size=3;
  824:             }
  825:             document.$formname.$sec_element.options[0].selected = false
  826:         }
  827:     }
  828: }
  829: 
  830: function setRole(crstype) {
  831: |;
  832:     if ($role_element eq '') {
  833:         $setsections .= '    return;
  834: }
  835: ';
  836:     } else {
  837:         $setsections .= qq|
  838:     var elementLength = document.$formname.$role_element.length;
  839:     var allroles = Array($rolestr);
  840:     var courserolenames = Array($courserolestr);
  841:     var communityrolenames = Array($communityrolestr);
  842:     if (elementLength != undefined) {
  843:         if (document.$formname.$role_element.options[5].value == 'cc') {
  844:             if (crstype == 'Course') {
  845:                 return;
  846:             } else {
  847:                 allroles[5] = 'co';
  848:                 for (var i=0; i<6; i++) {
  849:                     document.$formname.$role_element.options[i].value = allroles[i];
  850:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  851:                 }
  852:             }
  853:         } else {
  854:             if (crstype == 'Community') {
  855:                 return;
  856:             } else {
  857:                 allroles[5] = 'cc';
  858:                 for (var i=0; i<6; i++) {
  859:                     document.$formname.$role_element.options[i].value = allroles[i];
  860:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  861:                 }
  862:             }
  863:         }
  864:     }
  865:     return;
  866: }
  867: |;
  868:     }
  869:     if ($credits_element) {
  870:         $setsections .= qq|
  871: function setCredits(defaultcredits) {
  872:     document.$formname.$credits_element.value = defaultcredits;
  873:     return;
  874: }
  875: |;
  876:     }
  877:     return $setsections;
  878: }
  879: 
  880: sub selectcourse_link {
  881:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  882:        $typeelement) = @_;
  883:    my $type = $selecttype;
  884:    my $linktext = &mt('Select Course');
  885:    if ($selecttype eq 'Community') {
  886:        $linktext = &mt('Select Community');
  887:    } elsif ($selecttype eq 'Placement') {
  888:        $linktext = &mt('Select Placement Test'); 
  889:    } elsif ($selecttype eq 'Course/Community') {
  890:        $linktext = &mt('Select Course/Community');
  891:        $type = '';
  892:    } elsif ($selecttype eq 'Select') {
  893:        $linktext = &mt('Select');
  894:        $type = '';
  895:    }
  896:    return '<span class="LC_nobreak">'
  897:          ."<a href='"
  898:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  899:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  900:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  901:          ."'>".$linktext.'</a>'
  902:          .'</span>';
  903: }
  904: 
  905: sub selectauthor_link {
  906:    my ($form,$udom)=@_;
  907:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  908:           &mt('Select Author').'</a>';
  909: }
  910: 
  911: sub selectuser_link {
  912:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  913:         $coursedom,$linktext,$caller) = @_;
  914:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  915:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  916:            ');">'.$linktext.'</a>';
  917: }
  918: 
  919: sub check_uncheck_jscript {
  920:     my $jscript = <<"ENDSCRT";
  921: function checkAll(field) {
  922:     if (field.length > 0) {
  923:         for (i = 0; i < field.length; i++) {
  924:             if (!field[i].disabled) { 
  925:                 field[i].checked = true;
  926:             }
  927:         }
  928:     } else {
  929:         if (!field.disabled) { 
  930:             field.checked = true;
  931:         }
  932:     }
  933: }
  934:  
  935: function uncheckAll(field) {
  936:     if (field.length > 0) {
  937:         for (i = 0; i < field.length; i++) {
  938:             field[i].checked = false ;
  939:         }
  940:     } else {
  941:         field.checked = false ;
  942:     }
  943: }
  944: ENDSCRT
  945:     return $jscript;
  946: }
  947: 
  948: sub select_timezone {
  949:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  950:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  951:    if ($includeempty) {
  952:        $output .= '<option value=""';
  953:        if (($selected eq '') || ($selected eq 'local')) {
  954:            $output .= ' selected="selected" ';
  955:        }
  956:        $output .= '> </option>';
  957:    }
  958:    my @timezones = DateTime::TimeZone->all_names;
  959:    foreach my $tzone (@timezones) {
  960:        $output.= '<option value="'.$tzone.'"';
  961:        if ($tzone eq $selected) {
  962:            $output.=' selected="selected"';
  963:        }
  964:        $output.=">$tzone</option>\n";
  965:    }
  966:    $output.="</select>";
  967:    return $output;
  968: }
  969: 
  970: sub select_datelocale {
  971:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  972:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  973:     if ($includeempty) {
  974:         $output .= '<option value=""';
  975:         if ($selected eq '') {
  976:             $output .= ' selected="selected" ';
  977:         }
  978:         $output .= '> </option>';
  979:     }
  980:     my @languages = &Apache::lonlocal::preferred_languages();
  981:     my (@possibles,%locale_names);
  982:     my @locales = DateTime::Locale->ids();
  983:     foreach my $id (@locales) {
  984:         if ($id ne '') {
  985:             my ($en_terr,$native_terr);
  986:             my $loc = DateTime::Locale->load($id);
  987:             if (ref($loc)) {
  988:                 $en_terr = $loc->name();
  989:                 $native_terr = $loc->native_name();
  990:                 if (grep(/^en$/,@languages) || !@languages) {
  991:                     if ($en_terr ne '') {
  992:                         $locale_names{$id} = '('.$en_terr.')';
  993:                     } elsif ($native_terr ne '') {
  994:                         $locale_names{$id} = $native_terr;
  995:                     }
  996:                 } else {
  997:                     if ($native_terr ne '') {
  998:                         $locale_names{$id} = $native_terr.' ';
  999:                     } elsif ($en_terr ne '') {
 1000:                         $locale_names{$id} = '('.$en_terr.')';
 1001:                     }
 1002:                 }
 1003:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1004:                 push(@possibles,$id);
 1005:             } 
 1006:         }
 1007:     }
 1008:     foreach my $item (sort(@possibles)) {
 1009:         $output.= '<option value="'.$item.'"';
 1010:         if ($item eq $selected) {
 1011:             $output.=' selected="selected"';
 1012:         }
 1013:         $output.=">$item";
 1014:         if ($locale_names{$item} ne '') {
 1015:             $output.='  '.$locale_names{$item};
 1016:         }
 1017:         $output.="</option>\n";
 1018:     }
 1019:     $output.="</select>";
 1020:     return $output;
 1021: }
 1022: 
 1023: sub select_language {
 1024:     my ($name,$selected,$includeempty,$noedit) = @_;
 1025:     my %langchoices;
 1026:     if ($includeempty) {
 1027:         %langchoices = ('' => 'No language preference');
 1028:     }
 1029:     foreach my $id (&languageids()) {
 1030:         my $code = &supportedlanguagecode($id);
 1031:         if ($code) {
 1032:             $langchoices{$code} = &plainlanguagedescription($id);
 1033:         }
 1034:     }
 1035:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1036:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1037: }
 1038: 
 1039: =pod
 1040: 
 1041: 
 1042: =item * &list_languages()
 1043: 
 1044: Returns an array reference that is suitable for use in language prompters.
 1045: Each array element is itself a two element array.  The first element
 1046: is the language code.  The second element a descsriptiuon of the 
 1047: language itself.  This is suitable for use in e.g.
 1048: &Apache::edit::select_arg (once dereferenced that is).
 1049: 
 1050: =cut 
 1051: 
 1052: sub list_languages {
 1053:     my @lang_choices;
 1054: 
 1055:     foreach my $id (&languageids()) {
 1056: 	my $code = &supportedlanguagecode($id);
 1057: 	if ($code) {
 1058: 	    my $selector    = $supported_codes{$id};
 1059: 	    my $description = &plainlanguagedescription($id);
 1060: 	    push(@lang_choices, [$selector, $description]);
 1061: 	}
 1062:     }
 1063:     return \@lang_choices;
 1064: }
 1065: 
 1066: =pod
 1067: 
 1068: =item * &linked_select_forms(...)
 1069: 
 1070: linked_select_forms returns a string containing a <script></script> block
 1071: and html for two <select> menus.  The select menus will be linked in that
 1072: changing the value of the first menu will result in new values being placed
 1073: in the second menu.  The values in the select menu will appear in alphabetical
 1074: order unless a defined order is provided.
 1075: 
 1076: linked_select_forms takes the following ordered inputs:
 1077: 
 1078: =over 4
 1079: 
 1080: =item * $formname, the name of the <form> tag
 1081: 
 1082: =item * $middletext, the text which appears between the <select> tags
 1083: 
 1084: =item * $firstdefault, the default value for the first menu
 1085: 
 1086: =item * $firstselectname, the name of the first <select> tag
 1087: 
 1088: =item * $secondselectname, the name of the second <select> tag
 1089: 
 1090: =item * $hashref, a reference to a hash containing the data for the menus.
 1091: 
 1092: =item * $menuorder, the order of values in the first menu
 1093: 
 1094: =item * $onchangefirst, additional javascript call to execute for an onchange
 1095:         event for the first <select> tag
 1096: 
 1097: =item * $onchangesecond, additional javascript call to execute for an onchange
 1098:         event for the second <select> tag
 1099: 
 1100: =item * $suffix, to differentiate separate uses of select2data javascript
 1101:         objects in a page.
 1102: 
 1103: =back 
 1104: 
 1105: Below is an example of such a hash.  Only the 'text', 'default', and 
 1106: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1107: values for the first select menu.  The text that coincides with the 
 1108: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1109: and text for the second menu are given in the hash pointed to by 
 1110: $menu{$choice1}->{'select2'}.  
 1111: 
 1112:  my %menu = ( A1 => { text =>"Choice A1" ,
 1113:                        default => "B3",
 1114:                        select2 => { 
 1115:                            B1 => "Choice B1",
 1116:                            B2 => "Choice B2",
 1117:                            B3 => "Choice B3",
 1118:                            B4 => "Choice B4"
 1119:                            },
 1120:                        order => ['B4','B3','B1','B2'],
 1121:                    },
 1122:                A2 => { text =>"Choice A2" ,
 1123:                        default => "C2",
 1124:                        select2 => { 
 1125:                            C1 => "Choice C1",
 1126:                            C2 => "Choice C2",
 1127:                            C3 => "Choice C3"
 1128:                            },
 1129:                        order => ['C2','C1','C3'],
 1130:                    },
 1131:                A3 => { text =>"Choice A3" ,
 1132:                        default => "D6",
 1133:                        select2 => { 
 1134:                            D1 => "Choice D1",
 1135:                            D2 => "Choice D2",
 1136:                            D3 => "Choice D3",
 1137:                            D4 => "Choice D4",
 1138:                            D5 => "Choice D5",
 1139:                            D6 => "Choice D6",
 1140:                            D7 => "Choice D7"
 1141:                            },
 1142:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1143:                    }
 1144:                );
 1145: 
 1146: =cut
 1147: 
 1148: sub linked_select_forms {
 1149:     my ($formname,
 1150:         $middletext,
 1151:         $firstdefault,
 1152:         $firstselectname,
 1153:         $secondselectname, 
 1154:         $hashref,
 1155:         $menuorder,
 1156:         $onchangefirst,
 1157:         $onchangesecond,
 1158:         $suffix
 1159:         ) = @_;
 1160:     my $second = "document.$formname.$secondselectname";
 1161:     my $first = "document.$formname.$firstselectname";
 1162:     # output the javascript to do the changing
 1163:     my $result = '';
 1164:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1165:     $result.="// <![CDATA[\n";
 1166:     $result.="var select2data${suffix} = new Object();\n";
 1167:     $" = '","';
 1168:     my $debug = '';
 1169:     foreach my $s1 (sort(keys(%$hashref))) {
 1170:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1171:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1172:             $hashref->{$s1}->{'default'}."');\n";
 1173:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1174:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1175:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1176:             @s2values = @{$hashref->{$s1}->{'order'}};
 1177:         }
 1178:         $result.="\"@s2values\");\n";
 1179:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1180:         my @s2texts;
 1181:         foreach my $value (@s2values) {
 1182:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1183:         }
 1184:         $result.="\"@s2texts\");\n";
 1185:     }
 1186:     $"=' ';
 1187:     $result.= <<"END";
 1188: 
 1189: function select1${suffix}_changed() {
 1190:     // Determine new choice
 1191:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1192:     // update select2
 1193:     var values     = select2data${suffix}[newvalue].values;
 1194:     var texts      = select2data${suffix}[newvalue].texts;
 1195:     var select2def = select2data${suffix}[newvalue].def;
 1196:     var i;
 1197:     // out with the old
 1198:     $second.options.length = 0;
 1199:     // in with the new
 1200:     for (i=0;i<values.length; i++) {
 1201:         $second.options[i] = new Option(values[i]);
 1202:         $second.options[i].value = values[i];
 1203:         $second.options[i].text = texts[i];
 1204:         if (values[i] == select2def) {
 1205:             $second.options[i].selected = true;
 1206:         }
 1207:     }
 1208: }
 1209: // ]]>
 1210: </script>
 1211: END
 1212:     # output the initial values for the selection lists
 1213:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1214:     my @order = sort(keys(%{$hashref}));
 1215:     if (ref($menuorder) eq 'ARRAY') {
 1216:         @order = @{$menuorder};
 1217:     }
 1218:     foreach my $value (@order) {
 1219:         $result.="    <option value=\"$value\" ";
 1220:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1221:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1222:     }
 1223:     $result .= "</select>\n";
 1224:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1225:     $result .= $middletext;
 1226:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1227:     if ($onchangesecond) {
 1228:         $result .= ' onchange="'.$onchangesecond.'"';
 1229:     }
 1230:     $result .= ">\n";
 1231:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1232:     
 1233:     my @secondorder = sort(keys(%select2));
 1234:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1235:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1236:     }
 1237:     foreach my $value (@secondorder) {
 1238:         $result.="    <option value=\"$value\" ";        
 1239:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1240:         $result.=">".&mt($select2{$value})."</option>\n";
 1241:     }
 1242:     $result .= "</select>\n";
 1243:     #    return $debug;
 1244:     return $result;
 1245: }   #  end of sub linked_select_forms {
 1246: 
 1247: =pod
 1248: 
 1249: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1250: 
 1251: Returns a string corresponding to an HTML link to the given help
 1252: $topic, where $topic corresponds to the name of a .tex file in
 1253: /home/httpd/html/adm/help/tex, with underscores replaced by
 1254: spaces. 
 1255: 
 1256: $text will optionally be linked to the same topic, allowing you to
 1257: link text in addition to the graphic. If you do not want to link
 1258: text, but wish to specify one of the later parameters, pass an
 1259: empty string. 
 1260: 
 1261: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1262: the link will not open a new window. If false, the link will open
 1263: a new window using Javascript. (Default is false.) 
 1264: 
 1265: $width and $height are optional numerical parameters that will
 1266: override the width and height of the popped up window, which may
 1267: be useful for certain help topics with big pictures included.
 1268: 
 1269: $imgid is the id of the img tag used for the help icon. This may be
 1270: used in a javascript call to switch the image src.  See 
 1271: lonhtmlcommon::htmlareaselectactive() for an example.
 1272: 
 1273: =cut
 1274: 
 1275: sub help_open_topic {
 1276:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1277:     $text = "" if (not defined $text);
 1278:     $stayOnPage = 0 if (not defined $stayOnPage);
 1279:     $width = 500 if (not defined $width);
 1280:     $height = 400 if (not defined $height);
 1281:     my $filename = $topic;
 1282:     $filename =~ s/ /_/g;
 1283: 
 1284:     my $template = "";
 1285:     my $link;
 1286:     
 1287:     $topic=~s/\W/\_/g;
 1288: 
 1289:     if (!$stayOnPage) {
 1290: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1291:     } elsif ($stayOnPage eq 'popup') {
 1292:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1293:     } else {
 1294: 	$link = "/adm/help/${filename}.hlp";
 1295:     }
 1296: 
 1297:     # Add the text
 1298:     if ($text ne "") {	
 1299: 	$template.='<span class="LC_help_open_topic">'
 1300:                   .'<a target="_top" href="'.$link.'">'
 1301:                   .$text.'</a>';
 1302:     }
 1303: 
 1304:     # (Always) Add the graphic
 1305:     my $title = &mt('Online Help');
 1306:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1307:     if ($imgid ne '') {
 1308:         $imgid = ' id="'.$imgid.'"';
 1309:     }
 1310:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1311:               .'<img src="'.$helpicon.'" border="0"'
 1312:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1313:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1314:               .' /></a>';
 1315:     if ($text ne "") {	
 1316:         $template.='</span>';
 1317:     }
 1318:     return $template;
 1319: 
 1320: }
 1321: 
 1322: # This is a quicky function for Latex cheatsheet editing, since it 
 1323: # appears in at least four places
 1324: sub helpLatexCheatsheet {
 1325:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1326:     my $out;
 1327:     my $addOther = '';
 1328:     if ($topic) {
 1329: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1330:     }
 1331:     $out = '<span>' # Start cheatsheet
 1332: 	  .$addOther
 1333:           .'<span>'
 1334: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1335: 	  .'</span> <span>'
 1336: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1337: 	  .'</span>';
 1338:     unless ($not_author) {
 1339:         $out .= '<span>'
 1340:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1341:                .'</span> <span>'
 1342:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1343: 	       .'</span>';
 1344:     }
 1345:     $out .= '</span>'; # End cheatsheet
 1346:     return $out;
 1347: }
 1348: 
 1349: sub general_help {
 1350:     my $helptopic='Student_Intro';
 1351:     if ($env{'request.role'}=~/^(ca|au)/) {
 1352: 	$helptopic='Authoring_Intro';
 1353:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1354: 	$helptopic='Course_Coordination_Intro';
 1355:     } elsif ($env{'request.role'}=~/^dc/) {
 1356:         $helptopic='Domain_Coordination_Intro';
 1357:     }
 1358:     return $helptopic;
 1359: }
 1360: 
 1361: sub update_help_link {
 1362:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1363:     my $origurl = $ENV{'REQUEST_URI'};
 1364:     $origurl=~s|^/~|/priv/|;
 1365:     my $timestamp = time;
 1366:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1367:         $$datum = &escape($$datum);
 1368:     }
 1369: 
 1370:     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";
 1371:     my $output .= <<"ENDOUTPUT";
 1372: <script type="text/javascript">
 1373: // <![CDATA[
 1374: banner_link = '$banner_link';
 1375: // ]]>
 1376: </script>
 1377: ENDOUTPUT
 1378:     return $output;
 1379: }
 1380: 
 1381: # now just updates the help link and generates a blue icon
 1382: sub help_open_menu {
 1383:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1384: 	= @_;    
 1385:     $stayOnPage = 1;
 1386:     my $output;
 1387:     if ($component_help) {
 1388: 	if (!$text) {
 1389: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1390: 				       $width,$height);
 1391: 	} else {
 1392: 	    my $help_text;
 1393: 	    $help_text=&unescape($topic);
 1394: 	    $output='<table><tr><td>'.
 1395: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1396: 				 $width,$height).'</td></tr></table>';
 1397: 	}
 1398:     }
 1399:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1400:     return $output.$banner_link;
 1401: }
 1402: 
 1403: sub top_nav_help {
 1404:     my ($text) = @_;
 1405:     $text = &mt($text);
 1406:     my $stay_on_page = 1;
 1407: 
 1408:     my ($link,$banner_link);
 1409:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1410:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1411: 	                         : "javascript:helpMenu('open')";
 1412:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1413:     }
 1414:     my $title = &mt('Get help');
 1415:     if ($link) {
 1416:         return <<"END";
 1417: $banner_link
 1418: <a href="$link" title="$title">$text</a>
 1419: END
 1420:     } else {
 1421:         return '&nbsp;'.$text.'&nbsp;';
 1422:     }
 1423: }
 1424: 
 1425: sub help_menu_js {
 1426:     my ($httphost) = @_;
 1427:     my $stayOnPage = 1;
 1428:     my $width = 620;
 1429:     my $height = 600;
 1430:     my $helptopic=&general_help();
 1431:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1432:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1433:     my $start_page =
 1434:         &Apache::loncommon::start_page('Help Menu', undef,
 1435: 				       {'frameset'    => 1,
 1436: 					'js_ready'    => 1,
 1437:                                         'use_absolute' => $httphost,
 1438: 					'add_entries' => {
 1439: 					    'border' => '0', 
 1440: 					    'rows'   => "110,*",},});
 1441:     my $end_page =
 1442:         &Apache::loncommon::end_page({'frameset' => 1,
 1443: 				      'js_ready' => 1,});
 1444: 
 1445:     my $template .= <<"ENDTEMPLATE";
 1446: <script type="text/javascript">
 1447: // <![CDATA[
 1448: // <!-- BEGIN LON-CAPA Internal
 1449: var banner_link = '';
 1450: function helpMenu(target) {
 1451:     var caller = this;
 1452:     if (target == 'open') {
 1453:         var newWindow = null;
 1454:         try {
 1455:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1456:         }
 1457:         catch(error) {
 1458:             writeHelp(caller);
 1459:             return;
 1460:         }
 1461:         if (newWindow) {
 1462:             caller = newWindow;
 1463:         }
 1464:     }
 1465:     writeHelp(caller);
 1466:     return;
 1467: }
 1468: function writeHelp(caller) {
 1469:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1470:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1471:     caller.document.close();
 1472:     caller.focus();
 1473: }
 1474: // END LON-CAPA Internal -->
 1475: // ]]>
 1476: </script>
 1477: ENDTEMPLATE
 1478:     return $template;
 1479: }
 1480: 
 1481: sub help_open_bug {
 1482:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1483:     unless ($env{'user.adv'}) { return ''; }
 1484:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1485:     $text = "" if (not defined $text);
 1486: 	$stayOnPage=1;
 1487:     $width = 600 if (not defined $width);
 1488:     $height = 600 if (not defined $height);
 1489: 
 1490:     $topic=~s/\W+/\+/g;
 1491:     my $link='';
 1492:     my $template='';
 1493:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1494: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1495:     if (!$stayOnPage)
 1496:     {
 1497: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1498:     }
 1499:     else
 1500:     {
 1501: 	$link = $url;
 1502:     }
 1503:     # Add the text
 1504:     if ($text ne "")
 1505:     {
 1506: 	$template .= 
 1507:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1508:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1509:     }
 1510: 
 1511:     # Add the graphic
 1512:     my $title = &mt('Report a Bug');
 1513:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1514:     $template .= <<"ENDTEMPLATE";
 1515:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1516: ENDTEMPLATE
 1517:     if ($text ne '') { $template.='</td></tr></table>' };
 1518:     return $template;
 1519: 
 1520: }
 1521: 
 1522: sub help_open_faq {
 1523:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1524:     unless ($env{'user.adv'}) { return ''; }
 1525:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1526:     $text = "" if (not defined $text);
 1527: 	$stayOnPage=1;
 1528:     $width = 350 if (not defined $width);
 1529:     $height = 400 if (not defined $height);
 1530: 
 1531:     $topic=~s/\W+/\+/g;
 1532:     my $link='';
 1533:     my $template='';
 1534:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1535:     if (!$stayOnPage)
 1536:     {
 1537: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1538:     }
 1539:     else
 1540:     {
 1541: 	$link = $url;
 1542:     }
 1543: 
 1544:     # Add the text
 1545:     if ($text ne "")
 1546:     {
 1547: 	$template .= 
 1548:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1549:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1550:     }
 1551: 
 1552:     # Add the graphic
 1553:     my $title = &mt('View the FAQ');
 1554:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1555:     $template .= <<"ENDTEMPLATE";
 1556:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1557: ENDTEMPLATE
 1558:     if ($text ne '') { $template.='</td></tr></table>' };
 1559:     return $template;
 1560: 
 1561: }
 1562: 
 1563: ###############################################################
 1564: ###############################################################
 1565: 
 1566: =pod
 1567: 
 1568: =item * &change_content_javascript():
 1569: 
 1570: This and the next function allow you to create small sections of an
 1571: otherwise static HTML page that you can update on the fly with
 1572: Javascript, even in Netscape 4.
 1573: 
 1574: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1575: must be written to the HTML page once. It will prove the Javascript
 1576: function "change(name, content)". Calling the change function with the
 1577: name of the section 
 1578: you want to update, matching the name passed to C<changable_area>, and
 1579: the new content you want to put in there, will put the content into
 1580: that area.
 1581: 
 1582: B<Note>: Netscape 4 only reserves enough space for the changable area
 1583: to contain room for the original contents. You need to "make space"
 1584: for whatever changes you wish to make, and be B<sure> to check your
 1585: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1586: it's adequate for updating a one-line status display, but little more.
 1587: This script will set the space to 100% width, so you only need to
 1588: worry about height in Netscape 4.
 1589: 
 1590: Modern browsers are much less limiting, and if you can commit to the
 1591: user not using Netscape 4, this feature may be used freely with
 1592: pretty much any HTML.
 1593: 
 1594: =cut
 1595: 
 1596: sub change_content_javascript {
 1597:     # If we're on Netscape 4, we need to use Layer-based code
 1598:     if ($env{'browser.type'} eq 'netscape' &&
 1599: 	$env{'browser.version'} =~ /^4\./) {
 1600: 	return (<<NETSCAPE4);
 1601: 	function change(name, content) {
 1602: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1603: 	    doc.open();
 1604: 	    doc.write(content);
 1605: 	    doc.close();
 1606: 	}
 1607: NETSCAPE4
 1608:     } else {
 1609: 	# Otherwise, we need to use semi-standards-compliant code
 1610: 	# (technically, "innerHTML" isn't standard but the equivalent
 1611: 	# is really scary, and every useful browser supports it
 1612: 	return (<<DOMBASED);
 1613: 	function change(name, content) {
 1614: 	    element = document.getElementById(name);
 1615: 	    element.innerHTML = content;
 1616: 	}
 1617: DOMBASED
 1618:     }
 1619: }
 1620: 
 1621: =pod
 1622: 
 1623: =item * &changable_area($name,$origContent):
 1624: 
 1625: This provides a "changable area" that can be modified on the fly via
 1626: the Javascript code provided in C<change_content_javascript>. $name is
 1627: the name you will use to reference the area later; do not repeat the
 1628: same name on a given HTML page more then once. $origContent is what
 1629: the area will originally contain, which can be left blank.
 1630: 
 1631: =cut
 1632: 
 1633: sub changable_area {
 1634:     my ($name, $origContent) = @_;
 1635: 
 1636:     if ($env{'browser.type'} eq 'netscape' &&
 1637: 	$env{'browser.version'} =~ /^4\./) {
 1638: 	# If this is netscape 4, we need to use the Layer tag
 1639: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1640:     } else {
 1641: 	return "<span id='$name'>$origContent</span>";
 1642:     }
 1643: }
 1644: 
 1645: =pod
 1646: 
 1647: =item * &viewport_geometry_js 
 1648: 
 1649: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1650: 
 1651: =cut
 1652: 
 1653: 
 1654: sub viewport_geometry_js { 
 1655:     return <<"GEOMETRY";
 1656: var Geometry = {};
 1657: function init_geometry() {
 1658:     if (Geometry.init) { return };
 1659:     Geometry.init=1;
 1660:     if (window.innerHeight) {
 1661:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1662:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1663:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1664:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1665:     }
 1666:     else if (document.documentElement && document.documentElement.clientHeight) {
 1667:         Geometry.getViewportHeight =
 1668:             function() { return document.documentElement.clientHeight; };
 1669:         Geometry.getViewportWidth =
 1670:             function() { return document.documentElement.clientWidth; };
 1671: 
 1672:         Geometry.getHorizontalScroll =
 1673:             function() { return document.documentElement.scrollLeft; };
 1674:         Geometry.getVerticalScroll =
 1675:             function() { return document.documentElement.scrollTop; };
 1676:     }
 1677:     else if (document.body.clientHeight) {
 1678:         Geometry.getViewportHeight =
 1679:             function() { return document.body.clientHeight; };
 1680:         Geometry.getViewportWidth =
 1681:             function() { return document.body.clientWidth; };
 1682:         Geometry.getHorizontalScroll =
 1683:             function() { return document.body.scrollLeft; };
 1684:         Geometry.getVerticalScroll =
 1685:             function() { return document.body.scrollTop; };
 1686:     }
 1687: }
 1688: 
 1689: GEOMETRY
 1690: }
 1691: 
 1692: =pod
 1693: 
 1694: =item * &viewport_size_js()
 1695: 
 1696: 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. 
 1697: 
 1698: =cut
 1699: 
 1700: sub viewport_size_js {
 1701:     my $geometry = &viewport_geometry_js();
 1702:     return <<"DIMS";
 1703: 
 1704: $geometry
 1705: 
 1706: function getViewportDims(width,height) {
 1707:     init_geometry();
 1708:     width.value = Geometry.getViewportWidth();
 1709:     height.value = Geometry.getViewportHeight();
 1710:     return;
 1711: }
 1712: 
 1713: DIMS
 1714: }
 1715: 
 1716: =pod
 1717: 
 1718: =item * &resize_textarea_js()
 1719: 
 1720: emits the needed javascript to resize a textarea to be as big as possible
 1721: 
 1722: creates a function resize_textrea that takes two IDs first should be
 1723: the id of the element to resize, second should be the id of a div that
 1724: surrounds everything that comes after the textarea, this routine needs
 1725: to be attached to the <body> for the onload and onresize events.
 1726: 
 1727: =back
 1728: 
 1729: =cut
 1730: 
 1731: sub resize_textarea_js {
 1732:     my $geometry = &viewport_geometry_js();
 1733:     return <<"RESIZE";
 1734:     <script type="text/javascript">
 1735: // <![CDATA[
 1736: $geometry
 1737: 
 1738: function getX(element) {
 1739:     var x = 0;
 1740:     while (element) {
 1741: 	x += element.offsetLeft;
 1742: 	element = element.offsetParent;
 1743:     }
 1744:     return x;
 1745: }
 1746: function getY(element) {
 1747:     var y = 0;
 1748:     while (element) {
 1749: 	y += element.offsetTop;
 1750: 	element = element.offsetParent;
 1751:     }
 1752:     return y;
 1753: }
 1754: 
 1755: 
 1756: function resize_textarea(textarea_id,bottom_id) {
 1757:     init_geometry();
 1758:     var textarea        = document.getElementById(textarea_id);
 1759:     //alert(textarea);
 1760: 
 1761:     var textarea_top    = getY(textarea);
 1762:     var textarea_height = textarea.offsetHeight;
 1763:     var bottom          = document.getElementById(bottom_id);
 1764:     var bottom_top      = getY(bottom);
 1765:     var bottom_height   = bottom.offsetHeight;
 1766:     var window_height   = Geometry.getViewportHeight();
 1767:     var fudge           = 23;
 1768:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1769:     if (new_height < 300) {
 1770: 	new_height = 300;
 1771:     }
 1772:     textarea.style.height=new_height+'px';
 1773: }
 1774: // ]]>
 1775: </script>
 1776: RESIZE
 1777: 
 1778: }
 1779: 
 1780: sub colorfuleditor_js {
 1781:     my $browse_or_search;
 1782:     my $respath;
 1783:     my ($cnum,$cdom) = &crsauthor_url();
 1784:     if ($cnum) {
 1785:         $respath = "/res/$cdom/$cnum/";
 1786:         my %js_lt = &Apache::lonlocal::texthash(
 1787:             sunm => 'Sub-directory name',
 1788:             save => 'Save page to make this permanent',
 1789:         );
 1790:         &js_escape(\%js_lt);
 1791:         $browse_or_search = <<"END";
 1792: 
 1793:     function toggleChooser(form,element,titleid,only,search) {
 1794:         var disp = 'none';
 1795:         if (document.getElementById('chooser_'+element)) {
 1796:             var curr = document.getElementById('chooser_'+element).style.display;
 1797:             if (curr == 'none') {
 1798:                 disp='inline';
 1799:                 if (form.elements['chooser_'+element].length) {
 1800:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1801:                         form.elements['chooser_'+element][i].checked = false;
 1802:                     }
 1803:                 }
 1804:                 toggleResImport(form,element);
 1805:             }
 1806:             document.getElementById('chooser_'+element).style.display = disp;
 1807:         }
 1808:     }
 1809: 
 1810:     function toggleCrsFile(form,element,numdirs) {
 1811:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1812:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1813:             if (curr == 'none') {
 1814:                 if (numdirs) {
 1815:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1816:                     if (numdirs > 1) {
 1817:                         window['select1'+element+'_changed']();
 1818:                     }
 1819:                 }
 1820:             } 
 1821:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1822:             
 1823:         }
 1824:         if (document.getElementById('chooser_'+element+'_upload')) {
 1825:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1826:             if (document.getElementById('uploadcrsres_'+element)) {
 1827:                 document.getElementById('uploadcrsres_'+element).value = '';
 1828:             }
 1829:         }
 1830:         return;
 1831:     }
 1832: 
 1833:     function toggleCrsUpload(form,element,numcrsdirs) {
 1834:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1835:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1836:         }
 1837:         if (document.getElementById('chooser_'+element+'_upload')) {
 1838:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1839:             if (curr == 'none') {
 1840:                 if (numcrsdirs) {
 1841:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1842:                    form.elements['newsubdir_'+element][0].checked = true;
 1843:                    toggleNewsubdir(form,element);
 1844:                 }
 1845:             }
 1846:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1847:         }
 1848:         return;
 1849:     }
 1850: 
 1851:     function toggleResImport(form,element) {
 1852:         var choices = new Array('crsres','upload');
 1853:         for (var i=0; i<choices.length; i++) {
 1854:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1855:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1856:             }
 1857:         }
 1858:     }
 1859: 
 1860:     function toggleNewsubdir(form,element) {
 1861:         var newsub = form.elements['newsubdir_'+element];
 1862:         if (newsub) {
 1863:             if (newsub.length) {
 1864:                 for (var j=0; j<newsub.length; j++) {
 1865:                     if (newsub[j].checked) {
 1866:                         if (document.getElementById('newsubdirname_'+element)) {
 1867:                             if (newsub[j].value == '1') {
 1868:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1869:                                 if (document.getElementById('newsubdir_'+element)) {
 1870:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1871:                                 }
 1872:                             } else {
 1873:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1874:                                 document.getElementById('newsubdirname_'+element).value = "";
 1875:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1876:                             }
 1877:                         }
 1878:                         break; 
 1879:                     }
 1880:                 }
 1881:             }
 1882:         }
 1883:     }
 1884: 
 1885:     function updateCrsFile(form,element) {
 1886:         var directory = form.elements['coursepath_'+element];
 1887:         var filename = form.elements['coursefile_'+element];
 1888:         var path = directory.options[directory.selectedIndex].value;
 1889:         var file = filename.options[filename.selectedIndex].value;
 1890:         form.elements[element].value = '$respath';
 1891:         if (path == '/') {
 1892:             form.elements[element].value += file;
 1893:         } else {
 1894:             form.elements[element].value += path+'/'+file;
 1895:         }
 1896:         unClean();
 1897:         if (document.getElementById('previewimg_'+element)) {
 1898:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1899:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1900:         }
 1901:         if (document.getElementById('showimg_'+element)) {
 1902:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1903:         }
 1904:         toggleChooser(form,element);
 1905:         return;
 1906:     }
 1907: 
 1908:     function uploadDone(suffix,name) {
 1909:         if (name) {
 1910: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1911:             unClean();
 1912:             toggleChooser(document.forms["lonhomework"],suffix);
 1913:         }
 1914:     }
 1915: 
 1916: \$(document).ready(function(){
 1917: 
 1918:     \$(document).delegate('form :submit', 'click', function( event ) {
 1919:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1920:             var buttonId = this.id;
 1921:             var suffix = buttonId.toString();
 1922:             suffix = suffix.replace(/^crsupload_/,'');
 1923:             event.preventDefault();
 1924:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1925:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1926:             \$(this.form).submit();
 1927:             document.lonhomework.target = '';
 1928:             if (document.getElementById('crsuploadto_'+suffix)) {
 1929:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1930:             }
 1931:             return false;
 1932:         }
 1933:     });
 1934: });
 1935: END
 1936:     }
 1937:     return <<"COLORFULEDIT"
 1938: <script type="text/javascript">
 1939: // <![CDATA[>
 1940:     function fold_box(curDepth, lastresource){
 1941: 
 1942:     // we need a list because there can be several blocks you need to fold in one tag
 1943:         var block = document.getElementsByName('foldblock_'+curDepth);
 1944:     // but there is only one folding button per tag
 1945:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1946: 
 1947:         if(block.item(0).style.display == 'none'){
 1948: 
 1949:             foldbutton.value = '@{[&mt("Hide")]}';
 1950:             for (i = 0; i < block.length; i++){
 1951:                 block.item(i).style.display = '';
 1952:             }
 1953:         }else{
 1954: 
 1955:             foldbutton.value = '@{[&mt("Show")]}';
 1956:             for (i = 0; i < block.length; i++){
 1957:                 // block.item(i).style.visibility = 'collapse';
 1958:                 block.item(i).style.display = 'none';
 1959:             }
 1960:         };
 1961:         saveState(lastresource);
 1962:     }
 1963: 
 1964:     function saveState (lastresource) {
 1965: 
 1966:         var tag_list = getTagList();
 1967:         if(tag_list != null){
 1968:             var timestamp = new Date().getTime();
 1969:             var key = lastresource;
 1970: 
 1971:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1972:             // starting with timestamp
 1973:             var value = timestamp+';';
 1974: 
 1975:             // building the list of key-value pairs
 1976:             for(var i = 0; i < tag_list.length; i++){
 1977:                 value += tag_list[i]+',';
 1978:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1979:             }
 1980: 
 1981:             // only iterate whole storage if nothing to override
 1982:             if(localStorage.getItem(key) == null){        
 1983: 
 1984:                 // prevent storage from growing large
 1985:                 if(localStorage.length > 50){
 1986:                     var regex_getTimestamp = /^(?:\d)+;/;
 1987:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1988:                     var oldest_key;
 1989:                     
 1990:                     for(var i = 1; i < localStorage.length; i++){
 1991:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1992:                             oldest_key = localStorage.key(i);
 1993:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1994:                         }
 1995:                     }
 1996:                     localStorage.removeItem(oldest_key);
 1997:                 }
 1998:             }
 1999:             localStorage.setItem(key,value);
 2000:         }
 2001:     }
 2002: 
 2003:     // restore folding status of blocks (on page load)
 2004:     function restoreState (lastresource) {
 2005:         if(localStorage.getItem(lastresource) != null){
 2006:             var key = lastresource;
 2007:             var value = localStorage.getItem(key);
 2008:             var regex_delTimestamp = /^\d+;/;
 2009: 
 2010:             value.replace(regex_delTimestamp, '');
 2011: 
 2012:             var valueArr = value.split(';');
 2013:             var pairs;
 2014:             var elements;
 2015:             for (var i = 0; i < valueArr.length; i++){
 2016:                 pairs = valueArr[i].split(',');
 2017:                 elements = document.getElementsByName(pairs[0]);
 2018: 
 2019:                 for (var j = 0; j < elements.length; j++){  
 2020:                     elements[j].style.display = pairs[1];
 2021:                     if (pairs[1] == "none"){
 2022:                         var regex_id = /([_\\d]+)\$/;
 2023:                         regex_id.exec(pairs[0]);
 2024:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2025:                     }
 2026:                 }
 2027:             }
 2028:         }
 2029:     }
 2030: 
 2031:     function getTagList () {
 2032:         
 2033:         var stringToSearch = document.lonhomework.innerHTML;
 2034: 
 2035:         var ret = new Array();
 2036:         var regex_findBlock = /(foldblock_.*?)"/g;
 2037:         var tag_list = stringToSearch.match(regex_findBlock);
 2038: 
 2039:         if(tag_list != null){
 2040:             for(var i = 0; i < tag_list.length; i++){            
 2041:                 ret.push(tag_list[i].replace(/"/, ''));
 2042:             }
 2043:         }
 2044:         return ret;
 2045:     }
 2046: 
 2047:     function saveScrollPosition (resource) {
 2048:         var tag_list = getTagList();
 2049: 
 2050:         // we dont always want to jump to the first block
 2051:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2052:         if(\$(window).scrollTop() > 170){
 2053:             if(tag_list != null){
 2054:                 var result;
 2055:                 for(var i = 0; i < tag_list.length; i++){
 2056:                     if(isElementInViewport(tag_list[i])){
 2057:                         result += tag_list[i]+';';
 2058:                     }
 2059:                 }
 2060:                 sessionStorage.setItem('anchor_'+resource, result);
 2061:             }
 2062:         } else {
 2063:             // we dont need to save zero, just delete the item to leave everything tidy
 2064:             sessionStorage.removeItem('anchor_'+resource);
 2065:         }
 2066:     }
 2067: 
 2068:     function restoreScrollPosition(resource){
 2069: 
 2070:         var elem = sessionStorage.getItem('anchor_'+resource);
 2071:         if(elem != null){
 2072:             var tag_list = elem.split(';');
 2073:             var elem_list;
 2074: 
 2075:             for(var i = 0; i < tag_list.length; i++){
 2076:                 elem_list = document.getElementsByName(tag_list[i]);
 2077:                 
 2078:                 if(elem_list.length > 0){
 2079:                     elem = elem_list[0];
 2080:                     break;
 2081:                 }
 2082:             }
 2083:             elem.scrollIntoView();
 2084:         }
 2085:     }
 2086: 
 2087:     function isElementInViewport(el) {
 2088: 
 2089:         // change to last element instead of first
 2090:         var elem = document.getElementsByName(el);
 2091:         var rect = elem[0].getBoundingClientRect();
 2092: 
 2093:         return (
 2094:             rect.top >= 0 &&
 2095:             rect.left >= 0 &&
 2096:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2097:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2098:         );
 2099:     }
 2100:     
 2101:     function autosize(depth){
 2102:         var cmInst = window['cm'+depth];
 2103:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2104: 
 2105:         // is fixed size, switching to dynamic
 2106:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2107:             cmInst.setSize("","auto");
 2108:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2109:             sessionStorage.setItem("autosized_"+depth, "yes");
 2110: 
 2111:         // is dynamic size, switching to fixed
 2112:         } else {
 2113:             cmInst.setSize("","300px");
 2114:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2115:             sessionStorage.removeItem("autosized_"+depth);
 2116:         }
 2117:     }
 2118: 
 2119: $browse_or_search
 2120: 
 2121: // ]]>
 2122: </script>
 2123: COLORFULEDIT
 2124: }
 2125: 
 2126: sub xmleditor_js {
 2127:     return <<XMLEDIT
 2128: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2129: <script type="text/javascript">
 2130: // <![CDATA[>
 2131: 
 2132:     function saveScrollPosition (resource) {
 2133: 
 2134:         var scrollPos = \$(window).scrollTop();
 2135:         sessionStorage.setItem(resource,scrollPos);
 2136:     }
 2137: 
 2138:     function restoreScrollPosition(resource){
 2139: 
 2140:         var scrollPos = sessionStorage.getItem(resource);
 2141:         \$(window).scrollTop(scrollPos);
 2142:     }
 2143: 
 2144:     // unless internet explorer
 2145:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2146: 
 2147:         \$(document).ready(function() {
 2148:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2149:         });
 2150:     }
 2151: 
 2152:     // inserts text at cursor position into codemirror (xml editor only)
 2153:     function insertText(text){
 2154:         cm.focus();
 2155:         var curPos = cm.getCursor();
 2156:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2157:     }
 2158: // ]]>
 2159: </script>
 2160: XMLEDIT
 2161: }
 2162: 
 2163: sub insert_folding_button {
 2164:     my $curDepth = $Apache::lonxml::curdepth;
 2165:     my $lastresource = $env{'request.ambiguous'};
 2166: 
 2167:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2168:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2169: }
 2170: 
 2171: sub crsauthor_url {
 2172:     my ($url) = @_;
 2173:     if ($url eq '') {
 2174:         $url = $ENV{'REQUEST_URI'};
 2175:     }
 2176:     my ($cnum,$cdom);
 2177:     if ($env{'request.course.id'}) {
 2178:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2179:         if ($audom ne '' && $auname ne '') {
 2180:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2181:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2182:                 $cnum = $auname;
 2183:                 $cdom = $audom;
 2184:             }
 2185:         }
 2186:     }
 2187:     return ($cnum,$cdom);
 2188: }
 2189: 
 2190: sub import_crsauthor_form {
 2191:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2192:     return (0) unless ($env{'request.course.id'});
 2193:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2194:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2195:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2196:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2197:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2198:     my @ids=&Apache::lonnet::current_machine_ids();
 2199:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2200:     
 2201:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2202:         $is_home = 1;
 2203:     }
 2204:     $relpath = "/priv/$cdom/$cnum";
 2205:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2206:     my %lt = &Apache::lonlocal::texthash (
 2207:         fnam => 'Filename',
 2208:         dire => 'Directory',
 2209:     );
 2210:     my $numdirs = scalar(keys(%files));
 2211:     my (%possexts,$singledir,@singledirfiles);
 2212:     if ($only) {
 2213:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2214:     }
 2215:     my (%nonemptydirs,$possdirs);
 2216:     if ($numdirs > 1) {
 2217:         my @order;
 2218:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2219:             if (ref($files{$key}) eq 'HASH') {
 2220:                 my $shown = $key;
 2221:                 if ($key eq '') {
 2222:                     $shown = '/';
 2223:                 }
 2224:                 my @ordered = ();
 2225:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2226:                     if ($only) {
 2227:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2228:                         unless ($possexts{lc($ext)}) {
 2229:                             next;
 2230:                         }
 2231:                     }
 2232:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2233:                     push(@ordered,$file);
 2234:                 }
 2235:                 if (@ordered) {
 2236:                     push(@order,$key);
 2237:                     $nonemptydirs{$key} = 1;
 2238:                     $selimport_menus{$key}->{'text'} = $shown;
 2239:                     $selimport_menus{$key}->{'default'} = '';
 2240:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2241:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2242:                 }
 2243:             }
 2244:         }
 2245:         $possdirs = scalar(keys(%nonemptydirs));
 2246:         if ($possdirs > 1) {
 2247:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2248:             $output = $lt{'dire'}.
 2249:                       &linked_select_forms($form,'<br />'.
 2250:                                            $lt{'fnam'},'',
 2251:                                            $firstselectname,$secondselectname,
 2252:                                            \%selimport_menus,\@order,
 2253:                                            $onchangefirst,'',$suffix).'<br />';
 2254:         } elsif ($possdirs == 1) {
 2255:             $singledir = (keys(%nonemptydirs))[0];
 2256:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2257:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2258:             }
 2259:             delete($selimport_menus{$singledir});
 2260:         }
 2261:     } elsif ($numdirs == 1) {
 2262:         $singledir = (keys(%files))[0];
 2263:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2264:             if ($only) {
 2265:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2266:                 unless ($possexts{lc($ext)}) {
 2267:                     next;
 2268:                 }
 2269:             }
 2270:             push(@singledirfiles,$file);
 2271:         }
 2272:         if (@singledirfiles) {
 2273:             $possdirs == 1;
 2274:         }
 2275:     }
 2276:     if (($possdirs == 1) && (@singledirfiles)) {
 2277:         my $showdir = $singledir;
 2278:         if ($singledir eq '') {
 2279:             $showdir = '/';
 2280:         }
 2281:         $output = $lt{'dire'}.
 2282:                   '<select name="'.$firstselectname.'">'.
 2283:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2284:                   '</select><br />'.
 2285:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2286:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2287:         foreach my $file (@singledirfiles) {
 2288:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2289:         }
 2290:         $output .= '</select><br />'."\n";
 2291:     }
 2292:     return ($possdirs,$output);
 2293: }
 2294: 
 2295: =pod
 2296: 
 2297: =head1 Excel and CSV file utility routines
 2298: 
 2299: =cut
 2300: 
 2301: ###############################################################
 2302: ###############################################################
 2303: 
 2304: =pod
 2305: 
 2306: =over 4
 2307: 
 2308: =item * &csv_translate($text) 
 2309: 
 2310: Translate $text to allow it to be output as a 'comma separated values' 
 2311: format.
 2312: 
 2313: =cut
 2314: 
 2315: ###############################################################
 2316: ###############################################################
 2317: sub csv_translate {
 2318:     my $text = shift;
 2319:     $text =~ s/\"/\"\"/g;
 2320:     $text =~ s/\n/ /g;
 2321:     return $text;
 2322: }
 2323: 
 2324: ###############################################################
 2325: ###############################################################
 2326: 
 2327: =pod
 2328: 
 2329: =item * &define_excel_formats()
 2330: 
 2331: Define some commonly used Excel cell formats.
 2332: 
 2333: Currently supported formats:
 2334: 
 2335: =over 4
 2336: 
 2337: =item header
 2338: 
 2339: =item bold
 2340: 
 2341: =item h1
 2342: 
 2343: =item h2
 2344: 
 2345: =item h3
 2346: 
 2347: =item h4
 2348: 
 2349: =item i
 2350: 
 2351: =item date
 2352: 
 2353: =back
 2354: 
 2355: Inputs: $workbook
 2356: 
 2357: Returns: $format, a hash reference.
 2358: 
 2359: 
 2360: =cut
 2361: 
 2362: ###############################################################
 2363: ###############################################################
 2364: sub define_excel_formats {
 2365:     my ($workbook) = @_;
 2366:     my $format;
 2367:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2368:                                                 bottom    => 1,
 2369:                                                 align     => 'center');
 2370:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2371:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2372:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2373:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2374:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2375:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2376:     $format->{'date'} = $workbook->add_format(num_format=>
 2377:                                             'mm/dd/yyyy hh:mm:ss');
 2378:     return $format;
 2379: }
 2380: 
 2381: ###############################################################
 2382: ###############################################################
 2383: 
 2384: =pod
 2385: 
 2386: =item * &create_workbook()
 2387: 
 2388: Create an Excel worksheet.  If it fails, output message on the
 2389: request object and return undefs.
 2390: 
 2391: Inputs: Apache request object
 2392: 
 2393: Returns (undef) on failure, 
 2394:     Excel worksheet object, scalar with filename, and formats 
 2395:     from &Apache::loncommon::define_excel_formats on success
 2396: 
 2397: =cut
 2398: 
 2399: ###############################################################
 2400: ###############################################################
 2401: sub create_workbook {
 2402:     my ($r) = @_;
 2403:         #
 2404:     # Create the excel spreadsheet
 2405:     my $filename = '/prtspool/'.
 2406:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2407:         time.'_'.rand(1000000000).'.xls';
 2408:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2409:     if (! defined($workbook)) {
 2410:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2411:         $r->print(
 2412:             '<p class="LC_error">'
 2413:            .&mt('Problems occurred in creating the new Excel file.')
 2414:            .' '.&mt('This error has been logged.')
 2415:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2416:            .'</p>'
 2417:         );
 2418:         return (undef);
 2419:     }
 2420:     #
 2421:     $workbook->set_tempdir(LONCAPA::tempdir());
 2422:     #
 2423:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2424:     return ($workbook,$filename,$format);
 2425: }
 2426: 
 2427: ###############################################################
 2428: ###############################################################
 2429: 
 2430: =pod
 2431: 
 2432: =item * &create_text_file()
 2433: 
 2434: Create a file to write to and eventually make available to the user.
 2435: If file creation fails, outputs an error message on the request object and 
 2436: return undefs.
 2437: 
 2438: Inputs: Apache request object, and file suffix
 2439: 
 2440: Returns (undef) on failure, 
 2441:     Filehandle and filename on success.
 2442: 
 2443: =cut
 2444: 
 2445: ###############################################################
 2446: ###############################################################
 2447: sub create_text_file {
 2448:     my ($r,$suffix) = @_;
 2449:     if (! defined($suffix)) { $suffix = 'txt'; };
 2450:     my $fh;
 2451:     my $filename = '/prtspool/'.
 2452:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2453:         time.'_'.rand(1000000000).'.'.$suffix;
 2454:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2455:     if (! defined($fh)) {
 2456:         $r->log_error("Couldn't open $filename for output $!");
 2457:         $r->print(
 2458:             '<p class="LC_error">'
 2459:            .&mt('Problems occurred in creating the output file.')
 2460:            .' '.&mt('This error has been logged.')
 2461:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2462:            .'</p>'
 2463:         );
 2464:     }
 2465:     return ($fh,$filename)
 2466: }
 2467: 
 2468: 
 2469: =pod 
 2470: 
 2471: =back
 2472: 
 2473: =cut
 2474: 
 2475: ###############################################################
 2476: ##        Home server <option> list generating code          ##
 2477: ###############################################################
 2478: 
 2479: # ------------------------------------------
 2480: 
 2481: sub domain_select {
 2482:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2483:     my @possdoms;
 2484:     if (ref($incdoms) eq 'ARRAY') {
 2485:         @possdoms = @{$incdoms};
 2486:     } else {
 2487:         @possdoms = &Apache::lonnet::all_domains();
 2488:     }
 2489: 
 2490:     my %domains=map { 
 2491: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2492:     } @possdoms;
 2493: 
 2494:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2495:         foreach my $dom (@{$excdoms}) {
 2496:             delete($domains{$dom});
 2497:         }
 2498:     }
 2499: 
 2500:     if ($multiple) {
 2501: 	$domains{''}=&mt('Any domain');
 2502: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2503: 	return &multiple_select_form($name,$value,4,\%domains);
 2504:     } else {
 2505: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2506: 	return &select_form($name,$value,\%domains);
 2507:     }
 2508: }
 2509: 
 2510: #-------------------------------------------
 2511: 
 2512: =pod
 2513: 
 2514: =head1 Routines for form select boxes
 2515: 
 2516: =over 4
 2517: 
 2518: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2519: 
 2520: Returns a string containing a <select> element int multiple mode
 2521: 
 2522: 
 2523: Args:
 2524:   $name - name of the <select> element
 2525:   $value - scalar or array ref of values that should already be selected
 2526:   $size - number of rows long the select element is
 2527:   $hash - the elements should be 'option' => 'shown text'
 2528:           (shown text should already have been &mt())
 2529:   $order - (optional) array ref of the order to show the elements in
 2530: 
 2531: =cut
 2532: 
 2533: #-------------------------------------------
 2534: sub multiple_select_form {
 2535:     my ($name,$value,$size,$hash,$order)=@_;
 2536:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2537:     my $output='';
 2538:     if (! defined($size)) {
 2539:         $size = 4;
 2540:         if (scalar(keys(%$hash))<4) {
 2541:             $size = scalar(keys(%$hash));
 2542:         }
 2543:     }
 2544:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2545:     my @order;
 2546:     if (ref($order) eq 'ARRAY')  {
 2547:         @order = @{$order};
 2548:     } else {
 2549:         @order = sort(keys(%$hash));
 2550:     }
 2551:     if (exists($$hash{'select_form_order'})) {
 2552:         @order = @{$$hash{'select_form_order'}};
 2553:     }
 2554:         
 2555:     foreach my $key (@order) {
 2556:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2557:         $output.='selected="selected" ' if ($selected{$key});
 2558:         $output.='>'.$hash->{$key}."</option>\n";
 2559:     }
 2560:     $output.="</select>\n";
 2561:     return $output;
 2562: }
 2563: 
 2564: #-------------------------------------------
 2565: 
 2566: =pod
 2567: 
 2568: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2569: 
 2570: Returns a string containing a <select name='$name' size='1'> form to 
 2571: allow a user to select options from a ref to a hash containing:
 2572: option_name => displayed text. An optional $onchange can include
 2573: a javascript onchange item, e.g., onchange="this.form.submit();".
 2574: An optional arg -- $readonly -- if true will cause the select form
 2575: to be disabled, e.g., for the case where an instructor has a section-
 2576: specific role, and is viewing/modifying parameters. 
 2577: 
 2578: See lonrights.pm for an example invocation and use.
 2579: 
 2580: =cut
 2581: 
 2582: #-------------------------------------------
 2583: sub select_form {
 2584:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2585:     return unless (ref($hashref) eq 'HASH');
 2586:     if ($onchange) {
 2587:         $onchange = ' onchange="'.$onchange.'"';
 2588:     }
 2589:     my $disabled;
 2590:     if ($readonly) {
 2591:         $disabled = ' disabled="disabled"';
 2592:     }
 2593:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2594:     my @keys;
 2595:     if (exists($hashref->{'select_form_order'})) {
 2596: 	@keys=@{$hashref->{'select_form_order'}};
 2597:     } else {
 2598: 	@keys=sort(keys(%{$hashref}));
 2599:     }
 2600:     foreach my $key (@keys) {
 2601:         $selectform.=
 2602: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2603:             ($key eq $def ? 'selected="selected" ' : '').
 2604:                 ">".$hashref->{$key}."</option>\n";
 2605:     }
 2606:     $selectform.="</select>";
 2607:     return $selectform;
 2608: }
 2609: 
 2610: # For display filters
 2611: 
 2612: sub display_filter {
 2613:     my ($context) = @_;
 2614:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2615:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2616:     my $phraseinput = 'hidden';
 2617:     my $includeinput = 'hidden';
 2618:     my ($checked,$includetypestext);
 2619:     if ($env{'form.displayfilter'} eq 'containing') {
 2620:         $phraseinput = 'text'; 
 2621:         if ($context eq 'parmslog') {
 2622:             $includeinput = 'checkbox';
 2623:             if ($env{'form.includetypes'}) {
 2624:                 $checked = ' checked="checked"';
 2625:             }
 2626:             $includetypestext = &mt('Include parameter types');
 2627:         }
 2628:     } else {
 2629:         $includetypestext = '&nbsp;';
 2630:     }
 2631:     my ($additional,$secondid,$thirdid);
 2632:     if ($context eq 'parmslog') {
 2633:         $additional = 
 2634:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2635:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2636:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2637:             '</label>';
 2638:         $secondid = 'includetypes';
 2639:         $thirdid = 'includetypestext';
 2640:     }
 2641:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2642:                                                     '$secondid','$thirdid')";
 2643:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2644: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2645: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2646: 	   '</label></span> <span class="LC_nobreak">'.
 2647:            &mt('Filter: [_1]',
 2648: 	   &select_form($env{'form.displayfilter'},
 2649: 			'displayfilter',
 2650: 			{'currentfolder' => 'Current folder/page',
 2651: 			 'containing' => 'Containing phrase',
 2652: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2653: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2654:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2655:                          '" />'.$additional;
 2656: }
 2657: 
 2658: sub display_filter_js {
 2659:     my $includetext = &mt('Include parameter types');
 2660:     return <<"ENDJS";
 2661:   
 2662: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2663:     var firstType = 'hidden';
 2664:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2665:         firstType = 'text';
 2666:     }
 2667:     firstObject = document.getElementById(firstid);
 2668:     if (typeof(firstObject) == 'object') {
 2669:         if (firstObject.type != firstType) {
 2670:             changeInputType(firstObject,firstType);
 2671:         }
 2672:     }
 2673:     if (context == 'parmslog') {
 2674:         var secondType = 'hidden';
 2675:         if (firstType == 'text') {
 2676:             secondType = 'checkbox';
 2677:         }
 2678:         secondObject = document.getElementById(secondid);  
 2679:         if (typeof(secondObject) == 'object') {
 2680:             if (secondObject.type != secondType) {
 2681:                 changeInputType(secondObject,secondType);
 2682:             }
 2683:         }
 2684:         var textItem = document.getElementById(thirdid);
 2685:         var currtext = textItem.innerHTML;
 2686:         var newtext;
 2687:         if (firstType == 'text') {
 2688:             newtext = '$includetext';
 2689:         } else {
 2690:             newtext = '&nbsp;';
 2691:         }
 2692:         if (currtext != newtext) {
 2693:             textItem.innerHTML = newtext;
 2694:         }
 2695:     }
 2696:     return;
 2697: }
 2698: 
 2699: function changeInputType(oldObject,newType) {
 2700:     var newObject = document.createElement('input');
 2701:     newObject.type = newType;
 2702:     if (oldObject.size) {
 2703:         newObject.size = oldObject.size;
 2704:     }
 2705:     if (oldObject.value) {
 2706:         newObject.value = oldObject.value;
 2707:     }
 2708:     if (oldObject.name) {
 2709:         newObject.name = oldObject.name;
 2710:     }
 2711:     if (oldObject.id) {
 2712:         newObject.id = oldObject.id;
 2713:     }
 2714:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2715:     return;
 2716: }
 2717: 
 2718: ENDJS
 2719: }
 2720: 
 2721: sub gradeleveldescription {
 2722:     my $gradelevel=shift;
 2723:     my %gradelevels=(0 => 'Not specified',
 2724: 		     1 => 'Grade 1',
 2725: 		     2 => 'Grade 2',
 2726: 		     3 => 'Grade 3',
 2727: 		     4 => 'Grade 4',
 2728: 		     5 => 'Grade 5',
 2729: 		     6 => 'Grade 6',
 2730: 		     7 => 'Grade 7',
 2731: 		     8 => 'Grade 8',
 2732: 		     9 => 'Grade 9',
 2733: 		     10 => 'Grade 10',
 2734: 		     11 => 'Grade 11',
 2735: 		     12 => 'Grade 12',
 2736: 		     13 => 'Grade 13',
 2737: 		     14 => '100 Level',
 2738: 		     15 => '200 Level',
 2739: 		     16 => '300 Level',
 2740: 		     17 => '400 Level',
 2741: 		     18 => 'Graduate Level');
 2742:     return &mt($gradelevels{$gradelevel});
 2743: }
 2744: 
 2745: sub select_level_form {
 2746:     my ($deflevel,$name)=@_;
 2747:     unless ($deflevel) { $deflevel=0; }
 2748:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2749:     for (my $i=0; $i<=18; $i++) {
 2750:         $selectform.="<option value=\"$i\" ".
 2751:             ($i==$deflevel ? 'selected="selected" ' : '').
 2752:                 ">".&gradeleveldescription($i)."</option>\n";
 2753:     }
 2754:     $selectform.="</select>";
 2755:     return $selectform;
 2756: }
 2757: 
 2758: #-------------------------------------------
 2759: 
 2760: =pod
 2761: 
 2762: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2763: 
 2764: Returns a string containing a <select name='$name' size='1'> form to 
 2765: allow a user to select the domain to preform an operation in.  
 2766: See loncreateuser.pm for an example invocation and use.
 2767: 
 2768: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2769: selected");
 2770: 
 2771: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2772: 
 2773: 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.
 2774: 
 2775: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2776: 
 2777: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2778: 
 2779: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2780: 
 2781: =cut
 2782: 
 2783: #-------------------------------------------
 2784: sub select_dom_form {
 2785:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2786:     if ($onchange) {
 2787:         $onchange = ' onchange="'.$onchange.'"';
 2788:     }
 2789:     if ($disabled) {
 2790:         $disabled = ' disabled="disabled"';
 2791:     }
 2792:     my (@domains,%exclude);
 2793:     if (ref($incdoms) eq 'ARRAY') {
 2794:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2795:     } else {
 2796:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2797:     }
 2798:     if ($includeempty) { @domains=('',@domains); }
 2799:     if (ref($excdoms) eq 'ARRAY') {
 2800:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2801:     }
 2802:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2803:     foreach my $dom (@domains) {
 2804:         next if ($exclude{$dom});
 2805:         $selectdomain.="<option value=\"$dom\" ".
 2806:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2807:         if ($showdomdesc) {
 2808:             if ($dom ne '') {
 2809:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2810:                 if ($domdesc ne '') {
 2811:                     $selectdomain .= ' ('.$domdesc.')';
 2812:                 }
 2813:             } 
 2814:         }
 2815:         $selectdomain .= "</option>\n";
 2816:     }
 2817:     $selectdomain.="</select>";
 2818:     return $selectdomain;
 2819: }
 2820: 
 2821: #-------------------------------------------
 2822: 
 2823: =pod
 2824: 
 2825: =item * &home_server_form_item($domain,$name,$defaultflag)
 2826: 
 2827: input: 4 arguments (two required, two optional) - 
 2828:     $domain - domain of new user
 2829:     $name - name of form element
 2830:     $default - Value of 'default' causes a default item to be first 
 2831:                             option, and selected by default. 
 2832:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2833:                             if 1 server found, or default, if 0 found.
 2834: output: returns 2 items: 
 2835: (a) form element which contains either:
 2836:    (i) <select name="$name">
 2837:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2838:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2839:        </select>
 2840:        form item if there are multiple library servers in $domain, or
 2841:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2842:        if there is only one library server in $domain.
 2843: 
 2844: (b) number of library servers found.
 2845: 
 2846: See loncreateuser.pm for example of use.
 2847: 
 2848: =cut
 2849: 
 2850: #-------------------------------------------
 2851: sub home_server_form_item {
 2852:     my ($domain,$name,$default,$hide) = @_;
 2853:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2854:     my $result;
 2855:     my $numlib = keys(%servers);
 2856:     if ($numlib > 1) {
 2857:         $result .= '<select name="'.$name.'" />'."\n";
 2858:         if ($default) {
 2859:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2860:                        '</option>'."\n";
 2861:         }
 2862:         foreach my $hostid (sort(keys(%servers))) {
 2863:             $result.= '<option value="'.$hostid.'">'.
 2864: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2865:         }
 2866:         $result .= '</select>'."\n";
 2867:     } elsif ($numlib == 1) {
 2868:         my $hostid;
 2869:         foreach my $item (keys(%servers)) {
 2870:             $hostid = $item;
 2871:         }
 2872:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2873:                    $hostid.'" />';
 2874:                    if (!$hide) {
 2875:                        $result .= $hostid.' '.$servers{$hostid};
 2876:                    }
 2877:                    $result .= "\n";
 2878:     } elsif ($default) {
 2879:         $result .= '<input type="hidden" name="'.$name.
 2880:                    '" value="default" />';
 2881:                    if (!$hide) {
 2882:                        $result .= &mt('default');
 2883:                    }
 2884:                    $result .= "\n";
 2885:     }
 2886:     return ($result,$numlib);
 2887: }
 2888: 
 2889: =pod
 2890: 
 2891: =back 
 2892: 
 2893: =cut
 2894: 
 2895: ###############################################################
 2896: ##                  Decoding User Agent                      ##
 2897: ###############################################################
 2898: 
 2899: =pod
 2900: 
 2901: =head1 Decoding the User Agent
 2902: 
 2903: =over 4
 2904: 
 2905: =item * &decode_user_agent()
 2906: 
 2907: Inputs: $r
 2908: 
 2909: Outputs:
 2910: 
 2911: =over 4
 2912: 
 2913: =item * $httpbrowser
 2914: 
 2915: =item * $clientbrowser
 2916: 
 2917: =item * $clientversion
 2918: 
 2919: =item * $clientmathml
 2920: 
 2921: =item * $clientunicode
 2922: 
 2923: =item * $clientos
 2924: 
 2925: =item * $clientmobile
 2926: 
 2927: =item * $clientinfo
 2928: 
 2929: =item * $clientosversion
 2930: 
 2931: =back
 2932: 
 2933: =back 
 2934: 
 2935: =cut
 2936: 
 2937: ###############################################################
 2938: ###############################################################
 2939: sub decode_user_agent {
 2940:     my ($r)=@_;
 2941:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2942:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2943:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2944:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2945:     my $clientbrowser='unknown';
 2946:     my $clientversion='0';
 2947:     my $clientmathml='';
 2948:     my $clientunicode='0';
 2949:     my $clientmobile=0;
 2950:     my $clientosversion='';
 2951:     for (my $i=0;$i<=$#browsertype;$i++) {
 2952:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2953: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2954: 	    $clientbrowser=$bname;
 2955:             $httpbrowser=~/$vreg/i;
 2956: 	    $clientversion=$1;
 2957:             $clientmathml=($clientversion>=$minv);
 2958:             $clientunicode=($clientversion>=$univ);
 2959: 	}
 2960:     }
 2961:     my $clientos='unknown';
 2962:     my $clientinfo;
 2963:     if (($httpbrowser=~/linux/i) ||
 2964:         ($httpbrowser=~/unix/i) ||
 2965:         ($httpbrowser=~/ux/i) ||
 2966:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2967:     if (($httpbrowser=~/vax/i) ||
 2968:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2969:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2970:     if (($httpbrowser=~/mac/i) ||
 2971:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2972:     if ($httpbrowser=~/win/i) {
 2973:         $clientos='win';
 2974:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2975:             $clientosversion = $1;
 2976:         }
 2977:     }
 2978:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2979:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2980:         $clientmobile=lc($1);
 2981:     }
 2982:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2983:         $clientinfo = 'firefox-'.$1;
 2984:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2985:         $clientinfo = 'chromeframe-'.$1;
 2986:     }
 2987:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2988:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2989:             $clientosversion);
 2990: }
 2991: 
 2992: ###############################################################
 2993: ##    Authentication changing form generation subroutines    ##
 2994: ###############################################################
 2995: ##
 2996: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2997: ## hash, and have reasonable default values.
 2998: ##
 2999: ##    formname = the name given in the <form> tag.
 3000: #-------------------------------------------
 3001: 
 3002: =pod
 3003: 
 3004: =head1 Authentication Routines
 3005: 
 3006: =over 4
 3007: 
 3008: =item * &authform_xxxxxx()
 3009: 
 3010: The authform_xxxxxx subroutines provide javascript and html forms which 
 3011: handle some of the conveniences required for authentication forms.  
 3012: This is not an optimal method, but it works.  
 3013: 
 3014: =over 4
 3015: 
 3016: =item * authform_header
 3017: 
 3018: =item * authform_authorwarning
 3019: 
 3020: =item * authform_nochange
 3021: 
 3022: =item * authform_kerberos
 3023: 
 3024: =item * authform_internal
 3025: 
 3026: =item * authform_filesystem
 3027: 
 3028: =back
 3029: 
 3030: See loncreateuser.pm for invocation and use examples.
 3031: 
 3032: =cut
 3033: 
 3034: #-------------------------------------------
 3035: sub authform_header{  
 3036:     my %in = (
 3037:         formname => 'cu',
 3038:         kerb_def_dom => '',
 3039:         @_,
 3040:     );
 3041:     $in{'formname'} = 'document.' . $in{'formname'};
 3042:     my $result='';
 3043: 
 3044: #---------------------------------------------- Code for upper case translation
 3045:     my $Javascript_toUpperCase;
 3046:     unless ($in{kerb_def_dom}) {
 3047:         $Javascript_toUpperCase =<<"END";
 3048:         switch (choice) {
 3049:            case 'krb': currentform.elements[choicearg].value =
 3050:                currentform.elements[choicearg].value.toUpperCase();
 3051:                break;
 3052:            default:
 3053:         }
 3054: END
 3055:     } else {
 3056:         $Javascript_toUpperCase = "";
 3057:     }
 3058: 
 3059:     my $radioval = "'nochange'";
 3060:     if (defined($in{'curr_authtype'})) {
 3061:         if ($in{'curr_authtype'} ne '') {
 3062:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3063:         }
 3064:     }
 3065:     my $argfield = 'null';
 3066:     if (defined($in{'mode'})) {
 3067:         if ($in{'mode'} eq 'modifycourse')  {
 3068:             if (defined($in{'curr_autharg'})) {
 3069:                 if ($in{'curr_autharg'} ne '') {
 3070:                     $argfield = "'$in{'curr_autharg'}'";
 3071:                 }
 3072:             }
 3073:         }
 3074:     }
 3075: 
 3076:     $result.=<<"END";
 3077: var current = new Object();
 3078: current.radiovalue = $radioval;
 3079: current.argfield = $argfield;
 3080: 
 3081: function changed_radio(choice,currentform) {
 3082:     var choicearg = choice + 'arg';
 3083:     // If a radio button in changed, we need to change the argfield
 3084:     if (current.radiovalue != choice) {
 3085:         current.radiovalue = choice;
 3086:         if (current.argfield != null) {
 3087:             currentform.elements[current.argfield].value = '';
 3088:         }
 3089:         if (choice == 'nochange') {
 3090:             current.argfield = null;
 3091:         } else {
 3092:             current.argfield = choicearg;
 3093:             switch(choice) {
 3094:                 case 'krb': 
 3095:                     currentform.elements[current.argfield].value = 
 3096:                         "$in{'kerb_def_dom'}";
 3097:                 break;
 3098:               default:
 3099:                 break;
 3100:             }
 3101:         }
 3102:     }
 3103:     return;
 3104: }
 3105: 
 3106: function changed_text(choice,currentform) {
 3107:     var choicearg = choice + 'arg';
 3108:     if (currentform.elements[choicearg].value !='') {
 3109:         $Javascript_toUpperCase
 3110:         // clear old field
 3111:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3112:             currentform.elements[current.argfield].value = '';
 3113:         }
 3114:         current.argfield = choicearg;
 3115:     }
 3116:     set_auth_radio_buttons(choice,currentform);
 3117:     return;
 3118: }
 3119: 
 3120: function set_auth_radio_buttons(newvalue,currentform) {
 3121:     var numauthchoices = currentform.login.length;
 3122:     if (typeof numauthchoices  == "undefined") {
 3123:         return;
 3124:     } 
 3125:     var i=0;
 3126:     while (i < numauthchoices) {
 3127:         if (currentform.login[i].value == newvalue) { break; }
 3128:         i++;
 3129:     }
 3130:     if (i == numauthchoices) {
 3131:         return;
 3132:     }
 3133:     current.radiovalue = newvalue;
 3134:     currentform.login[i].checked = true;
 3135:     return;
 3136: }
 3137: END
 3138:     return $result;
 3139: }
 3140: 
 3141: sub authform_authorwarning {
 3142:     my $result='';
 3143:     $result='<i>'.
 3144:         &mt('As a general rule, only authors or co-authors should be '.
 3145:             'filesystem authenticated '.
 3146:             '(which allows access to the server filesystem).')."</i>\n";
 3147:     return $result;
 3148: }
 3149: 
 3150: sub authform_nochange {
 3151:     my %in = (
 3152:               formname => 'document.cu',
 3153:               kerb_def_dom => 'MSU.EDU',
 3154:               @_,
 3155:           );
 3156:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3157:     my $result;
 3158:     if (!$authnum) {
 3159:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3160:     } else {
 3161:         $result = '<label>'.&mt('[_1] Do not change login data',
 3162:                   '<input type="radio" name="login" value="nochange" '.
 3163:                   'checked="checked" onclick="'.
 3164:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3165: 	    '</label>';
 3166:     }
 3167:     return $result;
 3168: }
 3169: 
 3170: sub authform_kerberos {
 3171:     my %in = (
 3172:               formname => 'document.cu',
 3173:               kerb_def_dom => 'MSU.EDU',
 3174:               kerb_def_auth => 'krb4',
 3175:               @_,
 3176:               );
 3177:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3178:         $autharg,$jscall,$disabled);
 3179:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3180:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3181:        $check5 = ' checked="checked"';
 3182:     } else {
 3183:        $check4 = ' checked="checked"';
 3184:     }
 3185:     if ($in{'readonly'}) {
 3186:         $disabled = ' disabled="disabled"';
 3187:     }
 3188:     $krbarg = $in{'kerb_def_dom'};
 3189:     if (defined($in{'curr_authtype'})) {
 3190:         if ($in{'curr_authtype'} eq 'krb') {
 3191:             $krbcheck = ' checked="checked"';
 3192:             if (defined($in{'mode'})) {
 3193:                 if ($in{'mode'} eq 'modifyuser') {
 3194:                     $krbcheck = '';
 3195:                 }
 3196:             }
 3197:             if (defined($in{'curr_kerb_ver'})) {
 3198:                 if ($in{'curr_krb_ver'} eq '5') {
 3199:                     $check5 = ' checked="checked"';
 3200:                     $check4 = '';
 3201:                 } else {
 3202:                     $check4 = ' checked="checked"';
 3203:                     $check5 = '';
 3204:                 }
 3205:             }
 3206:             if (defined($in{'curr_autharg'})) {
 3207:                 $krbarg = $in{'curr_autharg'};
 3208:             }
 3209:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3210:                 if (defined($in{'curr_autharg'})) {
 3211:                     $result = 
 3212:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3213:         $in{'curr_autharg'},$krbver);
 3214:                 } else {
 3215:                     $result =
 3216:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3217:                 }
 3218:                 return $result; 
 3219:             }
 3220:         }
 3221:     } else {
 3222:         if ($authnum == 1) {
 3223:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3224:         }
 3225:     }
 3226:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3227:         return;
 3228:     } elsif ($authtype eq '') {
 3229:         if (defined($in{'mode'})) {
 3230:             if ($in{'mode'} eq 'modifycourse') {
 3231:                 if ($authnum == 1) {
 3232:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3233:                 }
 3234:             }
 3235:         }
 3236:     }
 3237:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3238:     if ($authtype eq '') {
 3239:         $authtype = '<input type="radio" name="login" value="krb" '.
 3240:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3241:                     $krbcheck.$disabled.' />';
 3242:     }
 3243:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3244:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3245:          $in{'curr_authtype'} eq 'krb5') ||
 3246:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3247:          $in{'curr_authtype'} eq 'krb4')) {
 3248:         $result .= &mt
 3249:         ('[_1] Kerberos authenticated with domain [_2] '.
 3250:          '[_3] Version 4 [_4] Version 5 [_5]',
 3251:          '<label>'.$authtype,
 3252:          '</label><input type="text" size="10" name="krbarg" '.
 3253:              'value="'.$krbarg.'" '.
 3254:              'onchange="'.$jscall.'"'.$disabled.' />',
 3255:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3256:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3257: 	 '</label>');
 3258:     } elsif ($can_assign{'krb4'}) {
 3259:         $result .= &mt
 3260:         ('[_1] Kerberos authenticated with domain [_2] '.
 3261:          '[_3] Version 4 [_4]',
 3262:          '<label>'.$authtype,
 3263:          '</label><input type="text" size="10" name="krbarg" '.
 3264:              'value="'.$krbarg.'" '.
 3265:              'onchange="'.$jscall.'"'.$disabled.' />',
 3266:          '<label><input type="hidden" name="krbver" value="4" />',
 3267:          '</label>');
 3268:     } elsif ($can_assign{'krb5'}) {
 3269:         $result .= &mt
 3270:         ('[_1] Kerberos authenticated with domain [_2] '.
 3271:          '[_3] Version 5 [_4]',
 3272:          '<label>'.$authtype,
 3273:          '</label><input type="text" size="10" name="krbarg" '.
 3274:              'value="'.$krbarg.'" '.
 3275:              'onchange="'.$jscall.'"'.$disabled.' />',
 3276:          '<label><input type="hidden" name="krbver" value="5" />',
 3277:          '</label>');
 3278:     }
 3279:     return $result;
 3280: }
 3281: 
 3282: sub authform_internal {
 3283:     my %in = (
 3284:                 formname => 'document.cu',
 3285:                 kerb_def_dom => 'MSU.EDU',
 3286:                 @_,
 3287:                 );
 3288:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3289:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3290:     if ($in{'readonly'}) {
 3291:         $disabled = ' disabled="disabled"';
 3292:     }
 3293:     if (defined($in{'curr_authtype'})) {
 3294:         if ($in{'curr_authtype'} eq 'int') {
 3295:             if ($can_assign{'int'}) {
 3296:                 $intcheck = 'checked="checked" ';
 3297:                 if (defined($in{'mode'})) {
 3298:                     if ($in{'mode'} eq 'modifyuser') {
 3299:                         $intcheck = '';
 3300:                     }
 3301:                 }
 3302:                 if (defined($in{'curr_autharg'})) {
 3303:                     $intarg = $in{'curr_autharg'};
 3304:                 }
 3305:             } else {
 3306:                 $result = &mt('Currently internally authenticated.');
 3307:                 return $result;
 3308:             }
 3309:         }
 3310:     } else {
 3311:         if ($authnum == 1) {
 3312:             $authtype = '<input type="hidden" name="login" value="int" />';
 3313:         }
 3314:     }
 3315:     if (!$can_assign{'int'}) {
 3316:         return;
 3317:     } elsif ($authtype eq '') {
 3318:         if (defined($in{'mode'})) {
 3319:             if ($in{'mode'} eq 'modifycourse') {
 3320:                 if ($authnum == 1) {
 3321:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3322:                 }
 3323:             }
 3324:         }
 3325:     }
 3326:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3327:     if ($authtype eq '') {
 3328:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3329:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3330:     }
 3331:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3332:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3333:     $result = &mt
 3334:         ('[_1] Internally authenticated (with initial password [_2])',
 3335:          '<label>'.$authtype,'</label>'.$autharg);
 3336:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
 3337:     return $result;
 3338: }
 3339: 
 3340: sub authform_local {
 3341:     my %in = (
 3342:               formname => 'document.cu',
 3343:               kerb_def_dom => 'MSU.EDU',
 3344:               @_,
 3345:               );
 3346:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3347:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3348:     if ($in{'readonly'}) {
 3349:         $disabled = ' disabled="disabled"';
 3350:     } 
 3351:     if (defined($in{'curr_authtype'})) {
 3352:         if ($in{'curr_authtype'} eq 'loc') {
 3353:             if ($can_assign{'loc'}) {
 3354:                 $loccheck = 'checked="checked" ';
 3355:                 if (defined($in{'mode'})) {
 3356:                     if ($in{'mode'} eq 'modifyuser') {
 3357:                         $loccheck = '';
 3358:                     }
 3359:                 }
 3360:                 if (defined($in{'curr_autharg'})) {
 3361:                     $locarg = $in{'curr_autharg'};
 3362:                 }
 3363:             } else {
 3364:                 $result = &mt('Currently using local (institutional) authentication.');
 3365:                 return $result;
 3366:             }
 3367:         }
 3368:     } else {
 3369:         if ($authnum == 1) {
 3370:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3371:         }
 3372:     }
 3373:     if (!$can_assign{'loc'}) {
 3374:         return;
 3375:     } elsif ($authtype eq '') {
 3376:         if (defined($in{'mode'})) {
 3377:             if ($in{'mode'} eq 'modifycourse') {
 3378:                 if ($authnum == 1) {
 3379:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3380:                 }
 3381:             }
 3382:         }
 3383:     }
 3384:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3385:     if ($authtype eq '') {
 3386:         $authtype = '<input type="radio" name="login" value="loc" '.
 3387:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3388:                     $jscall.'"'.$disabled.' />';
 3389:     }
 3390:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3391:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3392:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3393:                   '<label>'.$authtype,'</label>'.$autharg);
 3394:     return $result;
 3395: }
 3396: 
 3397: sub authform_filesystem {
 3398:     my %in = (
 3399:               formname => 'document.cu',
 3400:               kerb_def_dom => 'MSU.EDU',
 3401:               @_,
 3402:               );
 3403:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3404:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3405:     if ($in{'readonly'}) {
 3406:         $disabled = ' disabled="disabled"';
 3407:     }
 3408:     if (defined($in{'curr_authtype'})) {
 3409:         if ($in{'curr_authtype'} eq 'fsys') {
 3410:             if ($can_assign{'fsys'}) {
 3411:                 $fsyscheck = 'checked="checked" ';
 3412:                 if (defined($in{'mode'})) {
 3413:                     if ($in{'mode'} eq 'modifyuser') {
 3414:                         $fsyscheck = '';
 3415:                     }
 3416:                 }
 3417:             } else {
 3418:                 $result = &mt('Currently Filesystem Authenticated.');
 3419:                 return $result;
 3420:             }
 3421:         }
 3422:     } else {
 3423:         if ($authnum == 1) {
 3424:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3425:         }
 3426:     }
 3427:     if (!$can_assign{'fsys'}) {
 3428:         return;
 3429:     } elsif ($authtype eq '') {
 3430:         if (defined($in{'mode'})) {
 3431:             if ($in{'mode'} eq 'modifycourse') {
 3432:                 if ($authnum == 1) {
 3433:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3434:                 }
 3435:             }
 3436:         }
 3437:     }
 3438:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3439:     if ($authtype eq '') {
 3440:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3441:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3442:                     $jscall.'"'.$disabled.' />';
 3443:     }
 3444:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3445:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3446:     $result = &mt
 3447:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3448:          '<label><input type="radio" name="login" value="fsys" '.
 3449:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
 3450:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3451:                   'onchange="'.$jscall.'"'.$disabled.' />');
 3452:     return $result;
 3453: }
 3454: 
 3455: sub get_assignable_auth {
 3456:     my ($dom) = @_;
 3457:     if ($dom eq '') {
 3458:         $dom = $env{'request.role.domain'};
 3459:     }
 3460:     my %can_assign = (
 3461:                           krb4 => 1,
 3462:                           krb5 => 1,
 3463:                           int  => 1,
 3464:                           loc  => 1,
 3465:                      );
 3466:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3467:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3468:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3469:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3470:             my $context;
 3471:             if ($env{'request.role'} =~ /^au/) {
 3472:                 $context = 'author';
 3473:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3474:                 $context = 'domain';
 3475:             } elsif ($env{'request.course.id'}) {
 3476:                 $context = 'course';
 3477:             }
 3478:             if ($context) {
 3479:                 if (ref($authhash->{$context}) eq 'HASH') {
 3480:                    %can_assign = %{$authhash->{$context}}; 
 3481:                 }
 3482:             }
 3483:         }
 3484:     }
 3485:     my $authnum = 0;
 3486:     foreach my $key (keys(%can_assign)) {
 3487:         if ($can_assign{$key}) {
 3488:             $authnum ++;
 3489:         }
 3490:     }
 3491:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3492:         $authnum --;
 3493:     }
 3494:     return ($authnum,%can_assign);
 3495: }
 3496: 
 3497: ###############################################################
 3498: ##    Get Kerberos Defaults for Domain                 ##
 3499: ###############################################################
 3500: ##
 3501: ## Returns default kerberos version and an associated argument
 3502: ## as listed in file domain.tab. If not listed, provides
 3503: ## appropriate default domain and kerberos version.
 3504: ##
 3505: #-------------------------------------------
 3506: 
 3507: =pod
 3508: 
 3509: =item * &get_kerberos_defaults()
 3510: 
 3511: get_kerberos_defaults($target_domain) returns the default kerberos
 3512: version and domain. If not found, it defaults to version 4 and the 
 3513: domain of the server.
 3514: 
 3515: =over 4
 3516: 
 3517: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3518: 
 3519: =back
 3520: 
 3521: =back
 3522: 
 3523: =cut
 3524: 
 3525: #-------------------------------------------
 3526: sub get_kerberos_defaults {
 3527:     my $domain=shift;
 3528:     my ($krbdef,$krbdefdom);
 3529:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3530:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3531:         $krbdef = $domdefaults{'auth_def'};
 3532:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3533:     } else {
 3534:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3535:         my $krbdefdom=$1;
 3536:         $krbdefdom=~tr/a-z/A-Z/;
 3537:         $krbdef = "krb4";
 3538:     }
 3539:     return ($krbdef,$krbdefdom);
 3540: }
 3541: 
 3542: 
 3543: ###############################################################
 3544: ##                Thesaurus Functions                        ##
 3545: ###############################################################
 3546: 
 3547: =pod
 3548: 
 3549: =head1 Thesaurus Functions
 3550: 
 3551: =over 4
 3552: 
 3553: =item * &initialize_keywords()
 3554: 
 3555: Initializes the package variable %Keywords if it is empty.  Uses the
 3556: package variable $thesaurus_db_file.
 3557: 
 3558: =cut
 3559: 
 3560: ###################################################
 3561: 
 3562: sub initialize_keywords {
 3563:     return 1 if (scalar keys(%Keywords));
 3564:     # If we are here, %Keywords is empty, so fill it up
 3565:     #   Make sure the file we need exists...
 3566:     if (! -e $thesaurus_db_file) {
 3567:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3568:                                  " failed because it does not exist");
 3569:         return 0;
 3570:     }
 3571:     #   Set up the hash as a database
 3572:     my %thesaurus_db;
 3573:     if (! tie(%thesaurus_db,'GDBM_File',
 3574:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3575:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3576:                                  $thesaurus_db_file);
 3577:         return 0;
 3578:     } 
 3579:     #  Get the average number of appearances of a word.
 3580:     my $avecount = $thesaurus_db{'average.count'};
 3581:     #  Put keywords (those that appear > average) into %Keywords
 3582:     while (my ($word,$data)=each (%thesaurus_db)) {
 3583:         my ($count,undef) = split /:/,$data;
 3584:         $Keywords{$word}++ if ($count > $avecount);
 3585:     }
 3586:     untie %thesaurus_db;
 3587:     # Remove special values from %Keywords.
 3588:     foreach my $value ('total.count','average.count') {
 3589:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3590:   }
 3591:     return 1;
 3592: }
 3593: 
 3594: ###################################################
 3595: 
 3596: =pod
 3597: 
 3598: =item * &keyword($word)
 3599: 
 3600: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3601: than the average number of times in the thesaurus database.  Calls 
 3602: &initialize_keywords
 3603: 
 3604: =cut
 3605: 
 3606: ###################################################
 3607: 
 3608: sub keyword {
 3609:     return if (!&initialize_keywords());
 3610:     my $word=lc(shift());
 3611:     $word=~s/\W//g;
 3612:     return exists($Keywords{$word});
 3613: }
 3614: 
 3615: ###############################################################
 3616: 
 3617: =pod 
 3618: 
 3619: =item * &get_related_words()
 3620: 
 3621: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3622: an array of words.  If the keyword is not in the thesaurus, an empty array
 3623: will be returned.  The order of the words returned is determined by the
 3624: database which holds them.
 3625: 
 3626: Uses global $thesaurus_db_file.
 3627: 
 3628: 
 3629: =cut
 3630: 
 3631: ###############################################################
 3632: sub get_related_words {
 3633:     my $keyword = shift;
 3634:     my %thesaurus_db;
 3635:     if (! -e $thesaurus_db_file) {
 3636:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3637:                                  "failed because the file does not exist");
 3638:         return ();
 3639:     }
 3640:     if (! tie(%thesaurus_db,'GDBM_File',
 3641:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3642:         return ();
 3643:     } 
 3644:     my @Words=();
 3645:     my $count=0;
 3646:     if (exists($thesaurus_db{$keyword})) {
 3647: 	# The first element is the number of times
 3648: 	# the word appears.  We do not need it now.
 3649: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3650: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3651: 	my $threshold=$mostfrequentcount/10;
 3652:         foreach my $possibleword (@RelatedWords) {
 3653:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3654:             if ($wordcount>$threshold) {
 3655: 		push(@Words,$word);
 3656:                 $count++;
 3657:                 if ($count>10) { last; }
 3658: 	    }
 3659:         }
 3660:     }
 3661:     untie %thesaurus_db;
 3662:     return @Words;
 3663: }
 3664: ###############################################################
 3665: #
 3666: #  Spell checking
 3667: #
 3668: 
 3669: =pod
 3670: 
 3671: =back
 3672: 
 3673: =head1 Spell checking
 3674: 
 3675: =over 4
 3676: 
 3677: =item * &check_spelling($wordlist $language)
 3678: 
 3679: Takes a string containing words and feeds it to an external
 3680: spellcheck program via a pipeline. Returns a string containing
 3681: them mis-spelled words.
 3682: 
 3683: Parameters:
 3684: 
 3685: =over 4
 3686: 
 3687: =item - $wordlist
 3688: 
 3689: String that will be fed into the spellcheck program.
 3690: 
 3691: =item - $language
 3692: 
 3693: Language string that specifies the language for which the spell
 3694: check will be performed.
 3695: 
 3696: =back
 3697: 
 3698: =back
 3699: 
 3700: Note: This sub assumes that aspell is installed.
 3701: 
 3702: 
 3703: =cut
 3704: 
 3705: 
 3706: sub check_spelling {
 3707:     my ($wordlist, $language) = @_;
 3708:     my @misspellings;
 3709:     
 3710:     # Generate the speller and set the langauge.
 3711:     # if explicitly selected:
 3712: 
 3713:     my $speller = Text::Aspell->new;
 3714:     if ($language) {
 3715: 	$speller->set_option('lang', $language);
 3716:     }
 3717: 
 3718:     # Turn the word list into an array of words by splittingon whitespace
 3719: 
 3720:     my @words = split(/\s+/, $wordlist);
 3721: 
 3722:     foreach my $word (@words) {
 3723: 	if(! $speller->check($word)) {
 3724: 	    push(@misspellings, $word);
 3725: 	}
 3726:     }
 3727:     return join(' ', @misspellings);
 3728:     
 3729: }
 3730: 
 3731: # -------------------------------------------------------------- Plaintext name
 3732: =pod
 3733: 
 3734: =head1 User Name Functions
 3735: 
 3736: =over 4
 3737: 
 3738: =item * &plainname($uname,$udom,$first)
 3739: 
 3740: Takes a users logon name and returns it as a string in
 3741: "first middle last generation" form 
 3742: if $first is set to 'lastname' then it returns it as
 3743: 'lastname generation, firstname middlename' if their is a lastname
 3744: 
 3745: =cut
 3746: 
 3747: 
 3748: ###############################################################
 3749: sub plainname {
 3750:     my ($uname,$udom,$first)=@_;
 3751:     return if (!defined($uname) || !defined($udom));
 3752:     my %names=&getnames($uname,$udom);
 3753:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3754: 					  $names{'middlename'},
 3755: 					  $names{'lastname'},
 3756: 					  $names{'generation'},$first);
 3757:     $name=~s/^\s+//;
 3758:     $name=~s/\s+$//;
 3759:     $name=~s/\s+/ /g;
 3760:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3761:     return $name;
 3762: }
 3763: 
 3764: # -------------------------------------------------------------------- Nickname
 3765: =pod
 3766: 
 3767: =item * &nickname($uname,$udom)
 3768: 
 3769: Gets a users name and returns it as a string as
 3770: 
 3771: "&quot;nickname&quot;"
 3772: 
 3773: if the user has a nickname or
 3774: 
 3775: "first middle last generation"
 3776: 
 3777: if the user does not
 3778: 
 3779: =cut
 3780: 
 3781: sub nickname {
 3782:     my ($uname,$udom)=@_;
 3783:     return if (!defined($uname) || !defined($udom));
 3784:     my %names=&getnames($uname,$udom);
 3785:     my $name=$names{'nickname'};
 3786:     if ($name) {
 3787:        $name='&quot;'.$name.'&quot;'; 
 3788:     } else {
 3789:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3790: 	     $names{'lastname'}.' '.$names{'generation'};
 3791:        $name=~s/\s+$//;
 3792:        $name=~s/\s+/ /g;
 3793:     }
 3794:     return $name;
 3795: }
 3796: 
 3797: sub getnames {
 3798:     my ($uname,$udom)=@_;
 3799:     return if (!defined($uname) || !defined($udom));
 3800:     if ($udom eq 'public' && $uname eq 'public') {
 3801: 	return ('lastname' => &mt('Public'));
 3802:     }
 3803:     my $id=$uname.':'.$udom;
 3804:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3805:     if ($cached) {
 3806: 	return %{$names};
 3807:     } else {
 3808: 	my %loadnames=&Apache::lonnet::get('environment',
 3809:                     ['firstname','middlename','lastname','generation','nickname'],
 3810: 					 $udom,$uname);
 3811: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3812: 	return %loadnames;
 3813:     }
 3814: }
 3815: 
 3816: # -------------------------------------------------------------------- getemails
 3817: 
 3818: =pod
 3819: 
 3820: =item * &getemails($uname,$udom)
 3821: 
 3822: Gets a user's email information and returns it as a hash with keys:
 3823: notification, critnotification, permanentemail
 3824: 
 3825: For notification and critnotification, values are comma-separated lists 
 3826: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3827:  
 3828: 
 3829: =cut
 3830: 
 3831: 
 3832: sub getemails {
 3833:     my ($uname,$udom)=@_;
 3834:     if ($udom eq 'public' && $uname eq 'public') {
 3835: 	return;
 3836:     }
 3837:     if (!$udom) { $udom=$env{'user.domain'}; }
 3838:     if (!$uname) { $uname=$env{'user.name'}; }
 3839:     my $id=$uname.':'.$udom;
 3840:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3841:     if ($cached) {
 3842: 	return %{$names};
 3843:     } else {
 3844: 	my %loadnames=&Apache::lonnet::get('environment',
 3845:                     			   ['notification','critnotification',
 3846: 					    'permanentemail'],
 3847: 					   $udom,$uname);
 3848: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3849: 	return %loadnames;
 3850:     }
 3851: }
 3852: 
 3853: sub flush_email_cache {
 3854:     my ($uname,$udom)=@_;
 3855:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3856:     if (!$uname) { $uname=$env{'user.name'};   }
 3857:     return if ($udom eq 'public' && $uname eq 'public');
 3858:     my $id=$uname.':'.$udom;
 3859:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3860: }
 3861: 
 3862: # -------------------------------------------------------------------- getlangs
 3863: 
 3864: =pod
 3865: 
 3866: =item * &getlangs($uname,$udom)
 3867: 
 3868: Gets a user's language preference and returns it as a hash with key:
 3869: language.
 3870: 
 3871: =cut
 3872: 
 3873: 
 3874: sub getlangs {
 3875:     my ($uname,$udom) = @_;
 3876:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3877:     if (!$uname) { $uname=$env{'user.name'};   }
 3878:     my $id=$uname.':'.$udom;
 3879:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3880:     if ($cached) {
 3881:         return %{$langs};
 3882:     } else {
 3883:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3884:                                            $udom,$uname);
 3885:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3886:         return %loadlangs;
 3887:     }
 3888: }
 3889: 
 3890: sub flush_langs_cache {
 3891:     my ($uname,$udom)=@_;
 3892:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3893:     if (!$uname) { $uname=$env{'user.name'};   }
 3894:     return if ($udom eq 'public' && $uname eq 'public');
 3895:     my $id=$uname.':'.$udom;
 3896:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3897: }
 3898: 
 3899: # ------------------------------------------------------------------ Screenname
 3900: 
 3901: =pod
 3902: 
 3903: =item * &screenname($uname,$udom)
 3904: 
 3905: Gets a users screenname and returns it as a string
 3906: 
 3907: =cut
 3908: 
 3909: sub screenname {
 3910:     my ($uname,$udom)=@_;
 3911:     if ($uname eq $env{'user.name'} &&
 3912: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3913:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3914:     return $names{'screenname'};
 3915: }
 3916: 
 3917: 
 3918: # ------------------------------------------------------------- Confirm Wrapper
 3919: =pod
 3920: 
 3921: =item * &confirmwrapper($message)
 3922: 
 3923: Wrap messages about completion of operation in box
 3924: 
 3925: =cut
 3926: 
 3927: sub confirmwrapper {
 3928:     my ($message)=@_;
 3929:     if ($message) {
 3930:         return "\n".'<div class="LC_confirm_box">'."\n"
 3931:                .$message."\n"
 3932:                .'</div>'."\n";
 3933:     } else {
 3934:         return $message;
 3935:     }
 3936: }
 3937: 
 3938: # ------------------------------------------------------------- Message Wrapper
 3939: 
 3940: sub messagewrapper {
 3941:     my ($link,$username,$domain,$subject,$text)=@_;
 3942:     return 
 3943:         '<a href="/adm/email?compose=individual&amp;'.
 3944:         'recname='.$username.'&amp;recdom='.$domain.
 3945: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3946:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3947: }
 3948: 
 3949: # --------------------------------------------------------------- Notes Wrapper
 3950: 
 3951: sub noteswrapper {
 3952:     my ($link,$un,$do)=@_;
 3953:     return 
 3954: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3955: }
 3956: 
 3957: # ------------------------------------------------------------- Aboutme Wrapper
 3958: 
 3959: sub aboutmewrapper {
 3960:     my ($link,$username,$domain,$target,$class)=@_;
 3961:     if (!defined($username)  && !defined($domain)) {
 3962:         return;
 3963:     }
 3964:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3965: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3966: }
 3967: 
 3968: # ------------------------------------------------------------ Syllabus Wrapper
 3969: 
 3970: sub syllabuswrapper {
 3971:     my ($linktext,$coursedir,$domain)=@_;
 3972:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3973: }
 3974: 
 3975: # -----------------------------------------------------------------------------
 3976: 
 3977: sub track_student_link {
 3978:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3979:     my $link ="/adm/trackstudent?";
 3980:     my $title = 'View recent activity';
 3981:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3982:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3983:         $link .= "selected_student=$sname:$sdom";
 3984:         $title .= ' of this student';
 3985:     } 
 3986:     if (defined($target) && $target !~ /^\s*$/) {
 3987:         $target = qq{target="$target"};
 3988:     } else {
 3989:         $target = '';
 3990:     }
 3991:     if ($start) { $link.='&amp;start='.$start; }
 3992:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3993:     $title = &mt($title);
 3994:     $linktext = &mt($linktext);
 3995:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3996: 	&help_open_topic('View_recent_activity');
 3997: }
 3998: 
 3999: sub slot_reservations_link {
 4000:     my ($linktext,$sname,$sdom,$target) = @_;
 4001:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4002:     my $title = 'View slot reservation history';
 4003:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4004:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4005:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4006:         $title .= ' of this student';
 4007:     }
 4008:     if (defined($target) && $target !~ /^\s*$/) {
 4009:         $target = qq{target="$target"};
 4010:     } else {
 4011:         $target = '';
 4012:     }
 4013:     $title = &mt($title);
 4014:     $linktext = &mt($linktext);
 4015:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4016: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4017: 
 4018: }
 4019: 
 4020: # ===================================================== Display a student photo
 4021: 
 4022: 
 4023: sub student_image_tag {
 4024:     my ($domain,$user)=@_;
 4025:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4026:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4027: 	return '<img src="'.$imgsrc.'" align="right" />';
 4028:     } else {
 4029: 	return '';
 4030:     }
 4031: }
 4032: 
 4033: =pod
 4034: 
 4035: =back
 4036: 
 4037: =head1 Access .tab File Data
 4038: 
 4039: =over 4
 4040: 
 4041: =item * &languageids() 
 4042: 
 4043: returns list of all language ids
 4044: 
 4045: =cut
 4046: 
 4047: sub languageids {
 4048:     return sort(keys(%language));
 4049: }
 4050: 
 4051: =pod
 4052: 
 4053: =item * &languagedescription() 
 4054: 
 4055: returns description of a specified language id
 4056: 
 4057: =cut
 4058: 
 4059: sub languagedescription {
 4060:     my $code=shift;
 4061:     return  ($supported_language{$code}?'* ':'').
 4062:             $language{$code}.
 4063: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4064: }
 4065: 
 4066: =pod
 4067: 
 4068: =item * &plainlanguagedescription
 4069: 
 4070: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4071: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4072: 
 4073: =cut
 4074: 
 4075: sub plainlanguagedescription {
 4076:     my $code=shift;
 4077:     return $language{$code};
 4078: }
 4079: 
 4080: =pod
 4081: 
 4082: =item * &supportedlanguagecode
 4083: 
 4084: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4085: code.
 4086: 
 4087: =cut
 4088: 
 4089: sub supportedlanguagecode {
 4090:     my $code=shift;
 4091:     return $supported_language{$code};
 4092: }
 4093: 
 4094: =pod
 4095: 
 4096: =item * &latexlanguage()
 4097: 
 4098: Given a language key code returns the correspondnig language to use
 4099: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4100: is no supported hyphenation for the language code.
 4101: 
 4102: =cut
 4103: 
 4104: sub latexlanguage {
 4105:     my $code = shift;
 4106:     return $latex_language{$code};
 4107: }
 4108: 
 4109: =pod
 4110: 
 4111: =item * &latexhyphenation()
 4112: 
 4113: Same as above but what's supplied is the language as it might be stored
 4114: in the metadata.
 4115: 
 4116: =cut
 4117: 
 4118: sub latexhyphenation {
 4119:     my $key = shift;
 4120:     return $latex_language_bykey{$key};
 4121: }
 4122: 
 4123: =pod
 4124: 
 4125: =item * &copyrightids() 
 4126: 
 4127: returns list of all copyrights
 4128: 
 4129: =cut
 4130: 
 4131: sub copyrightids {
 4132:     return sort(keys(%cprtag));
 4133: }
 4134: 
 4135: =pod
 4136: 
 4137: =item * &copyrightdescription() 
 4138: 
 4139: returns description of a specified copyright id
 4140: 
 4141: =cut
 4142: 
 4143: sub copyrightdescription {
 4144:     return &mt($cprtag{shift(@_)});
 4145: }
 4146: 
 4147: =pod
 4148: 
 4149: =item * &source_copyrightids() 
 4150: 
 4151: returns list of all source copyrights
 4152: 
 4153: =cut
 4154: 
 4155: sub source_copyrightids {
 4156:     return sort(keys(%scprtag));
 4157: }
 4158: 
 4159: =pod
 4160: 
 4161: =item * &source_copyrightdescription() 
 4162: 
 4163: returns description of a specified source copyright id
 4164: 
 4165: =cut
 4166: 
 4167: sub source_copyrightdescription {
 4168:     return &mt($scprtag{shift(@_)});
 4169: }
 4170: 
 4171: =pod
 4172: 
 4173: =item * &filecategories() 
 4174: 
 4175: returns list of all file categories
 4176: 
 4177: =cut
 4178: 
 4179: sub filecategories {
 4180:     return sort(keys(%category_extensions));
 4181: }
 4182: 
 4183: =pod
 4184: 
 4185: =item * &filecategorytypes() 
 4186: 
 4187: returns list of file types belonging to a given file
 4188: category
 4189: 
 4190: =cut
 4191: 
 4192: sub filecategorytypes {
 4193:     my ($cat) = @_;
 4194:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4195:         return @{$category_extensions{lc($cat)}};
 4196:     } else {
 4197:         return ();
 4198:     }
 4199: }
 4200: 
 4201: =pod
 4202: 
 4203: =item * &fileembstyle() 
 4204: 
 4205: returns embedding style for a specified file type
 4206: 
 4207: =cut
 4208: 
 4209: sub fileembstyle {
 4210:     return $fe{lc(shift(@_))};
 4211: }
 4212: 
 4213: sub filemimetype {
 4214:     return $fm{lc(shift(@_))};
 4215: }
 4216: 
 4217: 
 4218: sub filecategoryselect {
 4219:     my ($name,$value)=@_;
 4220:     return &select_form($value,$name,
 4221:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4222: }
 4223: 
 4224: =pod
 4225: 
 4226: =item * &filedescription() 
 4227: 
 4228: returns description for a specified file type
 4229: 
 4230: =cut
 4231: 
 4232: sub filedescription {
 4233:     my $file_description = $fd{lc(shift())};
 4234:     $file_description =~ s:([\[\]]):~$1:g;
 4235:     return &mt($file_description);
 4236: }
 4237: 
 4238: =pod
 4239: 
 4240: =item * &filedescriptionex() 
 4241: 
 4242: returns description for a specified file type with
 4243: extra formatting
 4244: 
 4245: =cut
 4246: 
 4247: sub filedescriptionex {
 4248:     my $ex=shift;
 4249:     my $file_description = $fd{lc($ex)};
 4250:     $file_description =~ s:([\[\]]):~$1:g;
 4251:     return '.'.$ex.' '.&mt($file_description);
 4252: }
 4253: 
 4254: # End of .tab access
 4255: =pod
 4256: 
 4257: =back
 4258: 
 4259: =cut
 4260: 
 4261: # ------------------------------------------------------------------ File Types
 4262: sub fileextensions {
 4263:     return sort(keys(%fe));
 4264: }
 4265: 
 4266: # ----------------------------------------------------------- Display Languages
 4267: # returns a hash with all desired display languages
 4268: #
 4269: 
 4270: sub display_languages {
 4271:     my %languages=();
 4272:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4273: 	$languages{$lang}=1;
 4274:     }
 4275:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4276:     if ($env{'form.displaylanguage'}) {
 4277: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4278: 	    $languages{$lang}=1;
 4279:         }
 4280:     }
 4281:     return %languages;
 4282: }
 4283: 
 4284: sub languages {
 4285:     my ($possible_langs) = @_;
 4286:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4287:     if (!ref($possible_langs)) {
 4288: 	if( wantarray ) {
 4289: 	    return @preferred_langs;
 4290: 	} else {
 4291: 	    return $preferred_langs[0];
 4292: 	}
 4293:     }
 4294:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4295:     my @preferred_possibilities;
 4296:     foreach my $preferred_lang (@preferred_langs) {
 4297: 	if (exists($possibilities{$preferred_lang})) {
 4298: 	    push(@preferred_possibilities, $preferred_lang);
 4299: 	}
 4300:     }
 4301:     if( wantarray ) {
 4302: 	return @preferred_possibilities;
 4303:     }
 4304:     return $preferred_possibilities[0];
 4305: }
 4306: 
 4307: sub user_lang {
 4308:     my ($touname,$toudom,$fromcid) = @_;
 4309:     my @userlangs;
 4310:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4311:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4312:                     $env{'course.'.$fromcid.'.languages'}));
 4313:     } else {
 4314:         my %langhash = &getlangs($touname,$toudom);
 4315:         if ($langhash{'languages'} ne '') {
 4316:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4317:         } else {
 4318:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4319:             if ($domdefs{'lang_def'} ne '') {
 4320:                 @userlangs = ($domdefs{'lang_def'});
 4321:             }
 4322:         }
 4323:     }
 4324:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4325:     my $user_lh = Apache::localize->get_handle(@languages);
 4326:     return $user_lh;
 4327: }
 4328: 
 4329: 
 4330: ###############################################################
 4331: ##               Student Answer Attempts                     ##
 4332: ###############################################################
 4333: 
 4334: =pod
 4335: 
 4336: =head1 Alternate Problem Views
 4337: 
 4338: =over 4
 4339: 
 4340: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4341:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4342: 
 4343: Return string with previous attempt on problem. Arguments:
 4344: 
 4345: =over 4
 4346: 
 4347: =item * $symb: Problem, including path
 4348: 
 4349: =item * $username: username of the desired student
 4350: 
 4351: =item * $domain: domain of the desired student
 4352: 
 4353: =item * $course: Course ID
 4354: 
 4355: =item * $getattempt: Leave blank for all attempts, otherwise put
 4356:     something
 4357: 
 4358: =item * $regexp: if string matches this regexp, the string will be
 4359:     sent to $gradesub
 4360: 
 4361: =item * $gradesub: routine that processes the string if it matches $regexp
 4362: 
 4363: =item * $usec: section of the desired student
 4364: 
 4365: =item * $identifier: counter for student (multiple students one problem) or 
 4366:     problem (one student; whole sequence).
 4367: 
 4368: =back
 4369: 
 4370: The output string is a table containing all desired attempts, if any.
 4371: 
 4372: =cut
 4373: 
 4374: sub get_previous_attempt {
 4375:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4376:   my $prevattempts='';
 4377:   no strict 'refs';
 4378:   if ($symb) {
 4379:     my (%returnhash)=
 4380:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4381:     if ($returnhash{'version'}) {
 4382:       my %lasthash=();
 4383:       my $version;
 4384:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4385:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4386:             if ($key =~ /\.rawrndseed$/) {
 4387:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4388:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4389:             } else {
 4390:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4391:             }
 4392:         }
 4393:       }
 4394:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4395:       $prevattempts.='<th>'.&mt('History').'</th>';
 4396:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4397:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4398:       foreach my $key (sort(keys(%lasthash))) {
 4399: 	my ($ign,@parts) = split(/\./,$key);
 4400: 	if ($#parts > 0) {
 4401: 	  my $data=$parts[-1];
 4402:           next if ($data eq 'foilorder');
 4403: 	  pop(@parts);
 4404:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4405:           if ($data eq 'type') {
 4406:               unless ($showsurv) {
 4407:                   my $id = join(',',@parts);
 4408:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4409:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4410:                       $lasthidden{$ign.'.'.$id} = 1;
 4411:                   }
 4412:               }
 4413:               if ($identifier ne '') {
 4414:                   my $id = join(',',@parts);
 4415:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4416:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4417:                       $hidestatus{$ign.'.'.$id} = 1;
 4418:                   }
 4419:               }
 4420:           } elsif ($data eq 'regrader') {
 4421:               if (($identifier ne '') && (@parts)) {
 4422:                   my $id = join(',',@parts);
 4423:                   $regraded{$ign.'.'.$id} = 1;
 4424:               }
 4425:           } 
 4426: 	} else {
 4427: 	  if ($#parts == 0) {
 4428: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4429: 	  } else {
 4430: 	    $prevattempts.='<th>'.$ign.'</th>';
 4431: 	  }
 4432: 	}
 4433:       }
 4434:       $prevattempts.=&end_data_table_header_row();
 4435:       if ($getattempt eq '') {
 4436:         my (%solved,%resets,%probstatus);
 4437:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4438:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4439:                 foreach my $id (keys(%regraded)) {
 4440:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4441:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4442:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4443:                         push(@{$resets{$id}},$version);
 4444:                     }
 4445:                 }
 4446:             }
 4447:         }
 4448: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4449:             my (@hidden,@unsolved);
 4450:             if (%typeparts) {
 4451:                 foreach my $id (keys(%typeparts)) {
 4452:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4453:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4454:                         push(@hidden,$id);
 4455:                     } elsif ($identifier ne '') {
 4456:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4457:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4458:                                 ($hidestatus{$id})) {
 4459:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4460:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4461:                                 push(@{$solved{$id}},$version);
 4462:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4463:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4464:                                 my $skip;
 4465:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4466:                                     foreach my $reset (@{$resets{$id}}) {
 4467:                                         if ($reset > $solved{$id}[-1]) {
 4468:                                             $skip=1;
 4469:                                             last;
 4470:                                         }
 4471:                                     }
 4472:                                 }
 4473:                                 unless ($skip) {
 4474:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4475:                                     push(@unsolved,$partslist);
 4476:                                 }
 4477:                             }
 4478:                         }
 4479:                     }
 4480:                 }
 4481:             }
 4482:             $prevattempts.=&start_data_table_row().
 4483:                            '<td>'.&mt('Transaction [_1]',$version);
 4484:             if (@unsolved) {
 4485:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4486:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4487:                                  &mt('Hide').'</label></span>';
 4488:             }
 4489:             $prevattempts .= '</td>';
 4490:             if (@hidden) {
 4491:                 foreach my $key (sort(keys(%lasthash))) {
 4492:                     next if ($key =~ /\.foilorder$/);
 4493:                     my $hide;
 4494:                     foreach my $id (@hidden) {
 4495:                         if ($key =~ /^\Q$id\E/) {
 4496:                             $hide = 1;
 4497:                             last;
 4498:                         }
 4499:                     }
 4500:                     if ($hide) {
 4501:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4502:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4503:                             my $value = &format_previous_attempt_value($key,
 4504:                                              $returnhash{$version.':'.$key});
 4505:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4506:                         } else {
 4507:                             $prevattempts.='<td>&nbsp;</td>';
 4508:                         }
 4509:                     } else {
 4510:                         if ($key =~ /\./) {
 4511:                             my $value = $returnhash{$version.':'.$key};
 4512:                             if ($key =~ /\.rndseed$/) {
 4513:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4514:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4515:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4516:                                 }
 4517:                             }
 4518:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4519:                                            '&nbsp;</td>';
 4520:                         } else {
 4521:                             $prevattempts.='<td>&nbsp;</td>';
 4522:                         }
 4523:                     }
 4524:                 }
 4525:             } else {
 4526: 	        foreach my $key (sort(keys(%lasthash))) {
 4527:                     next if ($key =~ /\.foilorder$/);
 4528:                     my $value = $returnhash{$version.':'.$key};
 4529:                     if ($key =~ /\.rndseed$/) {
 4530:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4531:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4532:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4533:                         }
 4534:                     }
 4535:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4536:                                    '&nbsp;</td>';
 4537: 	        }
 4538:             }
 4539: 	    $prevattempts.=&end_data_table_row();
 4540: 	 }
 4541:       }
 4542:       my @currhidden = keys(%lasthidden);
 4543:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4544:       foreach my $key (sort(keys(%lasthash))) {
 4545:           next if ($key =~ /\.foilorder$/);
 4546:           if (%typeparts) {
 4547:               my $hidden;
 4548:               foreach my $id (@currhidden) {
 4549:                   if ($key =~ /^\Q$id\E/) {
 4550:                       $hidden = 1;
 4551:                       last;
 4552:                   }
 4553:               }
 4554:               if ($hidden) {
 4555:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4556:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4557:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4558:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4559:                           $value = &$gradesub($value);
 4560:                       }
 4561:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4562:                   } else {
 4563:                       $prevattempts.='<td>&nbsp;</td>';
 4564:                   }
 4565:               } else {
 4566:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4567:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4568:                       $value = &$gradesub($value);
 4569:                   }
 4570:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4571:               }
 4572:           } else {
 4573: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4574: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4575:                   $value = &$gradesub($value);
 4576:               }
 4577: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4578:           }
 4579:       }
 4580:       $prevattempts.= &end_data_table_row().&end_data_table();
 4581:     } else {
 4582:       $prevattempts=
 4583: 	  &start_data_table().&start_data_table_row().
 4584: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4585: 	  &end_data_table_row().&end_data_table();
 4586:     }
 4587:   } else {
 4588:     $prevattempts=
 4589: 	  &start_data_table().&start_data_table_row().
 4590: 	  '<td>'.&mt('No data.').'</td>'.
 4591: 	  &end_data_table_row().&end_data_table();
 4592:   }
 4593: }
 4594: 
 4595: sub format_previous_attempt_value {
 4596:     my ($key,$value) = @_;
 4597:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4598:         $value = &Apache::lonlocal::locallocaltime($value);
 4599:     } elsif (ref($value) eq 'ARRAY') {
 4600:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4601:     } elsif ($key =~ /answerstring$/) {
 4602:         my %answers = &Apache::lonnet::str2hash($value);
 4603:         my @answer = %answers;
 4604:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4605:         my @anskeys = sort(keys(%answers));
 4606:         if (@anskeys == 1) {
 4607:             my $answer = $answers{$anskeys[0]};
 4608:             if ($answer =~ m{\0}) {
 4609:                 $answer =~ s{\0}{,}g;
 4610:             }
 4611:             my $tag_internal_answer_name = 'INTERNAL';
 4612:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4613:                 $value = $answer; 
 4614:             } else {
 4615:                 $value = $anskeys[0].'='.$answer;
 4616:             }
 4617:         } else {
 4618:             foreach my $ans (@anskeys) {
 4619:                 my $answer = $answers{$ans};
 4620:                 if ($answer =~ m{\0}) {
 4621:                     $answer =~ s{\0}{,}g;
 4622:                 }
 4623:                 $value .=  $ans.'='.$answer.'<br />';;
 4624:             } 
 4625:         }
 4626:     } else {
 4627:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4628:     }
 4629:     return $value;
 4630: }
 4631: 
 4632: 
 4633: sub relative_to_absolute {
 4634:     my ($url,$output)=@_;
 4635:     my $parser=HTML::TokeParser->new(\$output);
 4636:     my $token;
 4637:     my $thisdir=$url;
 4638:     my @rlinks=();
 4639:     while ($token=$parser->get_token) {
 4640: 	if ($token->[0] eq 'S') {
 4641: 	    if ($token->[1] eq 'a') {
 4642: 		if ($token->[2]->{'href'}) {
 4643: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4644: 		}
 4645: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4646: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4647: 	    } elsif ($token->[1] eq 'base') {
 4648: 		$thisdir=$token->[2]->{'href'};
 4649: 	    }
 4650: 	}
 4651:     }
 4652:     $thisdir=~s-/[^/]*$--;
 4653:     foreach my $link (@rlinks) {
 4654: 	unless (($link=~/^https?\:\/\//i) ||
 4655: 		($link=~/^\//) ||
 4656: 		($link=~/^javascript:/i) ||
 4657: 		($link=~/^mailto:/i) ||
 4658: 		($link=~/^\#/)) {
 4659: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4660: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4661: 	}
 4662:     }
 4663: # -------------------------------------------------- Deal with Applet codebases
 4664:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4665:     return $output;
 4666: }
 4667: 
 4668: =pod
 4669: 
 4670: =item * &get_student_view()
 4671: 
 4672: show a snapshot of what student was looking at
 4673: 
 4674: =cut
 4675: 
 4676: sub get_student_view {
 4677:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4678:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4679:   my (%form);
 4680:   my @elements=('symb','courseid','domain','username');
 4681:   foreach my $element (@elements) {
 4682:       $form{'grade_'.$element}=eval '$'.$element #'
 4683:   }
 4684:   if (defined($moreenv)) {
 4685:       %form=(%form,%{$moreenv});
 4686:   }
 4687:   if (defined($target)) { $form{'grade_target'} = $target; }
 4688:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4689:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4690:   $userview=~s/\<body[^\>]*\>//gi;
 4691:   $userview=~s/\<\/body\>//gi;
 4692:   $userview=~s/\<html\>//gi;
 4693:   $userview=~s/\<\/html\>//gi;
 4694:   $userview=~s/\<head\>//gi;
 4695:   $userview=~s/\<\/head\>//gi;
 4696:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4697:   $userview=&relative_to_absolute($feedurl,$userview);
 4698:   if (wantarray) {
 4699:      return ($userview,$response);
 4700:   } else {
 4701:      return $userview;
 4702:   }
 4703: }
 4704: 
 4705: sub get_student_view_with_retries {
 4706:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4707: 
 4708:     my $ok = 0;                 # True if we got a good response.
 4709:     my $content;
 4710:     my $response;
 4711: 
 4712:     # Try to get the student_view done. within the retries count:
 4713:     
 4714:     do {
 4715:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4716:          $ok      = $response->is_success;
 4717:          if (!$ok) {
 4718:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4719:          }
 4720:          $retries--;
 4721:     } while (!$ok && ($retries > 0));
 4722:     
 4723:     if (!$ok) {
 4724:        $content = '';          # On error return an empty content.
 4725:     }
 4726:     if (wantarray) {
 4727:        return ($content, $response);
 4728:     } else {
 4729:        return $content;
 4730:     }
 4731: }
 4732: 
 4733: =pod
 4734: 
 4735: =item * &get_student_answers() 
 4736: 
 4737: show a snapshot of how student was answering problem
 4738: 
 4739: =cut
 4740: 
 4741: sub get_student_answers {
 4742:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4743:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4744:   my (%moreenv);
 4745:   my @elements=('symb','courseid','domain','username');
 4746:   foreach my $element (@elements) {
 4747:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4748:   }
 4749:   $moreenv{'grade_target'}='answer';
 4750:   %moreenv=(%form,%moreenv);
 4751:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4752:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4753:   return $userview;
 4754: }
 4755: 
 4756: =pod
 4757: 
 4758: =item * &submlink()
 4759: 
 4760: Inputs: $text $uname $udom $symb $target
 4761: 
 4762: Returns: A link to grades.pm such as to see the SUBM view of a student
 4763: 
 4764: =cut
 4765: 
 4766: ###############################################
 4767: sub submlink {
 4768:     my ($text,$uname,$udom,$symb,$target)=@_;
 4769:     if (!($uname && $udom)) {
 4770: 	(my $cursymb, my $courseid,$udom,$uname)=
 4771: 	    &Apache::lonnet::whichuser($symb);
 4772: 	if (!$symb) { $symb=$cursymb; }
 4773:     }
 4774:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4775:     $symb=&escape($symb);
 4776:     if ($target) { $target=" target=\"$target\""; }
 4777:     return
 4778:         '<a href="/adm/grades?command=submission'.
 4779:         '&amp;symb='.$symb.
 4780:         '&amp;student='.$uname.
 4781:         '&amp;userdom='.$udom.'"'.
 4782:         $target.'>'.$text.'</a>';
 4783: }
 4784: ##############################################
 4785: 
 4786: =pod
 4787: 
 4788: =item * &pgrdlink()
 4789: 
 4790: Inputs: $text $uname $udom $symb $target
 4791: 
 4792: Returns: A link to grades.pm such as to see the PGRD view of a student
 4793: 
 4794: =cut
 4795: 
 4796: ###############################################
 4797: sub pgrdlink {
 4798:     my $link=&submlink(@_);
 4799:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4800:     return $link;
 4801: }
 4802: ##############################################
 4803: 
 4804: =pod
 4805: 
 4806: =item * &pprmlink()
 4807: 
 4808: Inputs: $text $uname $udom $symb $target
 4809: 
 4810: Returns: A link to parmset.pm such as to see the PPRM view of a
 4811: student and a specific resource
 4812: 
 4813: =cut
 4814: 
 4815: ###############################################
 4816: sub pprmlink {
 4817:     my ($text,$uname,$udom,$symb,$target)=@_;
 4818:     if (!($uname && $udom)) {
 4819: 	(my $cursymb, my $courseid,$udom,$uname)=
 4820: 	    &Apache::lonnet::whichuser($symb);
 4821: 	if (!$symb) { $symb=$cursymb; }
 4822:     }
 4823:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4824:     $symb=&escape($symb);
 4825:     if ($target) { $target="target=\"$target\""; }
 4826:     return '<a href="/adm/parmset?command=set&amp;'.
 4827: 	'symb='.$symb.'&amp;uname='.$uname.
 4828: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4829: }
 4830: ##############################################
 4831: 
 4832: =pod
 4833: 
 4834: =back
 4835: 
 4836: =cut
 4837: 
 4838: ###############################################
 4839: 
 4840: 
 4841: sub timehash {
 4842:     my ($thistime) = @_;
 4843:     my $timezone = &Apache::lonlocal::gettimezone();
 4844:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4845:                      ->set_time_zone($timezone);
 4846:     my $wday = $dt->day_of_week();
 4847:     if ($wday == 7) { $wday = 0; }
 4848:     return ( 'second' => $dt->second(),
 4849:              'minute' => $dt->minute(),
 4850:              'hour'   => $dt->hour(),
 4851:              'day'     => $dt->day_of_month(),
 4852:              'month'   => $dt->month(),
 4853:              'year'    => $dt->year(),
 4854:              'weekday' => $wday,
 4855:              'dayyear' => $dt->day_of_year(),
 4856:              'dlsav'   => $dt->is_dst() );
 4857: }
 4858: 
 4859: sub utc_string {
 4860:     my ($date)=@_;
 4861:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4862: }
 4863: 
 4864: sub maketime {
 4865:     my %th=@_;
 4866:     my ($epoch_time,$timezone,$dt);
 4867:     $timezone = &Apache::lonlocal::gettimezone();
 4868:     eval {
 4869:         $dt = DateTime->new( year   => $th{'year'},
 4870:                              month  => $th{'month'},
 4871:                              day    => $th{'day'},
 4872:                              hour   => $th{'hour'},
 4873:                              minute => $th{'minute'},
 4874:                              second => $th{'second'},
 4875:                              time_zone => $timezone,
 4876:                          );
 4877:     };
 4878:     if (!$@) {
 4879:         $epoch_time = $dt->epoch;
 4880:         if ($epoch_time) {
 4881:             return $epoch_time;
 4882:         }
 4883:     }
 4884:     return POSIX::mktime(
 4885:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4886:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4887: }
 4888: 
 4889: #########################################
 4890: 
 4891: sub findallcourses {
 4892:     my ($roles,$uname,$udom) = @_;
 4893:     my %roles;
 4894:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4895:     my %courses;
 4896:     my $now=time;
 4897:     if (!defined($uname)) {
 4898:         $uname = $env{'user.name'};
 4899:     }
 4900:     if (!defined($udom)) {
 4901:         $udom = $env{'user.domain'};
 4902:     }
 4903:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4904:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4905:         if (!%roles) {
 4906:             %roles = (
 4907:                        cc => 1,
 4908:                        co => 1,
 4909:                        in => 1,
 4910:                        ep => 1,
 4911:                        ta => 1,
 4912:                        cr => 1,
 4913:                        st => 1,
 4914:              );
 4915:         }
 4916:         foreach my $entry (keys(%roleshash)) {
 4917:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4918:             if ($trole =~ /^cr/) { 
 4919:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4920:             } else {
 4921:                 next if (!exists($roles{$trole}));
 4922:             }
 4923:             if ($tend) {
 4924:                 next if ($tend < $now);
 4925:             }
 4926:             if ($tstart) {
 4927:                 next if ($tstart > $now);
 4928:             }
 4929:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4930:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4931:             my $value = $trole.'/'.$cdom.'/';
 4932:             if ($secpart eq '') {
 4933:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4934:                 $sec = 'none';
 4935:                 $value .= $cnum.'/';
 4936:             } else {
 4937:                 $cnum = $cnumpart;
 4938:                 ($sec,$role) = split(/_/,$secpart);
 4939:                 $value .= $cnum.'/'.$sec;
 4940:             }
 4941:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4942:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4943:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4944:                 }
 4945:             } else {
 4946:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4947:             }
 4948:         }
 4949:     } else {
 4950:         foreach my $key (keys(%env)) {
 4951: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4952:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4953: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4954: 	        next if ($role eq 'ca' || $role eq 'aa');
 4955: 	        next if (%roles && !exists($roles{$role}));
 4956: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4957:                 my $active=1;
 4958:                 if ($starttime) {
 4959: 		    if ($now<$starttime) { $active=0; }
 4960:                 }
 4961:                 if ($endtime) {
 4962:                     if ($now>$endtime) { $active=0; }
 4963:                 }
 4964:                 if ($active) {
 4965:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4966:                     if ($sec eq '') {
 4967:                         $sec = 'none';
 4968:                     } else {
 4969:                         $value .= $sec;
 4970:                     }
 4971:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4972:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4973:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4974:                         }
 4975:                     } else {
 4976:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4977:                     }
 4978:                 }
 4979:             }
 4980:         }
 4981:     }
 4982:     return %courses;
 4983: }
 4984: 
 4985: ###############################################
 4986: 
 4987: sub blockcheck {
 4988:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4989: 
 4990:     if (defined($udom) && defined($uname)) {
 4991:         # If uname and udom are for a course, check for blocks in the course.
 4992:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4993:             my ($startblock,$endblock,$triggerblock) =
 4994:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4995:             return ($startblock,$endblock,$triggerblock);
 4996:         }
 4997:     } else {
 4998:         $udom = $env{'user.domain'};
 4999:         $uname = $env{'user.name'};
 5000:     }
 5001: 
 5002:     my $startblock = 0;
 5003:     my $endblock = 0;
 5004:     my $triggerblock = '';
 5005:     my %live_courses = &findallcourses(undef,$uname,$udom);
 5006: 
 5007:     # If uname is for a user, and activity is course-specific, i.e.,
 5008:     # boards, chat or groups, check for blocking in current course only.
 5009: 
 5010:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5011:          $activity eq 'groups' || $activity eq 'printout' ||
 5012:          $activity eq 'reinit' || $activity eq 'alert') &&
 5013:         ($env{'request.course.id'})) {
 5014:         foreach my $key (keys(%live_courses)) {
 5015:             if ($key ne $env{'request.course.id'}) {
 5016:                 delete($live_courses{$key});
 5017:             }
 5018:         }
 5019:     }
 5020: 
 5021:     my $otheruser = 0;
 5022:     my %own_courses;
 5023:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5024:         # Resource belongs to user other than current user.
 5025:         $otheruser = 1;
 5026:         # Gather courses for current user
 5027:         %own_courses = 
 5028:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5029:     }
 5030: 
 5031:     # Gather active course roles - course coordinator, instructor, 
 5032:     # exam proctor, ta, student, or custom role.
 5033: 
 5034:     foreach my $course (keys(%live_courses)) {
 5035:         my ($cdom,$cnum);
 5036:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5037:             $cdom = $env{'course.'.$course.'.domain'};
 5038:             $cnum = $env{'course.'.$course.'.num'};
 5039:         } else {
 5040:             ($cdom,$cnum) = split(/_/,$course); 
 5041:         }
 5042:         my $no_ownblock = 0;
 5043:         my $no_userblock = 0;
 5044:         if ($otheruser && $activity ne 'com') {
 5045:             # Check if current user has 'evb' priv for this
 5046:             if (defined($own_courses{$course})) {
 5047:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5048:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5049:                     if ($sec ne 'none') {
 5050:                         $checkrole .= '/'.$sec;
 5051:                     }
 5052:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5053:                         $no_ownblock = 1;
 5054:                         last;
 5055:                     }
 5056:                 }
 5057:             }
 5058:             # if they have 'evb' priv and are currently not playing student
 5059:             next if (($no_ownblock) &&
 5060:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5061:         }
 5062:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5063:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5064:             if ($sec ne 'none') {
 5065:                 $checkrole .= '/'.$sec;
 5066:             }
 5067:             if ($otheruser) {
 5068:                 # Resource belongs to user other than current user.
 5069:                 # Assemble privs for that user, and check for 'evb' priv.
 5070:                 my (%allroles,%userroles);
 5071:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5072:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5073:                         my ($trole,$tdom,$tnum,$tsec);
 5074:                         if ($entry =~ /^cr/) {
 5075:                             ($trole,$tdom,$tnum,$tsec) = 
 5076:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5077:                         } else {
 5078:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5079:                         }
 5080:                         my ($spec,$area,$trest);
 5081:                         $area = '/'.$tdom.'/'.$tnum;
 5082:                         $trest = $tnum;
 5083:                         if ($tsec ne '') {
 5084:                             $area .= '/'.$tsec;
 5085:                             $trest .= '/'.$tsec;
 5086:                         }
 5087:                         $spec = $trole.'.'.$area;
 5088:                         if ($trole =~ /^cr/) {
 5089:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5090:                                                               $tdom,$spec,$trest,$area);
 5091:                         } else {
 5092:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5093:                                                                 $tdom,$spec,$trest,$area);
 5094:                         }
 5095:                     }
 5096:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5097:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5098:                         if ($1) {
 5099:                             $no_userblock = 1;
 5100:                             last;
 5101:                         }
 5102:                     }
 5103:                 }
 5104:             } else {
 5105:                 # Resource belongs to current user
 5106:                 # Check for 'evb' priv via lonnet::allowed().
 5107:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5108:                     $no_ownblock = 1;
 5109:                     last;
 5110:                 }
 5111:             }
 5112:         }
 5113:         # if they have the evb priv and are currently not playing student
 5114:         next if (($no_ownblock) &&
 5115:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5116:         next if ($no_userblock);
 5117: 
 5118:         # Retrieve blocking times and identity of locker for course
 5119:         # of specified user, unless user has 'evb' privilege.
 5120: 
 5121:         my ($start,$end,$trigger) = 
 5122:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 5123:         if (($start != 0) && 
 5124:             (($startblock == 0) || ($startblock > $start))) {
 5125:             $startblock = $start;
 5126:             if ($trigger ne '') {
 5127:                 $triggerblock = $trigger;
 5128:             }
 5129:         }
 5130:         if (($end != 0)  &&
 5131:             (($endblock == 0) || ($endblock < $end))) {
 5132:             $endblock = $end;
 5133:             if ($trigger ne '') {
 5134:                 $triggerblock = $trigger;
 5135:             }
 5136:         }
 5137:     }
 5138:     return ($startblock,$endblock,$triggerblock);
 5139: }
 5140: 
 5141: sub get_blocks {
 5142:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 5143:     my $startblock = 0;
 5144:     my $endblock = 0;
 5145:     my $triggerblock = '';
 5146:     my $course = $cdom.'_'.$cnum;
 5147:     $setters->{$course} = {};
 5148:     $setters->{$course}{'staff'} = [];
 5149:     $setters->{$course}{'times'} = [];
 5150:     $setters->{$course}{'triggers'} = [];
 5151:     my (@blockers,%triggered);
 5152:     my $now = time;
 5153:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5154:     if ($activity eq 'docs') {
 5155:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 5156:         foreach my $block (@blockers) {
 5157:             if ($block =~ /^firstaccess____(.+)$/) {
 5158:                 my $item = $1;
 5159:                 my $type = 'map';
 5160:                 my $timersymb = $item;
 5161:                 if ($item eq 'course') {
 5162:                     $type = 'course';
 5163:                 } elsif ($item =~ /___\d+___/) {
 5164:                     $type = 'resource';
 5165:                 } else {
 5166:                     $timersymb = &Apache::lonnet::symbread($item);
 5167:                 }
 5168:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5169:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5170:                 $triggered{$block} = {
 5171:                                        start => $start,
 5172:                                        end   => $end,
 5173:                                        type  => $type,
 5174:                                      };
 5175:             }
 5176:         }
 5177:     } else {
 5178:         foreach my $block (keys(%commblocks)) {
 5179:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5180:                 my ($start,$end) = ($1,$2);
 5181:                 if ($start <= time && $end >= time) {
 5182:                     if (ref($commblocks{$block}) eq 'HASH') {
 5183:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5184:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5185:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5186:                                     push(@blockers,$block);
 5187:                                 }
 5188:                             }
 5189:                         }
 5190:                     }
 5191:                 }
 5192:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5193:                 my $item = $1;
 5194:                 my $timersymb = $item; 
 5195:                 my $type = 'map';
 5196:                 if ($item eq 'course') {
 5197:                     $type = 'course';
 5198:                 } elsif ($item =~ /___\d+___/) {
 5199:                     $type = 'resource';
 5200:                 } else {
 5201:                     $timersymb = &Apache::lonnet::symbread($item);
 5202:                 }
 5203:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5204:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5205:                 if ($start && $end) {
 5206:                     if (($start <= time) && ($end >= time)) {
 5207:                         if (ref($commblocks{$block}) eq 'HASH') {
 5208:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5209:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5210:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5211:                                         push(@blockers,$block);
 5212:                                         $triggered{$block} = {
 5213:                                                                start => $start,
 5214:                                                                end   => $end,
 5215:                                                                type  => $type,
 5216:                                                              };
 5217:                                     }
 5218:                                 }
 5219:                             }
 5220:                         }
 5221:                     }
 5222:                 }
 5223:             }
 5224:         }
 5225:     }
 5226:     foreach my $blocker (@blockers) {
 5227:         my ($staff_name,$staff_dom,$title,$blocks) =
 5228:             &parse_block_record($commblocks{$blocker});
 5229:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5230:         my ($start,$end,$triggertype);
 5231:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5232:             ($start,$end) = ($1,$2);
 5233:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5234:             $start = $triggered{$blocker}{'start'};
 5235:             $end = $triggered{$blocker}{'end'};
 5236:             $triggertype = $triggered{$blocker}{'type'};
 5237:         }
 5238:         if ($start) {
 5239:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5240:             if ($triggertype) {
 5241:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5242:             } else {
 5243:                 push(@{$$setters{$course}{'triggers'}},0);
 5244:             }
 5245:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5246:                 $startblock = $start;
 5247:                 if ($triggertype) {
 5248:                     $triggerblock = $blocker;
 5249:                 }
 5250:             }
 5251:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5252:                $endblock = $end;
 5253:                if ($triggertype) {
 5254:                    $triggerblock = $blocker;
 5255:                }
 5256:             }
 5257:         }
 5258:     }
 5259:     return ($startblock,$endblock,$triggerblock);
 5260: }
 5261: 
 5262: sub parse_block_record {
 5263:     my ($record) = @_;
 5264:     my ($setuname,$setudom,$title,$blocks);
 5265:     if (ref($record) eq 'HASH') {
 5266:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5267:         $title = &unescape($record->{'event'});
 5268:         $blocks = $record->{'blocks'};
 5269:     } else {
 5270:         my @data = split(/:/,$record,3);
 5271:         if (scalar(@data) eq 2) {
 5272:             $title = $data[1];
 5273:             ($setuname,$setudom) = split(/@/,$data[0]);
 5274:         } else {
 5275:             ($setuname,$setudom,$title) = @data;
 5276:         }
 5277:         $blocks = { 'com' => 'on' };
 5278:     }
 5279:     return ($setuname,$setudom,$title,$blocks);
 5280: }
 5281: 
 5282: sub blocking_status {
 5283:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 5284:     my %setters;
 5285: 
 5286: # check for active blocking
 5287:     my ($startblock,$endblock,$triggerblock) = 
 5288:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 5289:     my $blocked = 0;
 5290:     if ($startblock && $endblock) {
 5291:         $blocked = 1;
 5292:     }
 5293: 
 5294: # caller just wants to know whether a block is active
 5295:     if (!wantarray) { return $blocked; }
 5296: 
 5297: # build a link to a popup window containing the details
 5298:     my $querystring  = "?activity=$activity";
 5299: # $uname and $udom decide whose portfolio the user is trying to look at
 5300:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 5301:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5302:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5303:     } elsif ($activity eq 'docs') {
 5304:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 5305:     }
 5306: 
 5307:     my $output .= <<'END_MYBLOCK';
 5308: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5309:     var options = "width=" + w + ",height=" + h + ",";
 5310:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5311:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5312:     var newWin = window.open(url, wdwName, options);
 5313:     newWin.focus();
 5314: }
 5315: END_MYBLOCK
 5316: 
 5317:     $output = Apache::lonhtmlcommon::scripttag($output);
 5318:   
 5319:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5320:     my $text = &mt('Communication Blocked');
 5321:     my $class = 'LC_comblock';
 5322:     if ($activity eq 'docs') {
 5323:         $text = &mt('Content Access Blocked');
 5324:         $class = '';
 5325:     } elsif ($activity eq 'printout') {
 5326:         $text = &mt('Printing Blocked');
 5327:     } elsif ($activity eq 'passwd') {
 5328:         $text = &mt('Password Changing Blocked');
 5329:     } elsif ($activity eq 'alert') {
 5330:         $text = &mt('Checking Critical Messages Blocked');
 5331:     } elsif ($activity eq 'reinit') {
 5332:         $text = &mt('Checking Course Update Blocked');
 5333:     }
 5334:     $output .= <<"END_BLOCK";
 5335: <div class='$class'>
 5336:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5337:   title='$text'>
 5338:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5339:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5340:   title='$text'>$text</a>
 5341: </div>
 5342: 
 5343: END_BLOCK
 5344: 
 5345:     return ($blocked, $output);
 5346: }
 5347: 
 5348: ###############################################
 5349: 
 5350: sub check_ip_acc {
 5351:     my ($acc,$clientip)=@_;
 5352:     &Apache::lonxml::debug("acc is $acc");
 5353:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5354:         return 1;
 5355:     }
 5356:     my $allowed;
 5357:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 5358: 
 5359:     my $name;
 5360:     my %access = (
 5361:                      allowfrom => 1,
 5362:                      denyfrom  => 0,
 5363:                  );
 5364:     my @allows;
 5365:     my @denies;
 5366:     foreach my $item (split(',',$acc)) {
 5367:         $item =~ s/^\s*//;
 5368:         $item =~ s/\s*$//;
 5369:         my $pattern;
 5370:         if ($item =~ /^\!(.+)$/) {
 5371:             push(@denies,$1);
 5372:         } else {
 5373:             push(@allows,$item);
 5374:         }
 5375:    }
 5376:    my $numdenies = scalar(@denies);
 5377:    my $numallows = scalar(@allows);
 5378:    my $count = 0;
 5379:    foreach my $pattern (@denies,@allows) {
 5380:         $count ++; 
 5381:         my $acctype = 'allowfrom';
 5382:         if ($count <= $numdenies) {
 5383:             $acctype = 'denyfrom';
 5384:         }
 5385:         if ($pattern =~ /\*$/) {
 5386:             #35.8.*
 5387:             $pattern=~s/\*//;
 5388:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5389:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5390:             #35.8.3.[34-56]
 5391:             my $low=$2;
 5392:             my $high=$3;
 5393:             $pattern=$1;
 5394:             if ($ip =~ /^\Q$pattern\E/) {
 5395:                 my $last=(split(/\./,$ip))[3];
 5396:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5397:             }
 5398:         } elsif ($pattern =~ /^\*/) {
 5399:             #*.msu.edu
 5400:             $pattern=~s/\*//;
 5401:             if (!defined($name)) {
 5402:                 use Socket;
 5403:                 my $netaddr=inet_aton($ip);
 5404:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5405:             }
 5406:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5407:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5408:             #127.0.0.1
 5409:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5410:         } else {
 5411:             #some.name.com
 5412:             if (!defined($name)) {
 5413:                 use Socket;
 5414:                 my $netaddr=inet_aton($ip);
 5415:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5416:             }
 5417:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5418:         }
 5419:         if ($allowed =~ /^(0|1)$/) { last; }
 5420:     }
 5421:     if ($allowed eq '') {
 5422:         if ($numdenies && !$numallows) {
 5423:             $allowed = 1;
 5424:         } else {
 5425:             $allowed = 0;
 5426:         }
 5427:     }
 5428:     return $allowed;
 5429: }
 5430: 
 5431: ###############################################
 5432: 
 5433: =pod
 5434: 
 5435: =head1 Domain Template Functions
 5436: 
 5437: =over 4
 5438: 
 5439: =item * &determinedomain()
 5440: 
 5441: Inputs: $domain (usually will be undef)
 5442: 
 5443: Returns: Determines which domain should be used for designs
 5444: 
 5445: =cut
 5446: 
 5447: ###############################################
 5448: sub determinedomain {
 5449:     my $domain=shift;
 5450:     if (! $domain) {
 5451:         # Determine domain if we have not been given one
 5452:         $domain = &Apache::lonnet::default_login_domain();
 5453:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5454:         if ($env{'request.role.domain'}) { 
 5455:             $domain=$env{'request.role.domain'}; 
 5456:         }
 5457:     }
 5458:     return $domain;
 5459: }
 5460: ###############################################
 5461: 
 5462: sub devalidate_domconfig_cache {
 5463:     my ($udom)=@_;
 5464:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5465: }
 5466: 
 5467: # ---------------------- Get domain configuration for a domain
 5468: sub get_domainconf {
 5469:     my ($udom) = @_;
 5470:     my $cachetime=1800;
 5471:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5472:     if (defined($cached)) { return %{$result}; }
 5473: 
 5474:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5475: 					     ['login','rolecolors','autoenroll'],$udom);
 5476:     my (%designhash,%legacy);
 5477:     if (keys(%domconfig) > 0) {
 5478:         if (ref($domconfig{'login'}) eq 'HASH') {
 5479:             if (keys(%{$domconfig{'login'}})) {
 5480:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5481:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5482:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5483:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5484:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5485:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5486:                                         if ($key eq 'loginvia') {
 5487:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5488:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5489:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5490:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5491: 
 5492:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5493:                                                 } else {
 5494:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5495:                                                 }
 5496:                                             }
 5497:                                         } elsif ($key eq 'headtag') {
 5498:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5499:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5500:                                             }
 5501:                                         }
 5502:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5503:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5504:                                         }
 5505:                                     }
 5506:                                 }
 5507:                             }
 5508:                         } else {
 5509:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5510:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5511:                                     $domconfig{'login'}{$key}{$img};
 5512:                             }
 5513:                         }
 5514:                     } else {
 5515:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5516:                     }
 5517:                 }
 5518:             } else {
 5519:                 $legacy{'login'} = 1;
 5520:             }
 5521:         } else {
 5522:             $legacy{'login'} = 1;
 5523:         }
 5524:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5525:             if (keys(%{$domconfig{'rolecolors'}})) {
 5526:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5527:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5528:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5529:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5530:                         }
 5531:                     }
 5532:                 }
 5533:             } else {
 5534:                 $legacy{'rolecolors'} = 1;
 5535:             }
 5536:         } else {
 5537:             $legacy{'rolecolors'} = 1;
 5538:         }
 5539:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5540:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5541:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5542:             }
 5543:         }
 5544:         if (keys(%legacy) > 0) {
 5545:             my %legacyhash = &get_legacy_domconf($udom);
 5546:             foreach my $item (keys(%legacyhash)) {
 5547:                 if ($item =~ /^\Q$udom\E\.login/) {
 5548:                     if ($legacy{'login'}) { 
 5549:                         $designhash{$item} = $legacyhash{$item};
 5550:                     }
 5551:                 } else {
 5552:                     if ($legacy{'rolecolors'}) {
 5553:                         $designhash{$item} = $legacyhash{$item};
 5554:                     }
 5555:                 }
 5556:             }
 5557:         }
 5558:     } else {
 5559:         %designhash = &get_legacy_domconf($udom); 
 5560:     }
 5561:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5562: 				  $cachetime);
 5563:     return %designhash;
 5564: }
 5565: 
 5566: sub get_legacy_domconf {
 5567:     my ($udom) = @_;
 5568:     my %legacyhash;
 5569:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5570:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5571:     if (-e $designfile) {
 5572:         if ( open (my $fh,"<$designfile") ) {
 5573:             while (my $line = <$fh>) {
 5574:                 next if ($line =~ /^\#/);
 5575:                 chomp($line);
 5576:                 my ($key,$val)=(split(/\=/,$line));
 5577:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5578:             }
 5579:             close($fh);
 5580:         }
 5581:     }
 5582:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5583:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5584:     }
 5585:     return %legacyhash;
 5586: }
 5587: 
 5588: =pod
 5589: 
 5590: =item * &domainlogo()
 5591: 
 5592: Inputs: $domain (usually will be undef)
 5593: 
 5594: Returns: A link to a domain logo, if the domain logo exists.
 5595: If the domain logo does not exist, a description of the domain.
 5596: 
 5597: =cut
 5598: 
 5599: ###############################################
 5600: sub domainlogo {
 5601:     my $domain = &determinedomain(shift);
 5602:     my %designhash = &get_domainconf($domain);    
 5603:     # See if there is a logo
 5604:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5605:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5606:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5607: 	    if ($imgsrc =~ m{^/res/}) {
 5608: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5609: 		&Apache::lonnet::repcopy($local_name);
 5610: 	    }
 5611: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5612:         } 
 5613:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5614:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5615:         return &Apache::lonnet::domain($domain,'description');
 5616:     } else {
 5617:         return '';
 5618:     }
 5619: }
 5620: ##############################################
 5621: 
 5622: =pod
 5623: 
 5624: =item * &designparm()
 5625: 
 5626: Inputs: $which parameter; $domain (usually will be undef)
 5627: 
 5628: Returns: value of designparamter $which
 5629: 
 5630: =cut
 5631: 
 5632: 
 5633: ##############################################
 5634: sub designparm {
 5635:     my ($which,$domain)=@_;
 5636:     if (exists($env{'environment.color.'.$which})) {
 5637:         return $env{'environment.color.'.$which};
 5638:     }
 5639:     $domain=&determinedomain($domain);
 5640:     my %domdesign;
 5641:     unless ($domain eq 'public') {
 5642:         %domdesign = &get_domainconf($domain);
 5643:     }
 5644:     my $output;
 5645:     if ($domdesign{$domain.'.'.$which} ne '') {
 5646:         $output = $domdesign{$domain.'.'.$which};
 5647:     } else {
 5648:         $output = $defaultdesign{$which};
 5649:     }
 5650:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5651:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5652:         if ($output =~ m{^/(adm|res)/}) {
 5653:             if ($output =~ m{^/res/}) {
 5654:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5655:                 &Apache::lonnet::repcopy($local_name);
 5656:             }
 5657:             $output = &lonhttpdurl($output);
 5658:         }
 5659:     }
 5660:     return $output;
 5661: }
 5662: 
 5663: ##############################################
 5664: =pod
 5665: 
 5666: =item * &authorspace()
 5667: 
 5668: Inputs: $url (usually will be undef).
 5669: 
 5670: Returns: Path to Authoring Space containing the resource or 
 5671:          directory being viewed (or for which action is being taken). 
 5672:          If $url is provided, and begins /priv/<domain>/<uname>
 5673:          the path will be that portion of the $context argument.
 5674:          Otherwise the path will be for the author space of the current
 5675:          user when the current role is author, or for that of the 
 5676:          co-author/assistant co-author space when the current role 
 5677:          is co-author or assistant co-author.
 5678: 
 5679: =cut
 5680: 
 5681: sub authorspace {
 5682:     my ($url) = @_;
 5683:     if ($url ne '') {
 5684:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5685:            return $1;
 5686:         }
 5687:     }
 5688:     my $caname = '';
 5689:     my $cadom = '';
 5690:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5691:         ($cadom,$caname) =
 5692:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5693:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5694:         $caname = $env{'user.name'};
 5695:         $cadom = $env{'user.domain'};
 5696:     }
 5697:     if (($caname ne '') && ($cadom ne '')) {
 5698:         return "/priv/$cadom/$caname/";
 5699:     }
 5700:     return;
 5701: }
 5702: 
 5703: ##############################################
 5704: =pod
 5705: 
 5706: =item * &head_subbox()
 5707: 
 5708: Inputs: $content (contains HTML code with page functions, etc.)
 5709: 
 5710: Returns: HTML div with $content
 5711:          To be included in page header
 5712: 
 5713: =cut
 5714: 
 5715: sub head_subbox {
 5716:     my ($content)=@_;
 5717:     my $output =
 5718:         '<div class="LC_head_subbox">'
 5719:        .$content
 5720:        .'</div>'
 5721: }
 5722: 
 5723: ##############################################
 5724: =pod
 5725: 
 5726: =item * &CSTR_pageheader()
 5727: 
 5728: Input: (optional) filename from which breadcrumb trail is built.
 5729:        In most cases no input as needed, as $env{'request.filename'}
 5730:        is appropriate for use in building the breadcrumb trail.
 5731: 
 5732: Returns: HTML div with CSTR path and recent box
 5733:          To be included on Authoring Space pages
 5734: 
 5735: =cut
 5736: 
 5737: sub CSTR_pageheader {
 5738:     my ($trailfile) = @_;
 5739:     if ($trailfile eq '') {
 5740:         $trailfile = $env{'request.filename'};
 5741:     }
 5742: 
 5743: # this is for resources; directories have customtitle, and crumbs
 5744: # and select recent are created in lonpubdir.pm
 5745: 
 5746:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5747:     my ($udom,$uname,$thisdisfn)=
 5748:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5749:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5750:     $formaction =~ s{/+}{/}g;
 5751: 
 5752:     my $parentpath = '';
 5753:     my $lastitem = '';
 5754:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5755:         $parentpath = $1;
 5756:         $lastitem = $2;
 5757:     } else {
 5758:         $lastitem = $thisdisfn;
 5759:     }
 5760: 
 5761:     my ($crsauthor,$title);
 5762:     if (($env{'request.course.id'}) &&
 5763:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 5764:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 5765:         $crsauthor = 1;
 5766:         $title = &mt('Course Authoring Space');
 5767:     } else {
 5768:         $title = &mt('Authoring Space');
 5769:     }
 5770: 
 5771:     my $output =
 5772:          '<div>'
 5773:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5774:         .'<b>'.$title.'</b> '
 5775:         .'<form name="dirs" method="post" action="'.$formaction
 5776:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5777:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5778: 
 5779:     if ($lastitem) {
 5780:         $output .=
 5781:              '<span class="LC_filename">'
 5782:             .$lastitem
 5783:             .'</span>';
 5784:     }
 5785: 
 5786:     if ($crsauthor) {
 5787:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 5788:     } else {
 5789:         $output .=
 5790:              '<br />'
 5791:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5792:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5793:             .'</form>'
 5794:             .&Apache::lonmenu::constspaceform();
 5795:     }
 5796:     $output .= '</div>';
 5797: 
 5798:     return $output;
 5799: }
 5800: 
 5801: ###############################################
 5802: ###############################################
 5803: 
 5804: =pod
 5805: 
 5806: =back
 5807: 
 5808: =head1 HTML Helpers
 5809: 
 5810: =over 4
 5811: 
 5812: =item * &bodytag()
 5813: 
 5814: Returns a uniform header for LON-CAPA web pages.
 5815: 
 5816: Inputs: 
 5817: 
 5818: =over 4
 5819: 
 5820: =item * $title, A title to be displayed on the page.
 5821: 
 5822: =item * $function, the current role (can be undef).
 5823: 
 5824: =item * $addentries, extra parameters for the <body> tag.
 5825: 
 5826: =item * $bodyonly, if defined, only return the <body> tag.
 5827: 
 5828: =item * $domain, if defined, force a given domain.
 5829: 
 5830: =item * $forcereg, if page should register as content page (relevant for 
 5831:             text interface only)
 5832: 
 5833: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5834:                      navigational links
 5835: 
 5836: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5837: 
 5838: =item * $args, optional argument valid values are
 5839:             no_auto_mt_title -> prevents &mt()ing the title arg
 5840:             use_absolute     -> for external resource or syllabus, this will
 5841:                                 contain https://<hostname> if server uses
 5842:                                 https (as per hosts.tab), but request is for http
 5843:             hostname         -> hostname, from $r->hostname().
 5844: 
 5845: =item * $advtoolsref, optional argument, ref to an array containing
 5846:             inlineremote items to be added in "Functions" menu below
 5847:             breadcrumbs.
 5848: 
 5849: =back
 5850: 
 5851: Returns: A uniform header for LON-CAPA web pages.  
 5852: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5853: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5854: other decorations will be returned.
 5855: 
 5856: =cut
 5857: 
 5858: sub bodytag {
 5859:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5860:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5861: 
 5862:     my $public;
 5863:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5864:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5865:         $public = 1;
 5866:     }
 5867:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5868:     my $httphost = $args->{'use_absolute'};
 5869:     my $hostname = $args->{'hostname'};
 5870: 
 5871:     $function = &get_users_function() if (!$function);
 5872:     my $img =    &designparm($function.'.img',$domain);
 5873:     my $font =   &designparm($function.'.font',$domain);
 5874:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5875: 
 5876:     my %design = ( 'style'   => 'margin-top: 0',
 5877: 		   'bgcolor' => $pgbg,
 5878: 		   'text'    => $font,
 5879:                    'alink'   => &designparm($function.'.alink',$domain),
 5880: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5881: 		   'link'    => &designparm($function.'.link',$domain),);
 5882:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5883: 
 5884:  # role and realm
 5885:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5886:     if ($realm) {
 5887:         $realm = '/'.$realm;
 5888:     }
 5889:     if ($role  eq 'ca') {
 5890:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5891:         $realm = &plainname($rname,$rdom);
 5892:     } 
 5893: # realm
 5894:     if ($env{'request.course.id'}) {
 5895:         if ($env{'request.role'} !~ /^cr/) {
 5896:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5897:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5898:             if ($env{'request.role.desc'}) {
 5899:                 $role = $env{'request.role.desc'};
 5900:             } else {
 5901:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5902:             }
 5903:         } else {
 5904:             $role = (split(/\//,$role,4))[-1]; 
 5905:         }
 5906:         if ($env{'request.course.sec'}) {
 5907:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5908:         }   
 5909: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5910:     } else {
 5911:         $role = &Apache::lonnet::plaintext($role);
 5912:     }
 5913: 
 5914:     if (!$realm) { $realm='&nbsp;'; }
 5915: 
 5916:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5917: 
 5918: # construct main body tag
 5919:     my $bodytag = "<body $extra_body_attr>".
 5920: 	&Apache::lontexconvert::init_math_support();
 5921: 
 5922:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5923: 
 5924:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5925:         return $bodytag;
 5926:     }
 5927: 
 5928:     if ($public) {
 5929: 	undef($role);
 5930:     }
 5931:     
 5932:     my $titleinfo = '<h1>'.$title.'</h1>';
 5933:     #
 5934:     # Extra info if you are the DC
 5935:     my $dc_info = '';
 5936:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5937:                         $env{'course.'.$env{'request.course.id'}.
 5938:                                  '.domain'}.'/'})) {
 5939:         my $cid = $env{'request.course.id'};
 5940:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5941:         $dc_info =~ s/\s+$//;
 5942:     }
 5943: 
 5944:     my $crstype;
 5945:     if ($env{'request.course.id'}) {
 5946:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 5947:     } elsif ($args->{'crstype'}) {
 5948:         $crstype = $args->{'crstype'};
 5949:     }
 5950:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 5951:         undef($role);
 5952:     } else {
 5953:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5954:     }
 5955: 
 5956:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5957: 
 5958:         #    if ($env{'request.state'} eq 'construct') {
 5959:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5960:         #    }
 5961: 
 5962:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5963:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5964: 
 5965:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
 5966: 
 5967:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5968:              if ($dc_info) {
 5969:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5970:              }
 5971:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5972:                 <em>$realm</em> $dc_info</div>|;
 5973:             return $bodytag;
 5974:         }
 5975: 
 5976:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5977:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5978:         }
 5979: 
 5980:         $bodytag .= $right;
 5981: 
 5982:         if ($dc_info) {
 5983:             $dc_info = &dc_courseid_toggle($dc_info);
 5984:         }
 5985:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5986: 
 5987:         #if directed to not display the secondary menu, don't.  
 5988:         if ($args->{'no_secondary_menu'}) {
 5989:             return $bodytag;
 5990:         }
 5991:         #don't show menus for public users
 5992:         if (!$public){
 5993:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5994:             $bodytag .= Apache::lonmenu::serverform();
 5995:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5996:             if ($env{'request.state'} eq 'construct') {
 5997:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5998:                                 $args->{'bread_crumbs'},'','',$hostname);
 5999:             } elsif ($forcereg) {
 6000:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6001:                                                             $args->{'group'},
 6002:                                                             $args->{'hide_buttons'},
 6003:                                                             $hostname);
 6004:             } else {
 6005:                 $bodytag .= 
 6006:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6007:                                                         $forcereg,$args->{'group'},
 6008:                                                         $args->{'bread_crumbs'},
 6009:                                                         $advtoolsref,'',$hostname);
 6010:             }
 6011:         }else{
 6012:             # this is to seperate menu from content when there's no secondary
 6013:             # menu. Especially needed for public accessible ressources.
 6014:             $bodytag .= '<hr style="clear:both" />';
 6015:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6016:         }
 6017: 
 6018:         return $bodytag;
 6019: }
 6020: 
 6021: sub dc_courseid_toggle {
 6022:     my ($dc_info) = @_;
 6023:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6024:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6025:            &mt('(More ...)').'</a></span>'.
 6026:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6027: }
 6028: 
 6029: sub make_attr_string {
 6030:     my ($register,$attr_ref) = @_;
 6031: 
 6032:     if ($attr_ref && !ref($attr_ref)) {
 6033: 	die("addentries Must be a hash ref ".
 6034: 	    join(':',caller(1))." ".
 6035: 	    join(':',caller(0))." ");
 6036:     }
 6037: 
 6038:     if ($register) {
 6039: 	my ($on_load,$on_unload);
 6040: 	foreach my $key (keys(%{$attr_ref})) {
 6041: 	    if      (lc($key) eq 'onload') {
 6042: 		$on_load.=$attr_ref->{$key}.';';
 6043: 		delete($attr_ref->{$key});
 6044: 
 6045: 	    } elsif (lc($key) eq 'onunload') {
 6046: 		$on_unload.=$attr_ref->{$key}.';';
 6047: 		delete($attr_ref->{$key});
 6048: 	    }
 6049: 	}
 6050: 	$attr_ref->{'onload'}  = $on_load;
 6051: 	$attr_ref->{'onunload'}= $on_unload;
 6052:     }
 6053: 
 6054:     my $attr_string;
 6055:     foreach my $attr (sort(keys(%$attr_ref))) {
 6056: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6057:     }
 6058:     return $attr_string;
 6059: }
 6060: 
 6061: 
 6062: ###############################################
 6063: ###############################################
 6064: 
 6065: =pod
 6066: 
 6067: =item * &endbodytag()
 6068: 
 6069: Returns a uniform footer for LON-CAPA web pages.
 6070: 
 6071: Inputs: 1 - optional reference to an args hash
 6072: If in the hash, key for noredirectlink has a value which evaluates to true,
 6073: a 'Continue' link is not displayed if the page contains an
 6074: internal redirect in the <head></head> section,
 6075: i.e., $env{'internal.head.redirect'} exists   
 6076: 
 6077: =cut
 6078: 
 6079: sub endbodytag {
 6080:     my ($args) = @_;
 6081:     my $endbodytag;
 6082:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6083:         $endbodytag='</body>';
 6084:     }
 6085:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6086:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6087: 	    $endbodytag=
 6088: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6089: 	        &mt('Continue').'</a>'.
 6090: 	        $endbodytag;
 6091:         }
 6092:     }
 6093:     return $endbodytag;
 6094: }
 6095: 
 6096: =pod
 6097: 
 6098: =item * &standard_css()
 6099: 
 6100: Returns a style sheet
 6101: 
 6102: Inputs: (all optional)
 6103:             domain         -> force to color decorate a page for a specific
 6104:                                domain
 6105:             function       -> force usage of a specific rolish color scheme
 6106:             bgcolor        -> override the default page bgcolor
 6107: 
 6108: =cut
 6109: 
 6110: sub standard_css {
 6111:     my ($function,$domain,$bgcolor) = @_;
 6112:     $function  = &get_users_function() if (!$function);
 6113:     my $img    = &designparm($function.'.img',   $domain);
 6114:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6115:     my $font   = &designparm($function.'.font',  $domain);
 6116:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6117: #second colour for later usage
 6118:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6119:     my $pgbg_or_bgcolor =
 6120: 	         $bgcolor ||
 6121: 	         &designparm($function.'.pgbg',  $domain);
 6122:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6123:     my $alink  = &designparm($function.'.alink', $domain);
 6124:     my $vlink  = &designparm($function.'.vlink', $domain);
 6125:     my $link   = &designparm($function.'.link',  $domain);
 6126: 
 6127:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6128:     my $mono                 = 'monospace';
 6129:     my $data_table_head      = $sidebg;
 6130:     my $data_table_light     = '#FAFAFA';
 6131:     my $data_table_dark      = '#E0E0E0';
 6132:     my $data_table_darker    = '#CCCCCC';
 6133:     my $data_table_highlight = '#FFFF00';
 6134:     my $mail_new             = '#FFBB77';
 6135:     my $mail_new_hover       = '#DD9955';
 6136:     my $mail_read            = '#BBBB77';
 6137:     my $mail_read_hover      = '#999944';
 6138:     my $mail_replied         = '#AAAA88';
 6139:     my $mail_replied_hover   = '#888855';
 6140:     my $mail_other           = '#99BBBB';
 6141:     my $mail_other_hover     = '#669999';
 6142:     my $table_header         = '#DDDDDD';
 6143:     my $feedback_link_bg     = '#BBBBBB';
 6144:     my $lg_border_color      = '#C8C8C8';
 6145:     my $button_hover         = '#BF2317';
 6146: 
 6147:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6148:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6149:                                              : '0 3px 0 4px';
 6150: 
 6151: 
 6152:     return <<END;
 6153: 
 6154: /* needed for iframe to allow 100% height in FF */
 6155: body, html { 
 6156:     margin: 0;
 6157:     padding: 0 0.5%;
 6158:     height: 99%; /* to avoid scrollbars */
 6159: }
 6160: 
 6161: body {
 6162:   font-family: $sans;
 6163:   line-height:130%;
 6164:   font-size:0.83em;
 6165:   color:$font;
 6166: }
 6167: 
 6168: a:focus,
 6169: a:focus img {
 6170:   color: red;
 6171: }
 6172: 
 6173: form, .inline {
 6174:   display: inline;
 6175: }
 6176: 
 6177: .LC_right {
 6178:   text-align:right;
 6179: }
 6180: 
 6181: .LC_middle {
 6182:   vertical-align:middle;
 6183: }
 6184: 
 6185: .LC_floatleft {
 6186:   float: left;
 6187: }
 6188: 
 6189: .LC_floatright {
 6190:   float: right;
 6191: }
 6192: 
 6193: .LC_400Box {
 6194:   width:400px;
 6195: }
 6196: 
 6197: .LC_iframecontainer {
 6198:     width: 98%;
 6199:     margin: 0;
 6200:     position: fixed;
 6201:     top: 8.5em;
 6202:     bottom: 0;
 6203: }
 6204: 
 6205: .LC_iframecontainer iframe{
 6206:     border: none;
 6207:     width: 100%;
 6208:     height: 100%;
 6209: }
 6210: 
 6211: .LC_filename {
 6212:   font-family: $mono;
 6213:   white-space:pre;
 6214:   font-size: 120%;
 6215: }
 6216: 
 6217: .LC_fileicon {
 6218:   border: none;
 6219:   height: 1.3em;
 6220:   vertical-align: text-bottom;
 6221:   margin-right: 0.3em;
 6222:   text-decoration:none;
 6223: }
 6224: 
 6225: .LC_setting {
 6226:   text-decoration:underline;
 6227: }
 6228: 
 6229: .LC_error {
 6230:   color: red;
 6231: }
 6232: 
 6233: .LC_warning {
 6234:   color: darkorange;
 6235: }
 6236: 
 6237: .LC_diff_removed {
 6238:   color: red;
 6239: }
 6240: 
 6241: .LC_info,
 6242: .LC_success,
 6243: .LC_diff_added {
 6244:   color: green;
 6245: }
 6246: 
 6247: div.LC_confirm_box {
 6248:   background-color: #FAFAFA;
 6249:   border: 1px solid $lg_border_color;
 6250:   margin-right: 0;
 6251:   padding: 5px;
 6252: }
 6253: 
 6254: div.LC_confirm_box .LC_error img,
 6255: div.LC_confirm_box .LC_success img {
 6256:   vertical-align: middle;
 6257: }
 6258: 
 6259: .LC_maxwidth {
 6260:   max-width: 100%;
 6261:   height: auto;
 6262: }
 6263: 
 6264: .LC_textsize_mobile {
 6265:   \@media only screen and (max-device-width: 480px) {
 6266:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6267:   }
 6268: }
 6269: 
 6270: .LC_icon {
 6271:   border: none;
 6272:   vertical-align: middle;
 6273: }
 6274: 
 6275: .LC_docs_spacer {
 6276:   width: 25px;
 6277:   height: 1px;
 6278:   border: none;
 6279: }
 6280: 
 6281: .LC_internal_info {
 6282:   color: #999999;
 6283: }
 6284: 
 6285: .LC_discussion {
 6286:   background: $data_table_dark;
 6287:   border: 1px solid black;
 6288:   margin: 2px;
 6289: }
 6290: 
 6291: .LC_disc_action_left {
 6292:   background: $sidebg;
 6293:   text-align: left;
 6294:   padding: 4px;
 6295:   margin: 2px;
 6296: }
 6297: 
 6298: .LC_disc_action_right {
 6299:   background: $sidebg;
 6300:   text-align: right;
 6301:   padding: 4px;
 6302:   margin: 2px;
 6303: }
 6304: 
 6305: .LC_disc_new_item {
 6306:   background: white;
 6307:   border: 2px solid red;
 6308:   margin: 4px;
 6309:   padding: 4px;
 6310: }
 6311: 
 6312: .LC_disc_old_item {
 6313:   background: white;
 6314:   margin: 4px;
 6315:   padding: 4px;
 6316: }
 6317: 
 6318: table.LC_pastsubmission {
 6319:   border: 1px solid black;
 6320:   margin: 2px;
 6321: }
 6322: 
 6323: table#LC_menubuttons {
 6324:   width: 100%;
 6325:   background: $pgbg;
 6326:   border: 2px;
 6327:   border-collapse: separate;
 6328:   padding: 0;
 6329: }
 6330: 
 6331: table#LC_title_bar a {
 6332:   color: $fontmenu;
 6333: }
 6334: 
 6335: table#LC_title_bar {
 6336:   clear: both;
 6337:   display: none;
 6338: }
 6339: 
 6340: table#LC_title_bar,
 6341: table.LC_breadcrumbs, /* obsolete? */
 6342: table#LC_title_bar.LC_with_remote {
 6343:   width: 100%;
 6344:   border-color: $pgbg;
 6345:   border-style: solid;
 6346:   border-width: $border;
 6347:   background: $pgbg;
 6348:   color: $fontmenu;
 6349:   border-collapse: collapse;
 6350:   padding: 0;
 6351:   margin: 0;
 6352: }
 6353: 
 6354: ul.LC_breadcrumb_tools_outerlist {
 6355:     margin: 0;
 6356:     padding: 0;
 6357:     position: relative;
 6358:     list-style: none;
 6359: }
 6360: ul.LC_breadcrumb_tools_outerlist li {
 6361:     display: inline;
 6362: }
 6363: 
 6364: .LC_breadcrumb_tools_navigation {
 6365:     padding: 0;
 6366:     margin: 0;
 6367:     float: left;
 6368: }
 6369: .LC_breadcrumb_tools_tools {
 6370:     padding: 0;
 6371:     margin: 0;
 6372:     float: right;
 6373: }
 6374: 
 6375: .LC_placement_prog {
 6376:     padding-right: 20px;
 6377:     font-weight: bold;
 6378:     font-size: 90%;
 6379: }
 6380: 
 6381: table#LC_title_bar td {
 6382:   background: $tabbg;
 6383: }
 6384: 
 6385: table#LC_menubuttons img {
 6386:   border: none;
 6387: }
 6388: 
 6389: .LC_breadcrumbs_component {
 6390:   float: right;
 6391:   margin: 0 1em;
 6392: }
 6393: .LC_breadcrumbs_component img {
 6394:   vertical-align: middle;
 6395: }
 6396: 
 6397: .LC_breadcrumbs_hoverable {
 6398:   background: $sidebg;
 6399: }
 6400: 
 6401: td.LC_table_cell_checkbox {
 6402:   text-align: center;
 6403: }
 6404: 
 6405: .LC_fontsize_small {
 6406:   font-size: 70%;
 6407: }
 6408: 
 6409: #LC_breadcrumbs {
 6410:   clear:both;
 6411:   background: $sidebg;
 6412:   border-bottom: 1px solid $lg_border_color;
 6413:   line-height: 2.5em;
 6414:   overflow: hidden;
 6415:   margin: 0;
 6416:   padding: 0;
 6417:   text-align: left;
 6418: }
 6419: 
 6420: .LC_head_subbox, .LC_actionbox {
 6421:   clear:both;
 6422:   background: #F8F8F8; /* $sidebg; */
 6423:   border: 1px solid $sidebg;
 6424:   margin: 0 0 10px 0;
 6425:   padding: 3px;
 6426:   text-align: left;
 6427: }
 6428: 
 6429: .LC_fontsize_medium {
 6430:   font-size: 85%;
 6431: }
 6432: 
 6433: .LC_fontsize_large {
 6434:   font-size: 120%;
 6435: }
 6436: 
 6437: .LC_menubuttons_inline_text {
 6438:   color: $font;
 6439:   font-size: 90%;
 6440:   padding-left:3px;
 6441: }
 6442: 
 6443: .LC_menubuttons_inline_text img{
 6444:   vertical-align: middle;
 6445: }
 6446: 
 6447: li.LC_menubuttons_inline_text img {
 6448:   cursor:pointer;
 6449:   text-decoration: none;
 6450: }
 6451: 
 6452: .LC_menubuttons_link {
 6453:   text-decoration: none;
 6454: }
 6455: 
 6456: .LC_menubuttons_category {
 6457:   color: $font;
 6458:   background: $pgbg;
 6459:   font-size: larger;
 6460:   font-weight: bold;
 6461: }
 6462: 
 6463: td.LC_menubuttons_text {
 6464:   color: $font;
 6465: }
 6466: 
 6467: .LC_current_location {
 6468:   background: $tabbg;
 6469: }
 6470: 
 6471: td.LC_zero_height {
 6472:   line-height: 0; 
 6473:   cellpadding: 0;
 6474: }
 6475: 
 6476: table.LC_data_table {
 6477:   border: 1px solid #000000;
 6478:   border-collapse: separate;
 6479:   border-spacing: 1px;
 6480:   background: $pgbg;
 6481: }
 6482: 
 6483: .LC_data_table_dense {
 6484:   font-size: small;
 6485: }
 6486: 
 6487: table.LC_nested_outer {
 6488:   border: 1px solid #000000;
 6489:   border-collapse: collapse;
 6490:   border-spacing: 0;
 6491:   width: 100%;
 6492: }
 6493: 
 6494: table.LC_innerpickbox,
 6495: table.LC_nested {
 6496:   border: none;
 6497:   border-collapse: collapse;
 6498:   border-spacing: 0;
 6499:   width: 100%;
 6500: }
 6501: 
 6502: table.LC_data_table tr th,
 6503: table.LC_calendar tr th,
 6504: table.LC_prior_tries tr th,
 6505: table.LC_innerpickbox tr th {
 6506:   font-weight: bold;
 6507:   background-color: $data_table_head;
 6508:   color:$fontmenu;
 6509:   font-size:90%;
 6510: }
 6511: 
 6512: table.LC_innerpickbox tr th,
 6513: table.LC_innerpickbox tr td {
 6514:   vertical-align: top;
 6515: }
 6516: 
 6517: table.LC_data_table tr.LC_info_row > td {
 6518:   background-color: #CCCCCC;
 6519:   font-weight: bold;
 6520:   text-align: left;
 6521: }
 6522: 
 6523: table.LC_data_table tr.LC_odd_row > td {
 6524:   background-color: $data_table_light;
 6525:   padding: 2px;
 6526:   vertical-align: top;
 6527: }
 6528: 
 6529: table.LC_pick_box tr > td.LC_odd_row {
 6530:   background-color: $data_table_light;
 6531:   vertical-align: top;
 6532: }
 6533: 
 6534: table.LC_data_table tr.LC_even_row > td {
 6535:   background-color: $data_table_dark;
 6536:   padding: 2px;
 6537:   vertical-align: top;
 6538: }
 6539: 
 6540: table.LC_pick_box tr > td.LC_even_row {
 6541:   background-color: $data_table_dark;
 6542:   vertical-align: top;
 6543: }
 6544: 
 6545: table.LC_data_table tr.LC_data_table_highlight td {
 6546:   background-color: $data_table_darker;
 6547: }
 6548: 
 6549: table.LC_data_table tr td.LC_leftcol_header {
 6550:   background-color: $data_table_head;
 6551:   font-weight: bold;
 6552: }
 6553: 
 6554: table.LC_data_table tr.LC_empty_row td,
 6555: table.LC_nested tr.LC_empty_row td {
 6556:   font-weight: bold;
 6557:   font-style: italic;
 6558:   text-align: center;
 6559:   padding: 8px;
 6560: }
 6561: 
 6562: table.LC_data_table tr.LC_empty_row td,
 6563: table.LC_data_table tr.LC_footer_row td {
 6564:   background-color: $sidebg;
 6565: }
 6566: 
 6567: table.LC_nested tr.LC_empty_row td {
 6568:   background-color: #FFFFFF;
 6569: }
 6570: 
 6571: table.LC_caption {
 6572: }
 6573: 
 6574: table.LC_nested tr.LC_empty_row td {
 6575:   padding: 4ex
 6576: }
 6577: 
 6578: table.LC_nested_outer tr th {
 6579:   font-weight: bold;
 6580:   color:$fontmenu;
 6581:   background-color: $data_table_head;
 6582:   font-size: small;
 6583:   border-bottom: 1px solid #000000;
 6584: }
 6585: 
 6586: table.LC_nested_outer tr td.LC_subheader {
 6587:   background-color: $data_table_head;
 6588:   font-weight: bold;
 6589:   font-size: small;
 6590:   border-bottom: 1px solid #000000;
 6591:   text-align: right;
 6592: }
 6593: 
 6594: table.LC_nested tr.LC_info_row td {
 6595:   background-color: #CCCCCC;
 6596:   font-weight: bold;
 6597:   font-size: small;
 6598:   text-align: center;
 6599: }
 6600: 
 6601: table.LC_nested tr.LC_info_row td.LC_left_item,
 6602: table.LC_nested_outer tr th.LC_left_item {
 6603:   text-align: left;
 6604: }
 6605: 
 6606: table.LC_nested td {
 6607:   background-color: #FFFFFF;
 6608:   font-size: small;
 6609: }
 6610: 
 6611: table.LC_nested_outer tr th.LC_right_item,
 6612: table.LC_nested tr.LC_info_row td.LC_right_item,
 6613: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6614: table.LC_nested tr td.LC_right_item {
 6615:   text-align: right;
 6616: }
 6617: 
 6618: table.LC_nested tr.LC_odd_row td {
 6619:   background-color: #EEEEEE;
 6620: }
 6621: 
 6622: table.LC_createuser {
 6623: }
 6624: 
 6625: table.LC_createuser tr.LC_section_row td {
 6626:   font-size: small;
 6627: }
 6628: 
 6629: table.LC_createuser tr.LC_info_row td  {
 6630:   background-color: #CCCCCC;
 6631:   font-weight: bold;
 6632:   text-align: center;
 6633: }
 6634: 
 6635: table.LC_calendar {
 6636:   border: 1px solid #000000;
 6637:   border-collapse: collapse;
 6638:   width: 98%;
 6639: }
 6640: 
 6641: table.LC_calendar_pickdate {
 6642:   font-size: xx-small;
 6643: }
 6644: 
 6645: table.LC_calendar tr td {
 6646:   border: 1px solid #000000;
 6647:   vertical-align: top;
 6648:   width: 14%;
 6649: }
 6650: 
 6651: table.LC_calendar tr td.LC_calendar_day_empty {
 6652:   background-color: $data_table_dark;
 6653: }
 6654: 
 6655: table.LC_calendar tr td.LC_calendar_day_current {
 6656:   background-color: $data_table_highlight;
 6657: }
 6658: 
 6659: table.LC_data_table tr td.LC_mail_new {
 6660:   background-color: $mail_new;
 6661: }
 6662: 
 6663: table.LC_data_table tr.LC_mail_new:hover {
 6664:   background-color: $mail_new_hover;
 6665: }
 6666: 
 6667: table.LC_data_table tr td.LC_mail_read {
 6668:   background-color: $mail_read;
 6669: }
 6670: 
 6671: /*
 6672: table.LC_data_table tr.LC_mail_read:hover {
 6673:   background-color: $mail_read_hover;
 6674: }
 6675: */
 6676: 
 6677: table.LC_data_table tr td.LC_mail_replied {
 6678:   background-color: $mail_replied;
 6679: }
 6680: 
 6681: /*
 6682: table.LC_data_table tr.LC_mail_replied:hover {
 6683:   background-color: $mail_replied_hover;
 6684: }
 6685: */
 6686: 
 6687: table.LC_data_table tr td.LC_mail_other {
 6688:   background-color: $mail_other;
 6689: }
 6690: 
 6691: /*
 6692: table.LC_data_table tr.LC_mail_other:hover {
 6693:   background-color: $mail_other_hover;
 6694: }
 6695: */
 6696: 
 6697: table.LC_data_table tr > td.LC_browser_file,
 6698: table.LC_data_table tr > td.LC_browser_file_published {
 6699:   background: #AAEE77;
 6700: }
 6701: 
 6702: table.LC_data_table tr > td.LC_browser_file_locked,
 6703: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6704:   background: #FFAA99;
 6705: }
 6706: 
 6707: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6708:   background: #888888;
 6709: }
 6710: 
 6711: table.LC_data_table tr > td.LC_browser_file_modified,
 6712: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6713:   background: #F8F866;
 6714: }
 6715: 
 6716: table.LC_data_table tr.LC_browser_folder > td {
 6717:   background: #E0E8FF;
 6718: }
 6719: 
 6720: table.LC_data_table tr > td.LC_roles_is {
 6721:   /* background: #77FF77; */
 6722: }
 6723: 
 6724: table.LC_data_table tr > td.LC_roles_future {
 6725:   border-right: 8px solid #FFFF77;
 6726: }
 6727: 
 6728: table.LC_data_table tr > td.LC_roles_will {
 6729:   border-right: 8px solid #FFAA77;
 6730: }
 6731: 
 6732: table.LC_data_table tr > td.LC_roles_expired {
 6733:   border-right: 8px solid #FF7777;
 6734: }
 6735: 
 6736: table.LC_data_table tr > td.LC_roles_will_not {
 6737:   border-right: 8px solid #AAFF77;
 6738: }
 6739: 
 6740: table.LC_data_table tr > td.LC_roles_selected {
 6741:   border-right: 8px solid #11CC55;
 6742: }
 6743: 
 6744: span.LC_current_location {
 6745:   font-size:larger;
 6746:   background: $pgbg;
 6747: }
 6748: 
 6749: span.LC_current_nav_location {
 6750:   font-weight:bold;
 6751:   background: $sidebg;
 6752: }
 6753: 
 6754: span.LC_parm_menu_item {
 6755:   font-size: larger;
 6756: }
 6757: 
 6758: span.LC_parm_scope_all {
 6759:   color: red;
 6760: }
 6761: 
 6762: span.LC_parm_scope_folder {
 6763:   color: green;
 6764: }
 6765: 
 6766: span.LC_parm_scope_resource {
 6767:   color: orange;
 6768: }
 6769: 
 6770: span.LC_parm_part {
 6771:   color: blue;
 6772: }
 6773: 
 6774: span.LC_parm_folder,
 6775: span.LC_parm_symb {
 6776:   font-size: x-small;
 6777:   font-family: $mono;
 6778:   color: #AAAAAA;
 6779: }
 6780: 
 6781: ul.LC_parm_parmlist li {
 6782:   display: inline-block;
 6783:   padding: 0.3em 0.8em;
 6784:   vertical-align: top;
 6785:   width: 150px;
 6786:   border-top:1px solid $lg_border_color;
 6787: }
 6788: 
 6789: td.LC_parm_overview_level_menu,
 6790: td.LC_parm_overview_map_menu,
 6791: td.LC_parm_overview_parm_selectors,
 6792: td.LC_parm_overview_restrictions  {
 6793:   border: 1px solid black;
 6794:   border-collapse: collapse;
 6795: }
 6796: 
 6797: span.LC_parm_recursive,
 6798: td.LC_parm_recursive {
 6799:   font-weight: bold;
 6800:   font-size: smaller;
 6801: }
 6802: 
 6803: table.LC_parm_overview_restrictions td {
 6804:   border-width: 1px 4px 1px 4px;
 6805:   border-style: solid;
 6806:   border-color: $pgbg;
 6807:   text-align: center;
 6808: }
 6809: 
 6810: table.LC_parm_overview_restrictions th {
 6811:   background: $tabbg;
 6812:   border-width: 1px 4px 1px 4px;
 6813:   border-style: solid;
 6814:   border-color: $pgbg;
 6815: }
 6816: 
 6817: table#LC_helpmenu {
 6818:   border: none;
 6819:   height: 55px;
 6820:   border-spacing: 0;
 6821: }
 6822: 
 6823: table#LC_helpmenu fieldset legend {
 6824:   font-size: larger;
 6825: }
 6826: 
 6827: table#LC_helpmenu_links {
 6828:   width: 100%;
 6829:   border: 1px solid black;
 6830:   background: $pgbg;
 6831:   padding: 0;
 6832:   border-spacing: 1px;
 6833: }
 6834: 
 6835: table#LC_helpmenu_links tr td {
 6836:   padding: 1px;
 6837:   background: $tabbg;
 6838:   text-align: center;
 6839:   font-weight: bold;
 6840: }
 6841: 
 6842: table#LC_helpmenu_links a:link,
 6843: table#LC_helpmenu_links a:visited,
 6844: table#LC_helpmenu_links a:active {
 6845:   text-decoration: none;
 6846:   color: $font;
 6847: }
 6848: 
 6849: table#LC_helpmenu_links a:hover {
 6850:   text-decoration: underline;
 6851:   color: $vlink;
 6852: }
 6853: 
 6854: .LC_chrt_popup_exists {
 6855:   border: 1px solid #339933;
 6856:   margin: -1px;
 6857: }
 6858: 
 6859: .LC_chrt_popup_up {
 6860:   border: 1px solid yellow;
 6861:   margin: -1px;
 6862: }
 6863: 
 6864: .LC_chrt_popup {
 6865:   border: 1px solid #8888FF;
 6866:   background: #CCCCFF;
 6867: }
 6868: 
 6869: table.LC_pick_box {
 6870:   border-collapse: separate;
 6871:   background: white;
 6872:   border: 1px solid black;
 6873:   border-spacing: 1px;
 6874: }
 6875: 
 6876: table.LC_pick_box td.LC_pick_box_title {
 6877:   background: $sidebg;
 6878:   font-weight: bold;
 6879:   text-align: left;
 6880:   vertical-align: top;
 6881:   width: 184px;
 6882:   padding: 8px;
 6883: }
 6884: 
 6885: table.LC_pick_box td.LC_pick_box_value {
 6886:   text-align: left;
 6887:   padding: 8px;
 6888: }
 6889: 
 6890: table.LC_pick_box td.LC_pick_box_select {
 6891:   text-align: left;
 6892:   padding: 8px;
 6893: }
 6894: 
 6895: table.LC_pick_box td.LC_pick_box_separator {
 6896:   padding: 0;
 6897:   height: 1px;
 6898:   background: black;
 6899: }
 6900: 
 6901: table.LC_pick_box td.LC_pick_box_submit {
 6902:   text-align: right;
 6903: }
 6904: 
 6905: table.LC_pick_box td.LC_evenrow_value {
 6906:   text-align: left;
 6907:   padding: 8px;
 6908:   background-color: $data_table_light;
 6909: }
 6910: 
 6911: table.LC_pick_box td.LC_oddrow_value {
 6912:   text-align: left;
 6913:   padding: 8px;
 6914:   background-color: $data_table_light;
 6915: }
 6916: 
 6917: span.LC_helpform_receipt_cat {
 6918:   font-weight: bold;
 6919: }
 6920: 
 6921: table.LC_group_priv_box {
 6922:   background: white;
 6923:   border: 1px solid black;
 6924:   border-spacing: 1px;
 6925: }
 6926: 
 6927: table.LC_group_priv_box td.LC_pick_box_title {
 6928:   background: $tabbg;
 6929:   font-weight: bold;
 6930:   text-align: right;
 6931:   width: 184px;
 6932: }
 6933: 
 6934: table.LC_group_priv_box td.LC_groups_fixed {
 6935:   background: $data_table_light;
 6936:   text-align: center;
 6937: }
 6938: 
 6939: table.LC_group_priv_box td.LC_groups_optional {
 6940:   background: $data_table_dark;
 6941:   text-align: center;
 6942: }
 6943: 
 6944: table.LC_group_priv_box td.LC_groups_functionality {
 6945:   background: $data_table_darker;
 6946:   text-align: center;
 6947:   font-weight: bold;
 6948: }
 6949: 
 6950: table.LC_group_priv td {
 6951:   text-align: left;
 6952:   padding: 0;
 6953: }
 6954: 
 6955: .LC_navbuttons {
 6956:   margin: 2ex 0ex 2ex 0ex;
 6957: }
 6958: 
 6959: .LC_topic_bar {
 6960:   font-weight: bold;
 6961:   background: $tabbg;
 6962:   margin: 1em 0em 1em 2em;
 6963:   padding: 3px;
 6964:   font-size: 1.2em;
 6965: }
 6966: 
 6967: .LC_topic_bar span {
 6968:   left: 0.5em;
 6969:   position: absolute;
 6970:   vertical-align: middle;
 6971:   font-size: 1.2em;
 6972: }
 6973: 
 6974: table.LC_course_group_status {
 6975:   margin: 20px;
 6976: }
 6977: 
 6978: table.LC_status_selector td {
 6979:   vertical-align: top;
 6980:   text-align: center;
 6981:   padding: 4px;
 6982: }
 6983: 
 6984: div.LC_feedback_link {
 6985:   clear: both;
 6986:   background: $sidebg;
 6987:   width: 100%;
 6988:   padding-bottom: 10px;
 6989:   border: 1px $tabbg solid;
 6990:   height: 22px;
 6991:   line-height: 22px;
 6992:   padding-top: 5px;
 6993: }
 6994: 
 6995: div.LC_feedback_link img {
 6996:   height: 22px;
 6997:   vertical-align:middle;
 6998: }
 6999: 
 7000: div.LC_feedback_link a {
 7001:   text-decoration: none;
 7002: }
 7003: 
 7004: div.LC_comblock {
 7005:   display:inline;
 7006:   color:$font;
 7007:   font-size:90%;
 7008: }
 7009: 
 7010: div.LC_feedback_link div.LC_comblock {
 7011:   padding-left:5px;
 7012: }
 7013: 
 7014: div.LC_feedback_link div.LC_comblock a {
 7015:   color:$font;
 7016: }
 7017: 
 7018: span.LC_feedback_link {
 7019:   /* background: $feedback_link_bg; */
 7020:   font-size: larger;
 7021: }
 7022: 
 7023: span.LC_message_link {
 7024:   /* background: $feedback_link_bg; */
 7025:   font-size: larger;
 7026:   position: absolute;
 7027:   right: 1em;
 7028: }
 7029: 
 7030: table.LC_prior_tries {
 7031:   border: 1px solid #000000;
 7032:   border-collapse: separate;
 7033:   border-spacing: 1px;
 7034: }
 7035: 
 7036: table.LC_prior_tries td {
 7037:   padding: 2px;
 7038: }
 7039: 
 7040: .LC_answer_correct {
 7041:   background: lightgreen;
 7042:   color: darkgreen;
 7043:   padding: 6px;
 7044: }
 7045: 
 7046: .LC_answer_charged_try {
 7047:   background: #FFAAAA;
 7048:   color: darkred;
 7049:   padding: 6px;
 7050: }
 7051: 
 7052: .LC_answer_not_charged_try,
 7053: .LC_answer_no_grade,
 7054: .LC_answer_late {
 7055:   background: lightyellow;
 7056:   color: black;
 7057:   padding: 6px;
 7058: }
 7059: 
 7060: .LC_answer_previous {
 7061:   background: lightblue;
 7062:   color: darkblue;
 7063:   padding: 6px;
 7064: }
 7065: 
 7066: .LC_answer_no_message {
 7067:   background: #FFFFFF;
 7068:   color: black;
 7069:   padding: 6px;
 7070: }
 7071: 
 7072: .LC_answer_unknown {
 7073:   background: orange;
 7074:   color: black;
 7075:   padding: 6px;
 7076: }
 7077: 
 7078: span.LC_prior_numerical,
 7079: span.LC_prior_string,
 7080: span.LC_prior_custom,
 7081: span.LC_prior_reaction,
 7082: span.LC_prior_math {
 7083:   font-family: $mono;
 7084:   white-space: pre;
 7085: }
 7086: 
 7087: span.LC_prior_string {
 7088:   font-family: $mono;
 7089:   white-space: pre;
 7090: }
 7091: 
 7092: table.LC_prior_option {
 7093:   width: 100%;
 7094:   border-collapse: collapse;
 7095: }
 7096: 
 7097: table.LC_prior_rank,
 7098: table.LC_prior_match {
 7099:   border-collapse: collapse;
 7100: }
 7101: 
 7102: table.LC_prior_option tr td,
 7103: table.LC_prior_rank tr td,
 7104: table.LC_prior_match tr td {
 7105:   border: 1px solid #000000;
 7106: }
 7107: 
 7108: .LC_nobreak {
 7109:   white-space: nowrap;
 7110: }
 7111: 
 7112: span.LC_cusr_emph {
 7113:   font-style: italic;
 7114: }
 7115: 
 7116: span.LC_cusr_subheading {
 7117:   font-weight: normal;
 7118:   font-size: 85%;
 7119: }
 7120: 
 7121: div.LC_docs_entry_move {
 7122:   border: 1px solid #BBBBBB;
 7123:   background: #DDDDDD;
 7124:   width: 22px;
 7125:   padding: 1px;
 7126:   margin: 0;
 7127: }
 7128: 
 7129: table.LC_data_table tr > td.LC_docs_entry_commands,
 7130: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7131:   font-size: x-small;
 7132: }
 7133: 
 7134: .LC_docs_entry_parameter {
 7135:   white-space: nowrap;
 7136: }
 7137: 
 7138: .LC_docs_copy {
 7139:   color: #000099;
 7140: }
 7141: 
 7142: .LC_docs_cut {
 7143:   color: #550044;
 7144: }
 7145: 
 7146: .LC_docs_rename {
 7147:   color: #009900;
 7148: }
 7149: 
 7150: .LC_docs_remove {
 7151:   color: #990000;
 7152: }
 7153: 
 7154: .LC_docs_alias {
 7155:   color: #440055;  
 7156: }
 7157: 
 7158: .LC_domprefs_email,
 7159: .LC_docs_alias_name,
 7160: .LC_docs_reinit_warn,
 7161: .LC_docs_ext_edit {
 7162:   font-size: x-small;
 7163: }
 7164: 
 7165: table.LC_docs_adddocs td,
 7166: table.LC_docs_adddocs th {
 7167:   border: 1px solid #BBBBBB;
 7168:   padding: 4px;
 7169:   background: #DDDDDD;
 7170: }
 7171: 
 7172: table.LC_sty_begin {
 7173:   background: #BBFFBB;
 7174: }
 7175: 
 7176: table.LC_sty_end {
 7177:   background: #FFBBBB;
 7178: }
 7179: 
 7180: table.LC_double_column {
 7181:   border-width: 0;
 7182:   border-collapse: collapse;
 7183:   width: 100%;
 7184:   padding: 2px;
 7185: }
 7186: 
 7187: table.LC_double_column tr td.LC_left_col {
 7188:   top: 2px;
 7189:   left: 2px;
 7190:   width: 47%;
 7191:   vertical-align: top;
 7192: }
 7193: 
 7194: table.LC_double_column tr td.LC_right_col {
 7195:   top: 2px;
 7196:   right: 2px;
 7197:   width: 47%;
 7198:   vertical-align: top;
 7199: }
 7200: 
 7201: div.LC_left_float {
 7202:   float: left;
 7203:   padding-right: 5%;
 7204:   padding-bottom: 4px;
 7205: }
 7206: 
 7207: div.LC_clear_float_header {
 7208:   padding-bottom: 2px;
 7209: }
 7210: 
 7211: div.LC_clear_float_footer {
 7212:   padding-top: 10px;
 7213:   clear: both;
 7214: }
 7215: 
 7216: div.LC_grade_show_user {
 7217: /*  border-left: 5px solid $sidebg; */
 7218:   border-top: 5px solid #000000;
 7219:   margin: 50px 0 0 0;
 7220:   padding: 15px 0 5px 10px;
 7221: }
 7222: 
 7223: div.LC_grade_show_user_odd_row {
 7224: /*  border-left: 5px solid #000000; */
 7225: }
 7226: 
 7227: div.LC_grade_show_user div.LC_Box {
 7228:   margin-right: 50px;
 7229: }
 7230: 
 7231: div.LC_grade_submissions,
 7232: div.LC_grade_message_center,
 7233: div.LC_grade_info_links {
 7234:   margin: 5px;
 7235:   width: 99%;
 7236:   background: #FFFFFF;
 7237: }
 7238: 
 7239: div.LC_grade_submissions_header,
 7240: div.LC_grade_message_center_header {
 7241:   font-weight: bold;
 7242:   font-size: large;
 7243: }
 7244: 
 7245: div.LC_grade_submissions_body,
 7246: div.LC_grade_message_center_body {
 7247:   border: 1px solid black;
 7248:   width: 99%;
 7249:   background: #FFFFFF;
 7250: }
 7251: 
 7252: table.LC_scantron_action {
 7253:   width: 100%;
 7254: }
 7255: 
 7256: table.LC_scantron_action tr th {
 7257:   font-weight:bold;
 7258:   font-style:normal;
 7259: }
 7260: 
 7261: .LC_edit_problem_header,
 7262: div.LC_edit_problem_footer {
 7263:   font-weight: normal;
 7264:   font-size:  medium;
 7265:   margin: 2px;
 7266:   background-color: $sidebg;
 7267: }
 7268: 
 7269: div.LC_edit_problem_header,
 7270: div.LC_edit_problem_header div,
 7271: div.LC_edit_problem_footer,
 7272: div.LC_edit_problem_footer div,
 7273: div.LC_edit_problem_editxml_header,
 7274: div.LC_edit_problem_editxml_header div {
 7275:   z-index: 100;
 7276: }
 7277: 
 7278: div.LC_edit_problem_header_title {
 7279:   font-weight: bold;
 7280:   font-size: larger;
 7281:   background: $tabbg;
 7282:   padding: 3px;
 7283:   margin: 0 0 5px 0;
 7284: }
 7285: 
 7286: table.LC_edit_problem_header_title {
 7287:   width: 100%;
 7288:   background: $tabbg;
 7289: }
 7290: 
 7291: div.LC_edit_actionbar {
 7292:     background-color: $sidebg;
 7293:     margin: 0;
 7294:     padding: 0;
 7295:     line-height: 200%;
 7296: }
 7297: 
 7298: div.LC_edit_actionbar div{
 7299:     padding: 0;
 7300:     margin: 0;
 7301:     display: inline-block;
 7302: }
 7303: 
 7304: .LC_edit_opt {
 7305:   padding-left: 1em;
 7306:   white-space: nowrap;
 7307: }
 7308: 
 7309: .LC_edit_problem_latexhelper{
 7310:     text-align: right;
 7311: }
 7312: 
 7313: #LC_edit_problem_colorful div{
 7314:     margin-left: 40px;
 7315: }
 7316: 
 7317: #LC_edit_problem_codemirror div{
 7318:     margin-left: 0px;
 7319: }
 7320: 
 7321: img.stift {
 7322:   border-width: 0;
 7323:   vertical-align: middle;
 7324: }
 7325: 
 7326: table td.LC_mainmenu_col_fieldset {
 7327:   vertical-align: top;
 7328: }
 7329: 
 7330: div.LC_createcourse {
 7331:   margin: 10px 10px 10px 10px;
 7332: }
 7333: 
 7334: .LC_dccid {
 7335:   float: right;
 7336:   margin: 0.2em 0 0 0;
 7337:   padding: 0;
 7338:   font-size: 90%;
 7339:   display:none;
 7340: }
 7341: 
 7342: ol.LC_primary_menu a:hover,
 7343: ol#LC_MenuBreadcrumbs a:hover,
 7344: ol#LC_PathBreadcrumbs a:hover,
 7345: ul#LC_secondary_menu a:hover,
 7346: .LC_FormSectionClearButton input:hover
 7347: ul.LC_TabContent   li:hover a {
 7348:   color:$button_hover;
 7349:   text-decoration:none;
 7350: }
 7351: 
 7352: h1 {
 7353:   padding: 0;
 7354:   line-height:130%;
 7355: }
 7356: 
 7357: h2,
 7358: h3,
 7359: h4,
 7360: h5,
 7361: h6 {
 7362:   margin: 5px 0 5px 0;
 7363:   padding: 0;
 7364:   line-height:130%;
 7365: }
 7366: 
 7367: .LC_hcell {
 7368:   padding:3px 15px 3px 15px;
 7369:   margin: 0;
 7370:   background-color:$tabbg;
 7371:   color:$fontmenu;
 7372:   border-bottom:solid 1px $lg_border_color;
 7373: }
 7374: 
 7375: .LC_Box > .LC_hcell {
 7376:   margin: 0 -10px 10px -10px;
 7377: }
 7378: 
 7379: .LC_noBorder {
 7380:   border: 0;
 7381: }
 7382: 
 7383: .LC_FormSectionClearButton input {
 7384:   background-color:transparent;
 7385:   border: none;
 7386:   cursor:pointer;
 7387:   text-decoration:underline;
 7388: }
 7389: 
 7390: .LC_help_open_topic {
 7391:   color: #FFFFFF;
 7392:   background-color: #EEEEFF;
 7393:   margin: 1px;
 7394:   padding: 4px;
 7395:   border: 1px solid #000033;
 7396:   white-space: nowrap;
 7397:   /* vertical-align: middle; */
 7398: }
 7399: 
 7400: dl,
 7401: ul,
 7402: div,
 7403: fieldset {
 7404:   margin: 10px 10px 10px 0;
 7405:   /* overflow: hidden; */
 7406: }
 7407: 
 7408: article.geogebraweb div {
 7409:     margin: 0;
 7410: }
 7411: 
 7412: fieldset > legend {
 7413:   font-weight: bold;
 7414:   padding: 0 5px 0 5px;
 7415: }
 7416: 
 7417: #LC_nav_bar {
 7418:   float: left;
 7419:   background-color: $pgbg_or_bgcolor;
 7420:   margin: 0 0 2px 0;
 7421: }
 7422: 
 7423: #LC_realm {
 7424:   margin: 0.2em 0 0 0;
 7425:   padding: 0;
 7426:   font-weight: bold;
 7427:   text-align: center;
 7428:   background-color: $pgbg_or_bgcolor;
 7429: }
 7430: 
 7431: #LC_nav_bar em {
 7432:   font-weight: bold;
 7433:   font-style: normal;
 7434: }
 7435: 
 7436: ol.LC_primary_menu {
 7437:   margin: 0;
 7438:   padding: 0;
 7439: }
 7440: 
 7441: ol#LC_PathBreadcrumbs {
 7442:   margin: 0;
 7443: }
 7444: 
 7445: ol.LC_primary_menu li {
 7446:   color: RGB(80, 80, 80);
 7447:   vertical-align: middle;
 7448:   text-align: left;
 7449:   list-style: none;
 7450:   position: relative;
 7451:   float: left;
 7452:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7453:   line-height: 1.5em;
 7454: }
 7455: 
 7456: ol.LC_primary_menu li a,
 7457: ol.LC_primary_menu li p {
 7458:   display: block;
 7459:   margin: 0;
 7460:   padding: 0 5px 0 10px;
 7461:   text-decoration: none;
 7462: }
 7463: 
 7464: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7465:   display: inline-block;
 7466:   width: 95%;
 7467:   text-align: left;
 7468: }
 7469: 
 7470: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7471:   display: inline-block;	
 7472:   width: 5%;
 7473:   float: right;
 7474:   text-align: right;
 7475:   font-size: 70%;
 7476: }
 7477: 
 7478: ol.LC_primary_menu ul {
 7479:   display: none;
 7480:   width: 15em;
 7481:   background-color: $data_table_light;
 7482:   position: absolute;
 7483:   top: 100%;
 7484: }
 7485: 
 7486: ol.LC_primary_menu ul ul {
 7487:   left: 100%;
 7488:   top: 0;
 7489: }
 7490: 
 7491: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7492:   display: block;
 7493:   position: absolute;
 7494:   margin: 0;
 7495:   padding: 0;
 7496:   z-index: 2;
 7497: }
 7498: 
 7499: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7500: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7501:   font-size: 90%;
 7502:   vertical-align: top;
 7503:   float: none;
 7504:   border-left: 1px solid black;
 7505:   border-right: 1px solid black;
 7506: /* A dark bottom border to visualize different menu options; 
 7507: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7508:   border-bottom: 1px solid $data_table_dark; 
 7509: }
 7510: 
 7511: ol.LC_primary_menu li li p:hover {
 7512:   color:$button_hover;
 7513:   text-decoration:none;
 7514:   background-color:$data_table_dark;
 7515: }
 7516: 
 7517: ol.LC_primary_menu li li a:hover {
 7518:    color:$button_hover;
 7519:    background-color:$data_table_dark;
 7520: }
 7521: 
 7522: /* Font-size equal to the size of the predecessors*/
 7523: ol.LC_primary_menu li:hover li li {
 7524:   font-size: 100%;
 7525: }
 7526: 
 7527: ol.LC_primary_menu li img {
 7528:   vertical-align: bottom;
 7529:   height: 1.1em;
 7530:   margin: 0.2em 0 0 0;
 7531: }
 7532: 
 7533: ol.LC_primary_menu a {
 7534:   color: RGB(80, 80, 80);
 7535:   text-decoration: none;
 7536: }
 7537: 
 7538: ol.LC_primary_menu a.LC_new_message {
 7539:   font-weight:bold;
 7540:   color: darkred;
 7541: }
 7542: 
 7543: ol.LC_docs_parameters {
 7544:   margin-left: 0;
 7545:   padding: 0;
 7546:   list-style: none;
 7547: }
 7548: 
 7549: ol.LC_docs_parameters li {
 7550:   margin: 0;
 7551:   padding-right: 20px;
 7552:   display: inline;
 7553: }
 7554: 
 7555: ol.LC_docs_parameters li:before {
 7556:   content: "\\002022 \\0020";
 7557: }
 7558: 
 7559: li.LC_docs_parameters_title {
 7560:   font-weight: bold;
 7561: }
 7562: 
 7563: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7564:   content: "";
 7565: }
 7566: 
 7567: ul#LC_secondary_menu {
 7568:   clear: right;
 7569:   color: $fontmenu;
 7570:   background: $tabbg;
 7571:   list-style: none;
 7572:   padding: 0;
 7573:   margin: 0;
 7574:   width: 100%;
 7575:   text-align: left;
 7576:   float: left;
 7577: }
 7578: 
 7579: ul#LC_secondary_menu li {
 7580:   font-weight: bold;
 7581:   line-height: 1.8em;
 7582:   border-right: 1px solid black;
 7583:   float: left;
 7584: }
 7585: 
 7586: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7587:   background-color: $data_table_light;
 7588: }
 7589: 
 7590: ul#LC_secondary_menu li a {
 7591:   padding: 0 0.8em;
 7592: }
 7593: 
 7594: ul#LC_secondary_menu li ul {
 7595:   display: none;
 7596: }
 7597: 
 7598: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7599:   display: block;
 7600:   position: absolute;
 7601:   margin: 0;
 7602:   padding: 0;
 7603:   list-style:none;
 7604:   float: none;
 7605:   background-color: $data_table_light;
 7606:   z-index: 2;
 7607:   margin-left: -1px;
 7608: }
 7609: 
 7610: ul#LC_secondary_menu li ul li {
 7611:   font-size: 90%;
 7612:   vertical-align: top;
 7613:   border-left: 1px solid black;
 7614:   border-right: 1px solid black;
 7615:   background-color: $data_table_light;
 7616:   list-style:none;
 7617:   float: none;
 7618: }
 7619: 
 7620: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7621:   background-color: $data_table_dark;
 7622: }
 7623: 
 7624: ul.LC_TabContent {
 7625:   display:block;
 7626:   background: $sidebg;
 7627:   border-bottom: solid 1px $lg_border_color;
 7628:   list-style:none;
 7629:   margin: -1px -10px 0 -10px;
 7630:   padding: 0;
 7631: }
 7632: 
 7633: ul.LC_TabContent li,
 7634: ul.LC_TabContentBigger li {
 7635:   float:left;
 7636: }
 7637: 
 7638: ul#LC_secondary_menu li a {
 7639:   color: $fontmenu;
 7640:   text-decoration: none;
 7641: }
 7642: 
 7643: ul.LC_TabContent {
 7644:   min-height:20px;
 7645: }
 7646: 
 7647: ul.LC_TabContent li {
 7648:   vertical-align:middle;
 7649:   padding: 0 16px 0 10px;
 7650:   background-color:$tabbg;
 7651:   border-bottom:solid 1px $lg_border_color;
 7652:   border-left: solid 1px $font;
 7653: }
 7654: 
 7655: ul.LC_TabContent .right {
 7656:   float:right;
 7657: }
 7658: 
 7659: ul.LC_TabContent li a,
 7660: ul.LC_TabContent li {
 7661:   color:rgb(47,47,47);
 7662:   text-decoration:none;
 7663:   font-size:95%;
 7664:   font-weight:bold;
 7665:   min-height:20px;
 7666: }
 7667: 
 7668: ul.LC_TabContent li a:hover,
 7669: ul.LC_TabContent li a:focus {
 7670:   color: $button_hover;
 7671:   background:none;
 7672:   outline:none;
 7673: }
 7674: 
 7675: ul.LC_TabContent li:hover {
 7676:   color: $button_hover;
 7677:   cursor:pointer;
 7678: }
 7679: 
 7680: ul.LC_TabContent li.active {
 7681:   color: $font;
 7682:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7683:   border-bottom:solid 1px #FFFFFF;
 7684:   cursor: default;
 7685: }
 7686: 
 7687: ul.LC_TabContent li.active a {
 7688:   color:$font;
 7689:   background:#FFFFFF;
 7690:   outline: none;
 7691: }
 7692: 
 7693: ul.LC_TabContent li.goback {
 7694:   float: left;
 7695:   border-left: none;
 7696: }
 7697: 
 7698: #maincoursedoc {
 7699:   clear:both;
 7700: }
 7701: 
 7702: ul.LC_TabContentBigger {
 7703:   display:block;
 7704:   list-style:none;
 7705:   padding: 0;
 7706: }
 7707: 
 7708: ul.LC_TabContentBigger li {
 7709:   vertical-align:bottom;
 7710:   height: 30px;
 7711:   font-size:110%;
 7712:   font-weight:bold;
 7713:   color: #737373;
 7714: }
 7715: 
 7716: ul.LC_TabContentBigger li.active {
 7717:   position: relative;
 7718:   top: 1px;
 7719: }
 7720: 
 7721: ul.LC_TabContentBigger li a {
 7722:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7723:   height: 30px;
 7724:   line-height: 30px;
 7725:   text-align: center;
 7726:   display: block;
 7727:   text-decoration: none;
 7728:   outline: none;  
 7729: }
 7730: 
 7731: ul.LC_TabContentBigger li.active a {
 7732:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7733:   color:$font;
 7734: }
 7735: 
 7736: ul.LC_TabContentBigger li b {
 7737:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7738:   display: block;
 7739:   float: left;
 7740:   padding: 0 30px;
 7741:   border-bottom: 1px solid $lg_border_color;
 7742: }
 7743: 
 7744: ul.LC_TabContentBigger li:hover b {
 7745:   color:$button_hover;
 7746: }
 7747: 
 7748: ul.LC_TabContentBigger li.active b {
 7749:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7750:   color:$font;
 7751:   border: 0;
 7752: }
 7753: 
 7754: 
 7755: ul.LC_CourseBreadcrumbs {
 7756:   background: $sidebg;
 7757:   height: 2em;
 7758:   padding-left: 10px;
 7759:   margin: 0;
 7760:   list-style-position: inside;
 7761: }
 7762: 
 7763: ol#LC_MenuBreadcrumbs,
 7764: ol#LC_PathBreadcrumbs {
 7765:   padding-left: 10px;
 7766:   margin: 0;
 7767:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7768: }
 7769: 
 7770: ol#LC_MenuBreadcrumbs li,
 7771: ol#LC_PathBreadcrumbs li,
 7772: ul.LC_CourseBreadcrumbs li {
 7773:   display: inline;
 7774:   white-space: normal;  
 7775: }
 7776: 
 7777: ol#LC_MenuBreadcrumbs li a,
 7778: ul.LC_CourseBreadcrumbs li a {
 7779:   text-decoration: none;
 7780:   font-size:90%;
 7781: }
 7782: 
 7783: ol#LC_MenuBreadcrumbs h1 {
 7784:   display: inline;
 7785:   font-size: 90%;
 7786:   line-height: 2.5em;
 7787:   margin: 0;
 7788:   padding: 0;
 7789: }
 7790: 
 7791: ol#LC_PathBreadcrumbs li a {
 7792:   text-decoration:none;
 7793:   font-size:100%;
 7794:   font-weight:bold;
 7795: }
 7796: 
 7797: .LC_Box {
 7798:   border: solid 1px $lg_border_color;
 7799:   padding: 0 10px 10px 10px;
 7800: }
 7801: 
 7802: .LC_DocsBox {
 7803:   border: solid 1px $lg_border_color;
 7804:   padding: 0 0 10px 10px;
 7805: }
 7806: 
 7807: .LC_AboutMe_Image {
 7808:   float:left;
 7809:   margin-right:10px;
 7810: }
 7811: 
 7812: .LC_Clear_AboutMe_Image {
 7813:   clear:left;
 7814: }
 7815: 
 7816: dl.LC_ListStyleClean dt {
 7817:   padding-right: 5px;
 7818:   display: table-header-group;
 7819: }
 7820: 
 7821: dl.LC_ListStyleClean dd {
 7822:   display: table-row;
 7823: }
 7824: 
 7825: .LC_ListStyleClean,
 7826: .LC_ListStyleSimple,
 7827: .LC_ListStyleNormal,
 7828: .LC_ListStyleSpecial {
 7829:   /* display:block; */
 7830:   list-style-position: inside;
 7831:   list-style-type: none;
 7832:   overflow: hidden;
 7833:   padding: 0;
 7834: }
 7835: 
 7836: .LC_ListStyleSimple li,
 7837: .LC_ListStyleSimple dd,
 7838: .LC_ListStyleNormal li,
 7839: .LC_ListStyleNormal dd,
 7840: .LC_ListStyleSpecial li,
 7841: .LC_ListStyleSpecial dd {
 7842:   margin: 0;
 7843:   padding: 5px 5px 5px 10px;
 7844:   clear: both;
 7845: }
 7846: 
 7847: .LC_ListStyleClean li,
 7848: .LC_ListStyleClean dd {
 7849:   padding-top: 0;
 7850:   padding-bottom: 0;
 7851: }
 7852: 
 7853: .LC_ListStyleSimple dd,
 7854: .LC_ListStyleSimple li {
 7855:   border-bottom: solid 1px $lg_border_color;
 7856: }
 7857: 
 7858: .LC_ListStyleSpecial li,
 7859: .LC_ListStyleSpecial dd {
 7860:   list-style-type: none;
 7861:   background-color: RGB(220, 220, 220);
 7862:   margin-bottom: 4px;
 7863: }
 7864: 
 7865: table.LC_SimpleTable {
 7866:   margin:5px;
 7867:   border:solid 1px $lg_border_color;
 7868: }
 7869: 
 7870: table.LC_SimpleTable tr {
 7871:   padding: 0;
 7872:   border:solid 1px $lg_border_color;
 7873: }
 7874: 
 7875: table.LC_SimpleTable thead {
 7876:   background:rgb(220,220,220);
 7877: }
 7878: 
 7879: div.LC_columnSection {
 7880:   display: block;
 7881:   clear: both;
 7882:   overflow: hidden;
 7883:   margin: 0;
 7884: }
 7885: 
 7886: div.LC_columnSection>* {
 7887:   float: left;
 7888:   margin: 10px 20px 10px 0;
 7889:   overflow:hidden;
 7890: }
 7891: 
 7892: table em {
 7893:   font-weight: bold;
 7894:   font-style: normal;
 7895: }
 7896: 
 7897: table.LC_tableBrowseRes,
 7898: table.LC_tableOfContent {
 7899:   border:none;
 7900:   border-spacing: 1px;
 7901:   padding: 3px;
 7902:   background-color: #FFFFFF;
 7903:   font-size: 90%;
 7904: }
 7905: 
 7906: table.LC_tableOfContent {
 7907:   border-collapse: collapse;
 7908: }
 7909: 
 7910: table.LC_tableBrowseRes a,
 7911: table.LC_tableOfContent a {
 7912:   background-color: transparent;
 7913:   text-decoration: none;
 7914: }
 7915: 
 7916: table.LC_tableOfContent img {
 7917:   border: none;
 7918:   height: 1.3em;
 7919:   vertical-align: text-bottom;
 7920:   margin-right: 0.3em;
 7921: }
 7922: 
 7923: a#LC_content_toolbar_firsthomework {
 7924:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7925: }
 7926: 
 7927: a#LC_content_toolbar_everything {
 7928:   background-image:url(/res/adm/pages/show-all.gif);
 7929: }
 7930: 
 7931: a#LC_content_toolbar_uncompleted {
 7932:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7933: }
 7934: 
 7935: #LC_content_toolbar_clearbubbles {
 7936:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7937: }
 7938: 
 7939: a#LC_content_toolbar_changefolder {
 7940:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7941: }
 7942: 
 7943: a#LC_content_toolbar_changefolder_toggled {
 7944:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7945: }
 7946: 
 7947: a#LC_content_toolbar_edittoplevel {
 7948:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7949: }
 7950: 
 7951: ul#LC_toolbar li a:hover {
 7952:   background-position: bottom center;
 7953: }
 7954: 
 7955: ul#LC_toolbar {
 7956:   padding: 0;
 7957:   margin: 2px;
 7958:   list-style:none;
 7959:   position:relative;
 7960:   background-color:white;
 7961:   overflow: auto;
 7962: }
 7963: 
 7964: ul#LC_toolbar li {
 7965:   border:1px solid white;
 7966:   padding: 0;
 7967:   margin: 0;
 7968:   float: left;
 7969:   display:inline;
 7970:   vertical-align:middle;
 7971:   white-space: nowrap;
 7972: }
 7973: 
 7974: 
 7975: a.LC_toolbarItem {
 7976:   display:block;
 7977:   padding: 0;
 7978:   margin: 0;
 7979:   height: 32px;
 7980:   width: 32px;
 7981:   color:white;
 7982:   border: none;
 7983:   background-repeat:no-repeat;
 7984:   background-color:transparent;
 7985: }
 7986: 
 7987: ul.LC_funclist {
 7988:     margin: 0;
 7989:     padding: 0.5em 1em 0.5em 0;
 7990: }
 7991: 
 7992: ul.LC_funclist > li:first-child {
 7993:     font-weight:bold; 
 7994:     margin-left:0.8em;
 7995: }
 7996: 
 7997: ul.LC_funclist + ul.LC_funclist {
 7998:     /* 
 7999:        left border as a seperator if we have more than
 8000:        one list 
 8001:     */
 8002:     border-left: 1px solid $sidebg;
 8003:     /* 
 8004:        this hides the left border behind the border of the 
 8005:        outer box if element is wrapped to the next 'line' 
 8006:     */
 8007:     margin-left: -1px;
 8008: }
 8009: 
 8010: ul.LC_funclist li {
 8011:   display: inline;
 8012:   white-space: nowrap;
 8013:   margin: 0 0 0 25px;
 8014:   line-height: 150%;
 8015: }
 8016: 
 8017: .LC_hidden {
 8018:   display: none;
 8019: }
 8020: 
 8021: .LCmodal-overlay {
 8022: 		position:fixed;
 8023: 		top:0;
 8024: 		right:0;
 8025: 		bottom:0;
 8026: 		left:0;
 8027: 		height:100%;
 8028: 		width:100%;
 8029: 		margin:0;
 8030: 		padding:0;
 8031: 		background:#999;
 8032: 		opacity:.75;
 8033: 		filter: alpha(opacity=75);
 8034: 		-moz-opacity: 0.75;
 8035: 		z-index:101;
 8036: }
 8037: 
 8038: * html .LCmodal-overlay {   
 8039: 		position: absolute;
 8040: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8041: }
 8042: 
 8043: .LCmodal-window {
 8044: 		position:fixed;
 8045: 		top:50%;
 8046: 		left:50%;
 8047: 		margin:0;
 8048: 		padding:0;
 8049: 		z-index:102;
 8050: 	}
 8051: 
 8052: * html .LCmodal-window {
 8053: 		position:absolute;
 8054: }
 8055: 
 8056: .LCclose-window {
 8057: 		position:absolute;
 8058: 		width:32px;
 8059: 		height:32px;
 8060: 		right:8px;
 8061: 		top:8px;
 8062: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8063: 		text-indent:-99999px;
 8064: 		overflow:hidden;
 8065: 		cursor:pointer;
 8066: }
 8067: 
 8068: /*
 8069:   styles used for response display
 8070: */
 8071: div.LC_radiofoil, div.LC_rankfoil {
 8072:   margin: .5em 0em .5em 0em;
 8073: }
 8074: table.LC_itemgroup {
 8075:   margin-top: 1em;
 8076: }
 8077: 
 8078: /*
 8079:   styles used by TTH when "Default set of options to pass to tth/m
 8080:   when converting TeX" in course settings has been set
 8081: 
 8082:   option passed: -t
 8083: 
 8084: */
 8085: 
 8086: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8087: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8088: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8089: td div.norm {line-height:normal;}
 8090: 
 8091: /*
 8092:   option passed -y3
 8093: */
 8094: 
 8095: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8096: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8097: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8098: 
 8099: /*
 8100:   sections with roles, for content only
 8101: */
 8102: section[class^="role-"] {
 8103:   padding-left: 10px;
 8104:   padding-right: 5px;
 8105:   margin-top: 8px;
 8106:   margin-bottom: 8px;
 8107:   border: 1px solid #2A4;
 8108:   border-radius: 5px;
 8109:   box-shadow: 0px 1px 1px #BBB;
 8110: }
 8111: section[class^="role-"]>h1 {
 8112:   position: relative;
 8113:   margin: 0px;
 8114:   padding-top: 10px;
 8115:   padding-left: 40px;
 8116: }
 8117: section[class^="role-"]>h1:before {
 8118:   position: absolute;
 8119:   left: -5px;
 8120:   top: 5px;
 8121: }
 8122: section.role-activity>h1:before {
 8123:   content:url('/adm/daxe/images/section_icons/activity.png');
 8124: }
 8125: section.role-advice>h1:before {
 8126:   content:url('/adm/daxe/images/section_icons/advice.png');
 8127: }
 8128: section.role-bibliography>h1:before {
 8129:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8130: }
 8131: section.role-citation>h1:before {
 8132:   content:url('/adm/daxe/images/section_icons/citation.png');
 8133: }
 8134: section.role-conclusion>h1:before {
 8135:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8136: }
 8137: section.role-definition>h1:before {
 8138:   content:url('/adm/daxe/images/section_icons/definition.png');
 8139: }
 8140: section.role-demonstration>h1:before {
 8141:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8142: }
 8143: section.role-example>h1:before {
 8144:   content:url('/adm/daxe/images/section_icons/example.png');
 8145: }
 8146: section.role-explanation>h1:before {
 8147:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8148: }
 8149: section.role-introduction>h1:before {
 8150:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8151: }
 8152: section.role-method>h1:before {
 8153:   content:url('/adm/daxe/images/section_icons/method.png');
 8154: }
 8155: section.role-more_information>h1:before {
 8156:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8157: }
 8158: section.role-objectives>h1:before {
 8159:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8160: }
 8161: section.role-prerequisites>h1:before {
 8162:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8163: }
 8164: section.role-remark>h1:before {
 8165:   content:url('/adm/daxe/images/section_icons/remark.png');
 8166: }
 8167: section.role-reminder>h1:before {
 8168:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8169: }
 8170: section.role-summary>h1:before {
 8171:   content:url('/adm/daxe/images/section_icons/summary.png');
 8172: }
 8173: section.role-syntax>h1:before {
 8174:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8175: }
 8176: section.role-warning>h1:before {
 8177:   content:url('/adm/daxe/images/section_icons/warning.png');
 8178: }
 8179: 
 8180: #LC_minitab_header {
 8181:   float:left;
 8182:   width:100%;
 8183:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8184:   font-size:93%;
 8185:   line-height:normal;
 8186:   margin: 0.5em 0 0.5em 0;
 8187: }
 8188: #LC_minitab_header ul {
 8189:   margin:0;
 8190:   padding:10px 10px 0;
 8191:   list-style:none;
 8192: }
 8193: #LC_minitab_header li {
 8194:   float:left;
 8195:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8196:   margin:0;
 8197:   padding:0 0 0 9px;
 8198: }
 8199: #LC_minitab_header a {
 8200:   display:block;
 8201:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8202:   padding:5px 15px 4px 6px;
 8203: }
 8204: #LC_minitab_header #LC_current_minitab {
 8205:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8206: }
 8207: #LC_minitab_header #LC_current_minitab a {
 8208:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8209:   padding-bottom:5px;
 8210: }
 8211: 
 8212: 
 8213: END
 8214: }
 8215: 
 8216: =pod
 8217: 
 8218: =item * &headtag()
 8219: 
 8220: Returns a uniform footer for LON-CAPA web pages.
 8221: 
 8222: Inputs: $title - optional title for the head
 8223:         $head_extra - optional extra HTML to put inside the <head>
 8224:         $args - optional arguments
 8225:             force_register - if is true call registerurl so the remote is 
 8226:                              informed
 8227:             redirect       -> array ref of
 8228:                                    1- seconds before redirect occurs
 8229:                                    2- url to redirect to
 8230:                                    3- whether the side effect should occur
 8231:                            (side effect of setting 
 8232:                                $env{'internal.head.redirect'} to the url 
 8233:                                redirected too)
 8234:             domain         -> force to color decorate a page for a specific
 8235:                                domain
 8236:             function       -> force usage of a specific rolish color scheme
 8237:             bgcolor        -> override the default page bgcolor
 8238:             no_auto_mt_title
 8239:                            -> prevent &mt()ing the title arg
 8240: 
 8241: =cut
 8242: 
 8243: sub headtag {
 8244:     my ($title,$head_extra,$args) = @_;
 8245:     
 8246:     my $function = $args->{'function'} || &get_users_function();
 8247:     my $domain   = $args->{'domain'}   || &determinedomain();
 8248:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8249:     my $httphost = $args->{'use_absolute'};
 8250:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8251: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8252: 		   #time(),
 8253: 		   $env{'environment.color.timestamp'},
 8254: 		   $function,$domain,$bgcolor);
 8255: 
 8256:     $url = '/adm/css/'.&escape($url).'.css';
 8257: 
 8258:     my $result =
 8259: 	'<head>'.
 8260: 	&font_settings($args);
 8261: 
 8262:     my $inhibitprint;
 8263:     if ($args->{'print_suppress'}) {
 8264:         $inhibitprint = &print_suppression();
 8265:     }
 8266: 
 8267:     if (!$args->{'frameset'}) {
 8268: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8269:     }
 8270:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8271:         $result .= Apache::lonxml::display_title();
 8272:     }
 8273:     if (!$args->{'no_nav_bar'} 
 8274: 	&& !$args->{'only_body'}
 8275: 	&& !$args->{'frameset'}) {
 8276: 	$result .= &help_menu_js($httphost);
 8277:         $result.=&modal_window();
 8278:         $result.=&togglebox_script();
 8279:         $result.=&wishlist_window();
 8280:         $result.=&LCprogressbarUpdate_script();
 8281:     } else {
 8282:         if ($args->{'add_modal'}) {
 8283:            $result.=&modal_window();
 8284:         }
 8285:         if ($args->{'add_wishlist'}) {
 8286:            $result.=&wishlist_window();
 8287:         }
 8288:         if ($args->{'add_togglebox'}) {
 8289:            $result.=&togglebox_script();
 8290:         }
 8291:         if ($args->{'add_progressbar'}) {
 8292:            $result.=&LCprogressbarUpdate_script();
 8293:         }
 8294:     }
 8295:     if (ref($args->{'redirect'})) {
 8296: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8297: 	$url = &Apache::lonenc::check_encrypt($url);
 8298: 	if (!$inhibit_continue) {
 8299: 	    $env{'internal.head.redirect'} = $url;
 8300: 	}
 8301: 	$result.=<<ADDMETA
 8302: <meta http-equiv="pragma" content="no-cache" />
 8303: <meta http-equiv="Refresh" content="$time; url=$url" />
 8304: ADDMETA
 8305:     } else {
 8306:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8307:             my $requrl = $env{'request.uri'};
 8308:             if ($requrl eq '') {
 8309:                 $requrl = $ENV{'REQUEST_URI'};
 8310:                 $requrl =~ s/\?.+$//;
 8311:             }
 8312:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8313:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8314:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8315:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8316:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8317:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8318:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8319:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8320:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8321:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 8322:                             if (($newserver) && ($newserver ne $lonhost)) {
 8323:                                 my $numsec = 5;
 8324:                                 my $timeout = $numsec * 1000;
 8325:                                 my ($newurl,$locknum,%locks,$msg);
 8326:                                 if ($env{'request.role.adv'}) {
 8327:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 8328:                                 }
 8329:                                 my $disable_submit = 0;
 8330:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 8331:                                     $disable_submit = 1;
 8332:                                 }
 8333:                                 if ($locknum) {
 8334:                                     my @lockinfo = sort(values(%locks));
 8335:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 8336:                                            join(", ",sort(values(%locks)))."\\n".
 8337:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 8338:                                 } else {
 8339:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8340:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 8341:                                     }
 8342:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8343:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 8344:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8345:                                         $newurl .= '&role='.$env{'request.role'};
 8346:                                     }
 8347:                                     if ($env{'request.symb'}) {
 8348:                                         $newurl .= '&symb='.$env{'request.symb'};
 8349:                                     } else {
 8350:                                         $newurl .= '&origurl='.$requrl;
 8351:                                     }
 8352:                                 }
 8353:                                 &js_escape(\$msg);
 8354:                                 $result.=<<OFFLOAD
 8355: <meta http-equiv="pragma" content="no-cache" />
 8356: <script type="text/javascript">
 8357: // <![CDATA[
 8358: function LC_Offload_Now() {
 8359:     var dest = "$newurl";
 8360:     if (dest != '') {
 8361:         window.location.href="$newurl";
 8362:     }
 8363: }
 8364: \$(document).ready(function () {
 8365:     window.alert('$msg');
 8366:     if ($disable_submit) {
 8367:         \$(".LC_hwk_submit").prop("disabled", true);
 8368:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8369:     }
 8370:     setTimeout('LC_Offload_Now()', $timeout);
 8371: });
 8372: // ]]>
 8373: </script>
 8374: OFFLOAD
 8375:                             }
 8376:                         }
 8377:                     }
 8378:                 }
 8379:             }
 8380:         }
 8381:     }
 8382:     if (!defined($title)) {
 8383: 	$title = 'The LearningOnline Network with CAPA';
 8384:     }
 8385:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8386:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8387: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8388:     if (!$args->{'frameset'}) {
 8389:         $result .= ' /';
 8390:     }
 8391:     $result .= '>' 
 8392:         .$inhibitprint
 8393: 	.$head_extra;
 8394:     my $clientmobile;
 8395:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8396:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8397:     } else {
 8398:         $clientmobile = $env{'browser.mobile'};
 8399:     }
 8400:     if ($clientmobile) {
 8401:         $result .= '
 8402: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8403: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8404:     }
 8405:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8406:     return $result.'</head>';
 8407: }
 8408: 
 8409: =pod
 8410: 
 8411: =item * &font_settings()
 8412: 
 8413: Returns neccessary <meta> to set the proper encoding
 8414: 
 8415: Inputs: optional reference to HASH -- $args passed to &headtag()
 8416: 
 8417: =cut
 8418: 
 8419: sub font_settings {
 8420:     my ($args) = @_;
 8421:     my $headerstring='';
 8422:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8423:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8424:         $headerstring.=
 8425:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8426:         if (!$args->{'frameset'}) {
 8427: 	    $headerstring.= ' /';
 8428:         }
 8429: 	$headerstring .= '>'."\n";
 8430:     }
 8431:     return $headerstring;
 8432: }
 8433: 
 8434: =pod
 8435: 
 8436: =item * &print_suppression()
 8437: 
 8438: In course context returns css which causes the body to be blank when media="print",
 8439: if printout generation is unavailable for the current resource.
 8440: 
 8441: This could be because:
 8442: 
 8443: (a) printstartdate is in the future
 8444: 
 8445: (b) printenddate is in the past
 8446: 
 8447: (c) there is an active exam block with "printout"
 8448: functionality blocked
 8449: 
 8450: Users with pav, pfo or evb privileges are exempt.
 8451: 
 8452: Inputs: none
 8453: 
 8454: =cut
 8455: 
 8456: 
 8457: sub print_suppression {
 8458:     my $noprint;
 8459:     if ($env{'request.course.id'}) {
 8460:         my $scope = $env{'request.course.id'};
 8461:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8462:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8463:             return;
 8464:         }
 8465:         if ($env{'request.course.sec'} ne '') {
 8466:             $scope .= "/$env{'request.course.sec'}";
 8467:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8468:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8469:                 return;
 8470:             }
 8471:         }
 8472:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8473:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8474:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8475:         if ($blocked) {
 8476:             my $checkrole = "cm./$cdom/$cnum";
 8477:             if ($env{'request.course.sec'} ne '') {
 8478:                 $checkrole .= "/$env{'request.course.sec'}";
 8479:             }
 8480:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8481:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8482:                 $noprint = 1;
 8483:             }
 8484:         }
 8485:         unless ($noprint) {
 8486:             my $symb = &Apache::lonnet::symbread();
 8487:             if ($symb ne '') {
 8488:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8489:                 if (ref($navmap)) {
 8490:                     my $res = $navmap->getBySymb($symb);
 8491:                     if (ref($res)) {
 8492:                         if (!$res->resprintable()) {
 8493:                             $noprint = 1;
 8494:                         }
 8495:                     }
 8496:                 }
 8497:             }
 8498:         }
 8499:         if ($noprint) {
 8500:             return <<"ENDSTYLE";
 8501: <style type="text/css" media="print">
 8502:     body { display:none }
 8503: </style>
 8504: ENDSTYLE
 8505:         }
 8506:     }
 8507:     return;
 8508: }
 8509: 
 8510: =pod
 8511: 
 8512: =item * &xml_begin()
 8513: 
 8514: Returns the needed doctype and <html>
 8515: 
 8516: Inputs: none
 8517: 
 8518: =cut
 8519: 
 8520: sub xml_begin {
 8521:     my ($is_frameset) = @_;
 8522:     my $output='';
 8523: 
 8524:     if ($env{'browser.mathml'}) {
 8525: 	$output='<?xml version="1.0"?>'
 8526:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8527: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8528:             
 8529: #	    .'<!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">] >'
 8530: 	    .'<!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">'
 8531:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8532: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8533:     } elsif ($is_frameset) {
 8534:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8535:                 '<html>'."\n";
 8536:     } else {
 8537: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8538:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8539:     }
 8540:     return $output;
 8541: }
 8542: 
 8543: =pod
 8544: 
 8545: =item * &start_page()
 8546: 
 8547: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8548: 
 8549: Inputs:
 8550: 
 8551: =over 4
 8552: 
 8553: $title - optional title for the page
 8554: 
 8555: $head_extra - optional extra HTML to incude inside the <head>
 8556: 
 8557: $args - additional optional args supported are:
 8558: 
 8559: =over 8
 8560: 
 8561:              only_body      -> is true will set &bodytag() onlybodytag
 8562:                                     arg on
 8563:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8564:              add_entries    -> additional attributes to add to the  <body>
 8565:              domain         -> force to color decorate a page for a 
 8566:                                     specific domain
 8567:              function       -> force usage of a specific rolish color
 8568:                                     scheme
 8569:              redirect       -> see &headtag()
 8570:              bgcolor        -> override the default page bg color
 8571:              js_ready       -> return a string ready for being used in 
 8572:                                     a javascript writeln
 8573:              html_encode    -> return a string ready for being used in 
 8574:                                     a html attribute
 8575:              force_register -> if is true will turn on the &bodytag()
 8576:                                     $forcereg arg
 8577:              frameset       -> if true will start with a <frameset>
 8578:                                     rather than <body>
 8579:              skip_phases    -> hash ref of 
 8580:                                     head -> skip the <html><head> generation
 8581:                                     body -> skip all <body> generation
 8582:              no_auto_mt_title -> prevent &mt()ing the title arg
 8583:              bread_crumbs ->             Array containing breadcrumbs
 8584:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8585:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8586:                                     to lonhtmlcommon::breadcrumbs
 8587:              group          -> includes the current group, if page is for a 
 8588:                                specific group
 8589:              use_absolute   -> for request for external resource or syllabus, this
 8590:                                will contain https://<hostname> if server uses
 8591:                                https (as per hosts.tab), but request is for http
 8592:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8593: 
 8594: =back
 8595: 
 8596: =back
 8597: 
 8598: =cut
 8599: 
 8600: sub start_page {
 8601:     my ($title,$head_extra,$args) = @_;
 8602:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8603: 
 8604:     $env{'internal.start_page'}++;
 8605:     my ($result,@advtools);
 8606: 
 8607:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8608:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8609:     }
 8610:     
 8611:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8612: 	if ($args->{'frameset'}) {
 8613: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8614: 						$args->{'add_entries'});
 8615: 	    $result .= "\n<frameset $attr_string>\n";
 8616:         } else {
 8617:             $result .=
 8618:                 &bodytag($title, 
 8619:                          $args->{'function'},       $args->{'add_entries'},
 8620:                          $args->{'only_body'},      $args->{'domain'},
 8621:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8622:                          $args->{'bgcolor'},        $args,
 8623:                          \@advtools);
 8624:         }
 8625:     }
 8626: 
 8627:     if ($args->{'js_ready'}) {
 8628: 		$result = &js_ready($result);
 8629:     }
 8630:     if ($args->{'html_encode'}) {
 8631: 		$result = &html_encode($result);
 8632:     }
 8633: 
 8634:     # Preparation for new and consistent functionlist at top of screen
 8635:     # if ($args->{'functionlist'}) {
 8636:     #            $result .= &build_functionlist();
 8637:     #}
 8638: 
 8639:     # Don't add anything more if only_body wanted or in const space
 8640:     return $result if    $args->{'only_body'} 
 8641:                       || $env{'request.state'} eq 'construct';
 8642: 
 8643:     #Breadcrumbs
 8644:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8645: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8646: 		#if any br links exists, add them to the breadcrumbs
 8647: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8648: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8649: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8650: 			}
 8651: 		}
 8652:                 # if @advtools array contains items add then to the breadcrumbs
 8653:                 if (@advtools > 0) {
 8654:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8655:                 }
 8656:                 my $menulink;
 8657:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8658:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8659:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 8660:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 8661:                      (!$env{'request.role.adv'}))) {
 8662:                     $menulink = 0;
 8663:                 } else {
 8664:                     undef($menulink);
 8665:                 }
 8666: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8667: 		if(exists($args->{'bread_crumbs_component'})){
 8668: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8669:                 } else {
 8670: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8671: 		}
 8672:     }
 8673:     return $result;
 8674: }
 8675: 
 8676: sub end_page {
 8677:     my ($args) = @_;
 8678:     $env{'internal.end_page'}++;
 8679:     my $result;
 8680:     if ($args->{'discussion'}) {
 8681: 	my ($target,$parser);
 8682: 	if (ref($args->{'discussion'})) {
 8683: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8684: 				$args->{'discussion'}{'parser'});
 8685: 	}
 8686: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8687:     }
 8688:     if ($args->{'frameset'}) {
 8689: 	$result .= '</frameset>';
 8690:     } else {
 8691: 	$result .= &endbodytag($args);
 8692:     }
 8693:     unless ($args->{'notbody'}) {
 8694:         $result .= "\n</html>";
 8695:     }
 8696: 
 8697:     if ($args->{'js_ready'}) {
 8698: 	$result = &js_ready($result);
 8699:     }
 8700: 
 8701:     if ($args->{'html_encode'}) {
 8702: 	$result = &html_encode($result);
 8703:     }
 8704: 
 8705:     return $result;
 8706: }
 8707: 
 8708: sub wishlist_window {
 8709:     return(<<'ENDWISHLIST');
 8710: <script type="text/javascript">
 8711: // <![CDATA[
 8712: // <!-- BEGIN LON-CAPA Internal
 8713: function set_wishlistlink(title, path) {
 8714:     if (!title) {
 8715:         title = document.title;
 8716:         title = title.replace(/^LON-CAPA /,'');
 8717:     }
 8718:     title = encodeURIComponent(title);
 8719:     title = title.replace("'","\\\'");
 8720:     if (!path) {
 8721:         path = location.pathname;
 8722:     }
 8723:     path = encodeURIComponent(path);
 8724:     path = path.replace("'","\\\'");
 8725:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8726:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8727: }
 8728: // END LON-CAPA Internal -->
 8729: // ]]>
 8730: </script>
 8731: ENDWISHLIST
 8732: }
 8733: 
 8734: sub modal_window {
 8735:     return(<<'ENDMODAL');
 8736: <script type="text/javascript">
 8737: // <![CDATA[
 8738: // <!-- BEGIN LON-CAPA Internal
 8739: var modalWindow = {
 8740: 	parent:"body",
 8741: 	windowId:null,
 8742: 	content:null,
 8743: 	width:null,
 8744: 	height:null,
 8745: 	close:function()
 8746: 	{
 8747: 	        $(".LCmodal-window").remove();
 8748: 	        $(".LCmodal-overlay").remove();
 8749: 	},
 8750: 	open:function()
 8751: 	{
 8752: 		var modal = "";
 8753: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8754: 		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;\">";
 8755: 		modal += this.content;
 8756: 		modal += "</div>";	
 8757: 
 8758: 		$(this.parent).append(modal);
 8759: 
 8760: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8761: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8762: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8763: 	}
 8764: };
 8765: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8766: 	{
 8767:                 source = source.replace(/'/g,"&#39;");
 8768: 		modalWindow.windowId = "myModal";
 8769: 		modalWindow.width = width;
 8770: 		modalWindow.height = height;
 8771: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8772: 		modalWindow.open();
 8773: 	};
 8774: // END LON-CAPA Internal -->
 8775: // ]]>
 8776: </script>
 8777: ENDMODAL
 8778: }
 8779: 
 8780: sub modal_link {
 8781:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8782:     unless ($width) { $width=480; }
 8783:     unless ($height) { $height=400; }
 8784:     unless ($scrolling) { $scrolling='yes'; }
 8785:     unless ($transparency) { $transparency='true'; }
 8786: 
 8787:     my $target_attr;
 8788:     if (defined($target)) {
 8789:         $target_attr = 'target="'.$target.'"';
 8790:     }
 8791:     return <<"ENDLINK";
 8792: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8793:            $linktext</a>
 8794: ENDLINK
 8795: }
 8796: 
 8797: sub modal_adhoc_script {
 8798:     my ($funcname,$width,$height,$content)=@_;
 8799:     return (<<ENDADHOC);
 8800: <script type="text/javascript">
 8801: // <![CDATA[
 8802:         var $funcname = function()
 8803:         {
 8804:                 modalWindow.windowId = "myModal";
 8805:                 modalWindow.width = $width;
 8806:                 modalWindow.height = $height;
 8807:                 modalWindow.content = '$content';
 8808:                 modalWindow.open();
 8809:         };  
 8810: // ]]>
 8811: </script>
 8812: ENDADHOC
 8813: }
 8814: 
 8815: sub modal_adhoc_inner {
 8816:     my ($funcname,$width,$height,$content)=@_;
 8817:     my $innerwidth=$width-20;
 8818:     $content=&js_ready(
 8819:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8820:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8821:                  $content.
 8822:                  &end_scrollbox().
 8823:                  &end_page()
 8824:              );
 8825:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8826: }
 8827: 
 8828: sub modal_adhoc_window {
 8829:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8830:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8831:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8832: }
 8833: 
 8834: sub modal_adhoc_launch {
 8835:     my ($funcname,$width,$height,$content)=@_;
 8836:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8837: <script type="text/javascript">
 8838: // <![CDATA[
 8839: $funcname();
 8840: // ]]>
 8841: </script>
 8842: ENDLAUNCH
 8843: }
 8844: 
 8845: sub modal_adhoc_close {
 8846:     return (<<ENDCLOSE);
 8847: <script type="text/javascript">
 8848: // <![CDATA[
 8849: modalWindow.close();
 8850: // ]]>
 8851: </script>
 8852: ENDCLOSE
 8853: }
 8854: 
 8855: sub togglebox_script {
 8856:    return(<<ENDTOGGLE);
 8857: <script type="text/javascript"> 
 8858: // <![CDATA[
 8859: function LCtoggleDisplay(id,hidetext,showtext) {
 8860:    link = document.getElementById(id + "link").childNodes[0];
 8861:    with (document.getElementById(id).style) {
 8862:       if (display == "none" ) {
 8863:           display = "inline";
 8864:           link.nodeValue = hidetext;
 8865:         } else {
 8866:           display = "none";
 8867:           link.nodeValue = showtext;
 8868:        }
 8869:    }
 8870: }
 8871: // ]]>
 8872: </script>
 8873: ENDTOGGLE
 8874: }
 8875: 
 8876: sub start_togglebox {
 8877:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8878:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8879:     unless ($showtext) { $showtext=&mt('show'); }
 8880:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8881:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8882:     return &start_data_table().
 8883:            &start_data_table_header_row().
 8884:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8885:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8886:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8887:            &end_data_table_header_row().
 8888:            '<tr id="'.$id.'" style="display:none""><td>';
 8889: }
 8890: 
 8891: sub end_togglebox {
 8892:     return '</td></tr>'.&end_data_table();
 8893: }
 8894: 
 8895: sub LCprogressbar_script {
 8896:    my ($id)=@_;
 8897:    return(<<ENDPROGRESS);
 8898: <script type="text/javascript">
 8899: // <![CDATA[
 8900: \$('#progressbar$id').progressbar({
 8901:   value: 0,
 8902:   change: function(event, ui) {
 8903:     var newVal = \$(this).progressbar('option', 'value');
 8904:     \$('.pblabel', this).text(LCprogressTxt);
 8905:   }
 8906: });
 8907: // ]]>
 8908: </script>
 8909: ENDPROGRESS
 8910: }
 8911: 
 8912: sub LCprogressbarUpdate_script {
 8913:    return(<<ENDPROGRESSUPDATE);
 8914: <style type="text/css">
 8915: .ui-progressbar { position:relative; }
 8916: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8917: </style>
 8918: <script type="text/javascript">
 8919: // <![CDATA[
 8920: var LCprogressTxt='---';
 8921: 
 8922: function LCupdateProgress(percent,progresstext,id) {
 8923:    LCprogressTxt=progresstext;
 8924:    if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 8925:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 8926:    } else {
 8927:        \$('#progressbar'+id).progressbar('value',percent);
 8928:    }
 8929: }
 8930: // ]]>
 8931: </script>
 8932: ENDPROGRESSUPDATE
 8933: }
 8934: 
 8935: my $LClastpercent;
 8936: my $LCidcnt;
 8937: my $LCcurrentid;
 8938: 
 8939: sub LCprogressbar {
 8940:     my ($r)=(@_);
 8941:     $LClastpercent=0;
 8942:     $LCidcnt++;
 8943:     $LCcurrentid=$$.'_'.$LCidcnt;
 8944:     my $starting=&mt('Starting');
 8945:     my $content=(<<ENDPROGBAR);
 8946:   <div id="progressbar$LCcurrentid">
 8947:     <span class="pblabel">$starting</span>
 8948:   </div>
 8949: ENDPROGBAR
 8950:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8951: }
 8952: 
 8953: sub LCprogressbarUpdate {
 8954:     my ($r,$val,$text)=@_;
 8955:     unless ($val) { 
 8956:        if ($LClastpercent) {
 8957:            $val=$LClastpercent;
 8958:        } else {
 8959:            $val=0;
 8960:        }
 8961:     }
 8962:     if ($val<0) { $val=0; }
 8963:     if ($val>100) { $val=0; }
 8964:     $LClastpercent=$val;
 8965:     unless ($text) { $text=$val.'%'; }
 8966:     $text=&js_ready($text);
 8967:     &r_print($r,<<ENDUPDATE);
 8968: <script type="text/javascript">
 8969: // <![CDATA[
 8970: LCupdateProgress($val,'$text','$LCcurrentid');
 8971: // ]]>
 8972: </script>
 8973: ENDUPDATE
 8974: }
 8975: 
 8976: sub LCprogressbarClose {
 8977:     my ($r)=@_;
 8978:     $LClastpercent=0;
 8979:     &r_print($r,<<ENDCLOSE);
 8980: <script type="text/javascript">
 8981: // <![CDATA[
 8982: \$("#progressbar$LCcurrentid").hide('slow'); 
 8983: // ]]>
 8984: </script>
 8985: ENDCLOSE
 8986: }
 8987: 
 8988: sub r_print {
 8989:     my ($r,$to_print)=@_;
 8990:     if ($r) {
 8991:       $r->print($to_print);
 8992:       $r->rflush();
 8993:     } else {
 8994:       print($to_print);
 8995:     }
 8996: }
 8997: 
 8998: sub html_encode {
 8999:     my ($result) = @_;
 9000: 
 9001:     $result = &HTML::Entities::encode($result,'<>&"');
 9002:     
 9003:     return $result;
 9004: }
 9005: 
 9006: sub js_ready {
 9007:     my ($result) = @_;
 9008: 
 9009:     $result =~ s/[\n\r]/ /xmsg;
 9010:     $result =~ s/\\/\\\\/xmsg;
 9011:     $result =~ s/'/\\'/xmsg;
 9012:     $result =~ s{</}{<\\/}xmsg;
 9013:     
 9014:     return $result;
 9015: }
 9016: 
 9017: sub validate_page {
 9018:     if (  exists($env{'internal.start_page'})
 9019: 	  &&     $env{'internal.start_page'} > 1) {
 9020: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9021: 				 $env{'internal.start_page'}.' '.
 9022: 				 $ENV{'request.filename'});
 9023:     }
 9024:     if (  exists($env{'internal.end_page'})
 9025: 	  &&     $env{'internal.end_page'} > 1) {
 9026: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9027: 				 $env{'internal.end_page'}.' '.
 9028: 				 $env{'request.filename'});
 9029:     }
 9030:     if (     exists($env{'internal.start_page'})
 9031: 	&& ! exists($env{'internal.end_page'})) {
 9032: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9033: 				 $env{'request.filename'});
 9034:     }
 9035:     if (   ! exists($env{'internal.start_page'})
 9036: 	&&   exists($env{'internal.end_page'})) {
 9037: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9038: 				 $env{'request.filename'});
 9039:     }
 9040: }
 9041: 
 9042: 
 9043: sub start_scrollbox {
 9044:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9045:     unless ($outerwidth) { $outerwidth='520px'; }
 9046:     unless ($width) { $width='500px'; }
 9047:     unless ($height) { $height='200px'; }
 9048:     my ($table_id,$div_id,$tdcol);
 9049:     if ($id ne '') {
 9050:         $table_id = ' id="table_'.$id.'"';
 9051:         $div_id = ' id="div_'.$id.'"';
 9052:     }
 9053:     if ($bgcolor ne '') {
 9054:         $tdcol = "background-color: $bgcolor;";
 9055:     }
 9056:     my $nicescroll_js;
 9057:     if ($env{'browser.mobile'}) {
 9058:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9059:     }
 9060:     return <<"END";
 9061: $nicescroll_js
 9062: 
 9063: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9064: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9065: END
 9066: }
 9067: 
 9068: sub end_scrollbox {
 9069:     return '</div></td></tr></table>';
 9070: }
 9071: 
 9072: sub nicescroll_javascript {
 9073:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9074:     my %options;
 9075:     if (ref($cursor) eq 'HASH') {
 9076:         %options = %{$cursor};
 9077:     }
 9078:     unless ($options{'railalign'} =~ /^left|right$/) {
 9079:         $options{'railalign'} = 'left';
 9080:     }
 9081:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9082:         my $function  = &get_users_function();
 9083:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9084:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9085:             $options{'cursorcolor'} = '#00F';
 9086:         }
 9087:     }
 9088:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9089:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9090:             $options{'cursoropacity'}='1.0';
 9091:         }
 9092:     } else {
 9093:         $options{'cursoropacity'}='1.0';
 9094:     }
 9095:     if ($options{'cursorfixedheight'} eq 'none') {
 9096:         delete($options{'cursorfixedheight'});
 9097:     } else {
 9098:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9099:     }
 9100:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9101:         delete($options{'railoffset'});
 9102:     }
 9103:     my @niceoptions;
 9104:     while (my($key,$value) = each(%options)) {
 9105:         if ($value =~ /^\{.+\}$/) {
 9106:             push(@niceoptions,$key.':'.$value);
 9107:         } else {
 9108:             push(@niceoptions,$key.':"'.$value.'"');
 9109:         }
 9110:     }
 9111:     my $nicescroll_js = '
 9112: $(document).ready(
 9113:       function() {
 9114:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9115:       }
 9116: );
 9117: ';
 9118:     if ($framecheck) {
 9119:         $nicescroll_js .= '
 9120: function expand_div(caller) {
 9121:     if (top === self) {
 9122:         document.getElementById("'.$id.'").style.width = "auto";
 9123:         document.getElementById("'.$id.'").style.height = "auto";
 9124:     } else {
 9125:         try {
 9126:             if (parent.frames) {
 9127:                 if (parent.frames.length > 1) {
 9128:                     var framesrc = parent.frames[1].location.href;
 9129:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9130:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9131:                         document.getElementById("'.$id.'").style.width = "auto";
 9132:                         document.getElementById("'.$id.'").style.height = "auto";
 9133:                     }
 9134:                 }
 9135:             }
 9136:         } catch (e) {
 9137:             return;
 9138:         }
 9139:     }
 9140:     return;
 9141: }
 9142: ';
 9143:     }
 9144:     if ($needjsready) {
 9145:         $nicescroll_js = '
 9146: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9147:     } else {
 9148:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9149:     }
 9150:     return $nicescroll_js;
 9151: }
 9152: 
 9153: sub simple_error_page {
 9154:     my ($r,$title,$msg,$args) = @_;
 9155:     if (ref($args) eq 'HASH') {
 9156:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9157:     } else {
 9158:         $msg = &mt($msg);
 9159:     }
 9160: 
 9161:     my $page =
 9162: 	&Apache::loncommon::start_page($title).
 9163: 	'<p class="LC_error">'.$msg.'</p>'.
 9164: 	&Apache::loncommon::end_page();
 9165:     if (ref($r)) {
 9166: 	$r->print($page);
 9167: 	return;
 9168:     }
 9169:     return $page;
 9170: }
 9171: 
 9172: {
 9173:     my @row_count;
 9174: 
 9175:     sub start_data_table_count {
 9176:         unshift(@row_count, 0);
 9177:         return;
 9178:     }
 9179: 
 9180:     sub end_data_table_count {
 9181:         shift(@row_count);
 9182:         return;
 9183:     }
 9184: 
 9185:     sub start_data_table {
 9186: 	my ($add_class,$id) = @_;
 9187: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9188:         my $table_id;
 9189:         if (defined($id)) {
 9190:             $table_id = ' id="'.$id.'"';
 9191:         }
 9192: 	&start_data_table_count();
 9193: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9194:     }
 9195: 
 9196:     sub end_data_table {
 9197: 	&end_data_table_count();
 9198: 	return '</table>'."\n";;
 9199:     }
 9200: 
 9201:     sub start_data_table_row {
 9202: 	my ($add_class, $id) = @_;
 9203: 	$row_count[0]++;
 9204: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9205: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9206:         $id = (' id="'.$id.'"') unless ($id eq '');
 9207:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9208:     }
 9209:     
 9210:     sub continue_data_table_row {
 9211: 	my ($add_class, $id) = @_;
 9212: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9213: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9214:         $id = (' id="'.$id.'"') unless ($id eq '');
 9215:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9216:     }
 9217: 
 9218:     sub end_data_table_row {
 9219: 	return '</tr>'."\n";;
 9220:     }
 9221: 
 9222:     sub start_data_table_empty_row {
 9223: #	$row_count[0]++;
 9224: 	return  '<tr class="LC_empty_row" >'."\n";;
 9225:     }
 9226: 
 9227:     sub end_data_table_empty_row {
 9228: 	return '</tr>'."\n";;
 9229:     }
 9230: 
 9231:     sub start_data_table_header_row {
 9232: 	return  '<tr class="LC_header_row">'."\n";;
 9233:     }
 9234: 
 9235:     sub end_data_table_header_row {
 9236: 	return '</tr>'."\n";;
 9237:     }
 9238: 
 9239:     sub data_table_caption {
 9240:         my $caption = shift;
 9241:         return "<caption class=\"LC_caption\">$caption</caption>";
 9242:     }
 9243: }
 9244: 
 9245: =pod
 9246: 
 9247: =item * &inhibit_menu_check($arg)
 9248: 
 9249: Checks for a inhibitmenu state and generates output to preserve it
 9250: 
 9251: Inputs:         $arg - can be any of
 9252:                      - undef - in which case the return value is a string 
 9253:                                to add  into arguments list of a uri
 9254:                      - 'input' - in which case the return value is a HTML
 9255:                                  <form> <input> field of type hidden to
 9256:                                  preserve the value
 9257:                      - a url - in which case the return value is the url with
 9258:                                the neccesary cgi args added to preserve the
 9259:                                inhibitmenu state
 9260:                      - a ref to a url - no return value, but the string is
 9261:                                         updated to include the neccessary cgi
 9262:                                         args to preserve the inhibitmenu state
 9263: 
 9264: =cut
 9265: 
 9266: sub inhibit_menu_check {
 9267:     my ($arg) = @_;
 9268:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9269:     if ($arg eq 'input') {
 9270: 	if ($env{'form.inhibitmenu'}) {
 9271: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9272: 	} else {
 9273: 	    return
 9274: 	}
 9275:     }
 9276:     if ($env{'form.inhibitmenu'}) {
 9277: 	if (ref($arg)) {
 9278: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9279: 	} elsif ($arg eq '') {
 9280: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9281: 	} else {
 9282: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9283: 	}
 9284:     }
 9285:     if (!ref($arg)) {
 9286: 	return $arg;
 9287:     }
 9288: }
 9289: 
 9290: ###############################################
 9291: 
 9292: =pod
 9293: 
 9294: =back
 9295: 
 9296: =head1 User Information Routines
 9297: 
 9298: =over 4
 9299: 
 9300: =item * &get_users_function()
 9301: 
 9302: Used by &bodytag to determine the current users primary role.
 9303: Returns either 'student','coordinator','admin', or 'author'.
 9304: 
 9305: =cut
 9306: 
 9307: ###############################################
 9308: sub get_users_function {
 9309:     my $function = 'norole';
 9310:     if ($env{'request.role'}=~/^(st)/) {
 9311:         $function='student';
 9312:     }
 9313:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9314:         $function='coordinator';
 9315:     }
 9316:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9317:         $function='admin';
 9318:     }
 9319:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9320:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9321:         $function='author';
 9322:     }
 9323:     return $function;
 9324: }
 9325: 
 9326: ###############################################
 9327: 
 9328: =pod
 9329: 
 9330: =item * &show_course()
 9331: 
 9332: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9333: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9334: 
 9335: Inputs:
 9336: None
 9337: 
 9338: Outputs:
 9339: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9340: 
 9341: =cut
 9342: 
 9343: ###############################################
 9344: sub show_course {
 9345:     my $course = !$env{'user.adv'};
 9346:     if (!$env{'user.adv'}) {
 9347:         foreach my $env (keys(%env)) {
 9348:             next if ($env !~ m/^user\.priv\./);
 9349:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9350:                 $course = 0;
 9351:                 last;
 9352:             }
 9353:         }
 9354:     }
 9355:     return $course;
 9356: }
 9357: 
 9358: ###############################################
 9359: 
 9360: =pod
 9361: 
 9362: =item * &check_user_status()
 9363: 
 9364: Determines current status of supplied role for a
 9365: specific user. Roles can be active, previous or future.
 9366: 
 9367: Inputs: 
 9368: user's domain, user's username, course's domain,
 9369: course's number, optional section ID.
 9370: 
 9371: Outputs:
 9372: role status: active, previous or future. 
 9373: 
 9374: =cut
 9375: 
 9376: sub check_user_status {
 9377:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9378:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9379:     my @uroles = keys(%userinfo);
 9380:     my $srchstr;
 9381:     my $active_chk = 'none';
 9382:     my $now = time;
 9383:     if (@uroles > 0) {
 9384:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9385:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9386:         } else {
 9387:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9388:         }
 9389:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9390:             my $role_end = 0;
 9391:             my $role_start = 0;
 9392:             $active_chk = 'active';
 9393:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9394:                 $role_end = $1;
 9395:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9396:                     $role_start = $1;
 9397:                 }
 9398:             }
 9399:             if ($role_start > 0) {
 9400:                 if ($now < $role_start) {
 9401:                     $active_chk = 'future';
 9402:                 }
 9403:             }
 9404:             if ($role_end > 0) {
 9405:                 if ($now > $role_end) {
 9406:                     $active_chk = 'previous';
 9407:                 }
 9408:             }
 9409:         }
 9410:     }
 9411:     return $active_chk;
 9412: }
 9413: 
 9414: ###############################################
 9415: 
 9416: =pod
 9417: 
 9418: =item * &get_sections()
 9419: 
 9420: Determines all the sections for a course including
 9421: sections with students and sections containing other roles.
 9422: Incoming parameters: 
 9423: 
 9424: 1. domain
 9425: 2. course number 
 9426: 3. reference to array containing roles for which sections should 
 9427: be gathered (optional).
 9428: 4. reference to array containing status types for which sections 
 9429: should be gathered (optional).
 9430: 
 9431: If the third argument is undefined, sections are gathered for any role. 
 9432: If the fourth argument is undefined, sections are gathered for any status.
 9433: Permissible values are 'active' or 'future' or 'previous'.
 9434:  
 9435: Returns section hash (keys are section IDs, values are
 9436: number of users in each section), subject to the
 9437: optional roles filter, optional status filter 
 9438: 
 9439: =cut
 9440: 
 9441: ###############################################
 9442: sub get_sections {
 9443:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9444:     if (!defined($cdom) || !defined($cnum)) {
 9445:         my $cid =  $env{'request.course.id'};
 9446: 
 9447: 	return if (!defined($cid));
 9448: 
 9449:         $cdom = $env{'course.'.$cid.'.domain'};
 9450:         $cnum = $env{'course.'.$cid.'.num'};
 9451:     }
 9452: 
 9453:     my %sectioncount;
 9454:     my $now = time;
 9455: 
 9456:     my $check_students = 1;
 9457:     my $only_students = 0;
 9458:     if (ref($possible_roles) eq 'ARRAY') {
 9459:         if (grep(/^st$/,@{$possible_roles})) {
 9460:             if (@{$possible_roles} == 1) {
 9461:                 $only_students = 1;
 9462:             }
 9463:         } else {
 9464:             $check_students = 0;
 9465:         }
 9466:     }
 9467: 
 9468:     if ($check_students) { 
 9469: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9470: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9471: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9472:         my $start_index = &Apache::loncoursedata::CL_START();
 9473:         my $end_index = &Apache::loncoursedata::CL_END();
 9474:         my $status;
 9475: 	while (my ($student,$data) = each(%$classlist)) {
 9476: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9477: 				                     $data->[$status_index],
 9478:                                                      $data->[$start_index],
 9479:                                                      $data->[$end_index]);
 9480:             if ($stu_status eq 'Active') {
 9481:                 $status = 'active';
 9482:             } elsif ($end < $now) {
 9483:                 $status = 'previous';
 9484:             } elsif ($start > $now) {
 9485:                 $status = 'future';
 9486:             } 
 9487: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9488:                 if ((!defined($possible_status)) || (($status ne '') && 
 9489:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9490: 		    $sectioncount{$section}++;
 9491:                 }
 9492: 	    }
 9493: 	}
 9494:     }
 9495:     if ($only_students) {
 9496:         return %sectioncount;
 9497:     }
 9498:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9499:     foreach my $user (sort(keys(%courseroles))) {
 9500: 	if ($user !~ /^(\w{2})/) { next; }
 9501: 	my ($role) = ($user =~ /^(\w{2})/);
 9502: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9503: 	my ($section,$status);
 9504: 	if ($role eq 'cr' &&
 9505: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9506: 	    $section=$1;
 9507: 	}
 9508: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9509: 	if (!defined($section) || $section eq '-1') { next; }
 9510:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9511:         if ($end == -1 && $start == -1) {
 9512:             next; #deleted role
 9513:         }
 9514:         if (!defined($possible_status)) { 
 9515:             $sectioncount{$section}++;
 9516:         } else {
 9517:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9518:                 $status = 'active';
 9519:             } elsif ($end < $now) {
 9520:                 $status = 'future';
 9521:             } elsif ($start > $now) {
 9522:                 $status = 'previous';
 9523:             }
 9524:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9525:                 $sectioncount{$section}++;
 9526:             }
 9527:         }
 9528:     }
 9529:     return %sectioncount;
 9530: }
 9531: 
 9532: ###############################################
 9533: 
 9534: =pod
 9535: 
 9536: =item * &get_course_users()
 9537: 
 9538: Retrieves usernames:domains for users in the specified course
 9539: with specific role(s), and access status. 
 9540: 
 9541: Incoming parameters:
 9542: 1. course domain
 9543: 2. course number
 9544: 3. access status: users must have - either active, 
 9545: previous, future, or all.
 9546: 4. reference to array of permissible roles
 9547: 5. reference to array of section restrictions (optional)
 9548: 6. reference to results object (hash of hashes).
 9549: 7. reference to optional userdata hash
 9550: 8. reference to optional statushash
 9551: 9. flag if privileged users (except those set to unhide in
 9552:    course settings) should be excluded    
 9553: Keys of top level results hash are roles.
 9554: Keys of inner hashes are username:domain, with 
 9555: values set to access type.
 9556: Optional userdata hash returns an array with arguments in the 
 9557: same order as loncoursedata::get_classlist() for student data.
 9558: 
 9559: Optional statushash returns
 9560: 
 9561: Entries for end, start, section and status are blank because
 9562: of the possibility of multiple values for non-student roles.
 9563: 
 9564: =cut
 9565: 
 9566: ###############################################
 9567: 
 9568: sub get_course_users {
 9569:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9570:     my %idx = ();
 9571:     my %seclists;
 9572: 
 9573:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9574:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9575:     $idx{end} = &Apache::loncoursedata::CL_END();
 9576:     $idx{start} = &Apache::loncoursedata::CL_START();
 9577:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9578:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9579:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9580:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9581: 
 9582:     if (grep(/^st$/,@{$roles})) {
 9583:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9584:         my $now = time;
 9585:         foreach my $student (keys(%{$classlist})) {
 9586:             my $match = 0;
 9587:             my $secmatch = 0;
 9588:             my $section = $$classlist{$student}[$idx{section}];
 9589:             my $status = $$classlist{$student}[$idx{status}];
 9590:             if ($section eq '') {
 9591:                 $section = 'none';
 9592:             }
 9593:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9594:                 if (grep(/^all$/,@{$sections})) {
 9595:                     $secmatch = 1;
 9596:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9597:                     if (grep(/^none$/,@{$sections})) {
 9598:                         $secmatch = 1;
 9599:                     }
 9600:                 } else {  
 9601: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9602: 		        $secmatch = 1;
 9603:                     }
 9604: 		}
 9605:                 if (!$secmatch) {
 9606:                     next;
 9607:                 }
 9608:             }
 9609:             if (defined($$types{'active'})) {
 9610:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9611:                     push(@{$$users{st}{$student}},'active');
 9612:                     $match = 1;
 9613:                 }
 9614:             }
 9615:             if (defined($$types{'previous'})) {
 9616:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9617:                     push(@{$$users{st}{$student}},'previous');
 9618:                     $match = 1;
 9619:                 }
 9620:             }
 9621:             if (defined($$types{'future'})) {
 9622:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9623:                     push(@{$$users{st}{$student}},'future');
 9624:                     $match = 1;
 9625:                 }
 9626:             }
 9627:             if ($match) {
 9628:                 push(@{$seclists{$student}},$section);
 9629:                 if (ref($userdata) eq 'HASH') {
 9630:                     $$userdata{$student} = $$classlist{$student};
 9631:                 }
 9632:                 if (ref($statushash) eq 'HASH') {
 9633:                     $statushash->{$student}{'st'}{$section} = $status;
 9634:                 }
 9635:             }
 9636:         }
 9637:     }
 9638:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9639:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9640:         my $now = time;
 9641:         my %displaystatus = ( previous => 'Expired',
 9642:                               active   => 'Active',
 9643:                               future   => 'Future',
 9644:                             );
 9645:         my (%nothide,@possdoms);
 9646:         if ($hidepriv) {
 9647:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9648:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9649:                 if ($user !~ /:/) {
 9650:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9651:                 } else {
 9652:                     $nothide{$user} = 1;
 9653:                 }
 9654:             }
 9655:             my @possdoms = ($cdom);
 9656:             if ($coursehash{'checkforpriv'}) {
 9657:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9658:             }
 9659:         }
 9660:         foreach my $person (sort(keys(%coursepersonnel))) {
 9661:             my $match = 0;
 9662:             my $secmatch = 0;
 9663:             my $status;
 9664:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9665:             $user =~ s/:$//;
 9666:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9667:             if ($end == -1 || $start == -1) {
 9668:                 next;
 9669:             }
 9670:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9671:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9672:                 my ($uname,$udom) = split(/:/,$user);
 9673:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9674:                     if (grep(/^all$/,@{$sections})) {
 9675:                         $secmatch = 1;
 9676:                     } elsif ($usec eq '') {
 9677:                         if (grep(/^none$/,@{$sections})) {
 9678:                             $secmatch = 1;
 9679:                         }
 9680:                     } else {
 9681:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9682:                             $secmatch = 1;
 9683:                         }
 9684:                     }
 9685:                     if (!$secmatch) {
 9686:                         next;
 9687:                     }
 9688:                 }
 9689:                 if ($usec eq '') {
 9690:                     $usec = 'none';
 9691:                 }
 9692:                 if ($uname ne '' && $udom ne '') {
 9693:                     if ($hidepriv) {
 9694:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9695:                             (!$nothide{$uname.':'.$udom})) {
 9696:                             next;
 9697:                         }
 9698:                     }
 9699:                     if ($end > 0 && $end < $now) {
 9700:                         $status = 'previous';
 9701:                     } elsif ($start > $now) {
 9702:                         $status = 'future';
 9703:                     } else {
 9704:                         $status = 'active';
 9705:                     }
 9706:                     foreach my $type (keys(%{$types})) { 
 9707:                         if ($status eq $type) {
 9708:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9709:                                 push(@{$$users{$role}{$user}},$type);
 9710:                             }
 9711:                             $match = 1;
 9712:                         }
 9713:                     }
 9714:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9715:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9716: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9717:                         }
 9718:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9719:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9720:                         }
 9721:                         if (ref($statushash) eq 'HASH') {
 9722:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9723:                         }
 9724:                     }
 9725:                 }
 9726:             }
 9727:         }
 9728:         if (grep(/^ow$/,@{$roles})) {
 9729:             if ((defined($cdom)) && (defined($cnum))) {
 9730:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9731:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9732:                     my $owner = $csettings{'internal.courseowner'};
 9733:                     next if ($owner eq '');
 9734:                     my ($ownername,$ownerdom);
 9735:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9736:                         $ownername = $1;
 9737:                         $ownerdom = $2;
 9738:                     } else {
 9739:                         $ownername = $owner;
 9740:                         $ownerdom = $cdom;
 9741:                         $owner = $ownername.':'.$ownerdom;
 9742:                     }
 9743:                     @{$$users{'ow'}{$owner}} = 'any';
 9744:                     if (defined($userdata) && 
 9745: 			!exists($$userdata{$owner})) {
 9746: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9747:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9748:                             push(@{$seclists{$owner}},'none');
 9749:                         }
 9750:                         if (ref($statushash) eq 'HASH') {
 9751:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9752:                         }
 9753: 		    }
 9754:                 }
 9755:             }
 9756:         }
 9757:         foreach my $user (keys(%seclists)) {
 9758:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9759:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9760:         }
 9761:     }
 9762:     return;
 9763: }
 9764: 
 9765: sub get_user_info {
 9766:     my ($udom,$uname,$idx,$userdata) = @_;
 9767:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9768: 	&plainname($uname,$udom,'lastname');
 9769:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9770:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9771:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9772:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9773:     return;
 9774: }
 9775: 
 9776: ###############################################
 9777: 
 9778: =pod
 9779: 
 9780: =item * &get_user_quota()
 9781: 
 9782: Retrieves quota assigned for storage of user files.
 9783: Default is to report quota for portfolio files.
 9784: 
 9785: Incoming parameters:
 9786: 1. user's username
 9787: 2. user's domain
 9788: 3. quota name - portfolio, author, or course
 9789:    (if no quota name provided, defaults to portfolio).
 9790: 4. crstype - official, unofficial, textbook, placement or community, 
 9791:    if quota name is course
 9792: 
 9793: Returns:
 9794: 1. Disk quota (in MB) assigned to student.
 9795: 2. (Optional) Type of setting: custom or default
 9796:    (individually assigned or default for user's 
 9797:    institutional status).
 9798: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9799:    or student - types as defined in localenroll::inst_usertypes 
 9800:    for user's domain, which determines default quota for user.
 9801: 4. (Optional) - Default quota which would apply to the user.
 9802: 
 9803: If a value has been stored in the user's environment, 
 9804: it will return that, otherwise it returns the maximal default
 9805: defined for the user's institutional status(es) in the domain.
 9806: 
 9807: =cut
 9808: 
 9809: ###############################################
 9810: 
 9811: 
 9812: sub get_user_quota {
 9813:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9814:     my ($quota,$quotatype,$settingstatus,$defquota);
 9815:     if (!defined($udom)) {
 9816:         $udom = $env{'user.domain'};
 9817:     }
 9818:     if (!defined($uname)) {
 9819:         $uname = $env{'user.name'};
 9820:     }
 9821:     if (($udom eq '' || $uname eq '') ||
 9822:         ($udom eq 'public') && ($uname eq 'public')) {
 9823:         $quota = 0;
 9824:         $quotatype = 'default';
 9825:         $defquota = 0; 
 9826:     } else {
 9827:         my $inststatus;
 9828:         if ($quotaname eq 'course') {
 9829:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9830:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9831:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9832:             } else {
 9833:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9834:                 $quota = $cenv{'internal.uploadquota'};
 9835:             }
 9836:         } else {
 9837:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9838:                 if ($quotaname eq 'author') {
 9839:                     $quota = $env{'environment.authorquota'};
 9840:                 } else {
 9841:                     $quota = $env{'environment.portfolioquota'};
 9842:                 }
 9843:                 $inststatus = $env{'environment.inststatus'};
 9844:             } else {
 9845:                 my %userenv = 
 9846:                     &Apache::lonnet::get('environment',['portfolioquota',
 9847:                                          'authorquota','inststatus'],$udom,$uname);
 9848:                 my ($tmp) = keys(%userenv);
 9849:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9850:                     if ($quotaname eq 'author') {
 9851:                         $quota = $userenv{'authorquota'};
 9852:                     } else {
 9853:                         $quota = $userenv{'portfolioquota'};
 9854:                     }
 9855:                     $inststatus = $userenv{'inststatus'};
 9856:                 } else {
 9857:                     undef(%userenv);
 9858:                 }
 9859:             }
 9860:         }
 9861:         if ($quota eq '' || wantarray) {
 9862:             if ($quotaname eq 'course') {
 9863:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9864:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 9865:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
 9866:                     ($crstype eq 'placement')) { 
 9867:                     $defquota = $domdefs{$crstype.'quota'};
 9868:                 }
 9869:                 if ($defquota eq '') {
 9870:                     $defquota = 500;
 9871:                 }
 9872:             } else {
 9873:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9874:             }
 9875:             if ($quota eq '') {
 9876:                 $quota = $defquota;
 9877:                 $quotatype = 'default';
 9878:             } else {
 9879:                 $quotatype = 'custom';
 9880:             }
 9881:         }
 9882:     }
 9883:     if (wantarray) {
 9884:         return ($quota,$quotatype,$settingstatus,$defquota);
 9885:     } else {
 9886:         return $quota;
 9887:     }
 9888: }
 9889: 
 9890: ###############################################
 9891: 
 9892: =pod
 9893: 
 9894: =item * &default_quota()
 9895: 
 9896: Retrieves default quota assigned for storage of user portfolio files,
 9897: given an (optional) user's institutional status.
 9898: 
 9899: Incoming parameters:
 9900: 
 9901: 1. domain
 9902: 2. (Optional) institutional status(es).  This is a : separated list of 
 9903:    status types (e.g., faculty, staff, student etc.)
 9904:    which apply to the user for whom the default is being retrieved.
 9905:    If the institutional status string in undefined, the domain
 9906:    default quota will be returned.
 9907: 3.  quota name - portfolio, author, or course
 9908:    (if no quota name provided, defaults to portfolio).
 9909: 
 9910: Returns:
 9911: 
 9912: 1. Default disk quota (in MB) for user portfolios in the domain.
 9913: 2. (Optional) institutional type which determined the value of the
 9914:    default quota.
 9915: 
 9916: If a value has been stored in the domain's configuration db,
 9917: it will return that, otherwise it returns 20 (for backwards 
 9918: compatibility with domains which have not set up a configuration
 9919: db file; the original statically defined portfolio quota was 20 MB). 
 9920: 
 9921: If the user's status includes multiple types (e.g., staff and student),
 9922: the largest default quota which applies to the user determines the
 9923: default quota returned.
 9924: 
 9925: =cut
 9926: 
 9927: ###############################################
 9928: 
 9929: 
 9930: sub default_quota {
 9931:     my ($udom,$inststatus,$quotaname) = @_;
 9932:     my ($defquota,$settingstatus);
 9933:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9934:                                             ['quotas'],$udom);
 9935:     my $key = 'defaultquota';
 9936:     if ($quotaname eq 'author') {
 9937:         $key = 'authorquota';
 9938:     }
 9939:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9940:         if ($inststatus ne '') {
 9941:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9942:             foreach my $item (@statuses) {
 9943:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9944:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9945:                         if ($defquota eq '') {
 9946:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9947:                             $settingstatus = $item;
 9948:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9949:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9950:                             $settingstatus = $item;
 9951:                         }
 9952:                     }
 9953:                 } elsif ($key eq 'defaultquota') {
 9954:                     if ($quotahash{'quotas'}{$item} ne '') {
 9955:                         if ($defquota eq '') {
 9956:                             $defquota = $quotahash{'quotas'}{$item};
 9957:                             $settingstatus = $item;
 9958:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9959:                             $defquota = $quotahash{'quotas'}{$item};
 9960:                             $settingstatus = $item;
 9961:                         }
 9962:                     }
 9963:                 }
 9964:             }
 9965:         }
 9966:         if ($defquota eq '') {
 9967:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9968:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9969:             } elsif ($key eq 'defaultquota') {
 9970:                 $defquota = $quotahash{'quotas'}{'default'};
 9971:             }
 9972:             $settingstatus = 'default';
 9973:             if ($defquota eq '') {
 9974:                 if ($quotaname eq 'author') {
 9975:                     $defquota = 500;
 9976:                 }
 9977:             }
 9978:         }
 9979:     } else {
 9980:         $settingstatus = 'default';
 9981:         if ($quotaname eq 'author') {
 9982:             $defquota = 500;
 9983:         } else {
 9984:             $defquota = 20;
 9985:         }
 9986:     }
 9987:     if (wantarray) {
 9988:         return ($defquota,$settingstatus);
 9989:     } else {
 9990:         return $defquota;
 9991:     }
 9992: }
 9993: 
 9994: ###############################################
 9995: 
 9996: =pod
 9997: 
 9998: =item * &excess_filesize_warning()
 9999: 
10000: Returns warning message if upload of file to authoring space, or copying
10001: of existing file within authoring space will cause quota for the authoring
10002: space to be exceeded.
10003: 
10004: Same, if upload of a file directly to a course/community via Course Editor
10005: will cause quota for uploaded content for the course to be exceeded.
10006: 
10007: Inputs: 7 
10008: 1. username or coursenum
10009: 2. domain
10010: 3. context ('author' or 'course')
10011: 4. filename of file for which action is being requested
10012: 5. filesize (kB) of file
10013: 6. action being taken: copy or upload.
10014: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10015: 
10016: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10017:          otherwise return null.
10018: 
10019: =back
10020: 
10021: =cut
10022: 
10023: sub excess_filesize_warning {
10024:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10025:     my $current_disk_usage = 0;
10026:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10027:     if ($context eq 'author') {
10028:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10029:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10030:     } else {
10031:         foreach my $subdir ('docs','supplemental') {
10032:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10033:         }
10034:     }
10035:     $disk_quota = int($disk_quota * 1000);
10036:     if (($current_disk_usage + $filesize) > $disk_quota) {
10037:         return '<p class="LC_warning">'.
10038:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10039:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10040:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10041:                             $disk_quota,$current_disk_usage).
10042:                '</p>';
10043:     }
10044:     return;
10045: }
10046: 
10047: ###############################################
10048: 
10049: 
10050: 
10051: 
10052: sub get_secgrprole_info {
10053:     my ($cdom,$cnum,$needroles,$type)  = @_;
10054:     my %sections_count = &get_sections($cdom,$cnum);
10055:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10056:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10057:     my @groups = sort(keys(%curr_groups));
10058:     my $allroles = [];
10059:     my $rolehash;
10060:     my $accesshash = {
10061:                      active => 'Currently has access',
10062:                      future => 'Will have future access',
10063:                      previous => 'Previously had access',
10064:                   };
10065:     if ($needroles) {
10066:         $rolehash = {'all' => 'all'};
10067:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10068: 	if (&Apache::lonnet::error(%user_roles)) {
10069: 	    undef(%user_roles);
10070: 	}
10071:         foreach my $item (keys(%user_roles)) {
10072:             my ($role)=split(/\:/,$item,2);
10073:             if ($role eq 'cr') { next; }
10074:             if ($role =~ /^cr/) {
10075:                 $$rolehash{$role} = (split('/',$role))[3];
10076:             } else {
10077:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10078:             }
10079:         }
10080:         foreach my $key (sort(keys(%{$rolehash}))) {
10081:             push(@{$allroles},$key);
10082:         }
10083:         push (@{$allroles},'st');
10084:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10085:     }
10086:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10087: }
10088: 
10089: sub user_picker {
10090:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10091:     my $currdom = $dom;
10092:     my @alldoms = &Apache::lonnet::all_domains();
10093:     if (@alldoms == 1) {
10094:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10095:                                                ['directorysrch'],$alldoms[0]);
10096:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10097:         my $showdom = $domdesc;
10098:         if ($showdom eq '') {
10099:             $showdom = $dom;
10100:         }
10101:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10102:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10103:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10104:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10105:             }
10106:         }
10107:     }
10108:     my %curr_selected = (
10109:                         srchin => 'dom',
10110:                         srchby => 'lastname',
10111:                       );
10112:     my $srchterm;
10113:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10114:         if ($srch->{'srchby'} ne '') {
10115:             $curr_selected{'srchby'} = $srch->{'srchby'};
10116:         }
10117:         if ($srch->{'srchin'} ne '') {
10118:             $curr_selected{'srchin'} = $srch->{'srchin'};
10119:         }
10120:         if ($srch->{'srchtype'} ne '') {
10121:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10122:         }
10123:         if ($srch->{'srchdomain'} ne '') {
10124:             $currdom = $srch->{'srchdomain'};
10125:         }
10126:         $srchterm = $srch->{'srchterm'};
10127:     }
10128:     my %html_lt=&Apache::lonlocal::texthash(
10129:                     'usr'       => 'Search criteria',
10130:                     'doma'      => 'Domain/institution to search',
10131:                     'uname'     => 'username',
10132:                     'lastname'  => 'last name',
10133:                     'lastfirst' => 'last name, first name',
10134:                     'crs'       => 'in this course',
10135:                     'dom'       => 'in selected LON-CAPA domain', 
10136:                     'alc'       => 'all LON-CAPA',
10137:                     'instd'     => 'in institutional directory for selected domain',
10138:                     'exact'     => 'is',
10139:                     'contains'  => 'contains',
10140:                     'begins'    => 'begins with',
10141:                                        );
10142:     my %js_lt=&Apache::lonlocal::texthash(
10143:                     'youm'      => "You must include some text to search for.",
10144:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10145:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10146:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10147:                     'ymcd'      => "You must choose a domain when using a domain search.",
10148:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10149:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10150:                      'thfo'     => "The following need to be corrected before the search can be run:",
10151:                                        );
10152:     &html_escape(\%html_lt);
10153:     &js_escape(\%js_lt);
10154:     my $domform;
10155:     my $allow_blank = 1;
10156:     if ($fixeddom) {
10157:         $allow_blank = 0;
10158:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10159:     } else {
10160:         my $defdom = $env{'request.role.domain'};
10161:         my ($trusted,$untrusted);
10162:         if (($context eq 'requestcrs') || ($context eq 'course')) {
10163:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
10164:         } elsif ($context eq 'author') {
10165:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
10166:         } elsif ($context eq 'domain') {
10167:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
10168:         }
10169:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
10170:     }
10171:     my $srchinsel = ' <select name="srchin">';
10172: 
10173:     my @srchins = ('crs','dom','alc','instd');
10174: 
10175:     foreach my $option (@srchins) {
10176:         # FIXME 'alc' option unavailable until 
10177:         #       loncreateuser::print_user_query_page()
10178:         #       has been completed.
10179:         next if ($option eq 'alc');
10180:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10181:         next if ($option eq 'crs' && !$env{'request.course.id'});
10182:         next if (($option eq 'instd') && ($noinstd));
10183:         if ($curr_selected{'srchin'} eq $option) {
10184:             $srchinsel .= ' 
10185:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10186:         } else {
10187:             $srchinsel .= '
10188:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10189:         }
10190:     }
10191:     $srchinsel .= "\n  </select>\n";
10192: 
10193:     my $srchbysel =  ' <select name="srchby">';
10194:     foreach my $option ('lastname','lastfirst','uname') {
10195:         if ($curr_selected{'srchby'} eq $option) {
10196:             $srchbysel .= '
10197:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10198:         } else {
10199:             $srchbysel .= '
10200:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10201:          }
10202:     }
10203:     $srchbysel .= "\n  </select>\n";
10204: 
10205:     my $srchtypesel = ' <select name="srchtype">';
10206:     foreach my $option ('begins','contains','exact') {
10207:         if ($curr_selected{'srchtype'} eq $option) {
10208:             $srchtypesel .= '
10209:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10210:         } else {
10211:             $srchtypesel .= '
10212:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10213:         }
10214:     }
10215:     $srchtypesel .= "\n  </select>\n";
10216: 
10217:     my ($newuserscript,$new_user_create);
10218:     my $context_dom = $env{'request.role.domain'};
10219:     if ($context eq 'requestcrs') {
10220:         if ($env{'form.coursedom'} ne '') { 
10221:             $context_dom = $env{'form.coursedom'};
10222:         }
10223:     }
10224:     if ($forcenewuser) {
10225:         if (ref($srch) eq 'HASH') {
10226:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10227:                 if ($cancreate) {
10228:                     $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>';
10229:                 } else {
10230:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10231:                     my %usertypetext = (
10232:                         official   => 'institutional',
10233:                         unofficial => 'non-institutional',
10234:                     );
10235:                     $new_user_create = '<p class="LC_warning">'
10236:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10237:                                       .' '
10238:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10239:                                           ,'<a href="'.$helplink.'">','</a>')
10240:                                       .'</p><br />';
10241:                 }
10242:             }
10243:         }
10244: 
10245:         $newuserscript = <<"ENDSCRIPT";
10246: 
10247: function setSearch(createnew,callingForm) {
10248:     if (createnew == 1) {
10249:         for (var i=0; i<callingForm.srchby.length; i++) {
10250:             if (callingForm.srchby.options[i].value == 'uname') {
10251:                 callingForm.srchby.selectedIndex = i;
10252:             }
10253:         }
10254:         for (var i=0; i<callingForm.srchin.length; i++) {
10255:             if ( callingForm.srchin.options[i].value == 'dom') {
10256: 		callingForm.srchin.selectedIndex = i;
10257:             }
10258:         }
10259:         for (var i=0; i<callingForm.srchtype.length; i++) {
10260:             if (callingForm.srchtype.options[i].value == 'exact') {
10261:                 callingForm.srchtype.selectedIndex = i;
10262:             }
10263:         }
10264:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10265:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10266:                 callingForm.srchdomain.selectedIndex = i;
10267:             }
10268:         }
10269:     }
10270: }
10271: ENDSCRIPT
10272: 
10273:     }
10274: 
10275:     my $output = <<"END_BLOCK";
10276: <script type="text/javascript">
10277: // <![CDATA[
10278: function validateEntry(callingForm) {
10279: 
10280:     var checkok = 1;
10281:     var srchin;
10282:     for (var i=0; i<callingForm.srchin.length; i++) {
10283: 	if ( callingForm.srchin[i].checked ) {
10284: 	    srchin = callingForm.srchin[i].value;
10285: 	}
10286:     }
10287: 
10288:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10289:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10290:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10291:     var srchterm =  callingForm.srchterm.value;
10292:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10293:     var msg = "";
10294: 
10295:     if (srchterm == "") {
10296:         checkok = 0;
10297:         msg += "$js_lt{'youm'}\\n";
10298:     }
10299: 
10300:     if (srchtype== 'begins') {
10301:         if (srchterm.length < 2) {
10302:             checkok = 0;
10303:             msg += "$js_lt{'thte'}\\n";
10304:         }
10305:     }
10306: 
10307:     if (srchtype== 'contains') {
10308:         if (srchterm.length < 3) {
10309:             checkok = 0;
10310:             msg += "$js_lt{'thet'}\\n";
10311:         }
10312:     }
10313:     if (srchin == 'instd') {
10314:         if (srchdomain == '') {
10315:             checkok = 0;
10316:             msg += "$js_lt{'yomc'}\\n";
10317:         }
10318:     }
10319:     if (srchin == 'dom') {
10320:         if (srchdomain == '') {
10321:             checkok = 0;
10322:             msg += "$js_lt{'ymcd'}\\n";
10323:         }
10324:     }
10325:     if (srchby == 'lastfirst') {
10326:         if (srchterm.indexOf(",") == -1) {
10327:             checkok = 0;
10328:             msg += "$js_lt{'whus'}\\n";
10329:         }
10330:         if (srchterm.indexOf(",") == srchterm.length -1) {
10331:             checkok = 0;
10332:             msg += "$js_lt{'whse'}\\n";
10333:         }
10334:     }
10335:     if (checkok == 0) {
10336:         alert("$js_lt{'thfo'}\\n"+msg);
10337:         return;
10338:     }
10339:     if (checkok == 1) {
10340:         callingForm.submit();
10341:     }
10342: }
10343: 
10344: $newuserscript
10345: 
10346: // ]]>
10347: </script>
10348: 
10349: $new_user_create
10350: 
10351: END_BLOCK
10352: 
10353:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10354:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10355:                $domform.
10356:                &Apache::lonhtmlcommon::row_closure().
10357:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10358:                $srchbysel.
10359:                $srchtypesel. 
10360:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10361:                $srchinsel.
10362:                &Apache::lonhtmlcommon::row_closure(1). 
10363:                &Apache::lonhtmlcommon::end_pick_box().
10364:                '<br />';
10365:     return ($output,1);
10366: }
10367: 
10368: sub user_rule_check {
10369:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10370:     my ($response,%inst_response);
10371:     if (ref($usershash) eq 'HASH') {
10372:         if (keys(%{$usershash}) > 1) {
10373:             my (%by_username,%by_id,%userdoms);
10374:             my $checkid; 
10375:             if (ref($checks) eq 'HASH') {
10376:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10377:                     $checkid = 1;
10378:                 }
10379:             }
10380:             foreach my $user (keys(%{$usershash})) {
10381:                 my ($uname,$udom) = split(/:/,$user);
10382:                 if ($checkid) {
10383:                     if (ref($usershash->{$user}) eq 'HASH') {
10384:                         if ($usershash->{$user}->{'id'} ne '') {
10385:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10386:                             $userdoms{$udom} = 1;
10387:                             if (ref($inst_results) eq 'HASH') {
10388:                                 $inst_results->{$uname.':'.$udom} = {};
10389:                             }
10390:                         }
10391:                     }
10392:                 } else {
10393:                     $by_username{$udom}{$uname} = 1;
10394:                     $userdoms{$udom} = 1;
10395:                     if (ref($inst_results) eq 'HASH') {
10396:                         $inst_results->{$uname.':'.$udom} = {};
10397:                     }
10398:                 }
10399:             }
10400:             foreach my $udom (keys(%userdoms)) {
10401:                 if (!$got_rules->{$udom}) {
10402:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10403:                                                              ['usercreation'],$udom);
10404:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10405:                         foreach my $item ('username','id') {
10406:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10407:                                 $$curr_rules{$udom}{$item} =
10408:                                     $domconfig{'usercreation'}{$item.'_rule'};
10409:                             }
10410:                         }
10411:                     }
10412:                     $got_rules->{$udom} = 1;
10413:                 }
10414:             }
10415:             if ($checkid) {
10416:                 foreach my $udom (keys(%by_id)) {
10417:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10418:                     if ($outcome eq 'ok') {
10419:                         foreach my $id (keys(%{$by_id{$udom}})) {
10420:                             my $uname = $by_id{$udom}{$id};
10421:                             $inst_response{$uname.':'.$udom} = $outcome;
10422:                         }
10423:                         if (ref($results) eq 'HASH') {
10424:                             foreach my $uname (keys(%{$results})) {
10425:                                 if (exists($inst_response{$uname.':'.$udom})) {
10426:                                     $inst_response{$uname.':'.$udom} = $outcome;
10427:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10428:                                 }
10429:                             }
10430:                         }
10431:                     }
10432:                 }
10433:             } else {
10434:                 foreach my $udom (keys(%by_username)) {
10435:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10436:                     if ($outcome eq 'ok') {
10437:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10438:                             $inst_response{$uname.':'.$udom} = $outcome;
10439:                         }
10440:                         if (ref($results) eq 'HASH') {
10441:                             foreach my $uname (keys(%{$results})) {
10442:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10443:                             }
10444:                         }
10445:                     }
10446:                 }
10447:             }
10448:         } elsif (keys(%{$usershash}) == 1) {
10449:             my $user = (keys(%{$usershash}))[0];
10450:             my ($uname,$udom) = split(/:/,$user);
10451:             if (($udom ne '') && ($uname ne '')) {
10452:                 if (ref($usershash->{$user}) eq 'HASH') {
10453:                     if (ref($checks) eq 'HASH') {
10454:                         if (defined($checks->{'username'})) {
10455:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
10456:                                 &Apache::lonnet::get_instuser($udom,$uname);
10457:                         } elsif (defined($checks->{'id'})) {
10458:                             if ($usershash->{$user}->{'id'} ne '') {
10459:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10460:                                     &Apache::lonnet::get_instuser($udom,undef,
10461:                                                                   $usershash->{$user}->{'id'});
10462:                             } else {
10463:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10464:                                     &Apache::lonnet::get_instuser($udom,$uname);
10465:                             }
10466:                         }
10467:                     } else {
10468:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10469:                             &Apache::lonnet::get_instuser($udom,$uname);
10470:                        return;
10471:                     }
10472:                     if (!$got_rules->{$udom}) {
10473:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10474:                                                                  ['usercreation'],$udom);
10475:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10476:                             foreach my $item ('username','id') {
10477:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10478:                                    $$curr_rules{$udom}{$item} = 
10479:                                        $domconfig{'usercreation'}{$item.'_rule'};
10480:                                 }
10481:                             }
10482:                         }
10483:                         $got_rules->{$udom} = 1;
10484:                     }
10485:                 }
10486:             } else {
10487:                 return;
10488:             }
10489:         } else {
10490:             return;
10491:         }
10492:         foreach my $user (keys(%{$usershash})) {
10493:             my ($uname,$udom) = split(/:/,$user);
10494:             next if (($udom eq '') || ($uname eq ''));
10495:             my $id;
10496:             if (ref($inst_results) eq 'HASH') {
10497:                 if (ref($inst_results->{$user}) eq 'HASH') {
10498:                     $id = $inst_results->{$user}->{'id'};
10499:                 }
10500:             }
10501:             if ($id eq '') { 
10502:                 if (ref($usershash->{$user})) {
10503:                     $id = $usershash->{$user}->{'id'};
10504:                 }
10505:             }
10506:             foreach my $item (keys(%{$checks})) {
10507:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10508:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10509:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10510:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10511:                                                                              $$curr_rules{$udom}{$item});
10512:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10513:                                 if ($rule_check{$rule}) {
10514:                                     $$rulematch{$user}{$item} = $rule;
10515:                                     if ($inst_response{$user} eq 'ok') {
10516:                                         if (ref($inst_results) eq 'HASH') {
10517:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10518:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10519:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10520:                                                 } elsif ($item eq 'id') {
10521:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10522:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10523:                                                     }
10524:                                                 }
10525:                                             }
10526:                                         }
10527:                                     }
10528:                                     last;
10529:                                 }
10530:                             }
10531:                         }
10532:                     }
10533:                 }
10534:             }
10535:         }
10536:     }
10537:     return;
10538: }
10539: 
10540: sub user_rule_formats {
10541:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10542:     my %text = ( 
10543:                  'username' => 'Usernames',
10544:                  'id'       => 'IDs',
10545:                );
10546:     my $output;
10547:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10548:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10549:         if (@{$ruleorder} > 0) {
10550:             $output = '<br />'.
10551:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10552:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10553:                       ' <ul>';
10554:             foreach my $rule (@{$ruleorder}) {
10555:                 if (ref($curr_rules) eq 'ARRAY') {
10556:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10557:                         if (ref($rules->{$rule}) eq 'HASH') {
10558:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10559:                                         $rules->{$rule}{'desc'}.'</li>';
10560:                         }
10561:                     }
10562:                 }
10563:             }
10564:             $output .= '</ul>';
10565:         }
10566:     }
10567:     return $output;
10568: }
10569: 
10570: sub instrule_disallow_msg {
10571:     my ($checkitem,$domdesc,$count,$mode) = @_;
10572:     my $response;
10573:     my %text = (
10574:                   item   => 'username',
10575:                   items  => 'usernames',
10576:                   match  => 'matches',
10577:                   do     => 'does',
10578:                   action => 'a username',
10579:                   one    => 'one',
10580:                );
10581:     if ($count > 1) {
10582:         $text{'item'} = 'usernames';
10583:         $text{'match'} ='match';
10584:         $text{'do'} = 'do';
10585:         $text{'action'} = 'usernames',
10586:         $text{'one'} = 'ones';
10587:     }
10588:     if ($checkitem eq 'id') {
10589:         $text{'items'} = 'IDs';
10590:         $text{'item'} = 'ID';
10591:         $text{'action'} = 'an ID';
10592:         if ($count > 1) {
10593:             $text{'item'} = 'IDs';
10594:             $text{'action'} = 'IDs';
10595:         }
10596:     }
10597:     $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 />';
10598:     if ($mode eq 'upload') {
10599:         if ($checkitem eq 'username') {
10600:             $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'}.");
10601:         } elsif ($checkitem eq 'id') {
10602:             $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.");
10603:         }
10604:     } elsif ($mode eq 'selfcreate') {
10605:         if ($checkitem eq 'id') {
10606:             $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.");
10607:         }
10608:     } else {
10609:         if ($checkitem eq 'username') {
10610:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10611:         } elsif ($checkitem eq 'id') {
10612:             $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.");
10613:         }
10614:     }
10615:     return $response;
10616: }
10617: 
10618: sub personal_data_fieldtitles {
10619:     my %fieldtitles = &Apache::lonlocal::texthash (
10620:                         id => 'Student/Employee ID',
10621:                         permanentemail => 'E-mail address',
10622:                         lastname => 'Last Name',
10623:                         firstname => 'First Name',
10624:                         middlename => 'Middle Name',
10625:                         generation => 'Generation',
10626:                         gen => 'Generation',
10627:                         inststatus => 'Affiliation',
10628:                    );
10629:     return %fieldtitles;
10630: }
10631: 
10632: sub sorted_inst_types {
10633:     my ($dom) = @_;
10634:     my ($usertypes,$order);
10635:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10636:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10637:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10638:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10639:     } else {
10640:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10641:     }
10642:     my $othertitle = &mt('All users');
10643:     if ($env{'request.course.id'}) {
10644:         $othertitle  = &mt('Any users');
10645:     }
10646:     my @types;
10647:     if (ref($order) eq 'ARRAY') {
10648:         @types = @{$order};
10649:     }
10650:     if (@types == 0) {
10651:         if (ref($usertypes) eq 'HASH') {
10652:             @types = sort(keys(%{$usertypes}));
10653:         }
10654:     }
10655:     if (keys(%{$usertypes}) > 0) {
10656:         $othertitle = &mt('Other users');
10657:     }
10658:     return ($othertitle,$usertypes,\@types);
10659: }
10660: 
10661: sub get_institutional_codes {
10662:     my ($settings,$allcourses,$LC_code) = @_;
10663: # Get complete list of course sections to update
10664:     my @currsections = ();
10665:     my @currxlists = ();
10666:     my $coursecode = $$settings{'internal.coursecode'};
10667: 
10668:     if ($$settings{'internal.sectionnums'} ne '') {
10669:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10670:     }
10671: 
10672:     if ($$settings{'internal.crosslistings'} ne '') {
10673:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10674:     }
10675: 
10676:     if (@currxlists > 0) {
10677:         foreach (@currxlists) {
10678:             if (m/^([^:]+):(\w*)$/) {
10679:                 unless (grep/^$1$/,@{$allcourses}) {
10680:                     push(@{$allcourses},$1);
10681:                     $$LC_code{$1} = $2;
10682:                 }
10683:             }
10684:         }
10685:     }
10686:  
10687:     if (@currsections > 0) {
10688:         foreach (@currsections) {
10689:             if (m/^(\w+):(\w*)$/) {
10690:                 my $sec = $coursecode.$1;
10691:                 my $lc_sec = $2;
10692:                 unless (grep/^$sec$/,@{$allcourses}) {
10693:                     push(@{$allcourses},$sec);
10694:                     $$LC_code{$sec} = $lc_sec;
10695:                 }
10696:             }
10697:         }
10698:     }
10699:     return;
10700: }
10701: 
10702: sub get_standard_codeitems {
10703:     return ('Year','Semester','Department','Number','Section');
10704: }
10705: 
10706: =pod
10707: 
10708: =head1 Slot Helpers
10709: 
10710: =over 4
10711: 
10712: =item * sorted_slots()
10713: 
10714: Sorts an array of slot names in order of an optional sort key,
10715: default sort is by slot start time (earliest first). 
10716: 
10717: Inputs:
10718: 
10719: =over 4
10720: 
10721: slotsarr  - Reference to array of unsorted slot names.
10722: 
10723: slots     - Reference to hash of hash, where outer hash keys are slot names.
10724: 
10725: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10726: 
10727: =back
10728: 
10729: Returns:
10730: 
10731: =over 4
10732: 
10733: sorted   - An array of slot names sorted by a specified sort key 
10734:            (default sort key is start time of the slot).
10735: 
10736: =back
10737: 
10738: =cut
10739: 
10740: 
10741: sub sorted_slots {
10742:     my ($slotsarr,$slots,$sortkey) = @_;
10743:     if ($sortkey eq '') {
10744:         $sortkey = 'starttime';
10745:     }
10746:     my @sorted;
10747:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10748:         @sorted =
10749:             sort {
10750:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10751:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10752:                      }
10753:                      if (ref($slots->{$a})) { return -1;}
10754:                      if (ref($slots->{$b})) { return 1;}
10755:                      return 0;
10756:                  } @{$slotsarr};
10757:     }
10758:     return @sorted;
10759: }
10760: 
10761: =pod
10762: 
10763: =item * get_future_slots()
10764: 
10765: Inputs:
10766: 
10767: =over 4
10768: 
10769: cnum - course number
10770: 
10771: cdom - course domain
10772: 
10773: now - current UNIX time
10774: 
10775: symb - optional symb
10776: 
10777: =back
10778: 
10779: Returns:
10780: 
10781: =over 4
10782: 
10783: sorted_reservable - ref to array of student_schedulable slots currently 
10784:                     reservable, ordered by end date of reservation period.
10785: 
10786: reservable_now - ref to hash of student_schedulable slots currently
10787:                  reservable.
10788: 
10789:     Keys in inner hash are:
10790:     (a) symb: either blank or symb to which slot use is restricted.
10791:     (b) endreserve: end date of reservation period.
10792:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10793:         selected.
10794: 
10795: sorted_future - ref to array of student_schedulable slots reservable in
10796:                 the future, ordered by start date of reservation period.
10797: 
10798: future_reservable - ref to hash of student_schedulable slots reservable
10799:                     in the future.
10800: 
10801:     Keys in inner hash are:
10802:     (a) symb: either blank or symb to which slot use is restricted.
10803:     (b) startreserve: start date of reservation period.
10804:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10805:         selected.
10806: 
10807: =back
10808: 
10809: =cut
10810: 
10811: sub get_future_slots {
10812:     my ($cnum,$cdom,$now,$symb) = @_;
10813:     my $map;
10814:     if ($symb) {
10815:         ($map) = &Apache::lonnet::decode_symb($symb);
10816:     }
10817:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10818:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10819:     foreach my $slot (keys(%slots)) {
10820:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10821:         if ($symb) {
10822:             if ($slots{$slot}->{'symb'} ne '') {
10823:                 my $canuse;
10824:                 my %oksymbs;
10825:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10826:                 map { $oksymbs{$_} = 1; } @slotsymbs;
10827:                 if ($oksymbs{$symb}) {
10828:                     $canuse = 1;
10829:                 } else {
10830:                     foreach my $item (@slotsymbs) {
10831:                         if ($item =~ /\.(page|sequence)$/) {
10832:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10833:                             if (($map ne '') && ($map eq $sloturl)) {
10834:                                 $canuse = 1;
10835:                                 last;
10836:                             }
10837:                         }
10838:                     }
10839:                 }
10840:                 next unless ($canuse);
10841:             }
10842:         }
10843:         if (($slots{$slot}->{'starttime'} > $now) &&
10844:             ($slots{$slot}->{'endtime'} > $now)) {
10845:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10846:                 my $userallowed = 0;
10847:                 if ($slots{$slot}->{'allowedsections'}) {
10848:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10849:                     if (!defined($env{'request.role.sec'})
10850:                         && grep(/^No section assigned$/,@allowed_sec)) {
10851:                         $userallowed=1;
10852:                     } else {
10853:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10854:                             $userallowed=1;
10855:                         }
10856:                     }
10857:                     unless ($userallowed) {
10858:                         if (defined($env{'request.course.groups'})) {
10859:                             my @groups = split(/:/,$env{'request.course.groups'});
10860:                             foreach my $group (@groups) {
10861:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10862:                                     $userallowed=1;
10863:                                     last;
10864:                                 }
10865:                             }
10866:                         }
10867:                     }
10868:                 }
10869:                 if ($slots{$slot}->{'allowedusers'}) {
10870:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10871:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10872:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10873:                         $userallowed = 1;
10874:                     }
10875:                 }
10876:                 next unless($userallowed);
10877:             }
10878:             my $startreserve = $slots{$slot}->{'startreserve'};
10879:             my $endreserve = $slots{$slot}->{'endreserve'};
10880:             my $symb = $slots{$slot}->{'symb'};
10881:             my $uniqueperiod;
10882:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10883:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10884:             }
10885:             if (($startreserve < $now) &&
10886:                 (!$endreserve || $endreserve > $now)) {
10887:                 my $lastres = $endreserve;
10888:                 if (!$lastres) {
10889:                     $lastres = $slots{$slot}->{'starttime'};
10890:                 }
10891:                 $reservable_now{$slot} = {
10892:                                            symb       => $symb,
10893:                                            endreserve => $lastres,
10894:                                            uniqueperiod => $uniqueperiod,
10895:                                          };
10896:             } elsif (($startreserve > $now) &&
10897:                      (!$endreserve || $endreserve > $startreserve)) {
10898:                 $future_reservable{$slot} = {
10899:                                               symb         => $symb,
10900:                                               startreserve => $startreserve,
10901:                                               uniqueperiod => $uniqueperiod,
10902:                                             };
10903:             }
10904:         }
10905:     }
10906:     my @unsorted_reservable = keys(%reservable_now);
10907:     if (@unsorted_reservable > 0) {
10908:         @sorted_reservable = 
10909:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10910:     }
10911:     my @unsorted_future = keys(%future_reservable);
10912:     if (@unsorted_future > 0) {
10913:         @sorted_future =
10914:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10915:     }
10916:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10917: }
10918: 
10919: =pod
10920: 
10921: =back
10922: 
10923: =head1 HTTP Helpers
10924: 
10925: =over 4
10926: 
10927: =item * &get_unprocessed_cgi($query,$possible_names)
10928: 
10929: Modify the %env hash to contain unprocessed CGI form parameters held in
10930: $query.  The parameters listed in $possible_names (an array reference),
10931: will be set in $env{'form.name'} if they do not already exist.
10932: 
10933: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10934: $possible_names is an ref to an array of form element names.  As an example:
10935: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10936: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10937: 
10938: =cut
10939: 
10940: sub get_unprocessed_cgi {
10941:   my ($query,$possible_names)= @_;
10942:   # $Apache::lonxml::debug=1;
10943:   foreach my $pair (split(/&/,$query)) {
10944:     my ($name, $value) = split(/=/,$pair);
10945:     $name = &unescape($name);
10946:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10947:       $value =~ tr/+/ /;
10948:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10949:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10950:     }
10951:   }
10952: }
10953: 
10954: =pod
10955: 
10956: =item * &cacheheader() 
10957: 
10958: returns cache-controlling header code
10959: 
10960: =cut
10961: 
10962: sub cacheheader {
10963:     unless ($env{'request.method'} eq 'GET') { return ''; }
10964:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10965:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10966:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10967:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10968:     return $output;
10969: }
10970: 
10971: =pod
10972: 
10973: =item * &no_cache($r) 
10974: 
10975: specifies header code to not have cache
10976: 
10977: =cut
10978: 
10979: sub no_cache {
10980:     my ($r) = @_;
10981:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10982: 	$env{'request.method'} ne 'GET') { return ''; }
10983:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10984:     $r->no_cache(1);
10985:     $r->header_out("Expires" => $date);
10986:     $r->header_out("Pragma" => "no-cache");
10987: }
10988: 
10989: sub content_type {
10990:     my ($r,$type,$charset) = @_;
10991:     if ($r) {
10992: 	#  Note that printout.pl calls this with undef for $r.
10993: 	&no_cache($r);
10994:     }
10995:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10996:     unless ($charset) {
10997: 	$charset=&Apache::lonlocal::current_encoding;
10998:     }
10999:     if ($charset) { $type.='; charset='.$charset; }
11000:     if ($r) {
11001: 	$r->content_type($type);
11002:     } else {
11003: 	print("Content-type: $type\n\n");
11004:     }
11005: }
11006: 
11007: =pod
11008: 
11009: =item * &add_to_env($name,$value) 
11010: 
11011: adds $name to the %env hash with value
11012: $value, if $name already exists, the entry is converted to an array
11013: reference and $value is added to the array.
11014: 
11015: =cut
11016: 
11017: sub add_to_env {
11018:   my ($name,$value)=@_;
11019:   if (defined($env{$name})) {
11020:     if (ref($env{$name})) {
11021:       #already have multiple values
11022:       push(@{ $env{$name} },$value);
11023:     } else {
11024:       #first time seeing multiple values, convert hash entry to an arrayref
11025:       my $first=$env{$name};
11026:       undef($env{$name});
11027:       push(@{ $env{$name} },$first,$value);
11028:     }
11029:   } else {
11030:     $env{$name}=$value;
11031:   }
11032: }
11033: 
11034: =pod
11035: 
11036: =item * &get_env_multiple($name) 
11037: 
11038: gets $name from the %env hash, it seemlessly handles the cases where multiple
11039: values may be defined and end up as an array ref.
11040: 
11041: returns an array of values
11042: 
11043: =cut
11044: 
11045: sub get_env_multiple {
11046:     my ($name) = @_;
11047:     my @values;
11048:     if (defined($env{$name})) {
11049:         # exists is it an array
11050:         if (ref($env{$name})) {
11051:             @values=@{ $env{$name} };
11052:         } else {
11053:             $values[0]=$env{$name};
11054:         }
11055:     }
11056:     return(@values);
11057: }
11058: 
11059: # Looks at given dependencies, and returns something depending on the context.
11060: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11061: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11062: # For all other contexts, returns ($output, $counter, $numpathchg).
11063: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11064: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
11065: # $numpathchg: integer with the number of cleaned up dependency paths.
11066: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11067: # \%mapping: hash reference clean path -> original path for all dependencies.
11068: # @param {string} actionurl - The path to the handler, indicative of the context.
11069: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11070: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11071: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11072: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
11073: # @return {Array} - array depending on the context (not a reference)
11074: sub ask_for_embedded_content {
11075:     # NOTE: documentation was added afterwards, it could be wrong
11076:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11077:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11078:         %currsubfile,%unused,$rem);
11079:     my $counter = 0;
11080:     my $numnew = 0;
11081:     my $numremref = 0;
11082:     my $numinvalid = 0;
11083:     my $numpathchg = 0;
11084:     my $numexisting = 0;
11085:     my $numunused = 0;
11086:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11087:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11088:     my $heading = &mt('Upload embedded files');
11089:     my $buttontext = &mt('Upload');
11090: 
11091:     # fills these variables based on the context:
11092:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11093:     # $path, $fileloc, $title, $rem, $filename
11094:     if ($env{'request.course.id'}) {
11095:         if ($actionurl eq '/adm/dependencies') {
11096:             $navmap = Apache::lonnavmaps::navmap->new();
11097:         }
11098:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11099:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11100:     }
11101:     if (($actionurl eq '/adm/portfolio') || 
11102:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11103:         my $current_path='/';
11104:         if ($env{'form.currentpath'}) {
11105:             $current_path = $env{'form.currentpath'};
11106:         }
11107:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11108:             $udom = $cdom;
11109:             $uname = $cnum;
11110:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11111:         } else {
11112:             $udom = $env{'user.domain'};
11113:             $uname = $env{'user.name'};
11114:             $url = '/userfiles/portfolio';
11115:         }
11116:         $toplevel = $url.'/';
11117:         $url .= $current_path;
11118:         $getpropath = 1;
11119:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11120:              ($actionurl eq '/adm/imsimport')) { 
11121:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11122:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11123:         $toplevel = $url;
11124:         if ($rest ne '') {
11125:             $url .= $rest;
11126:         }
11127:     } elsif ($actionurl eq '/adm/coursedocs') {
11128:         if (ref($args) eq 'HASH') {
11129:             $url = $args->{'docs_url'};
11130:             $toplevel = $url;
11131:             if ($args->{'context'} eq 'paste') {
11132:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11133:                 ($path) = 
11134:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11135:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11136:                 $fileloc =~ s{^/}{};
11137:             }
11138:         }
11139:     } elsif ($actionurl eq '/adm/dependencies')  {
11140:         if ($env{'request.course.id'} ne '') {
11141:             if (ref($args) eq 'HASH') {
11142:                 $url = $args->{'docs_url'};
11143:                 $title = $args->{'docs_title'};
11144:                 $toplevel = $url; 
11145:                 unless ($toplevel =~ m{^/}) {
11146:                     $toplevel = "/$url";
11147:                 }
11148:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11149:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11150:                     $path = $1;
11151:                 } else {
11152:                     ($path) =
11153:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11154:                 }
11155:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11156:                     $fileloc = $toplevel;
11157:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11158:                     my ($udom,$uname,$fname) =
11159:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11160:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11161:                 } else {
11162:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11163:                 }
11164:                 $fileloc =~ s{^/}{};
11165:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11166:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11167:             }
11168:         }
11169:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11170:         $udom = $cdom;
11171:         $uname = $cnum;
11172:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11173:         $toplevel = $url;
11174:         $path = $url;
11175:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11176:         $fileloc =~ s{^/}{};
11177:     }
11178:     
11179:     # parses the dependency paths to get some info
11180:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11181:     # $newfiles: hash URL -> 1 for new files or external URLs
11182:     # (will be completed later)
11183:     # $mapping:
11184:     #   for external URLs: external URL -> external URL
11185:     #   for relative paths: clean path -> original path
11186:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11187:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11188:     foreach my $file (keys(%{$allfiles})) {
11189:         my $embed_file;
11190:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11191:             $embed_file = $1;
11192:         } else {
11193:             $embed_file = $file;
11194:         }
11195:         my ($absolutepath,$cleaned_file);
11196:         if ($embed_file =~ m{^\w+://}) {
11197:             $cleaned_file = $embed_file;
11198:             $newfiles{$cleaned_file} = 1;
11199:             $mapping{$cleaned_file} = $embed_file;
11200:         } else {
11201:             $cleaned_file = &clean_path($embed_file);
11202:             if ($embed_file =~ m{^/}) {
11203:                 $absolutepath = $embed_file;
11204:             }
11205:             if ($cleaned_file =~ m{/}) {
11206:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11207:                 $path = &check_for_traversal($path,$url,$toplevel);
11208:                 my $item = $fname;
11209:                 if ($path ne '') {
11210:                     $item = $path.'/'.$fname;
11211:                     $subdependencies{$path}{$fname} = 1;
11212:                 } else {
11213:                     $dependencies{$item} = 1;
11214:                 }
11215:                 if ($absolutepath) {
11216:                     $mapping{$item} = $absolutepath;
11217:                 } else {
11218:                     $mapping{$item} = $embed_file;
11219:                 }
11220:             } else {
11221:                 $dependencies{$embed_file} = 1;
11222:                 if ($absolutepath) {
11223:                     $mapping{$cleaned_file} = $absolutepath;
11224:                 } else {
11225:                     $mapping{$cleaned_file} = $embed_file;
11226:                 }
11227:             }
11228:         }
11229:     }
11230:     
11231:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11232:     # and lists
11233:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11234:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11235:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11236:     #                                    the path had to be cleaned up
11237:     # $existing: hash clean path -> 1 if the file exists
11238:     # $numexisting: number of keys in $existing
11239:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11240:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11241:     #                                      dependency subdirectories that are
11242:     #                                      not listed as dependencies, with some exceptions using $rem
11243:     my $dirptr = 16384;
11244:     foreach my $path (keys(%subdependencies)) {
11245:         $currsubfile{$path} = {};
11246:         if (($actionurl eq '/adm/portfolio') || 
11247:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11248:             my ($sublistref,$listerror) =
11249:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11250:             if (ref($sublistref) eq 'ARRAY') {
11251:                 foreach my $line (@{$sublistref}) {
11252:                     my ($file_name,$rest) = split(/\&/,$line,2);
11253:                     $currsubfile{$path}{$file_name} = 1;
11254:                 }
11255:             }
11256:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11257:             if (opendir(my $dir,$url.'/'.$path)) {
11258:                 my @subdir_list = grep(!/^\./,readdir($dir));
11259:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11260:             }
11261:         } elsif (($actionurl eq '/adm/dependencies') ||
11262:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11263:                   ($args->{'context'} eq 'paste')) ||
11264:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11265:             if ($env{'request.course.id'} ne '') {
11266:                 my $dir;
11267:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11268:                     $dir = $fileloc;
11269:                 } else {
11270:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11271:                 }
11272:                 if ($dir ne '') {
11273:                     my ($sublistref,$listerror) =
11274:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11275:                     if (ref($sublistref) eq 'ARRAY') {
11276:                         foreach my $line (@{$sublistref}) {
11277:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11278:                                 undef,$mtime)=split(/\&/,$line,12);
11279:                             unless (($testdir&$dirptr) ||
11280:                                     ($file_name =~ /^\.\.?$/)) {
11281:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11282:                             }
11283:                         }
11284:                     }
11285:                 }
11286:             }
11287:         }
11288:         foreach my $file (keys(%{$subdependencies{$path}})) {
11289:             if (exists($currsubfile{$path}{$file})) {
11290:                 my $item = $path.'/'.$file;
11291:                 unless ($mapping{$item} eq $item) {
11292:                     $pathchanges{$item} = 1;
11293:                 }
11294:                 $existing{$item} = 1;
11295:                 $numexisting ++;
11296:             } else {
11297:                 $newfiles{$path.'/'.$file} = 1;
11298:             }
11299:         }
11300:         if ($actionurl eq '/adm/dependencies') {
11301:             foreach my $path (keys(%currsubfile)) {
11302:                 if (ref($currsubfile{$path}) eq 'HASH') {
11303:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11304:                          unless ($subdependencies{$path}{$file}) {
11305:                              next if (($rem ne '') &&
11306:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11307:                                        (ref($navmap) &&
11308:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11309:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11310:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11311:                              $unused{$path.'/'.$file} = 1; 
11312:                          }
11313:                     }
11314:                 }
11315:             }
11316:         }
11317:     }
11318:     
11319:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11320:     # for files in $url or $fileloc (target directory) in some contexts
11321:     my %currfile;
11322:     if (($actionurl eq '/adm/portfolio') ||
11323:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11324:         my ($dirlistref,$listerror) =
11325:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11326:         if (ref($dirlistref) eq 'ARRAY') {
11327:             foreach my $line (@{$dirlistref}) {
11328:                 my ($file_name,$rest) = split(/\&/,$line,2);
11329:                 $currfile{$file_name} = 1;
11330:             }
11331:         }
11332:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11333:         if (opendir(my $dir,$url)) {
11334:             my @dir_list = grep(!/^\./,readdir($dir));
11335:             map {$currfile{$_} = 1;} @dir_list;
11336:         }
11337:     } elsif (($actionurl eq '/adm/dependencies') ||
11338:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11339:               ($args->{'context'} eq 'paste')) ||
11340:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11341:         if ($env{'request.course.id'} ne '') {
11342:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11343:             if ($dir ne '') {
11344:                 my ($dirlistref,$listerror) =
11345:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11346:                 if (ref($dirlistref) eq 'ARRAY') {
11347:                     foreach my $line (@{$dirlistref}) {
11348:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11349:                             $size,undef,$mtime)=split(/\&/,$line,12);
11350:                         unless (($testdir&$dirptr) ||
11351:                                 ($file_name =~ /^\.\.?$/)) {
11352:                             $currfile{$file_name} = [$size,$mtime];
11353:                         }
11354:                     }
11355:                 }
11356:             }
11357:         }
11358:     }
11359:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11360:     # are not in subdirectories, using $currfile
11361:     foreach my $file (keys(%dependencies)) {
11362:         if (exists($currfile{$file})) {
11363:             unless ($mapping{$file} eq $file) {
11364:                 $pathchanges{$file} = 1;
11365:             }
11366:             $existing{$file} = 1;
11367:             $numexisting ++;
11368:         } else {
11369:             $newfiles{$file} = 1;
11370:         }
11371:     }
11372:     foreach my $file (keys(%currfile)) {
11373:         unless (($file eq $filename) ||
11374:                 ($file eq $filename.'.bak') ||
11375:                 ($dependencies{$file})) {
11376:             if ($actionurl eq '/adm/dependencies') {
11377:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11378:                     next if (($rem ne '') &&
11379:                              (($env{"httpref.$rem".$file} ne '') ||
11380:                               (ref($navmap) &&
11381:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11382:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11383:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11384:                 }
11385:             }
11386:             $unused{$file} = 1;
11387:         }
11388:     }
11389:     
11390:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11391:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11392:         ($args->{'context'} eq 'paste')) {
11393:         $counter = scalar(keys(%existing));
11394:         $numpathchg = scalar(keys(%pathchanges));
11395:         return ($output,$counter,$numpathchg,\%existing);
11396:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
11397:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11398:         $counter = scalar(keys(%existing));
11399:         $numpathchg = scalar(keys(%pathchanges));
11400:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11401:     }
11402:     
11403:     # returns HTML otherwise, with dependency results and to ask for more uploads
11404:     
11405:     # $upload_output: missing dependencies (with upload form)
11406:     # $modify_output: uploaded dependencies (in use)
11407:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11408:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11409:         if ($actionurl eq '/adm/dependencies') {
11410:             next if ($embed_file =~ m{^\w+://});
11411:         }
11412:         $upload_output .= &start_data_table_row().
11413:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11414:                           '<span class="LC_filename">'.$embed_file.'</span>';
11415:         unless ($mapping{$embed_file} eq $embed_file) {
11416:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11417:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11418:         }
11419:         $upload_output .= '</td>';
11420:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11421:             $upload_output.='<td align="right">'.
11422:                             '<span class="LC_info LC_fontsize_medium">'.
11423:                             &mt("URL points to web address").'</span>';
11424:             $numremref++;
11425:         } elsif ($args->{'error_on_invalid_names'}
11426:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11427:             $upload_output.='<td align="right"><span class="LC_warning">'.
11428:                             &mt('Invalid characters').'</span>';
11429:             $numinvalid++;
11430:         } else {
11431:             $upload_output .= '<td>'.
11432:                               &embedded_file_element('upload_embedded',$counter,
11433:                                                      $embed_file,\%mapping,
11434:                                                      $allfiles,$codebase,'upload');
11435:             $counter ++;
11436:             $numnew ++;
11437:         }
11438:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11439:     }
11440:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11441:         if ($actionurl eq '/adm/dependencies') {
11442:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11443:             $modify_output .= &start_data_table_row().
11444:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11445:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11446:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11447:                               '<td>'.$size.'</td>'.
11448:                               '<td>'.$mtime.'</td>'.
11449:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11450:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11451:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11452:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11453:                               &embedded_file_element('upload_embedded',$counter,
11454:                                                      $embed_file,\%mapping,
11455:                                                      $allfiles,$codebase,'modify').
11456:                               '</div></td>'.
11457:                               &end_data_table_row()."\n";
11458:             $counter ++;
11459:         } else {
11460:             $upload_output .= &start_data_table_row().
11461:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11462:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11463:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11464:                               &Apache::loncommon::end_data_table_row()."\n";
11465:         }
11466:     }
11467:     my $delidx = $counter;
11468:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11469:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11470:         $delete_output .= &start_data_table_row().
11471:                           '<td><img src="'.&icon($oldfile).'" />'.
11472:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11473:                           '<td>'.$size.'</td>'.
11474:                           '<td>'.$mtime.'</td>'.
11475:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11476:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11477:                           &embedded_file_element('upload_embedded',$delidx,
11478:                                                  $oldfile,\%mapping,$allfiles,
11479:                                                  $codebase,'delete').'</td>'.
11480:                           &end_data_table_row()."\n"; 
11481:         $numunused ++;
11482:         $delidx ++;
11483:     }
11484:     if ($upload_output) {
11485:         $upload_output = &start_data_table().
11486:                          $upload_output.
11487:                          &end_data_table()."\n";
11488:     }
11489:     if ($modify_output) {
11490:         $modify_output = &start_data_table().
11491:                          &start_data_table_header_row().
11492:                          '<th>'.&mt('File').'</th>'.
11493:                          '<th>'.&mt('Size (KB)').'</th>'.
11494:                          '<th>'.&mt('Modified').'</th>'.
11495:                          '<th>'.&mt('Upload replacement?').'</th>'.
11496:                          &end_data_table_header_row().
11497:                          $modify_output.
11498:                          &end_data_table()."\n";
11499:     }
11500:     if ($delete_output) {
11501:         $delete_output = &start_data_table().
11502:                          &start_data_table_header_row().
11503:                          '<th>'.&mt('File').'</th>'.
11504:                          '<th>'.&mt('Size (KB)').'</th>'.
11505:                          '<th>'.&mt('Modified').'</th>'.
11506:                          '<th>'.&mt('Delete?').'</th>'.
11507:                          &end_data_table_header_row().
11508:                          $delete_output.
11509:                          &end_data_table()."\n";
11510:     }
11511:     my $applies = 0;
11512:     if ($numremref) {
11513:         $applies ++;
11514:     }
11515:     if ($numinvalid) {
11516:         $applies ++;
11517:     }
11518:     if ($numexisting) {
11519:         $applies ++;
11520:     }
11521:     if ($counter || $numunused) {
11522:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11523:                   ' method="post" enctype="multipart/form-data">'."\n".
11524:                   $state.'<h3>'.$heading.'</h3>'; 
11525:         if ($actionurl eq '/adm/dependencies') {
11526:             if ($numnew) {
11527:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11528:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11529:                            $upload_output.'<br />'."\n";
11530:             }
11531:             if ($numexisting) {
11532:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11533:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11534:                            $modify_output.'<br />'."\n";
11535:                            $buttontext = &mt('Save changes');
11536:             }
11537:             if ($numunused) {
11538:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11539:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11540:                            $delete_output.'<br />'."\n";
11541:                            $buttontext = &mt('Save changes');
11542:             }
11543:         } else {
11544:             $output .= $upload_output.'<br />'."\n";
11545:         }
11546:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11547:                    $counter.'" />'."\n";
11548:         if ($actionurl eq '/adm/dependencies') { 
11549:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11550:                        $numnew.'" />'."\n";
11551:         } elsif ($actionurl eq '') {
11552:             $output .=  '<input type="hidden" name="phase" value="three" />';
11553:         }
11554:     } elsif ($applies) {
11555:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11556:         if ($applies > 1) {
11557:             $output .=  
11558:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11559:             if ($numremref) {
11560:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11561:             }
11562:             if ($numinvalid) {
11563:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11564:             }
11565:             if ($numexisting) {
11566:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11567:             }
11568:             $output .= '</ul><br />';
11569:         } elsif ($numremref) {
11570:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11571:         } elsif ($numinvalid) {
11572:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11573:         } elsif ($numexisting) {
11574:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11575:         }
11576:         $output .= $upload_output.'<br />';
11577:     }
11578:     my ($pathchange_output,$chgcount);
11579:     $chgcount = $counter;
11580:     if (keys(%pathchanges) > 0) {
11581:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11582:             if ($counter) {
11583:                 $output .= &embedded_file_element('pathchange',$chgcount,
11584:                                                   $embed_file,\%mapping,
11585:                                                   $allfiles,$codebase,'change');
11586:             } else {
11587:                 $pathchange_output .= 
11588:                     &start_data_table_row().
11589:                     '<td><input type ="checkbox" name="namechange" value="'.
11590:                     $chgcount.'" checked="checked" /></td>'.
11591:                     '<td>'.$mapping{$embed_file}.'</td>'.
11592:                     '<td>'.$embed_file.
11593:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11594:                                            \%mapping,$allfiles,$codebase,'change').
11595:                     '</td>'.&end_data_table_row();
11596:             }
11597:             $numpathchg ++;
11598:             $chgcount ++;
11599:         }
11600:     }
11601:     if (($counter) || ($numunused)) {
11602:         if ($numpathchg) {
11603:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11604:                        $numpathchg.'" />'."\n";
11605:         }
11606:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11607:             ($actionurl eq '/adm/imsimport')) {
11608:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11609:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11610:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11611:         } elsif ($actionurl eq '/adm/dependencies') {
11612:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11613:         }
11614:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11615:     } elsif ($numpathchg) {
11616:         my %pathchange = ();
11617:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11618:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11619:             $output .= '<p>'.&mt('or').'</p>'; 
11620:         }
11621:     }
11622:     return ($output,$counter,$numpathchg);
11623: }
11624: 
11625: =pod
11626: 
11627: =item * clean_path($name)
11628: 
11629: Performs clean-up of directories, subdirectories and filename in an
11630: embedded object, referenced in an HTML file which is being uploaded
11631: to a course or portfolio, where 
11632: "Upload embedded images/multimedia files if HTML file" checkbox was
11633: checked.
11634: 
11635: Clean-up is similar to replacements in lonnet::clean_filename()
11636: except each / between sub-directory and next level is preserved.
11637: 
11638: =cut
11639: 
11640: sub clean_path {
11641:     my ($embed_file) = @_;
11642:     $embed_file =~s{^/+}{};
11643:     my @contents;
11644:     if ($embed_file =~ m{/}) {
11645:         @contents = split(/\//,$embed_file);
11646:     } else {
11647:         @contents = ($embed_file);
11648:     }
11649:     my $lastidx = scalar(@contents)-1;
11650:     for (my $i=0; $i<=$lastidx; $i++) { 
11651:         $contents[$i]=~s{\\}{/}g;
11652:         $contents[$i]=~s/\s+/\_/g;
11653:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11654:         if ($i == $lastidx) {
11655:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11656:         }
11657:     }
11658:     if ($lastidx > 0) {
11659:         return join('/',@contents);
11660:     } else {
11661:         return $contents[0];
11662:     }
11663: }
11664: 
11665: sub embedded_file_element {
11666:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11667:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11668:                    (ref($codebase) eq 'HASH'));
11669:     my $output;
11670:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11671:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11672:     }
11673:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11674:                &escape($embed_file).'" />';
11675:     unless (($context eq 'upload_embedded') && 
11676:             ($mapping->{$embed_file} eq $embed_file)) {
11677:         $output .='
11678:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11679:     }
11680:     my $attrib;
11681:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11682:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11683:     }
11684:     $output .=
11685:         "\n\t\t".
11686:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11687:         $attrib.'" />';
11688:     if (exists($codebase->{$mapping->{$embed_file}})) {
11689:         $output .=
11690:             "\n\t\t".
11691:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11692:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11693:     }
11694:     return $output;
11695: }
11696: 
11697: sub get_dependency_details {
11698:     my ($currfile,$currsubfile,$embed_file) = @_;
11699:     my ($size,$mtime,$showsize,$showmtime);
11700:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11701:         if ($embed_file =~ m{/}) {
11702:             my ($path,$fname) = split(/\//,$embed_file);
11703:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11704:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11705:             }
11706:         } else {
11707:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11708:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11709:             }
11710:         }
11711:         $showsize = $size/1024.0;
11712:         $showsize = sprintf("%.1f",$showsize);
11713:         if ($mtime > 0) {
11714:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11715:         }
11716:     }
11717:     return ($showsize,$showmtime);
11718: }
11719: 
11720: sub ask_embedded_js {
11721:     return <<"END";
11722: <script type="text/javascript"">
11723: // <![CDATA[
11724: function toggleBrowse(counter) {
11725:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11726:     var fileid = document.getElementById('embedded_item_'+counter);
11727:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11728:     if (chkboxid.checked == true) {
11729:         uploaddivid.style.display='block';
11730:     } else {
11731:         uploaddivid.style.display='none';
11732:         fileid.value = '';
11733:     }
11734: }
11735: // ]]>
11736: </script>
11737: 
11738: END
11739: }
11740: 
11741: sub upload_embedded {
11742:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11743:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11744:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11745:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11746:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11747:         my $orig_uploaded_filename =
11748:             $env{'form.embedded_item_'.$i.'.filename'};
11749:         foreach my $type ('orig','ref','attrib','codebase') {
11750:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11751:                 $env{'form.embedded_'.$type.'_'.$i} =
11752:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11753:             }
11754:         }
11755:         my ($path,$fname) =
11756:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11757:         # no path, whole string is fname
11758:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11759:         $fname = &Apache::lonnet::clean_filename($fname);
11760:         # See if there is anything left
11761:         next if ($fname eq '');
11762: 
11763:         # Check if file already exists as a file or directory.
11764:         my ($state,$msg);
11765:         if ($context eq 'portfolio') {
11766:             my $port_path = $dirpath;
11767:             if ($group ne '') {
11768:                 $port_path = "groups/$group/$port_path";
11769:             }
11770:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11771:                                               $fname,$group,'embedded_item_'.$i,
11772:                                               $dir_root,$port_path,$disk_quota,
11773:                                               $current_disk_usage,$uname,$udom);
11774:             if ($state eq 'will_exceed_quota'
11775:                 || $state eq 'file_locked') {
11776:                 $output .= $msg;
11777:                 next;
11778:             }
11779:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11780:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11781:             if ($state eq 'exists') {
11782:                 $output .= $msg;
11783:                 next;
11784:             }
11785:         }
11786:         # Check if extension is valid
11787:         if (($fname =~ /\.(\w+)$/) &&
11788:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11789:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11790:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11791:             next;
11792:         } elsif (($fname =~ /\.(\w+)$/) &&
11793:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11794:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11795:             next;
11796:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11797:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11798:             next;
11799:         }
11800:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11801:         my $subdir = $path;
11802:         $subdir =~ s{/+$}{};
11803:         if ($context eq 'portfolio') {
11804:             my $result;
11805:             if ($state eq 'existingfile') {
11806:                 $result=
11807:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11808:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11809:             } else {
11810:                 $result=
11811:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11812:                                                     $dirpath.
11813:                                                     $env{'form.currentpath'}.$subdir);
11814:                 if ($result !~ m|^/uploaded/|) {
11815:                     $output .= '<span class="LC_error">'
11816:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11817:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11818:                                .'</span><br />';
11819:                     next;
11820:                 } else {
11821:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11822:                                $path.$fname.'</span>').'<br />';     
11823:                 }
11824:             }
11825:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11826:             my $extendedsubdir = $dirpath.'/'.$subdir;
11827:             $extendedsubdir =~ s{/+$}{};
11828:             my $result =
11829:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11830:             if ($result !~ m|^/uploaded/|) {
11831:                 $output .= '<span class="LC_error">'
11832:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11833:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11834:                            .'</span><br />';
11835:                     next;
11836:             } else {
11837:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11838:                            $path.$fname.'</span>').'<br />';
11839:                 if ($context eq 'syllabus') {
11840:                     &Apache::lonnet::make_public_indefinitely($result);
11841:                 }
11842:             }
11843:         } else {
11844: # Save the file
11845:             my $target = $env{'form.embedded_item_'.$i};
11846:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11847:             my $dest = $fullpath.$fname;
11848:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11849:             my @parts=split(/\//,"$dirpath/$path");
11850:             my $count;
11851:             my $filepath = $dir_root;
11852:             foreach my $subdir (@parts) {
11853:                 $filepath .= "/$subdir";
11854:                 if (!-e $filepath) {
11855:                     mkdir($filepath,0770);
11856:                 }
11857:             }
11858:             my $fh;
11859:             if (!open($fh,'>'.$dest)) {
11860:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11861:                 $output .= '<span class="LC_error">'.
11862:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11863:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11864:                            '</span><br />';
11865:             } else {
11866:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11867:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11868:                     $output .= '<span class="LC_error">'.
11869:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11870:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11871:                               '</span><br />';
11872:                 } else {
11873:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11874:                                $url.'</span>').'<br />';
11875:                     unless ($context eq 'testbank') {
11876:                         $footer .= &mt('View embedded file: [_1]',
11877:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11878:                     }
11879:                 }
11880:                 close($fh);
11881:             }
11882:         }
11883:         if ($env{'form.embedded_ref_'.$i}) {
11884:             $pathchange{$i} = 1;
11885:         }
11886:     }
11887:     if ($output) {
11888:         $output = '<p>'.$output.'</p>';
11889:     }
11890:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11891:     $returnflag = 'ok';
11892:     my $numpathchgs = scalar(keys(%pathchange));
11893:     if ($numpathchgs > 0) {
11894:         if ($context eq 'portfolio') {
11895:             $output .= '<p>'.&mt('or').'</p>';
11896:         } elsif ($context eq 'testbank') {
11897:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11898:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11899:             $returnflag = 'modify_orightml';
11900:         }
11901:     }
11902:     return ($output.$footer,$returnflag,$numpathchgs);
11903: }
11904: 
11905: sub modify_html_form {
11906:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11907:     my $end = 0;
11908:     my $modifyform;
11909:     if ($context eq 'upload_embedded') {
11910:         return unless (ref($pathchange) eq 'HASH');
11911:         if ($env{'form.number_embedded_items'}) {
11912:             $end += $env{'form.number_embedded_items'};
11913:         }
11914:         if ($env{'form.number_pathchange_items'}) {
11915:             $end += $env{'form.number_pathchange_items'};
11916:         }
11917:         if ($end) {
11918:             for (my $i=0; $i<$end; $i++) {
11919:                 if ($i < $env{'form.number_embedded_items'}) {
11920:                     next unless($pathchange->{$i});
11921:                 }
11922:                 $modifyform .=
11923:                     &start_data_table_row().
11924:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11925:                     'checked="checked" /></td>'.
11926:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11927:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11928:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11929:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11930:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11931:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11932:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11933:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11934:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11935:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11936:                     &end_data_table_row();
11937:             }
11938:         }
11939:     } else {
11940:         $modifyform = $pathchgtable;
11941:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11942:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11943:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11944:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11945:         }
11946:     }
11947:     if ($modifyform) {
11948:         if ($actionurl eq '/adm/dependencies') {
11949:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11950:         }
11951:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11952:                '<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".
11953:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11954:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11955:                '</ol></p>'."\n".'<p>'.
11956:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11957:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11958:                &start_data_table()."\n".
11959:                &start_data_table_header_row().
11960:                '<th>'.&mt('Change?').'</th>'.
11961:                '<th>'.&mt('Current reference').'</th>'.
11962:                '<th>'.&mt('Required reference').'</th>'.
11963:                &end_data_table_header_row()."\n".
11964:                $modifyform.
11965:                &end_data_table().'<br />'."\n".$hiddenstate.
11966:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11967:                '</form>'."\n";
11968:     }
11969:     return;
11970: }
11971: 
11972: sub modify_html_refs {
11973:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11974:     my $container;
11975:     if ($context eq 'portfolio') {
11976:         $container = $env{'form.container'};
11977:     } elsif ($context eq 'coursedoc') {
11978:         $container = $env{'form.primaryurl'};
11979:     } elsif ($context eq 'manage_dependencies') {
11980:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11981:         $container = "/$container";
11982:     } elsif ($context eq 'syllabus') {
11983:         $container = $url;
11984:     } else {
11985:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11986:     }
11987:     my (%allfiles,%codebase,$output,$content);
11988:     my @changes = &get_env_multiple('form.namechange');
11989:     unless ((@changes > 0) || ($context eq 'syllabus')) {
11990:         if (wantarray) {
11991:             return ('',0,0); 
11992:         } else {
11993:             return;
11994:         }
11995:     }
11996:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11997:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11998:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11999:             if (wantarray) {
12000:                 return ('',0,0);
12001:             } else {
12002:                 return;
12003:             }
12004:         } 
12005:         $content = &Apache::lonnet::getfile($container);
12006:         if ($content eq '-1') {
12007:             if (wantarray) {
12008:                 return ('',0,0);
12009:             } else {
12010:                 return;
12011:             }
12012:         }
12013:     } else {
12014:         unless ($container =~ /^\Q$dir_root\E/) {
12015:             if (wantarray) {
12016:                 return ('',0,0);
12017:             } else {
12018:                 return;
12019:             }
12020:         } 
12021:         if (open(my $fh,"<$container")) {
12022:             $content = join('', <$fh>);
12023:             close($fh);
12024:         } else {
12025:             if (wantarray) {
12026:                 return ('',0,0);
12027:             } else {
12028:                 return;
12029:             }
12030:         }
12031:     }
12032:     my ($count,$codebasecount) = (0,0);
12033:     my $mm = new File::MMagic;
12034:     my $mime_type = $mm->checktype_contents($content);
12035:     if ($mime_type eq 'text/html') {
12036:         my $parse_result = 
12037:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12038:                                                     \%codebase,\$content);
12039:         if ($parse_result eq 'ok') {
12040:             foreach my $i (@changes) {
12041:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12042:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12043:                 if ($allfiles{$ref}) {
12044:                     my $newname =  $orig;
12045:                     my ($attrib_regexp,$codebase);
12046:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12047:                     if ($attrib_regexp =~ /:/) {
12048:                         $attrib_regexp =~ s/\:/|/g;
12049:                     }
12050:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12051:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12052:                         $count += $numchg;
12053:                         $allfiles{$newname} = $allfiles{$ref};
12054:                         delete($allfiles{$ref});
12055:                     }
12056:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12057:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12058:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12059:                         $codebasecount ++;
12060:                     }
12061:                 }
12062:             }
12063:             my $skiprewrites;
12064:             if ($count || $codebasecount) {
12065:                 my $saveresult;
12066:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12067:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12068:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12069:                     if ($url eq $container) {
12070:                         my ($fname) = ($container =~ m{/([^/]+)$});
12071:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12072:                                             $count,'<span class="LC_filename">'.
12073:                                             $fname.'</span>').'</p>';
12074:                     } else {
12075:                          $output = '<p class="LC_error">'.
12076:                                    &mt('Error: update failed for: [_1].',
12077:                                    '<span class="LC_filename">'.
12078:                                    $container.'</span>').'</p>';
12079:                     }
12080:                     if ($context eq 'syllabus') {
12081:                         unless ($saveresult eq 'ok') {
12082:                             $skiprewrites = 1;
12083:                         }
12084:                     }
12085:                 } else {
12086:                     if (open(my $fh,">$container")) {
12087:                         print $fh $content;
12088:                         close($fh);
12089:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12090:                                   $count,'<span class="LC_filename">'.
12091:                                   $container.'</span>').'</p>';
12092:                     } else {
12093:                          $output = '<p class="LC_error">'.
12094:                                    &mt('Error: could not update [_1].',
12095:                                    '<span class="LC_filename">'.
12096:                                    $container.'</span>').'</p>';
12097:                     }
12098:                 }
12099:             }
12100:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12101:                 my ($actionurl,$state);
12102:                 $actionurl = "/public/$udom/$uname/syllabus";
12103:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12104:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12105:                                               \%codebase,
12106:                                               {'context' => 'rewrites',
12107:                                                'ignore_remote_references' => 1,});
12108:                 if (ref($mapping) eq 'HASH') {
12109:                     my $rewrites = 0;
12110:                     foreach my $key (keys(%{$mapping})) {
12111:                         next if ($key =~ m{^https?://});
12112:                         my $ref = $mapping->{$key};
12113:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12114:                         my $attrib;
12115:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12116:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12117:                         }
12118:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12119:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12120:                             $rewrites += $numchg;
12121:                         }
12122:                     }
12123:                     if ($rewrites) {
12124:                         my $saveresult; 
12125:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12126:                         if ($url eq $container) {
12127:                             my ($fname) = ($container =~ m{/([^/]+)$});
12128:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12129:                                             $count,'<span class="LC_filename">'.
12130:                                             $fname.'</span>').'</p>';
12131:                         } else {
12132:                             $output .= '<p class="LC_error">'.
12133:                                        &mt('Error: could not update links in [_1].',
12134:                                        '<span class="LC_filename">'.
12135:                                        $container.'</span>').'</p>';
12136: 
12137:                         }
12138:                     }
12139:                 }
12140:             }
12141:         } else {
12142:             &logthis('Failed to parse '.$container.
12143:                      ' to modify references: '.$parse_result);
12144:         }
12145:     }
12146:     if (wantarray) {
12147:         return ($output,$count,$codebasecount);
12148:     } else {
12149:         return $output;
12150:     }
12151: }
12152: 
12153: sub check_for_existing {
12154:     my ($path,$fname,$element) = @_;
12155:     my ($state,$msg);
12156:     if (-d $path.'/'.$fname) {
12157:         $state = 'exists';
12158:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12159:     } elsif (-e $path.'/'.$fname) {
12160:         $state = 'exists';
12161:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12162:     }
12163:     if ($state eq 'exists') {
12164:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12165:     }
12166:     return ($state,$msg);
12167: }
12168: 
12169: sub check_for_upload {
12170:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12171:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12172:     my $filesize = length($env{'form.'.$element});
12173:     if (!$filesize) {
12174:         my $msg = '<span class="LC_error">'.
12175:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12176:                       '<span class="LC_filename">'.$fname.'</span>',
12177:                       $filesize).'<br />'.
12178:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12179:                   '</span>';
12180:         return ('zero_bytes',$msg);
12181:     }
12182:     $filesize =  $filesize/1000; #express in k (1024?)
12183:     my $getpropath = 1;
12184:     my ($dirlistref,$listerror) =
12185:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12186:     my $found_file = 0;
12187:     my $locked_file = 0;
12188:     my @lockers;
12189:     my $navmap;
12190:     if ($env{'request.course.id'}) {
12191:         $navmap = Apache::lonnavmaps::navmap->new();
12192:     }
12193:     if (ref($dirlistref) eq 'ARRAY') {
12194:         foreach my $line (@{$dirlistref}) {
12195:             my ($file_name,$rest)=split(/\&/,$line,2);
12196:             if ($file_name eq $fname){
12197:                 $file_name = $path.$file_name;
12198:                 if ($group ne '') {
12199:                     $file_name = $group.$file_name;
12200:                 }
12201:                 $found_file = 1;
12202:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12203:                     foreach my $lock (@lockers) {
12204:                         if (ref($lock) eq 'ARRAY') {
12205:                             my ($symb,$crsid) = @{$lock};
12206:                             if ($crsid eq $env{'request.course.id'}) {
12207:                                 if (ref($navmap)) {
12208:                                     my $res = $navmap->getBySymb($symb);
12209:                                     foreach my $part (@{$res->parts()}) { 
12210:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12211:                                         unless (($slot_status == $res->RESERVED) ||
12212:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12213:                                             $locked_file = 1;
12214:                                         }
12215:                                     }
12216:                                 } else {
12217:                                     $locked_file = 1;
12218:                                 }
12219:                             } else {
12220:                                 $locked_file = 1;
12221:                             }
12222:                         }
12223:                    }
12224:                 } else {
12225:                     my @info = split(/\&/,$rest);
12226:                     my $currsize = $info[6]/1000;
12227:                     if ($currsize < $filesize) {
12228:                         my $extra = $filesize - $currsize;
12229:                         if (($current_disk_usage + $extra) > $disk_quota) {
12230:                             my $msg = '<p class="LC_warning">'.
12231:                                       &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.',
12232:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12233:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12234:                                                    $disk_quota,$current_disk_usage).'</p>';
12235:                             return ('will_exceed_quota',$msg);
12236:                         }
12237:                     }
12238:                 }
12239:             }
12240:         }
12241:     }
12242:     if (($current_disk_usage + $filesize) > $disk_quota){
12243:         my $msg = '<p class="LC_warning">'.
12244:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12245:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12246:         return ('will_exceed_quota',$msg);
12247:     } elsif ($found_file) {
12248:         if ($locked_file) {
12249:             my $msg = '<p class="LC_warning">';
12250:             $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>');
12251:             $msg .= '</p>';
12252:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12253:             return ('file_locked',$msg);
12254:         } else {
12255:             my $msg = '<p class="LC_error">';
12256:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12257:             $msg .= '</p>';
12258:             return ('existingfile',$msg);
12259:         }
12260:     }
12261: }
12262: 
12263: sub check_for_traversal {
12264:     my ($path,$url,$toplevel) = @_;
12265:     my @parts=split(/\//,$path);
12266:     my $cleanpath;
12267:     my $fullpath = $url;
12268:     for (my $i=0;$i<@parts;$i++) {
12269:         next if ($parts[$i] eq '.');
12270:         if ($parts[$i] eq '..') {
12271:             $fullpath =~ s{([^/]+/)$}{};
12272:         } else {
12273:             $fullpath .= $parts[$i].'/';
12274:         }
12275:     }
12276:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12277:         $cleanpath = $1;
12278:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12279:         my $curr_toprel = $1;
12280:         my @parts = split(/\//,$curr_toprel);
12281:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12282:         my @urlparts = split(/\//,$url_toprel);
12283:         my $doubledots;
12284:         my $startdiff = -1;
12285:         for (my $i=0; $i<@urlparts; $i++) {
12286:             if ($startdiff == -1) {
12287:                 unless ($urlparts[$i] eq $parts[$i]) {
12288:                     $startdiff = $i;
12289:                     $doubledots .= '../';
12290:                 }
12291:             } else {
12292:                 $doubledots .= '../';
12293:             }
12294:         }
12295:         if ($startdiff > -1) {
12296:             $cleanpath = $doubledots;
12297:             for (my $i=$startdiff; $i<@parts; $i++) {
12298:                 $cleanpath .= $parts[$i].'/';
12299:             }
12300:         }
12301:     }
12302:     $cleanpath =~ s{(/)$}{};
12303:     return $cleanpath;
12304: }
12305: 
12306: sub is_archive_file {
12307:     my ($mimetype) = @_;
12308:     if (($mimetype eq 'application/octet-stream') ||
12309:         ($mimetype eq 'application/x-stuffit') ||
12310:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12311:         return 1;
12312:     }
12313:     return;
12314: }
12315: 
12316: sub decompress_form {
12317:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12318:     my %lt = &Apache::lonlocal::texthash (
12319:         this => 'This file is an archive file.',
12320:         camt => 'This file is a Camtasia archive file.',
12321:         itsc => 'Its contents are as follows:',
12322:         youm => 'You may wish to extract its contents.',
12323:         extr => 'Extract contents',
12324:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12325:         proa => 'Process automatically?',
12326:         yes  => 'Yes',
12327:         no   => 'No',
12328:         fold => 'Title for folder containing movie',
12329:         movi => 'Title for page containing embedded movie', 
12330:     );
12331:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12332:     my ($is_camtasia,$topdir,%toplevel,@paths);
12333:     my $info = &list_archive_contents($fileloc,\@paths);
12334:     if (@paths) {
12335:         foreach my $path (@paths) {
12336:             $path =~ s{^/}{};
12337:             if ($path =~ m{^([^/]+)/$}) {
12338:                 $topdir = $1;
12339:             }
12340:             if ($path =~ m{^([^/]+)/}) {
12341:                 $toplevel{$1} = $path;
12342:             } else {
12343:                 $toplevel{$path} = $path;
12344:             }
12345:         }
12346:     }
12347:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12348:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12349:                         "$topdir/media/",
12350:                         "$topdir/media/$topdir.mp4",
12351:                         "$topdir/media/FirstFrame.png",
12352:                         "$topdir/media/player.swf",
12353:                         "$topdir/media/swfobject.js",
12354:                         "$topdir/media/expressInstall.swf");
12355:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12356:                          "$topdir/$topdir.mp4",
12357:                          "$topdir/$topdir\_config.xml",
12358:                          "$topdir/$topdir\_controller.swf",
12359:                          "$topdir/$topdir\_embed.css",
12360:                          "$topdir/$topdir\_First_Frame.png",
12361:                          "$topdir/$topdir\_player.html",
12362:                          "$topdir/$topdir\_Thumbnails.png",
12363:                          "$topdir/playerProductInstall.swf",
12364:                          "$topdir/scripts/",
12365:                          "$topdir/scripts/config_xml.js",
12366:                          "$topdir/scripts/handlebars.js",
12367:                          "$topdir/scripts/jquery-1.7.1.min.js",
12368:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12369:                          "$topdir/scripts/modernizr.js",
12370:                          "$topdir/scripts/player-min.js",
12371:                          "$topdir/scripts/swfobject.js",
12372:                          "$topdir/skins/",
12373:                          "$topdir/skins/configuration_express.xml",
12374:                          "$topdir/skins/express_show/",
12375:                          "$topdir/skins/express_show/player-min.css",
12376:                          "$topdir/skins/express_show/spritesheet.png");
12377:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12378:                          "$topdir/$topdir.mp4",
12379:                          "$topdir/$topdir\_config.xml",
12380:                          "$topdir/$topdir\_controller.swf",
12381:                          "$topdir/$topdir\_embed.css",
12382:                          "$topdir/$topdir\_First_Frame.png",
12383:                          "$topdir/$topdir\_player.html",
12384:                          "$topdir/$topdir\_Thumbnails.png",
12385:                          "$topdir/playerProductInstall.swf",
12386:                          "$topdir/scripts/",
12387:                          "$topdir/scripts/config_xml.js",
12388:                          "$topdir/scripts/techsmith-smart-player.min.js",
12389:                          "$topdir/skins/",
12390:                          "$topdir/skins/configuration_express.xml",
12391:                          "$topdir/skins/express_show/",
12392:                          "$topdir/skins/express_show/spritesheet.min.css",
12393:                          "$topdir/skins/express_show/spritesheet.png",
12394:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12395:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12396:         if (@diffs == 0) {
12397:             $is_camtasia = 6;
12398:         } else {
12399:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12400:             if (@diffs == 0) {
12401:                 $is_camtasia = 8;
12402:             } else {
12403:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12404:                 if (@diffs == 0) {
12405:                     $is_camtasia = 8;
12406:                 }
12407:             }
12408:         }
12409:     }
12410:     my $output;
12411:     if ($is_camtasia) {
12412:         $output = <<"ENDCAM";
12413: <script type="text/javascript" language="Javascript">
12414: // <![CDATA[
12415: 
12416: function camtasiaToggle() {
12417:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12418:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12419:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12420:                 document.getElementById('camtasia_titles').style.display='block';
12421:             } else {
12422:                 document.getElementById('camtasia_titles').style.display='none';
12423:             }
12424:         }
12425:     }
12426:     return;
12427: }
12428: 
12429: // ]]>
12430: </script>
12431: <p>$lt{'camt'}</p>
12432: ENDCAM
12433:     } else {
12434:         $output = '<p>'.$lt{'this'};
12435:         if ($info eq '') {
12436:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12437:         } else {
12438:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12439:                        '<div><pre>'.$info.'</pre></div>';
12440:         }
12441:     }
12442:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12443:     my $duplicates;
12444:     my $num = 0;
12445:     if (ref($dirlist) eq 'ARRAY') {
12446:         foreach my $item (@{$dirlist}) {
12447:             if (ref($item) eq 'ARRAY') {
12448:                 if (exists($toplevel{$item->[0]})) {
12449:                     $duplicates .= 
12450:                         &start_data_table_row().
12451:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12452:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12453:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12454:                         'value="1" />'.&mt('Yes').'</label>'.
12455:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12456:                         '<td>'.$item->[0].'</td>';
12457:                     if ($item->[2]) {
12458:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12459:                     } else {
12460:                         $duplicates .= '<td>'.&mt('File').'</td>';
12461:                     }
12462:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12463:                                    '<td>'.
12464:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12465:                                    '</td>'.
12466:                                    &end_data_table_row();
12467:                     $num ++;
12468:                 }
12469:             }
12470:         }
12471:     }
12472:     my $itemcount;
12473:     if (@paths > 0) {
12474:         $itemcount = scalar(@paths);
12475:     } else {
12476:         $itemcount = 1;
12477:     }
12478:     if ($is_camtasia) {
12479:         $output .= $lt{'auto'}.'<br />'.
12480:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12481:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12482:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12483:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12484:                    $lt{'no'}.'</label></span><br />'.
12485:                    '<div id="camtasia_titles" style="display:block">'.
12486:                    &Apache::lonhtmlcommon::start_pick_box().
12487:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12488:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12489:                    &Apache::lonhtmlcommon::row_closure().
12490:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12491:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12492:                    &Apache::lonhtmlcommon::row_closure(1).
12493:                    &Apache::lonhtmlcommon::end_pick_box().
12494:                    '</div>';
12495:     }
12496:     $output .= 
12497:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12498:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12499:         "\n";
12500:     if ($duplicates ne '') {
12501:         $output .= '<p><span class="LC_warning">'.
12502:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12503:                    &start_data_table().
12504:                    &start_data_table_header_row().
12505:                    '<th>'.&mt('Overwrite?').'</th>'.
12506:                    '<th>'.&mt('Name').'</th>'.
12507:                    '<th>'.&mt('Type').'</th>'.
12508:                    '<th>'.&mt('Size').'</th>'.
12509:                    '<th>'.&mt('Last modified').'</th>'.
12510:                    &end_data_table_header_row().
12511:                    $duplicates.
12512:                    &end_data_table().
12513:                    '</p>';
12514:     }
12515:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12516:     if (ref($hiddenelements) eq 'HASH') {
12517:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12518:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12519:         }
12520:     }
12521:     $output .= <<"END";
12522: <br />
12523: <input type="submit" name="decompress" value="$lt{'extr'}" />
12524: </form>
12525: $noextract
12526: END
12527:     return $output;
12528: }
12529: 
12530: sub decompression_utility {
12531:     my ($program) = @_;
12532:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12533:     my $location;
12534:     if (grep(/^\Q$program\E$/,@utilities)) { 
12535:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12536:                          '/usr/sbin/') {
12537:             if (-x $dir.$program) {
12538:                 $location = $dir.$program;
12539:                 last;
12540:             }
12541:         }
12542:     }
12543:     return $location;
12544: }
12545: 
12546: sub list_archive_contents {
12547:     my ($file,$pathsref) = @_;
12548:     my (@cmd,$output);
12549:     my $needsregexp;
12550:     if ($file =~ /\.zip$/) {
12551:         @cmd = (&decompression_utility('unzip'),"-l");
12552:         $needsregexp = 1;
12553:     } elsif (($file =~ m/\.tar\.gz$/) ||
12554:              ($file =~ /\.tgz$/)) {
12555:         @cmd = (&decompression_utility('tar'),"-ztf");
12556:     } elsif ($file =~ /\.tar\.bz2$/) {
12557:         @cmd = (&decompression_utility('tar'),"-jtf");
12558:     } elsif ($file =~ m|\.tar$|) {
12559:         @cmd = (&decompression_utility('tar'),"-tf");
12560:     }
12561:     if (@cmd) {
12562:         undef($!);
12563:         undef($@);
12564:         if (open(my $fh,"-|", @cmd, $file)) {
12565:             while (my $line = <$fh>) {
12566:                 $output .= $line;
12567:                 chomp($line);
12568:                 my $item;
12569:                 if ($needsregexp) {
12570:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12571:                 } else {
12572:                     $item = $line;
12573:                 }
12574:                 if ($item ne '') {
12575:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12576:                         push(@{$pathsref},$item);
12577:                     } 
12578:                 }
12579:             }
12580:             close($fh);
12581:         }
12582:     }
12583:     return $output;
12584: }
12585: 
12586: sub decompress_uploaded_file {
12587:     my ($file,$dir) = @_;
12588:     &Apache::lonnet::appenv({'cgi.file' => $file});
12589:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12590:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12591:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12592:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12593:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12594:     my $decompressed = $env{'cgi.decompressed'};
12595:     &Apache::lonnet::delenv('cgi.file');
12596:     &Apache::lonnet::delenv('cgi.dir');
12597:     &Apache::lonnet::delenv('cgi.decompressed');
12598:     return ($decompressed,$result);
12599: }
12600: 
12601: sub process_decompression {
12602:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12603:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12604:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12605:                &mt('Unexpected file path.').'</p>'."\n";
12606:     }
12607:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12608:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12609:                &mt('Unexpected course context.').'</p>'."\n";
12610:     }
12611:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12612:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12613:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12614:     }
12615:     my ($dir,$error,$warning,$output);
12616:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12617:         $error = &mt('Filename not a supported archive file type.').
12618:                  '<br />'.&mt('Filename should end with one of: [_1].',
12619:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12620:     } else {
12621:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12622:         if ($docuhome eq 'no_host') {
12623:             $error = &mt('Could not determine home server for course.');
12624:         } else {
12625:             my @ids=&Apache::lonnet::current_machine_ids();
12626:             my $currdir = "$dir_root/$destination";
12627:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12628:                 $dir = &LONCAPA::propath($docudom,$docuname).
12629:                        "$dir_root/$destination";
12630:             } else {
12631:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12632:                        "$dir_root/$docudom/$docuname/$destination";
12633:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12634:                     $error = &mt('Archive file not found.');
12635:                 }
12636:             }
12637:             my (@to_overwrite,@to_skip);
12638:             if ($env{'form.archive_overwrite_total'} > 0) {
12639:                 my $total = $env{'form.archive_overwrite_total'};
12640:                 for (my $i=0; $i<$total; $i++) {
12641:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12642:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12643:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12644:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12645:                     }
12646:                 }
12647:             }
12648:             my $numskip = scalar(@to_skip);
12649:             my $numoverwrite = scalar(@to_overwrite);
12650:             if (($numskip) && (!$numoverwrite)) { 
12651:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12652:             } elsif ($dir eq '') {
12653:                 $error = &mt('Directory containing archive file unavailable.');
12654:             } elsif (!$error) {
12655:                 my ($decompressed,$display);
12656:                 if (($numskip) || ($numoverwrite)) {
12657:                     my $tempdir = time.'_'.$$.int(rand(10000));
12658:                     mkdir("$dir/$tempdir",0755);
12659:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12660:                         ($decompressed,$display) = 
12661:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12662:                         foreach my $item (@to_skip) {
12663:                             if (($item ne '') && ($item !~ /\.\./)) {
12664:                                 if (-f "$dir/$tempdir/$item") { 
12665:                                     unlink("$dir/$tempdir/$item");
12666:                                 } elsif (-d "$dir/$tempdir/$item") {
12667:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12668:                                 }
12669:                             }
12670:                         }
12671:                         foreach my $item (@to_overwrite) {
12672:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12673:                                 if (($item ne '') && ($item !~ /\.\./)) {
12674:                                     if (-f "$dir/$item") {
12675:                                         unlink("$dir/$item");
12676:                                     } elsif (-d "$dir/$item") {
12677:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12678:                                     }
12679:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12680:                                 }
12681:                             }
12682:                         }
12683:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12684:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12685:                         }
12686:                     }
12687:                 } else {
12688:                     ($decompressed,$display) = 
12689:                         &decompress_uploaded_file($file,$dir);
12690:                 }
12691:                 if ($decompressed eq 'ok') {
12692:                     $output = '<p class="LC_info">'.
12693:                               &mt('Files extracted successfully from archive.').
12694:                               '</p>'."\n";
12695:                     my ($warning,$result,@contents);
12696:                     my ($newdirlistref,$newlisterror) =
12697:                         &Apache::lonnet::dirlist($currdir,$docudom,
12698:                                                  $docuname,1);
12699:                     my (%is_dir,%changes,@newitems);
12700:                     my $dirptr = 16384;
12701:                     if (ref($newdirlistref) eq 'ARRAY') {
12702:                         foreach my $dir_line (@{$newdirlistref}) {
12703:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12704:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
12705:                                 push(@newitems,$item);
12706:                                 if ($dirptr&$testdir) {
12707:                                     $is_dir{$item} = 1;
12708:                                 }
12709:                                 $changes{$item} = 1;
12710:                             }
12711:                         }
12712:                     }
12713:                     if (keys(%changes) > 0) {
12714:                         foreach my $item (sort(@newitems)) {
12715:                             if ($changes{$item}) {
12716:                                 push(@contents,$item);
12717:                             }
12718:                         }
12719:                     }
12720:                     if (@contents > 0) {
12721:                         my $wantform;
12722:                         unless ($env{'form.autoextract_camtasia'}) {
12723:                             $wantform = 1;
12724:                         }
12725:                         my (%children,%parent,%dirorder,%titles);
12726:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12727:                                                                 $currdir,\%is_dir,
12728:                                                                 \%children,\%parent,
12729:                                                                 \@contents,\%dirorder,
12730:                                                                 \%titles,$wantform);
12731:                         if ($datatable ne '') {
12732:                             $output .= &archive_options_form('decompressed',$datatable,
12733:                                                              $count,$hiddenelem);
12734:                             my $startcount = 6;
12735:                             $output .= &archive_javascript($startcount,$count,
12736:                                                            \%titles,\%children);
12737:                         }
12738:                         if ($env{'form.autoextract_camtasia'}) {
12739:                             my $version = $env{'form.autoextract_camtasia'};
12740:                             my %displayed;
12741:                             my $total = 1;
12742:                             $env{'form.archive_directory'} = [];
12743:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12744:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12745:                                 $path =~ s{/$}{};
12746:                                 my $item;
12747:                                 if ($path ne '') {
12748:                                     $item = "$path/$titles{$i}";
12749:                                 } else {
12750:                                     $item = $titles{$i};
12751:                                 }
12752:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12753:                                 if ($item eq $contents[0]) {
12754:                                     push(@{$env{'form.archive_directory'}},$i);
12755:                                     $env{'form.archive_'.$i} = 'display';
12756:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12757:                                     $displayed{'folder'} = $i;
12758:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12759:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
12760:                                     $env{'form.archive_'.$i} = 'display';
12761:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12762:                                     $displayed{'web'} = $i;
12763:                                 } else {
12764:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12765:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12766:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12767:                                         push(@{$env{'form.archive_directory'}},$i);
12768:                                     }
12769:                                     $env{'form.archive_'.$i} = 'dependency';
12770:                                 }
12771:                                 $total ++;
12772:                             }
12773:                             for (my $i=1; $i<$total; $i++) {
12774:                                 next if ($i == $displayed{'web'});
12775:                                 next if ($i == $displayed{'folder'});
12776:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12777:                             }
12778:                             $env{'form.phase'} = 'decompress_cleanup';
12779:                             $env{'form.archivedelete'} = 1;
12780:                             $env{'form.archive_count'} = $total-1;
12781:                             $output .=
12782:                                 &process_extracted_files('coursedocs',$docudom,
12783:                                                          $docuname,$destination,
12784:                                                          $dir_root,$hiddenelem);
12785:                         }
12786:                     } else {
12787:                         $warning = &mt('No new items extracted from archive file.');
12788:                     }
12789:                 } else {
12790:                     $output = $display;
12791:                     $error = &mt('An error occurred during extraction from the archive file.');
12792:                 }
12793:             }
12794:         }
12795:     }
12796:     if ($error) {
12797:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12798:                    $error.'</p>'."\n";
12799:     }
12800:     if ($warning) {
12801:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12802:     }
12803:     return $output;
12804: }
12805: 
12806: sub get_extracted {
12807:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12808:         $titles,$wantform) = @_;
12809:     my $count = 0;
12810:     my $depth = 0;
12811:     my $datatable;
12812:     my @hierarchy;
12813:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12814:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12815:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12816:     foreach my $item (@{$contents}) {
12817:         $count ++;
12818:         @{$dirorder->{$count}} = @hierarchy;
12819:         $titles->{$count} = $item;
12820:         &archive_hierarchy($depth,$count,$parent,$children);
12821:         if ($wantform) {
12822:             $datatable .= &archive_row($is_dir->{$item},$item,
12823:                                        $currdir,$depth,$count);
12824:         }
12825:         if ($is_dir->{$item}) {
12826:             $depth ++;
12827:             push(@hierarchy,$count);
12828:             $parent->{$depth} = $count;
12829:             $datatable .=
12830:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12831:                                            \$depth,\$count,\@hierarchy,$dirorder,
12832:                                            $children,$parent,$titles,$wantform);
12833:             $depth --;
12834:             pop(@hierarchy);
12835:         }
12836:     }
12837:     return ($count,$datatable);
12838: }
12839: 
12840: sub recurse_extracted_archive {
12841:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12842:         $children,$parent,$titles,$wantform) = @_;
12843:     my $result='';
12844:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12845:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12846:             (ref($dirorder) eq 'HASH')) {
12847:         return $result;
12848:     }
12849:     my $dirptr = 16384;
12850:     my ($newdirlistref,$newlisterror) =
12851:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12852:     if (ref($newdirlistref) eq 'ARRAY') {
12853:         foreach my $dir_line (@{$newdirlistref}) {
12854:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12855:             unless ($item =~ /^\.+$/) {
12856:                 $$count ++;
12857:                 @{$dirorder->{$$count}} = @{$hierarchy};
12858:                 $titles->{$$count} = $item;
12859:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12860: 
12861:                 my $is_dir;
12862:                 if ($dirptr&$testdir) {
12863:                     $is_dir = 1;
12864:                 }
12865:                 if ($wantform) {
12866:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12867:                 }
12868:                 if ($is_dir) {
12869:                     $$depth ++;
12870:                     push(@{$hierarchy},$$count);
12871:                     $parent->{$$depth} = $$count;
12872:                     $result .=
12873:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12874:                                                    $docuname,$depth,$count,
12875:                                                    $hierarchy,$dirorder,$children,
12876:                                                    $parent,$titles,$wantform);
12877:                     $$depth --;
12878:                     pop(@{$hierarchy});
12879:                 }
12880:             }
12881:         }
12882:     }
12883:     return $result;
12884: }
12885: 
12886: sub archive_hierarchy {
12887:     my ($depth,$count,$parent,$children) =@_;
12888:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12889:         if (exists($parent->{$depth})) {
12890:              $children->{$parent->{$depth}} .= $count.':';
12891:         }
12892:     }
12893:     return;
12894: }
12895: 
12896: sub archive_row {
12897:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12898:     my ($name) = ($item =~ m{([^/]+)$});
12899:     my %choices = &Apache::lonlocal::texthash (
12900:                                        'display'    => 'Add as file',
12901:                                        'dependency' => 'Include as dependency',
12902:                                        'discard'    => 'Discard',
12903:                                       );
12904:     if ($is_dir) {
12905:         $choices{'display'} = &mt('Add as folder'); 
12906:     }
12907:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12908:     my $offset = 0;
12909:     foreach my $action ('display','dependency','discard') {
12910:         $offset ++;
12911:         if ($action ne 'display') {
12912:             $offset ++;
12913:         }  
12914:         $output .= '<td><span class="LC_nobreak">'.
12915:                    '<label><input type="radio" name="archive_'.$count.
12916:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12917:         my $text = $choices{$action};
12918:         if ($is_dir) {
12919:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12920:             if ($action eq 'display') {
12921:                 $text = &mt('Add as folder');
12922:             }
12923:         } else {
12924:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12925: 
12926:         }
12927:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12928:         if ($action eq 'dependency') {
12929:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12930:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12931:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12932:                        '<option value=""></option>'."\n".
12933:                        '</select>'."\n".
12934:                        '</div>';
12935:         } elsif ($action eq 'display') {
12936:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12937:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12938:                        '</div>';
12939:         }
12940:         $output .= '</td>';
12941:     }
12942:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12943:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12944:     for (my $i=0; $i<$depth; $i++) {
12945:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12946:     }
12947:     if ($is_dir) {
12948:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12949:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12950:     } else {
12951:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12952:     }
12953:     $output .= '&nbsp;'.$name.'</td>'."\n".
12954:                &end_data_table_row();
12955:     return $output;
12956: }
12957: 
12958: sub archive_options_form {
12959:     my ($form,$display,$count,$hiddenelem) = @_;
12960:     my %lt = &Apache::lonlocal::texthash(
12961:                perm => 'Permanently remove archive file?',
12962:                hows => 'How should each extracted item be incorporated in the course?',
12963:                cont => 'Content actions for all',
12964:                addf => 'Add as folder/file',
12965:                incd => 'Include as dependency for a displayed file',
12966:                disc => 'Discard',
12967:                no   => 'No',
12968:                yes  => 'Yes',
12969:                save => 'Save',
12970:     );
12971:     my $output = <<"END";
12972: <form name="$form" method="post" action="">
12973: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12974: <label>
12975:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12976: </label>
12977: &nbsp;
12978: <label>
12979:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12980: </span>
12981: </p>
12982: <input type="hidden" name="phase" value="decompress_cleanup" />
12983: <br />$lt{'hows'}
12984: <div class="LC_columnSection">
12985:   <fieldset>
12986:     <legend>$lt{'cont'}</legend>
12987:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12988:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12989:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12990:   </fieldset>
12991: </div>
12992: END
12993:     return $output.
12994:            &start_data_table()."\n".
12995:            $display."\n".
12996:            &end_data_table()."\n".
12997:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12998:            $hiddenelem.
12999:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13000:            '</form>';
13001: }
13002: 
13003: sub archive_javascript {
13004:     my ($startcount,$numitems,$titles,$children) = @_;
13005:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13006:     my $maintitle = $env{'form.comment'};
13007:     my $scripttag = <<START;
13008: <script type="text/javascript">
13009: // <![CDATA[
13010: 
13011: function checkAll(form,prefix) {
13012:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13013:     for (var i=0; i < form.elements.length; i++) {
13014:         var id = form.elements[i].id;
13015:         if ((id != '') && (id != undefined)) {
13016:             if (idstr.test(id)) {
13017:                 if (form.elements[i].type == 'radio') {
13018:                     form.elements[i].checked = true;
13019:                     var nostart = i-$startcount;
13020:                     var offset = nostart%7;
13021:                     var count = (nostart-offset)/7;    
13022:                     dependencyCheck(form,count,offset);
13023:                 }
13024:             }
13025:         }
13026:     }
13027: }
13028: 
13029: function propagateCheck(form,count) {
13030:     if (count > 0) {
13031:         var startelement = $startcount + ((count-1) * 7);
13032:         for (var j=1; j<6; j++) {
13033:             if ((j != 2) && (j != 4)) {
13034:                 var item = startelement + j; 
13035:                 if (form.elements[item].type == 'radio') {
13036:                     if (form.elements[item].checked) {
13037:                         containerCheck(form,count,j);
13038:                         break;
13039:                     }
13040:                 }
13041:             }
13042:         }
13043:     }
13044: }
13045: 
13046: numitems = $numitems
13047: var titles = new Array(numitems);
13048: var parents = new Array(numitems);
13049: for (var i=0; i<numitems; i++) {
13050:     parents[i] = new Array;
13051: }
13052: var maintitle = '$maintitle';
13053: 
13054: START
13055: 
13056:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13057:         my @contents = split(/:/,$children->{$container});
13058:         for (my $i=0; $i<@contents; $i ++) {
13059:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13060:         }
13061:     }
13062: 
13063:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13064:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13065:     }
13066: 
13067:     $scripttag .= <<END;
13068: 
13069: function containerCheck(form,count,offset) {
13070:     if (count > 0) {
13071:         dependencyCheck(form,count,offset);
13072:         var item = (offset+$startcount)+7*(count-1);
13073:         form.elements[item].checked = true;
13074:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13075:             if (parents[count].length > 0) {
13076:                 for (var j=0; j<parents[count].length; j++) {
13077:                     containerCheck(form,parents[count][j],offset);
13078:                 }
13079:             }
13080:         }
13081:     }
13082: }
13083: 
13084: function dependencyCheck(form,count,offset) {
13085:     if (count > 0) {
13086:         var chosen = (offset+$startcount)+7*(count-1);
13087:         var depitem = $startcount + ((count-1) * 7) + 4;
13088:         var currtype = form.elements[depitem].type;
13089:         if (form.elements[chosen].value == 'dependency') {
13090:             document.getElementById('arc_depon_'+count).style.display='block'; 
13091:             form.elements[depitem].options.length = 0;
13092:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13093:             for (var i=1; i<=numitems; i++) {
13094:                 if (i == count) {
13095:                     continue;
13096:                 }
13097:                 var startelement = $startcount + (i-1) * 7;
13098:                 for (var j=1; j<6; j++) {
13099:                     if ((j != 2) && (j!= 4)) {
13100:                         var item = startelement + j;
13101:                         if (form.elements[item].type == 'radio') {
13102:                             if (form.elements[item].checked) {
13103:                                 if (form.elements[item].value == 'display') {
13104:                                     var n = form.elements[depitem].options.length;
13105:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13106:                                 }
13107:                             }
13108:                         }
13109:                     }
13110:                 }
13111:             }
13112:         } else {
13113:             document.getElementById('arc_depon_'+count).style.display='none';
13114:             form.elements[depitem].options.length = 0;
13115:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13116:         }
13117:         titleCheck(form,count,offset);
13118:     }
13119: }
13120: 
13121: function propagateSelect(form,count,offset) {
13122:     if (count > 0) {
13123:         var item = (1+offset+$startcount)+7*(count-1);
13124:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13125:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13126:             if (parents[count].length > 0) {
13127:                 for (var j=0; j<parents[count].length; j++) {
13128:                     containerSelect(form,parents[count][j],offset,picked);
13129:                 }
13130:             }
13131:         }
13132:     }
13133: }
13134: 
13135: function containerSelect(form,count,offset,picked) {
13136:     if (count > 0) {
13137:         var item = (offset+$startcount)+7*(count-1);
13138:         if (form.elements[item].type == 'radio') {
13139:             if (form.elements[item].value == 'dependency') {
13140:                 if (form.elements[item+1].type == 'select-one') {
13141:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13142:                         if (form.elements[item+1].options[i].value == picked) {
13143:                             form.elements[item+1].selectedIndex = i;
13144:                             break;
13145:                         }
13146:                     }
13147:                 }
13148:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13149:                     if (parents[count].length > 0) {
13150:                         for (var j=0; j<parents[count].length; j++) {
13151:                             containerSelect(form,parents[count][j],offset,picked);
13152:                         }
13153:                     }
13154:                 }
13155:             }
13156:         }
13157:     }
13158: }
13159: 
13160: function titleCheck(form,count,offset) {
13161:     if (count > 0) {
13162:         var chosen = (offset+$startcount)+7*(count-1);
13163:         var depitem = $startcount + ((count-1) * 7) + 2;
13164:         var currtype = form.elements[depitem].type;
13165:         if (form.elements[chosen].value == 'display') {
13166:             document.getElementById('arc_title_'+count).style.display='block';
13167:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13168:                 document.getElementById('archive_title_'+count).value=maintitle;
13169:             }
13170:         } else {
13171:             document.getElementById('arc_title_'+count).style.display='none';
13172:             if (currtype == 'text') { 
13173:                 document.getElementById('archive_title_'+count).value='';
13174:             }
13175:         }
13176:     }
13177:     return;
13178: }
13179: 
13180: // ]]>
13181: </script>
13182: END
13183:     return $scripttag;
13184: }
13185: 
13186: sub process_extracted_files {
13187:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13188:     my $numitems = $env{'form.archive_count'};
13189:     return if ((!$numitems) || ($numitems =~ /\D/));
13190:     my @ids=&Apache::lonnet::current_machine_ids();
13191:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13192:         %folders,%containers,%mapinner,%prompttofetch);
13193:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13194:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13195:         $prefix = &LONCAPA::propath($docudom,$docuname);
13196:         $pathtocheck = "$dir_root/$destination";
13197:         $dir = $dir_root;
13198:         $ishome = 1;
13199:     } else {
13200:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13201:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13202:         $dir = "$dir_root/$docudom/$docuname";
13203:     }
13204:     my $currdir = "$dir_root/$destination";
13205:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13206:     if ($env{'form.folderpath'}) {
13207:         my @items = split('&',$env{'form.folderpath'});
13208:         $folders{'0'} = $items[-2];
13209:         if ($env{'form.folderpath'} =~ /\:1$/) {
13210:             $containers{'0'}='page';
13211:         } else {  
13212:             $containers{'0'}='sequence';
13213:         }
13214:     }
13215:     my @archdirs = &get_env_multiple('form.archive_directory');
13216:     if ($numitems) {
13217:         for (my $i=1; $i<=$numitems; $i++) {
13218:             my $path = $env{'form.archive_content_'.$i};
13219:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13220:                 my $item = $1;
13221:                 $toplevelitems{$item} = $i;
13222:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13223:                     $is_dir{$item} = 1;
13224:                 }
13225:             }
13226:         }
13227:     }
13228:     my ($output,%children,%parent,%titles,%dirorder,$result);
13229:     if (keys(%toplevelitems) > 0) {
13230:         my @contents = sort(keys(%toplevelitems));
13231:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13232:                                            \%parent,\@contents,\%dirorder,\%titles);
13233:     }
13234:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13235:     if ($numitems) {
13236:         for (my $i=1; $i<=$numitems; $i++) {
13237:             next if ($env{'form.archive_'.$i} eq 'dependency');
13238:             my $path = $env{'form.archive_content_'.$i};
13239:             if ($path =~ /^\Q$pathtocheck\E/) {
13240:                 if ($env{'form.archive_'.$i} eq 'discard') {
13241:                     if ($prefix ne '' && $path ne '') {
13242:                         if (-e $prefix.$path) {
13243:                             if ((@archdirs > 0) && 
13244:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13245:                                 $todeletedir{$prefix.$path} = 1;
13246:                             } else {
13247:                                 $todelete{$prefix.$path} = 1;
13248:                             }
13249:                         }
13250:                     }
13251:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13252:                     my ($docstitle,$title,$url,$outer);
13253:                     ($title) = ($path =~ m{/([^/]+)$});
13254:                     $docstitle = $env{'form.archive_title_'.$i};
13255:                     if ($docstitle eq '') {
13256:                         $docstitle = $title;
13257:                     }
13258:                     $outer = 0;
13259:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13260:                         if (@{$dirorder{$i}} > 0) {
13261:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13262:                                 if ($env{'form.archive_'.$item} eq 'display') {
13263:                                     $outer = $item;
13264:                                     last;
13265:                                 }
13266:                             }
13267:                         }
13268:                     }
13269:                     my ($errtext,$fatal) = 
13270:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13271:                                                '/'.$folders{$outer}.'.'.
13272:                                                $containers{$outer});
13273:                     next if ($fatal);
13274:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13275:                         if ($context eq 'coursedocs') {
13276:                             $mapinner{$i} = time;
13277:                             $folders{$i} = 'default_'.$mapinner{$i};
13278:                             $containers{$i} = 'sequence';
13279:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13280:                                       $folders{$i}.'.'.$containers{$i};
13281:                             my $newidx = &LONCAPA::map::getresidx();
13282:                             $LONCAPA::map::resources[$newidx]=
13283:                                 $docstitle.':'.$url.':false:normal:res';
13284:                             push(@LONCAPA::map::order,$newidx);
13285:                             my ($outtext,$errtext) =
13286:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13287:                                                         $docuname.'/'.$folders{$outer}.
13288:                                                         '.'.$containers{$outer},1,1);
13289:                             $newseqid{$i} = $newidx;
13290:                             unless ($errtext) {
13291:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13292:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
13293:                                             '</li>'."\n";
13294:                             }
13295:                         }
13296:                     } else {
13297:                         if ($context eq 'coursedocs') {
13298:                             my $newidx=&LONCAPA::map::getresidx();
13299:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13300:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13301:                                       $title;
13302:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13303:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13304:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13305:                                 }
13306:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13307:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13308:                                 }
13309:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13310:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13311:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13312:                                         unless ($ishome) {
13313:                                             my $fetch = "$newdest{$i}/$title";
13314:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13315:                                             $prompttofetch{$fetch} = 1;
13316:                                         }
13317:                                     }
13318:                                 }
13319:                                 $LONCAPA::map::resources[$newidx]=
13320:                                     $docstitle.':'.$url.':false:normal:res';
13321:                                 push(@LONCAPA::map::order, $newidx);
13322:                                 my ($outtext,$errtext)=
13323:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13324:                                                             $docuname.'/'.$folders{$outer}.
13325:                                                             '.'.$containers{$outer},1,1);
13326:                                 unless ($errtext) {
13327:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13328:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13329:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13330:                                                    '</li>'."\n";
13331:                                     }
13332:                                 }
13333:                             } else {
13334:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13335:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13336:                             }
13337:                         }
13338:                     }
13339:                 }
13340:             } else {
13341:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13342:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
13343:             }
13344:         }
13345:         for (my $i=1; $i<=$numitems; $i++) {
13346:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13347:             my $path = $env{'form.archive_content_'.$i};
13348:             if ($path =~ /^\Q$pathtocheck\E/) {
13349:                 my ($title) = ($path =~ m{/([^/]+)$});
13350:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13351:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13352:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13353:                         my ($itemidx,$fullpath,$relpath);
13354:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13355:                             my $container = $dirorder{$referrer{$i}}->[-1];
13356:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13357:                                 if ($dirorder{$i}->[$j] eq $container) {
13358:                                     $itemidx = $j;
13359:                                 }
13360:                             }
13361:                         }
13362:                         if ($itemidx eq '') {
13363:                             $itemidx =  0;
13364:                         } 
13365:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13366:                             if ($mapinner{$referrer{$i}}) {
13367:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13368:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13369:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13370:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13371:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13372:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13373:                                             if (!-e $fullpath) {
13374:                                                 mkdir($fullpath,0755);
13375:                                             }
13376:                                         }
13377:                                     } else {
13378:                                         last;
13379:                                     }
13380:                                 }
13381:                             }
13382:                         } elsif ($newdest{$referrer{$i}}) {
13383:                             $fullpath = $newdest{$referrer{$i}};
13384:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13385:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13386:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13387:                                     last;
13388:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13389:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13390:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13391:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13392:                                         if (!-e $fullpath) {
13393:                                             mkdir($fullpath,0755);
13394:                                         }
13395:                                     }
13396:                                 } else {
13397:                                     last;
13398:                                 }
13399:                             }
13400:                         }
13401:                         if ($fullpath ne '') {
13402:                             if (-e "$prefix$path") {
13403:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13404:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13405:                                 }
13406:                             }
13407:                             if (-e "$fullpath/$title") {
13408:                                 my $showpath;
13409:                                 if ($relpath ne '') {
13410:                                     $showpath = "$relpath/$title";
13411:                                 } else {
13412:                                     $showpath = "/$title";
13413:                                 } 
13414:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13415:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13416:                                            '</li>'."\n";
13417:                                 unless ($ishome) {
13418:                                     my $fetch = "$fullpath/$title";
13419:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
13420:                                     $prompttofetch{$fetch} = 1;
13421:                                 }
13422:                             }
13423:                         }
13424:                     }
13425:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13426:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13427:                                     &HTML::Entities::encode($path,'<>&"'),
13428:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13429:                                 '<br />';
13430:                 }
13431:             } else {
13432:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13433:                                 &HTML::Entities::encode($path)).'<br />';
13434:             }
13435:         }
13436:         if (keys(%todelete)) {
13437:             foreach my $key (keys(%todelete)) {
13438:                 unlink($key);
13439:             }
13440:         }
13441:         if (keys(%todeletedir)) {
13442:             foreach my $key (keys(%todeletedir)) {
13443:                 rmdir($key);
13444:             }
13445:         }
13446:         foreach my $dir (sort(keys(%is_dir))) {
13447:             if (($pathtocheck ne '') && ($dir ne ''))  {
13448:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13449:             }
13450:         }
13451:         if ($result ne '') {
13452:             $output .= '<ul>'."\n".
13453:                        $result."\n".
13454:                        '</ul>';
13455:         }
13456:         unless ($ishome) {
13457:             my $replicationfail;
13458:             foreach my $item (keys(%prompttofetch)) {
13459:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13460:                 unless ($fetchresult eq 'ok') {
13461:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13462:                 }
13463:             }
13464:             if ($replicationfail) {
13465:                 $output .= '<p class="LC_error">'.
13466:                            &mt('Course home server failed to retrieve:').'<ul>'.
13467:                            $replicationfail.
13468:                            '</ul></p>';
13469:             }
13470:         }
13471:     } else {
13472:         $warning = &mt('No items found in archive.');
13473:     }
13474:     if ($error) {
13475:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13476:                    $error.'</p>'."\n";
13477:     }
13478:     if ($warning) {
13479:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13480:     }
13481:     return $output;
13482: }
13483: 
13484: sub cleanup_empty_dirs {
13485:     my ($path) = @_;
13486:     if (($path ne '') && (-d $path)) {
13487:         if (opendir(my $dirh,$path)) {
13488:             my @dircontents = grep(!/^\./,readdir($dirh));
13489:             my $numitems = 0;
13490:             foreach my $item (@dircontents) {
13491:                 if (-d "$path/$item") {
13492:                     &cleanup_empty_dirs("$path/$item");
13493:                     if (-e "$path/$item") {
13494:                         $numitems ++;
13495:                     }
13496:                 } else {
13497:                     $numitems ++;
13498:                 }
13499:             }
13500:             if ($numitems == 0) {
13501:                 rmdir($path);
13502:             }
13503:             closedir($dirh);
13504:         }
13505:     }
13506:     return;
13507: }
13508: 
13509: =pod
13510: 
13511: =item * &get_folder_hierarchy()
13512: 
13513: Provides hierarchy of names of folders/sub-folders containing the current
13514: item,
13515: 
13516: Inputs: 3
13517:      - $navmap - navmaps object
13518: 
13519:      - $map - url for map (either the trigger itself, or map containing
13520:                            the resource, which is the trigger).
13521: 
13522:      - $showitem - 1 => show title for map itself; 0 => do not show.
13523: 
13524: Outputs: 1 @pathitems - array of folder/subfolder names.
13525: 
13526: =cut
13527: 
13528: sub get_folder_hierarchy {
13529:     my ($navmap,$map,$showitem) = @_;
13530:     my @pathitems;
13531:     if (ref($navmap)) {
13532:         my $mapres = $navmap->getResourceByUrl($map);
13533:         if (ref($mapres)) {
13534:             my $pcslist = $mapres->map_hierarchy();
13535:             if ($pcslist ne '') {
13536:                 my @pcs = split(/,/,$pcslist);
13537:                 foreach my $pc (@pcs) {
13538:                     if ($pc == 1) {
13539:                         push(@pathitems,&mt('Main Content'));
13540:                     } else {
13541:                         my $res = $navmap->getByMapPc($pc);
13542:                         if (ref($res)) {
13543:                             my $title = $res->compTitle();
13544:                             $title =~ s/\W+/_/g;
13545:                             if ($title ne '') {
13546:                                 push(@pathitems,$title);
13547:                             }
13548:                         }
13549:                     }
13550:                 }
13551:             }
13552:             if ($showitem) {
13553:                 if ($mapres->{ID} eq '0.0') {
13554:                     push(@pathitems,&mt('Main Content'));
13555:                 } else {
13556:                     my $maptitle = $mapres->compTitle();
13557:                     $maptitle =~ s/\W+/_/g;
13558:                     if ($maptitle ne '') {
13559:                         push(@pathitems,$maptitle);
13560:                     }
13561:                 }
13562:             }
13563:         }
13564:     }
13565:     return @pathitems;
13566: }
13567: 
13568: =pod
13569: 
13570: =item * &get_turnedin_filepath()
13571: 
13572: Determines path in a user's portfolio file for storage of files uploaded
13573: to a specific essayresponse or dropbox item.
13574: 
13575: Inputs: 3 required + 1 optional.
13576: $symb is symb for resource, $uname and $udom are for current user (required).
13577: $caller is optional (can be "submission", if routine is called when storing
13578: an upoaded file when "Submit Answer" button was pressed).
13579: 
13580: Returns array containing $path and $multiresp. 
13581: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13582: than one file upload item.  Callers of routine should append partid as a 
13583: subdirectory to $path in cases where $multiresp is 1.
13584: 
13585: Called by: homework/essayresponse.pm and homework/structuretags.pm
13586: 
13587: =cut
13588: 
13589: sub get_turnedin_filepath {
13590:     my ($symb,$uname,$udom,$caller) = @_;
13591:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13592:     my $turnindir;
13593:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13594:     $turnindir = $userhash{'turnindir'};
13595:     my ($path,$multiresp);
13596:     if ($turnindir eq '') {
13597:         if ($caller eq 'submission') {
13598:             $turnindir = &mt('turned in');
13599:             $turnindir =~ s/\W+/_/g;
13600:             my %newhash = (
13601:                             'turnindir' => $turnindir,
13602:                           );
13603:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13604:         }
13605:     }
13606:     if ($turnindir ne '') {
13607:         $path = '/'.$turnindir.'/';
13608:         my ($multipart,$turnin,@pathitems);
13609:         my $navmap = Apache::lonnavmaps::navmap->new();
13610:         if (defined($navmap)) {
13611:             my $mapres = $navmap->getResourceByUrl($map);
13612:             if (ref($mapres)) {
13613:                 my $pcslist = $mapres->map_hierarchy();
13614:                 if ($pcslist ne '') {
13615:                     foreach my $pc (split(/,/,$pcslist)) {
13616:                         my $res = $navmap->getByMapPc($pc);
13617:                         if (ref($res)) {
13618:                             my $title = $res->compTitle();
13619:                             $title =~ s/\W+/_/g;
13620:                             if ($title ne '') {
13621:                                 if (($pc > 1) && (length($title) > 12)) {
13622:                                     $title = substr($title,0,12);
13623:                                 }
13624:                                 push(@pathitems,$title);
13625:                             }
13626:                         }
13627:                     }
13628:                 }
13629:                 my $maptitle = $mapres->compTitle();
13630:                 $maptitle =~ s/\W+/_/g;
13631:                 if ($maptitle ne '') {
13632:                     if (length($maptitle) > 12) {
13633:                         $maptitle = substr($maptitle,0,12);
13634:                     }
13635:                     push(@pathitems,$maptitle);
13636:                 }
13637:                 unless ($env{'request.state'} eq 'construct') {
13638:                     my $res = $navmap->getBySymb($symb);
13639:                     if (ref($res)) {
13640:                         my $partlist = $res->parts();
13641:                         my $totaluploads = 0;
13642:                         if (ref($partlist) eq 'ARRAY') {
13643:                             foreach my $part (@{$partlist}) {
13644:                                 my @types = $res->responseType($part);
13645:                                 my @ids = $res->responseIds($part);
13646:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13647:                                     if ($types[$i] eq 'essay') {
13648:                                         my $partid = $part.'_'.$ids[$i];
13649:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13650:                                             $totaluploads ++;
13651:                                         }
13652:                                     }
13653:                                 }
13654:                             }
13655:                             if ($totaluploads > 1) {
13656:                                 $multiresp = 1;
13657:                             }
13658:                         }
13659:                     }
13660:                 }
13661:             } else {
13662:                 return;
13663:             }
13664:         } else {
13665:             return;
13666:         }
13667:         my $restitle=&Apache::lonnet::gettitle($symb);
13668:         $restitle =~ s/\W+/_/g;
13669:         if ($restitle eq '') {
13670:             $restitle = ($resurl =~ m{/[^/]+$});
13671:             if ($restitle eq '') {
13672:                 $restitle = time;
13673:             }
13674:         }
13675:         if (length($restitle) > 12) {
13676:             $restitle = substr($restitle,0,12);
13677:         }
13678:         push(@pathitems,$restitle);
13679:         $path .= join('/',@pathitems);
13680:     }
13681:     return ($path,$multiresp);
13682: }
13683: 
13684: =pod
13685: 
13686: =back
13687: 
13688: =head1 CSV Upload/Handling functions
13689: 
13690: =over 4
13691: 
13692: =item * &upfile_store($r)
13693: 
13694: Store uploaded file, $r should be the HTTP Request object,
13695: needs $env{'form.upfile'}
13696: returns $datatoken to be put into hidden field
13697: 
13698: =cut
13699: 
13700: sub upfile_store {
13701:     my $r=shift;
13702:     $env{'form.upfile'}=~s/\r/\n/gs;
13703:     $env{'form.upfile'}=~s/\f/\n/gs;
13704:     $env{'form.upfile'}=~s/\n+/\n/gs;
13705:     $env{'form.upfile'}=~s/\n+$//gs;
13706: 
13707:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13708:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13709:                                      time.'_'.$$);
13710:     return if ($datatoken eq '');
13711: 
13712:     {
13713:         my $datafile = $r->dir_config('lonDaemons').
13714:                            '/tmp/'.$datatoken.'.tmp';
13715:         if ( open(my $fh,">$datafile") ) {
13716:             print $fh $env{'form.upfile'};
13717:             close($fh);
13718:         }
13719:     }
13720:     return $datatoken;
13721: }
13722: 
13723: =pod
13724: 
13725: =item * &load_tmp_file($r,$datatoken)
13726: 
13727: Load uploaded file from tmp, $r should be the HTTP Request object,
13728: $datatoken is the name to assign to the temporary file.
13729: sets $env{'form.upfile'} to the contents of the file
13730: 
13731: =cut
13732: 
13733: sub load_tmp_file {
13734:     my ($r,$datatoken) = @_;
13735:     return if ($datatoken eq '');
13736:     my @studentdata=();
13737:     {
13738:         my $studentfile = $r->dir_config('lonDaemons').
13739:                               '/tmp/'.$datatoken.'.tmp';
13740:         if ( open(my $fh,"<$studentfile") ) {
13741:             @studentdata=<$fh>;
13742:             close($fh);
13743:         }
13744:     }
13745:     $env{'form.upfile'}=join('',@studentdata);
13746: }
13747: 
13748: sub valid_datatoken {
13749:     my ($datatoken) = @_;
13750:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_$match_domain\_$match_courseid\_\d+_\d+$/) {
13751:         return $datatoken;
13752:     }
13753:     return;
13754: }
13755: 
13756: =pod
13757: 
13758: =item * &upfile_record_sep()
13759: 
13760: Separate uploaded file into records
13761: returns array of records,
13762: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13763: 
13764: =cut
13765: 
13766: sub upfile_record_sep {
13767:     if ($env{'form.upfiletype'} eq 'xml') {
13768:     } else {
13769: 	my @records;
13770: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13771: 	    if ($line=~/^\s*$/) { next; }
13772: 	    push(@records,$line);
13773: 	}
13774: 	return @records;
13775:     }
13776: }
13777: 
13778: =pod
13779: 
13780: =item * &record_sep($record)
13781: 
13782: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13783: 
13784: =cut
13785: 
13786: sub takeleft {
13787:     my $index=shift;
13788:     return substr('0000'.$index,-4,4);
13789: }
13790: 
13791: sub record_sep {
13792:     my $record=shift;
13793:     my %components=();
13794:     if ($env{'form.upfiletype'} eq 'xml') {
13795:     } elsif ($env{'form.upfiletype'} eq 'space') {
13796:         my $i=0;
13797:         foreach my $field (split(/\s+/,$record)) {
13798:             $field=~s/^(\"|\')//;
13799:             $field=~s/(\"|\')$//;
13800:             $components{&takeleft($i)}=$field;
13801:             $i++;
13802:         }
13803:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13804:         my $i=0;
13805:         foreach my $field (split(/\t/,$record)) {
13806:             $field=~s/^(\"|\')//;
13807:             $field=~s/(\"|\')$//;
13808:             $components{&takeleft($i)}=$field;
13809:             $i++;
13810:         }
13811:     } else {
13812:         my $separator=',';
13813:         if ($env{'form.upfiletype'} eq 'semisv') {
13814:             $separator=';';
13815:         }
13816:         my $i=0;
13817: # the character we are looking for to indicate the end of a quote or a record 
13818:         my $looking_for=$separator;
13819: # do not add the characters to the fields
13820:         my $ignore=0;
13821: # we just encountered a separator (or the beginning of the record)
13822:         my $just_found_separator=1;
13823: # store the field we are working on here
13824:         my $field='';
13825: # work our way through all characters in record
13826:         foreach my $character ($record=~/(.)/g) {
13827:             if ($character eq $looking_for) {
13828:                if ($character ne $separator) {
13829: # Found the end of a quote, again looking for separator
13830:                   $looking_for=$separator;
13831:                   $ignore=1;
13832:                } else {
13833: # Found a separator, store away what we got
13834:                   $components{&takeleft($i)}=$field;
13835: 	          $i++;
13836:                   $just_found_separator=1;
13837:                   $ignore=0;
13838:                   $field='';
13839:                }
13840:                next;
13841:             }
13842: # single or double quotation marks after a separator indicate beginning of a quote
13843: # we are now looking for the end of the quote and need to ignore separators
13844:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13845:                $looking_for=$character;
13846:                next;
13847:             }
13848: # ignore would be true after we reached the end of a quote
13849:             if ($ignore) { next; }
13850:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13851:             $field.=$character;
13852:             $just_found_separator=0; 
13853:         }
13854: # catch the very last entry, since we never encountered the separator
13855:         $components{&takeleft($i)}=$field;
13856:     }
13857:     return %components;
13858: }
13859: 
13860: ######################################################
13861: ######################################################
13862: 
13863: =pod
13864: 
13865: =item * &upfile_select_html()
13866: 
13867: Return HTML code to select a file from the users machine and specify 
13868: the file type.
13869: 
13870: =cut
13871: 
13872: ######################################################
13873: ######################################################
13874: sub upfile_select_html {
13875:     my %Types = (
13876:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13877:                  semisv => &mt('Semicolon separated values'),
13878:                  space => &mt('Space separated'),
13879:                  tab   => &mt('Tabulator separated'),
13880: #                 xml   => &mt('HTML/XML'),
13881:                  );
13882:     my $Str = '<input type="file" name="upfile" size="50" />'.
13883:         '<br />'.&mt('Type').': <select name="upfiletype">';
13884:     foreach my $type (sort(keys(%Types))) {
13885:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13886:     }
13887:     $Str .= "</select>\n";
13888:     return $Str;
13889: }
13890: 
13891: sub get_samples {
13892:     my ($records,$toget) = @_;
13893:     my @samples=({});
13894:     my $got=0;
13895:     foreach my $rec (@$records) {
13896: 	my %temp = &record_sep($rec);
13897: 	if (! grep(/\S/, values(%temp))) { next; }
13898: 	if (%temp) {
13899: 	    $samples[$got]=\%temp;
13900: 	    $got++;
13901: 	    if ($got == $toget) { last; }
13902: 	}
13903:     }
13904:     return \@samples;
13905: }
13906: 
13907: ######################################################
13908: ######################################################
13909: 
13910: =pod
13911: 
13912: =item * &csv_print_samples($r,$records)
13913: 
13914: Prints a table of sample values from each column uploaded $r is an
13915: Apache Request ref, $records is an arrayref from
13916: &Apache::loncommon::upfile_record_sep
13917: 
13918: =cut
13919: 
13920: ######################################################
13921: ######################################################
13922: sub csv_print_samples {
13923:     my ($r,$records) = @_;
13924:     my $samples = &get_samples($records,5);
13925: 
13926:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13927:               &start_data_table_header_row());
13928:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13929:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13930:     $r->print(&end_data_table_header_row());
13931:     foreach my $hash (@$samples) {
13932: 	$r->print(&start_data_table_row());
13933: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13934: 	    $r->print('<td>');
13935: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13936: 	    $r->print('</td>');
13937: 	}
13938: 	$r->print(&end_data_table_row());
13939:     }
13940:     $r->print(&end_data_table().'<br />'."\n");
13941: }
13942: 
13943: ######################################################
13944: ######################################################
13945: 
13946: =pod
13947: 
13948: =item * &csv_print_select_table($r,$records,$d)
13949: 
13950: Prints a table to create associations between values and table columns.
13951: 
13952: $r is an Apache Request ref,
13953: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13954: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13955: 
13956: =cut
13957: 
13958: ######################################################
13959: ######################################################
13960: sub csv_print_select_table {
13961:     my ($r,$records,$d) = @_;
13962:     my $i=0;
13963:     my $samples = &get_samples($records,1);
13964:     $r->print(&mt('Associate columns with student attributes.')."\n".
13965: 	      &start_data_table().&start_data_table_header_row().
13966:               '<th>'.&mt('Attribute').'</th>'.
13967:               '<th>'.&mt('Column').'</th>'.
13968:               &end_data_table_header_row()."\n");
13969:     foreach my $array_ref (@$d) {
13970: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13971: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13972: 
13973: 	$r->print('<td><select name="f'.$i.'"'.
13974: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13975: 	$r->print('<option value="none"></option>');
13976: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13977: 	    $r->print('<option value="'.$sample.'"'.
13978:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13979:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13980: 	}
13981: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13982: 	$i++;
13983:     }
13984:     $r->print(&end_data_table());
13985:     $i--;
13986:     return $i;
13987: }
13988: 
13989: ######################################################
13990: ######################################################
13991: 
13992: =pod
13993: 
13994: =item * &csv_samples_select_table($r,$records,$d)
13995: 
13996: Prints a table of sample values from the upload and can make associate samples to internal names.
13997: 
13998: $r is an Apache Request ref,
13999: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14000: $d is an array of 2 element arrays (internal name, displayed name)
14001: 
14002: =cut
14003: 
14004: ######################################################
14005: ######################################################
14006: sub csv_samples_select_table {
14007:     my ($r,$records,$d) = @_;
14008:     my $i=0;
14009:     #
14010:     my $max_samples = 5;
14011:     my $samples = &get_samples($records,$max_samples);
14012:     $r->print(&start_data_table().
14013:               &start_data_table_header_row().'<th>'.
14014:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14015:               &end_data_table_header_row());
14016: 
14017:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14018: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14019: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14020: 	foreach my $option (@$d) {
14021: 	    my ($value,$display,$defaultcol)=@{ $option };
14022: 	    $r->print('<option value="'.$value.'"'.
14023:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14024:                       $display.'</option>');
14025: 	}
14026: 	$r->print('</select></td><td>');
14027: 	foreach my $line (0..($max_samples-1)) {
14028: 	    if (defined($samples->[$line]{$key})) { 
14029: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14030: 	    }
14031: 	}
14032: 	$r->print('</td>'.&end_data_table_row());
14033: 	$i++;
14034:     }
14035:     $r->print(&end_data_table());
14036:     $i--;
14037:     return($i);
14038: }
14039: 
14040: ######################################################
14041: ######################################################
14042: 
14043: =pod
14044: 
14045: =item * &clean_excel_name($name)
14046: 
14047: Returns a replacement for $name which does not contain any illegal characters.
14048: 
14049: =cut
14050: 
14051: ######################################################
14052: ######################################################
14053: sub clean_excel_name {
14054:     my ($name) = @_;
14055:     $name =~ s/[:\*\?\/\\]//g;
14056:     if (length($name) > 31) {
14057:         $name = substr($name,0,31);
14058:     }
14059:     return $name;
14060: }
14061: 
14062: =pod
14063: 
14064: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14065: 
14066: Returns either 1 or undef
14067: 
14068: 1 if the part is to be hidden, undef if it is to be shown
14069: 
14070: Arguments are:
14071: 
14072: $id the id of the part to be checked
14073: $symb, optional the symb of the resource to check
14074: $udom, optional the domain of the user to check for
14075: $uname, optional the username of the user to check for
14076: 
14077: =cut
14078: 
14079: sub check_if_partid_hidden {
14080:     my ($id,$symb,$udom,$uname) = @_;
14081:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14082: 					 $symb,$udom,$uname);
14083:     my $truth=1;
14084:     #if the string starts with !, then the list is the list to show not hide
14085:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14086:     my @hiddenlist=split(/,/,$hiddenparts);
14087:     foreach my $checkid (@hiddenlist) {
14088: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14089:     }
14090:     return !$truth;
14091: }
14092: 
14093: 
14094: ############################################################
14095: ############################################################
14096: 
14097: =pod
14098: 
14099: =back 
14100: 
14101: =head1 cgi-bin script and graphing routines
14102: 
14103: =over 4
14104: 
14105: =item * &get_cgi_id()
14106: 
14107: Inputs: none
14108: 
14109: Returns an id which can be used to pass environment variables
14110: to various cgi-bin scripts.  These environment variables will
14111: be removed from the users environment after a given time by
14112: the routine &Apache::lonnet::transfer_profile_to_env.
14113: 
14114: =cut
14115: 
14116: ############################################################
14117: ############################################################
14118: my $uniq=0;
14119: sub get_cgi_id {
14120:     $uniq=($uniq+1)%100000;
14121:     return (time.'_'.$$.'_'.$uniq);
14122: }
14123: 
14124: ############################################################
14125: ############################################################
14126: 
14127: =pod
14128: 
14129: =item * &DrawBarGraph()
14130: 
14131: Facilitates the plotting of data in a (stacked) bar graph.
14132: Puts plot definition data into the users environment in order for 
14133: graph.png to plot it.  Returns an <img> tag for the plot.
14134: The bars on the plot are labeled '1','2',...,'n'.
14135: 
14136: Inputs:
14137: 
14138: =over 4
14139: 
14140: =item $Title: string, the title of the plot
14141: 
14142: =item $xlabel: string, text describing the X-axis of the plot
14143: 
14144: =item $ylabel: string, text describing the Y-axis of the plot
14145: 
14146: =item $Max: scalar, the maximum Y value to use in the plot
14147: If $Max is < any data point, the graph will not be rendered.
14148: 
14149: =item $colors: array ref holding the colors to be used for the data sets when
14150: they are plotted.  If undefined, default values will be used.
14151: 
14152: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14153: 
14154: =item @Values: An array of array references.  Each array reference holds data
14155: to be plotted in a stacked bar chart.
14156: 
14157: =item If the final element of @Values is a hash reference the key/value
14158: pairs will be added to the graph definition.
14159: 
14160: =back
14161: 
14162: Returns:
14163: 
14164: An <img> tag which references graph.png and the appropriate identifying
14165: information for the plot.
14166: 
14167: =cut
14168: 
14169: ############################################################
14170: ############################################################
14171: sub DrawBarGraph {
14172:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14173:     #
14174:     if (! defined($colors)) {
14175:         $colors = ['#33ff00', 
14176:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14177:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14178:                   ]; 
14179:     }
14180:     my $extra_settings = {};
14181:     if (ref($Values[-1]) eq 'HASH') {
14182:         $extra_settings = pop(@Values);
14183:     }
14184:     #
14185:     my $identifier = &get_cgi_id();
14186:     my $id = 'cgi.'.$identifier;        
14187:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14188:         return '';
14189:     }
14190:     #
14191:     my @Labels;
14192:     if (defined($labels)) {
14193:         @Labels = @$labels;
14194:     } else {
14195:         for (my $i=0;$i<@{$Values[0]};$i++) {
14196:             push(@Labels,$i+1);
14197:         }
14198:     }
14199:     #
14200:     my $NumBars = scalar(@{$Values[0]});
14201:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14202:     my %ValuesHash;
14203:     my $NumSets=1;
14204:     foreach my $array (@Values) {
14205:         next if (! ref($array));
14206:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14207:             join(',',@$array);
14208:     }
14209:     #
14210:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14211:     if ($NumBars < 3) {
14212:         $width = 120+$NumBars*32;
14213:         $xskip = 1;
14214:         $bar_width = 30;
14215:     } elsif ($NumBars < 5) {
14216:         $width = 120+$NumBars*20;
14217:         $xskip = 1;
14218:         $bar_width = 20;
14219:     } elsif ($NumBars < 10) {
14220:         $width = 120+$NumBars*15;
14221:         $xskip = 1;
14222:         $bar_width = 15;
14223:     } elsif ($NumBars <= 25) {
14224:         $width = 120+$NumBars*11;
14225:         $xskip = 5;
14226:         $bar_width = 8;
14227:     } elsif ($NumBars <= 50) {
14228:         $width = 120+$NumBars*8;
14229:         $xskip = 5;
14230:         $bar_width = 4;
14231:     } else {
14232:         $width = 120+$NumBars*8;
14233:         $xskip = 5;
14234:         $bar_width = 4;
14235:     }
14236:     #
14237:     $Max = 1 if ($Max < 1);
14238:     if ( int($Max) < $Max ) {
14239:         $Max++;
14240:         $Max = int($Max);
14241:     }
14242:     $Title  = '' if (! defined($Title));
14243:     $xlabel = '' if (! defined($xlabel));
14244:     $ylabel = '' if (! defined($ylabel));
14245:     $ValuesHash{$id.'.title'}    = &escape($Title);
14246:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14247:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14248:     $ValuesHash{$id.'.y_max_value'} = $Max;
14249:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14250:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14251:     $ValuesHash{$id.'.PlotType'} = 'bar';
14252:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14253:     $ValuesHash{$id.'.height'}   = $height;
14254:     $ValuesHash{$id.'.width'}    = $width;
14255:     $ValuesHash{$id.'.xskip'}    = $xskip;
14256:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14257:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14258:     #
14259:     # Deal with other parameters
14260:     while (my ($key,$value) = each(%$extra_settings)) {
14261:         $ValuesHash{$id.'.'.$key} = $value;
14262:     }
14263:     #
14264:     &Apache::lonnet::appenv(\%ValuesHash);
14265:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14266: }
14267: 
14268: ############################################################
14269: ############################################################
14270: 
14271: =pod
14272: 
14273: =item * &DrawXYGraph()
14274: 
14275: Facilitates the plotting of data in an XY graph.
14276: Puts plot definition data into the users environment in order for 
14277: graph.png to plot it.  Returns an <img> tag for the plot.
14278: 
14279: Inputs:
14280: 
14281: =over 4
14282: 
14283: =item $Title: string, the title of the plot
14284: 
14285: =item $xlabel: string, text describing the X-axis of the plot
14286: 
14287: =item $ylabel: string, text describing the Y-axis of the plot
14288: 
14289: =item $Max: scalar, the maximum Y value to use in the plot
14290: If $Max is < any data point, the graph will not be rendered.
14291: 
14292: =item $colors: Array ref containing the hex color codes for the data to be 
14293: plotted in.  If undefined, default values will be used.
14294: 
14295: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14296: 
14297: =item $Ydata: Array ref containing Array refs.  
14298: Each of the contained arrays will be plotted as a separate curve.
14299: 
14300: =item %Values: hash indicating or overriding any default values which are 
14301: passed to graph.png.  
14302: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14303: 
14304: =back
14305: 
14306: Returns:
14307: 
14308: An <img> tag which references graph.png and the appropriate identifying
14309: information for the plot.
14310: 
14311: =cut
14312: 
14313: ############################################################
14314: ############################################################
14315: sub DrawXYGraph {
14316:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14317:     #
14318:     # Create the identifier for the graph
14319:     my $identifier = &get_cgi_id();
14320:     my $id = 'cgi.'.$identifier;
14321:     #
14322:     $Title  = '' if (! defined($Title));
14323:     $xlabel = '' if (! defined($xlabel));
14324:     $ylabel = '' if (! defined($ylabel));
14325:     my %ValuesHash = 
14326:         (
14327:          $id.'.title'  => &escape($Title),
14328:          $id.'.xlabel' => &escape($xlabel),
14329:          $id.'.ylabel' => &escape($ylabel),
14330:          $id.'.y_max_value'=> $Max,
14331:          $id.'.labels'     => join(',',@$Xlabels),
14332:          $id.'.PlotType'   => 'XY',
14333:          );
14334:     #
14335:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14336:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14337:     }
14338:     #
14339:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14340:         return '';
14341:     }
14342:     my $NumSets=1;
14343:     foreach my $array (@{$Ydata}){
14344:         next if (! ref($array));
14345:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14346:     }
14347:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14348:     #
14349:     # Deal with other parameters
14350:     while (my ($key,$value) = each(%Values)) {
14351:         $ValuesHash{$id.'.'.$key} = $value;
14352:     }
14353:     #
14354:     &Apache::lonnet::appenv(\%ValuesHash);
14355:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14356: }
14357: 
14358: ############################################################
14359: ############################################################
14360: 
14361: =pod
14362: 
14363: =item * &DrawXYYGraph()
14364: 
14365: Facilitates the plotting of data in an XY graph with two Y axes.
14366: Puts plot definition data into the users environment in order for 
14367: graph.png to plot it.  Returns an <img> tag for the plot.
14368: 
14369: Inputs:
14370: 
14371: =over 4
14372: 
14373: =item $Title: string, the title of the plot
14374: 
14375: =item $xlabel: string, text describing the X-axis of the plot
14376: 
14377: =item $ylabel: string, text describing the Y-axis of the plot
14378: 
14379: =item $colors: Array ref containing the hex color codes for the data to be 
14380: plotted in.  If undefined, default values will be used.
14381: 
14382: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14383: 
14384: =item $Ydata1: The first data set
14385: 
14386: =item $Min1: The minimum value of the left Y-axis
14387: 
14388: =item $Max1: The maximum value of the left Y-axis
14389: 
14390: =item $Ydata2: The second data set
14391: 
14392: =item $Min2: The minimum value of the right Y-axis
14393: 
14394: =item $Max2: The maximum value of the left Y-axis
14395: 
14396: =item %Values: hash indicating or overriding any default values which are 
14397: passed to graph.png.  
14398: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14399: 
14400: =back
14401: 
14402: Returns:
14403: 
14404: An <img> tag which references graph.png and the appropriate identifying
14405: information for the plot.
14406: 
14407: =cut
14408: 
14409: ############################################################
14410: ############################################################
14411: sub DrawXYYGraph {
14412:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14413:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14414:     #
14415:     # Create the identifier for the graph
14416:     my $identifier = &get_cgi_id();
14417:     my $id = 'cgi.'.$identifier;
14418:     #
14419:     $Title  = '' if (! defined($Title));
14420:     $xlabel = '' if (! defined($xlabel));
14421:     $ylabel = '' if (! defined($ylabel));
14422:     my %ValuesHash = 
14423:         (
14424:          $id.'.title'  => &escape($Title),
14425:          $id.'.xlabel' => &escape($xlabel),
14426:          $id.'.ylabel' => &escape($ylabel),
14427:          $id.'.labels' => join(',',@$Xlabels),
14428:          $id.'.PlotType' => 'XY',
14429:          $id.'.NumSets' => 2,
14430:          $id.'.two_axes' => 1,
14431:          $id.'.y1_max_value' => $Max1,
14432:          $id.'.y1_min_value' => $Min1,
14433:          $id.'.y2_max_value' => $Max2,
14434:          $id.'.y2_min_value' => $Min2,
14435:          );
14436:     #
14437:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14438:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14439:     }
14440:     #
14441:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14442:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14443:         return '';
14444:     }
14445:     my $NumSets=1;
14446:     foreach my $array ($Ydata1,$Ydata2){
14447:         next if (! ref($array));
14448:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14449:     }
14450:     #
14451:     # Deal with other parameters
14452:     while (my ($key,$value) = each(%Values)) {
14453:         $ValuesHash{$id.'.'.$key} = $value;
14454:     }
14455:     #
14456:     &Apache::lonnet::appenv(\%ValuesHash);
14457:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14458: }
14459: 
14460: ############################################################
14461: ############################################################
14462: 
14463: =pod
14464: 
14465: =back 
14466: 
14467: =head1 Statistics helper routines?  
14468: 
14469: Bad place for them but what the hell.
14470: 
14471: =over 4
14472: 
14473: =item * &chartlink()
14474: 
14475: Returns a link to the chart for a specific student.  
14476: 
14477: Inputs:
14478: 
14479: =over 4
14480: 
14481: =item $linktext: The text of the link
14482: 
14483: =item $sname: The students username
14484: 
14485: =item $sdomain: The students domain
14486: 
14487: =back
14488: 
14489: =back
14490: 
14491: =cut
14492: 
14493: ############################################################
14494: ############################################################
14495: sub chartlink {
14496:     my ($linktext, $sname, $sdomain) = @_;
14497:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14498:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14499:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14500:        '">'.$linktext.'</a>';
14501: }
14502: 
14503: #######################################################
14504: #######################################################
14505: 
14506: =pod
14507: 
14508: =head1 Course Environment Routines
14509: 
14510: =over 4
14511: 
14512: =item * &restore_course_settings()
14513: 
14514: =item * &store_course_settings()
14515: 
14516: Restores/Store indicated form parameters from the course environment.
14517: Will not overwrite existing values of the form parameters.
14518: 
14519: Inputs: 
14520: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14521: 
14522: a hash ref describing the data to be stored.  For example:
14523:    
14524: %Save_Parameters = ('Status' => 'scalar',
14525:     'chartoutputmode' => 'scalar',
14526:     'chartoutputdata' => 'scalar',
14527:     'Section' => 'array',
14528:     'Group' => 'array',
14529:     'StudentData' => 'array',
14530:     'Maps' => 'array');
14531: 
14532: Returns: both routines return nothing
14533: 
14534: =back
14535: 
14536: =cut
14537: 
14538: #######################################################
14539: #######################################################
14540: sub store_course_settings {
14541:     return &store_settings($env{'request.course.id'},@_);
14542: }
14543: 
14544: sub store_settings {
14545:     # save to the environment
14546:     # appenv the same items, just to be safe
14547:     my $udom  = $env{'user.domain'};
14548:     my $uname = $env{'user.name'};
14549:     my ($context,$prefix,$Settings) = @_;
14550:     my %SaveHash;
14551:     my %AppHash;
14552:     while (my ($setting,$type) = each(%$Settings)) {
14553:         my $basename = join('.','internal',$context,$prefix,$setting);
14554:         my $envname = 'environment.'.$basename;
14555:         if (exists($env{'form.'.$setting})) {
14556:             # Save this value away
14557:             if ($type eq 'scalar' &&
14558:                 (! exists($env{$envname}) || 
14559:                  $env{$envname} ne $env{'form.'.$setting})) {
14560:                 $SaveHash{$basename} = $env{'form.'.$setting};
14561:                 $AppHash{$envname}   = $env{'form.'.$setting};
14562:             } elsif ($type eq 'array') {
14563:                 my $stored_form;
14564:                 if (ref($env{'form.'.$setting})) {
14565:                     $stored_form = join(',',
14566:                                         map {
14567:                                             &escape($_);
14568:                                         } sort(@{$env{'form.'.$setting}}));
14569:                 } else {
14570:                     $stored_form = 
14571:                         &escape($env{'form.'.$setting});
14572:                 }
14573:                 # Determine if the array contents are the same.
14574:                 if ($stored_form ne $env{$envname}) {
14575:                     $SaveHash{$basename} = $stored_form;
14576:                     $AppHash{$envname}   = $stored_form;
14577:                 }
14578:             }
14579:         }
14580:     }
14581:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14582:                                           $udom,$uname);
14583:     if ($put_result !~ /^(ok|delayed)/) {
14584:         &Apache::lonnet::logthis('unable to save form parameters, '.
14585:                                  'got error:'.$put_result);
14586:     }
14587:     # Make sure these settings stick around in this session, too
14588:     &Apache::lonnet::appenv(\%AppHash);
14589:     return;
14590: }
14591: 
14592: sub restore_course_settings {
14593:     return &restore_settings($env{'request.course.id'},@_);
14594: }
14595: 
14596: sub restore_settings {
14597:     my ($context,$prefix,$Settings) = @_;
14598:     while (my ($setting,$type) = each(%$Settings)) {
14599:         next if (exists($env{'form.'.$setting}));
14600:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14601:             '.'.$setting;
14602:         if (exists($env{$envname})) {
14603:             if ($type eq 'scalar') {
14604:                 $env{'form.'.$setting} = $env{$envname};
14605:             } elsif ($type eq 'array') {
14606:                 $env{'form.'.$setting} = [ 
14607:                                            map { 
14608:                                                &unescape($_); 
14609:                                            } split(',',$env{$envname})
14610:                                            ];
14611:             }
14612:         }
14613:     }
14614: }
14615: 
14616: #######################################################
14617: #######################################################
14618: 
14619: =pod
14620: 
14621: =head1 Domain E-mail Routines  
14622: 
14623: =over 4
14624: 
14625: =item * &build_recipient_list()
14626: 
14627: Build recipient lists for following types of e-mail:
14628: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14629: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14630: module change checking, student/employee ID conflict checks, as
14631: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14632: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14633: 
14634: Inputs:
14635: defmail (scalar - email address of default recipient), 
14636: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14637: requestsmail, updatesmail, or idconflictsmail).
14638: 
14639: defdom (domain for which to retrieve configuration settings),
14640: 
14641: origmail (scalar - email address of recipient from loncapa.conf, 
14642: i.e., predates configuration by DC via domainprefs.pm
14643: 
14644: $requname username of requester (if mailing type is helpdeskmail)
14645: 
14646: $requdom domain of requester (if mailing type is helpdeskmail)
14647: 
14648: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14649: 
14650: 
14651: Returns: comma separated list of addresses to which to send e-mail.
14652: 
14653: =back
14654: 
14655: =cut
14656: 
14657: ############################################################
14658: ############################################################
14659: sub build_recipient_list {
14660:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14661:     my @recipients;
14662:     my ($otheremails,$lastresort,$allbcc,$addtext);
14663:     my %domconfig =
14664:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14665:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14666:         if (exists($domconfig{'contacts'}{$mailing})) {
14667:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14668:                 my @contacts = ('adminemail','supportemail');
14669:                 foreach my $item (@contacts) {
14670:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14671:                         my $addr = $domconfig{'contacts'}{$item}; 
14672:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14673:                             push(@recipients,$addr);
14674:                         }
14675:                     }
14676:                 }
14677:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14678:                 if ($mailing eq 'helpdeskmail') {
14679:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14680:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14681:                         my @ok_bccs;
14682:                         foreach my $bcc (@bccs) {
14683:                             $bcc =~ s/^\s+//g;
14684:                             $bcc =~ s/\s+$//g;
14685:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14686:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14687:                                     push(@ok_bccs,$bcc);
14688:                                 }
14689:                             }
14690:                         }
14691:                         if (@ok_bccs > 0) {
14692:                             $allbcc = join(', ',@ok_bccs);
14693:                         }
14694:                     }
14695:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14696:                 }
14697:             }
14698:         } elsif ($origmail ne '') {
14699:             $lastresort = $origmail;
14700:         }
14701:         if ($mailing eq 'helpdeskmail') {
14702:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14703:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14704:                 my ($inststatus,$inststatus_checked);
14705:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14706:                     ($env{'user.domain'} ne 'public')) {
14707:                     $inststatus_checked = 1;
14708:                     $inststatus = $env{'environment.inststatus'};
14709:                 }
14710:                 unless ($inststatus_checked) {
14711:                     if (($requname ne '') && ($requdom ne '')) {
14712:                         if (($requname =~ /^$match_username$/) &&
14713:                             ($requdom =~ /^$match_domain$/) &&
14714:                             (&Apache::lonnet::domain($requdom))) {
14715:                             my $requhome = &Apache::lonnet::homeserver($requname,
14716:                                                                       $requdom);
14717:                             unless ($requhome eq 'no_host') {
14718:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14719:                                 $inststatus = $userenv{'inststatus'};
14720:                                 $inststatus_checked = 1;
14721:                             }
14722:                         }
14723:                     }
14724:                 }
14725:                 unless ($inststatus_checked) {
14726:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14727:                         my %srch = (srchby     => 'email',
14728:                                     srchdomain => $defdom,
14729:                                     srchterm   => $reqemail,
14730:                                     srchtype   => 'exact');
14731:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
14732:                         foreach my $uname (keys(%srch_results)) {
14733:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14734:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14735:                                 $inststatus_checked = 1;
14736:                                 last;
14737:                             }
14738:                         }
14739:                         unless ($inststatus_checked) {
14740:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14741:                             if ($dirsrchres eq 'ok') {
14742:                                 foreach my $uname (keys(%srch_results)) {
14743:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14744:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14745:                                         $inststatus_checked = 1;
14746:                                         last;
14747:                                     }
14748:                                 }
14749:                             }
14750:                         }
14751:                     }
14752:                 }
14753:                 if ($inststatus ne '') {
14754:                     foreach my $status (split(/\:/,$inststatus)) {
14755:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14756:                             my @contacts = ('adminemail','supportemail');
14757:                             foreach my $item (@contacts) {
14758:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14759:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14760:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
14761:                                         push(@recipients,$addr);
14762:                                     }
14763:                                 }
14764:                             }
14765:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14766:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14767:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14768:                                 my @ok_bccs;
14769:                                 foreach my $bcc (@bccs) {
14770:                                     $bcc =~ s/^\s+//g;
14771:                                     $bcc =~ s/\s+$//g;
14772:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14773:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14774:                                             push(@ok_bccs,$bcc);
14775:                                         }
14776:                                     }
14777:                                 }
14778:                                 if (@ok_bccs > 0) {
14779:                                     $allbcc = join(', ',@ok_bccs);
14780:                                 }
14781:                             }
14782:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14783:                             last;
14784:                         }
14785:                     }
14786:                 }
14787:             }
14788:         }
14789:     } elsif ($origmail ne '') {
14790:         $lastresort = $origmail;
14791:     }
14792:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14793:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14794:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14795:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14796:             my %what = (
14797:                           perlvar => 1,
14798:                        );
14799:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14800:             if ($primary) {
14801:                 my $gotaddr;
14802:                 my ($result,$returnhash) =
14803:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14804:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14805:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14806:                         $lastresort = $returnhash->{'lonSupportEMail'};
14807:                         $gotaddr = 1;
14808:                     }
14809:                 }
14810:                 unless ($gotaddr) {
14811:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14812:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14813:                     unless ($uintdom eq $intdom) {
14814:                         my %domconfig =
14815:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14816:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14817:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14818:                                 my @contacts = ('adminemail','supportemail');
14819:                                 foreach my $item (@contacts) {
14820:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14821:                                         my $addr = $domconfig{'contacts'}{$item};
14822:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14823:                                             push(@recipients,$addr);
14824:                                         }
14825:                                     }
14826:                                 }
14827:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14828:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14829:                                 }
14830:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14831:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14832:                                     my @ok_bccs;
14833:                                     foreach my $bcc (@bccs) {
14834:                                         $bcc =~ s/^\s+//g;
14835:                                         $bcc =~ s/\s+$//g;
14836:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14837:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14838:                                                 push(@ok_bccs,$bcc);
14839:                                             }
14840:                                         }
14841:                                     }
14842:                                     if (@ok_bccs > 0) {
14843:                                         $allbcc = join(', ',@ok_bccs);
14844:                                     }
14845:                                 }
14846:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14847:                             }
14848:                         }
14849:                     }
14850:                 }
14851:             }
14852:         }
14853:     }
14854:     if (defined($defmail)) {
14855:         if ($defmail ne '') {
14856:             push(@recipients,$defmail);
14857:         }
14858:     }
14859:     if ($otheremails) {
14860:         my @others;
14861:         if ($otheremails =~ /,/) {
14862:             @others = split(/,/,$otheremails);
14863:         } else {
14864:             push(@others,$otheremails);
14865:         }
14866:         foreach my $addr (@others) {
14867:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14868:                 push(@recipients,$addr);
14869:             }
14870:         }
14871:     }
14872:     if ($mailing eq 'helpdeskmail') {
14873:         if ((!@recipients) && ($lastresort ne '')) {
14874:             push(@recipients,$lastresort);
14875:         }
14876:     } elsif ($lastresort ne '') {
14877:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14878:             push(@recipients,$lastresort);
14879:         }
14880:     }
14881:     my $recipientlist = join(',',@recipients);
14882:     if (wantarray) {
14883:         return ($recipientlist,$allbcc,$addtext);
14884:     } else {
14885:         return $recipientlist;
14886:     }
14887: }
14888: 
14889: ############################################################
14890: ############################################################
14891: 
14892: =pod
14893: 
14894: =over 4
14895: 
14896: =item * &mime_email()
14897: 
14898: Sends an email with a possible attachment
14899: 
14900: Inputs:
14901: 
14902: =over 4
14903: 
14904: from -              Sender's email address
14905: 
14906: to -                Email address of recipient
14907: 
14908: subject -           Subject of email
14909: 
14910: body -              Body of email
14911: 
14912: cc_string -         Carbon copy email address
14913: 
14914: bcc -               Blind carbon copy email address
14915: 
14916: type -              File type of attachment
14917: 
14918: attachment_path -   Path of file to be attached
14919: 
14920: file_name -         Name of file to be attached
14921: 
14922: attachment_text -   The body of an attachment of type "TEXT"
14923: 
14924: =back
14925: 
14926: =back
14927: 
14928: =cut
14929: 
14930: ############################################################
14931: ############################################################
14932: 
14933: sub mime_email {
14934:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
14935:         $file_name, $attachment_text) = @_;
14936:     my $msg = MIME::Lite->new(
14937:              From    => $from,
14938:              To      => $to,
14939:              Subject => $subject,
14940:              Type    =>'TEXT',
14941:              Data    => $body,
14942:              );
14943:     if ($cc_string ne '') {
14944:         $msg->add("Cc" => $cc_string);
14945:     }
14946:     if ($bcc ne '') {
14947:         $msg->add("Bcc" => $bcc);
14948:     }
14949:     $msg->attr("content-type"         => "text/plain");
14950:     $msg->attr("content-type.charset" => "UTF-8");
14951:     # Attach file if given
14952:     if ($attachment_path) {
14953:         unless ($file_name) {
14954:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
14955:         }
14956:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
14957:         $msg->attach(Type     => $type,
14958:                      Path     => $attachment_path,
14959:                      Filename => $file_name
14960:                      );
14961:     # Otherwise attach text if given
14962:     } elsif ($attachment_text) {
14963:         $msg->attach(Type => 'TEXT',
14964:                      Data => $attachment_text);
14965:     }
14966:     # Send it
14967:     $msg->send('sendmail');
14968: }
14969: 
14970: ############################################################
14971: ############################################################
14972: 
14973: =pod
14974: 
14975: =head1 Course Catalog Routines
14976: 
14977: =over 4
14978: 
14979: =item * &gather_categories()
14980: 
14981: Converts category definitions - keys of categories hash stored in  
14982: coursecategories in configuration.db on the primary library server in a 
14983: domain - to an array.  Also generates javascript and idx hash used to 
14984: generate Domain Coordinator interface for editing Course Categories.
14985: 
14986: Inputs:
14987: 
14988: categories (reference to hash of category definitions).
14989: 
14990: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14991:       categories and subcategories).
14992: 
14993: idx (reference to hash of counters used in Domain Coordinator interface for 
14994:       editing Course Categories).
14995: 
14996: jsarray (reference to array of categories used to create Javascript arrays for
14997:          Domain Coordinator interface for editing Course Categories).
14998: 
14999: Returns: nothing
15000: 
15001: Side effects: populates cats, idx and jsarray. 
15002: 
15003: =cut
15004: 
15005: sub gather_categories {
15006:     my ($categories,$cats,$idx,$jsarray) = @_;
15007:     my %counters;
15008:     my $num = 0;
15009:     foreach my $item (keys(%{$categories})) {
15010:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15011:         if ($container eq '' && $depth == 0) {
15012:             $cats->[$depth][$categories->{$item}] = $cat;
15013:         } else {
15014:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15015:         }
15016:         my ($escitem,$tail) = split(/:/,$item,2);
15017:         if ($counters{$tail} eq '') {
15018:             $counters{$tail} = $num;
15019:             $num ++;
15020:         }
15021:         if (ref($idx) eq 'HASH') {
15022:             $idx->{$item} = $counters{$tail};
15023:         }
15024:         if (ref($jsarray) eq 'ARRAY') {
15025:             push(@{$jsarray->[$counters{$tail}]},$item);
15026:         }
15027:     }
15028:     return;
15029: }
15030: 
15031: =pod
15032: 
15033: =item * &extract_categories()
15034: 
15035: Used to generate breadcrumb trails for course categories.
15036: 
15037: Inputs:
15038: 
15039: categories (reference to hash of category definitions).
15040: 
15041: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15042:       categories and subcategories).
15043: 
15044: trails (reference to array of breacrumb trails for each category).
15045: 
15046: allitems (reference to hash - key is category key 
15047:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15048: 
15049: idx (reference to hash of counters used in Domain Coordinator interface for
15050:       editing Course Categories).
15051: 
15052: jsarray (reference to array of categories used to create Javascript arrays for
15053:          Domain Coordinator interface for editing Course Categories).
15054: 
15055: subcats (reference to hash of arrays containing all subcategories within each 
15056:          category, -recursive)
15057: 
15058: Returns: nothing
15059: 
15060: Side effects: populates trails and allitems hash references.
15061: 
15062: =cut
15063: 
15064: sub extract_categories {
15065:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
15066:     if (ref($categories) eq 'HASH') {
15067:         &gather_categories($categories,$cats,$idx,$jsarray);
15068:         if (ref($cats->[0]) eq 'ARRAY') {
15069:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15070:                 my $name = $cats->[0][$i];
15071:                 my $item = &escape($name).'::0';
15072:                 my $trailstr;
15073:                 if ($name eq 'instcode') {
15074:                     $trailstr = &mt('Official courses (with institutional codes)');
15075:                 } elsif ($name eq 'communities') {
15076:                     $trailstr = &mt('Communities');
15077:                 } elsif ($name eq 'placement') {
15078:                     $trailstr = &mt('Placement Tests');
15079:                 } else {
15080:                     $trailstr = $name;
15081:                 }
15082:                 if ($allitems->{$item} eq '') {
15083:                     push(@{$trails},$trailstr);
15084:                     $allitems->{$item} = scalar(@{$trails})-1;
15085:                 }
15086:                 my @parents = ($name);
15087:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15088:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15089:                         my $category = $cats->[1]{$name}[$j];
15090:                         if (ref($subcats) eq 'HASH') {
15091:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15092:                         }
15093:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
15094:                     }
15095:                 } else {
15096:                     if (ref($subcats) eq 'HASH') {
15097:                         $subcats->{$item} = [];
15098:                     }
15099:                 }
15100:             }
15101:         }
15102:     }
15103:     return;
15104: }
15105: 
15106: =pod
15107: 
15108: =item * &recurse_categories()
15109: 
15110: Recursively used to generate breadcrumb trails for course categories.
15111: 
15112: Inputs:
15113: 
15114: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15115:       categories and subcategories).
15116: 
15117: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15118: 
15119: category (current course category, for which breadcrumb trail is being generated).
15120: 
15121: trails (reference to array of breadcrumb trails for each category).
15122: 
15123: allitems (reference to hash - key is category key
15124:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15125: 
15126: parents (array containing containers directories for current category, 
15127:          back to top level). 
15128: 
15129: Returns: nothing
15130: 
15131: Side effects: populates trails and allitems hash references
15132: 
15133: =cut
15134: 
15135: sub recurse_categories {
15136:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
15137:     my $shallower = $depth - 1;
15138:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15139:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15140:             my $name = $cats->[$depth]{$category}[$k];
15141:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15142:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
15143:             if ($allitems->{$item} eq '') {
15144:                 push(@{$trails},$trailstr);
15145:                 $allitems->{$item} = scalar(@{$trails})-1;
15146:             }
15147:             my $deeper = $depth+1;
15148:             push(@{$parents},$category);
15149:             if (ref($subcats) eq 'HASH') {
15150:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15151:                 for (my $j=@{$parents}; $j>=0; $j--) {
15152:                     my $higher;
15153:                     if ($j > 0) {
15154:                         $higher = &escape($parents->[$j]).':'.
15155:                                   &escape($parents->[$j-1]).':'.$j;
15156:                     } else {
15157:                         $higher = &escape($parents->[$j]).'::'.$j;
15158:                     }
15159:                     push(@{$subcats->{$higher}},$subcat);
15160:                 }
15161:             }
15162:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15163:                                 $subcats);
15164:             pop(@{$parents});
15165:         }
15166:     } else {
15167:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15168:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
15169:         if ($allitems->{$item} eq '') {
15170:             push(@{$trails},$trailstr);
15171:             $allitems->{$item} = scalar(@{$trails})-1;
15172:         }
15173:     }
15174:     return;
15175: }
15176: 
15177: =pod
15178: 
15179: =item * &assign_categories_table()
15180: 
15181: Create a datatable for display of hierarchical categories in a domain,
15182: with checkboxes to allow a course to be categorized. 
15183: 
15184: Inputs:
15185: 
15186: cathash - reference to hash of categories defined for the domain (from
15187:           configuration.db)
15188: 
15189: currcat - scalar with an & separated list of categories assigned to a course. 
15190: 
15191: type    - scalar contains course type (Course or Community).
15192: 
15193: disabled - scalar (optional) contains disabled="disabled" if input elements are
15194:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15195: 
15196: Returns: $output (markup to be displayed) 
15197: 
15198: =cut
15199: 
15200: sub assign_categories_table {
15201:     my ($cathash,$currcat,$type,$disabled) = @_;
15202:     my $output;
15203:     if (ref($cathash) eq 'HASH') {
15204:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
15205:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
15206:         $maxdepth = scalar(@cats);
15207:         if (@cats > 0) {
15208:             my $itemcount = 0;
15209:             if (ref($cats[0]) eq 'ARRAY') {
15210:                 my @currcategories;
15211:                 if ($currcat ne '') {
15212:                     @currcategories = split('&',$currcat);
15213:                 }
15214:                 my $table;
15215:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15216:                     my $parent = $cats[0][$i];
15217:                     next if ($parent eq 'instcode');
15218:                     if ($type eq 'Community') {
15219:                         next unless ($parent eq 'communities');
15220:                     } elsif ($type eq 'Placement') {
15221:                         next unless ($parent eq 'placement');
15222:                     } else {
15223:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
15224:                     }
15225:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15226:                     my $item = &escape($parent).'::0';
15227:                     my $checked = '';
15228:                     if (@currcategories > 0) {
15229:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15230:                             $checked = ' checked="checked"';
15231:                         }
15232:                     }
15233:                     my $parent_title = $parent;
15234:                     if ($parent eq 'communities') {
15235:                         $parent_title = &mt('Communities');
15236:                     } elsif ($parent eq 'placement') {
15237:                         $parent_title = &mt('Placement Tests');
15238:                     }
15239:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15240:                               '<input type="checkbox" name="usecategory" value="'.
15241:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15242:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15243:                     my $depth = 1;
15244:                     push(@path,$parent);
15245:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15246:                     pop(@path);
15247:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15248:                     $itemcount ++;
15249:                 }
15250:                 if ($itemcount) {
15251:                     $output = &Apache::loncommon::start_data_table().
15252:                               $table.
15253:                               &Apache::loncommon::end_data_table();
15254:                 }
15255:             }
15256:         }
15257:     }
15258:     return $output;
15259: }
15260: 
15261: =pod
15262: 
15263: =item * &assign_category_rows()
15264: 
15265: Create a datatable row for display of nested categories in a domain,
15266: with checkboxes to allow a course to be categorized,called recursively.
15267: 
15268: Inputs:
15269: 
15270: itemcount - track row number for alternating colors
15271: 
15272: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15273:       categories and subcategories.
15274: 
15275: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15276: 
15277: parent - parent of current category item
15278: 
15279: path - Array containing all categories back up through the hierarchy from the
15280:        current category to the top level.
15281: 
15282: currcategories - reference to array of current categories assigned to the course
15283: 
15284: disabled - scalar (optional) contains disabled="disabled" if input elements are
15285:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15286: 
15287: Returns: $output (markup to be displayed).
15288: 
15289: =cut
15290: 
15291: sub assign_category_rows {
15292:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15293:     my ($text,$name,$item,$chgstr);
15294:     if (ref($cats) eq 'ARRAY') {
15295:         my $maxdepth = scalar(@{$cats});
15296:         if (ref($cats->[$depth]) eq 'HASH') {
15297:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15298:                 my $numchildren = @{$cats->[$depth]{$parent}};
15299:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15300:                 $text .= '<td><table class="LC_data_table">';
15301:                 for (my $j=0; $j<$numchildren; $j++) {
15302:                     $name = $cats->[$depth]{$parent}[$j];
15303:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15304:                     my $deeper = $depth+1;
15305:                     my $checked = '';
15306:                     if (ref($currcategories) eq 'ARRAY') {
15307:                         if (@{$currcategories} > 0) {
15308:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15309:                                 $checked = ' checked="checked"';
15310:                             }
15311:                         }
15312:                     }
15313:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15314:                              '<input type="checkbox" name="usecategory" value="'.
15315:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15316:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15317:                              '</td><td>';
15318:                     if (ref($path) eq 'ARRAY') {
15319:                         push(@{$path},$name);
15320:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15321:                         pop(@{$path});
15322:                     }
15323:                     $text .= '</td></tr>';
15324:                 }
15325:                 $text .= '</table></td>';
15326:             }
15327:         }
15328:     }
15329:     return $text;
15330: }
15331: 
15332: =pod
15333: 
15334: =back
15335: 
15336: =cut
15337: 
15338: ############################################################
15339: ############################################################
15340: 
15341: 
15342: sub commit_customrole {
15343:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15344:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15345:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15346:                          ($end?', ending '.localtime($end):'').': <b>'.
15347:               &Apache::lonnet::assigncustomrole(
15348:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15349:                  '</b><br />';
15350:     return $output;
15351: }
15352: 
15353: sub commit_standardrole {
15354:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15355:     my ($output,$logmsg,$linefeed);
15356:     if ($context eq 'auto') {
15357:         $linefeed = "\n";
15358:     } else {
15359:         $linefeed = "<br />\n";
15360:     }  
15361:     if ($three eq 'st') {
15362:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15363:                                          $one,$two,$sec,$context,$credits);
15364:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15365:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15366:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15367:         } else {
15368:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15369:                ($start?', '.&mt('starting').' '.localtime($start):'').
15370:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15371:             if ($context eq 'auto') {
15372:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15373:             } else {
15374:                $output .= '<b>'.$result.'</b>'.$linefeed.
15375:                &mt('Add to classlist').': <b>ok</b>';
15376:             }
15377:             $output .= $linefeed;
15378:         }
15379:     } else {
15380:         $output = &mt('Assigning').' '.$three.' in '.$url.
15381:                ($start?', '.&mt('starting').' '.localtime($start):'').
15382:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15383:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15384:         if ($context eq 'auto') {
15385:             $output .= $result.$linefeed;
15386:         } else {
15387:             $output .= '<b>'.$result.'</b>'.$linefeed;
15388:         }
15389:     }
15390:     return $output;
15391: }
15392: 
15393: sub commit_studentrole {
15394:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15395:         $credits) = @_;
15396:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15397:     if ($context eq 'auto') {
15398:         $linefeed = "\n";
15399:     } else {
15400:         $linefeed = '<br />'."\n";
15401:     }
15402:     if (defined($one) && defined($two)) {
15403:         my $cid=$one.'_'.$two;
15404:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15405:         my $secchange = 0;
15406:         my $expire_role_result;
15407:         my $modify_section_result;
15408:         if ($oldsec ne '-1') { 
15409:             if ($oldsec ne $sec) {
15410:                 $secchange = 1;
15411:                 my $now = time;
15412:                 my $uurl='/'.$cid;
15413:                 $uurl=~s/\_/\//g;
15414:                 if ($oldsec) {
15415:                     $uurl.='/'.$oldsec;
15416:                 }
15417:                 $oldsecurl = $uurl;
15418:                 $expire_role_result = 
15419:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15420:                 if ($env{'request.course.sec'} ne '') { 
15421:                     if ($expire_role_result eq 'refused') {
15422:                         my @roles = ('st');
15423:                         my @statuses = ('previous');
15424:                         my @roledoms = ($one);
15425:                         my $withsec = 1;
15426:                         my %roleshash = 
15427:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15428:                                               \@statuses,\@roles,\@roledoms,$withsec);
15429:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15430:                             my ($oldstart,$oldend) = 
15431:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15432:                             if ($oldend > 0 && $oldend <= $now) {
15433:                                 $expire_role_result = 'ok';
15434:                             }
15435:                         }
15436:                     }
15437:                 }
15438:                 $result = $expire_role_result;
15439:             }
15440:         }
15441:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15442:             $modify_section_result = 
15443:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15444:                                                            undef,undef,undef,$sec,
15445:                                                            $end,$start,'','',$cid,
15446:                                                            '',$context,$credits);
15447:             if ($modify_section_result =~ /^ok/) {
15448:                 if ($secchange == 1) {
15449:                     if ($sec eq '') {
15450:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15451:                     } else {
15452:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15453:                     }
15454:                 } elsif ($oldsec eq '-1') {
15455:                     if ($sec eq '') {
15456:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15457:                     } else {
15458:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15459:                     }
15460:                 } else {
15461:                     if ($sec eq '') {
15462:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15463:                     } else {
15464:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15465:                     }
15466:                 }
15467:             } else {
15468:                 if ($secchange) { 
15469:                     $$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;
15470:                 } else {
15471:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15472:                 }
15473:             }
15474:             $result = $modify_section_result;
15475:         } elsif ($secchange == 1) {
15476:             if ($oldsec eq '') {
15477:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15478:             } else {
15479:                 $$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;
15480:             }
15481:             if ($expire_role_result eq 'refused') {
15482:                 my $newsecurl = '/'.$cid;
15483:                 $newsecurl =~ s/\_/\//g;
15484:                 if ($sec ne '') {
15485:                     $newsecurl.='/'.$sec;
15486:                 }
15487:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15488:                     if ($sec eq '') {
15489:                         $$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;
15490:                     } else {
15491:                         $$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;
15492:                     }
15493:                 }
15494:             }
15495:         }
15496:     } else {
15497:         $$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;
15498:         $result = "error: incomplete course id\n";
15499:     }
15500:     return $result;
15501: }
15502: 
15503: sub show_role_extent {
15504:     my ($scope,$context,$role) = @_;
15505:     $scope =~ s{^/}{};
15506:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15507:     push(@courseroles,'co');
15508:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15509:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15510:         $scope =~ s{/}{_};
15511:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15512:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15513:         my ($audom,$auname) = split(/\//,$scope);
15514:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15515:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15516:     } else {
15517:         $scope =~ s{/$}{};
15518:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15519:                    &Apache::lonnet::domain($scope,'description').'</span>');
15520:     }
15521: }
15522: 
15523: ############################################################
15524: ############################################################
15525: 
15526: sub check_clone {
15527:     my ($args,$linefeed) = @_;
15528:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15529:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15530:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15531:     my $clonemsg;
15532:     my $can_clone = 0;
15533:     my $lctype = lc($args->{'crstype'});
15534:     if ($lctype ne 'community') {
15535:         $lctype = 'course';
15536:     }
15537:     if ($clonehome eq 'no_host') {
15538:         if ($args->{'crstype'} eq 'Community') {
15539:             $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'});
15540:         } else {
15541:             $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'});
15542:         }     
15543:     } else {
15544: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15545:         if ($args->{'crstype'} eq 'Community') {
15546:             if ($clonedesc{'type'} ne 'Community') {
15547:                 $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'});
15548:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15549:             }
15550:         }
15551: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15552:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15553: 	    $can_clone = 1;
15554: 	} else {
15555: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15556: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15557:             if ($clonehash{'cloners'} eq '') {
15558:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15559:                 if ($domdefs{'canclone'}) {
15560:                     unless ($domdefs{'canclone'} eq 'none') {
15561:                         if ($domdefs{'canclone'} eq 'domain') {
15562:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15563:                                 $can_clone = 1;
15564:                             }
15565:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15566:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15567:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15568:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15569:                                 $can_clone = 1;
15570:                             }
15571:                         }
15572:                     }
15573:                 }
15574:             } else {
15575: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15576:                 if (grep(/^\*$/,@cloners)) {
15577:                     $can_clone = 1;
15578:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15579:                     $can_clone = 1;
15580:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15581:                     $can_clone = 1;
15582:                 }
15583:                 unless ($can_clone) {
15584:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15585:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15586:                         my (%gotdomdefaults,%gotcodedefaults);
15587:                         foreach my $cloner (@cloners) {
15588:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15589:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15590:                                 my (%codedefaults,@code_order);
15591:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15592:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15593:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15594:                                     }
15595:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15596:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15597:                                     }
15598:                                 } else {
15599:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15600:                                                                             \%codedefaults,
15601:                                                                             \@code_order);
15602:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15603:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15604:                                 }
15605:                                 if (@code_order > 0) {
15606:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15607:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15608:                                                                                 $args->{'crscode'})) {
15609:                                         $can_clone = 1;
15610:                                         last;
15611:                                     }
15612:                                 }
15613:                             }
15614:                         }
15615:                     }
15616:                 }
15617:             }
15618:             unless ($can_clone) {
15619:                 my $ccrole = 'cc';
15620:                 if ($args->{'crstype'} eq 'Community') {
15621:                     $ccrole = 'co';
15622:                 }
15623: 	        my %roleshash =
15624: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
15625: 					          $args->{'ccdomain'},
15626:                                                   'userroles',['active'],[$ccrole],
15627: 					          [$args->{'clonedomain'}]);
15628: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15629:                     $can_clone = 1;
15630:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15631:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15632:                     $can_clone = 1;
15633:                 }
15634:             }
15635:             unless ($can_clone) {
15636:                 if ($args->{'crstype'} eq 'Community') {
15637:                     $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'});
15638:                 } else {
15639:                     $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'});
15640:                 }
15641: 	    }
15642:         }
15643:     }
15644:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15645: }
15646: 
15647: sub construct_course {
15648:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15649:         $cnum,$category,$coderef) = @_;
15650:     my $outcome;
15651:     my $linefeed =  '<br />'."\n";
15652:     if ($context eq 'auto') {
15653:         $linefeed = "\n";
15654:     }
15655: 
15656: #
15657: # Are we cloning?
15658: #
15659:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15660:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15661: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15662: 	if ($context ne 'auto') {
15663:             if ($clonemsg ne '') {
15664: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15665:             }
15666: 	}
15667: 	$outcome .= $clonemsg.$linefeed;
15668: 
15669:         if (!$can_clone) {
15670: 	    return (0,$outcome);
15671: 	}
15672:     }
15673: 
15674: #
15675: # Open course
15676: #
15677:     my $showncrstype;
15678:     if ($args->{'crstype'} eq 'Placement') {
15679:         $showncrstype = 'placement test'; 
15680:     } else {  
15681:         $showncrstype = lc($args->{'crstype'});
15682:     }
15683:     my %cenv=();
15684:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15685:                                              $args->{'cdescr'},
15686:                                              $args->{'curl'},
15687:                                              $args->{'course_home'},
15688:                                              $args->{'nonstandard'},
15689:                                              $args->{'crscode'},
15690:                                              $args->{'ccuname'}.':'.
15691:                                              $args->{'ccdomain'},
15692:                                              $args->{'crstype'},
15693:                                              $cnum,$context,$category);
15694: 
15695:     # Note: The testing routines depend on this being output; see 
15696:     # Utils::Course. This needs to at least be output as a comment
15697:     # if anyone ever decides to not show this, and Utils::Course::new
15698:     # will need to be suitably modified.
15699:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15700:     if ($$courseid =~ /^error:/) {
15701:         return (0,$outcome);
15702:     }
15703: 
15704: #
15705: # Check if created correctly
15706: #
15707:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15708:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15709:     if ($crsuhome eq 'no_host') {
15710:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15711:         return (0,$outcome);
15712:     }
15713:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15714: 
15715: #
15716: # Do the cloning
15717: #   
15718:     if ($can_clone && $cloneid) {
15719: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
15720: 	if ($context ne 'auto') {
15721: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15722: 	}
15723: 	$outcome .= $clonemsg.$linefeed;
15724: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15725: # Copy all files
15726: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15727: # Restore URL
15728: 	$cenv{'url'}=$oldcenv{'url'};
15729: # Restore title
15730: 	$cenv{'description'}=$oldcenv{'description'};
15731: # Restore creation date, creator and creation context.
15732:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15733:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15734:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15735: # Mark as cloned
15736: 	$cenv{'clonedfrom'}=$cloneid;
15737: # Need to clone grading mode
15738:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15739:         $cenv{'grading'}=$newenv{'grading'};
15740: # Do not clone these environment entries
15741:         &Apache::lonnet::del('environment',
15742:                   ['default_enrollment_start_date',
15743:                    'default_enrollment_end_date',
15744:                    'question.email',
15745:                    'policy.email',
15746:                    'comment.email',
15747:                    'pch.users.denied',
15748:                    'plc.users.denied',
15749:                    'hidefromcat',
15750:                    'checkforpriv',
15751:                    'categories',
15752:                    'internal.uniquecode'],
15753:                    $$crsudom,$$crsunum);
15754:         if ($args->{'textbook'}) {
15755:             $cenv{'internal.textbook'} = $args->{'textbook'};
15756:         }
15757:     }
15758: 
15759: #
15760: # Set environment (will override cloned, if existing)
15761: #
15762:     my @sections = ();
15763:     my @xlists = ();
15764:     if ($args->{'crstype'}) {
15765:         $cenv{'type'}=$args->{'crstype'};
15766:     }
15767:     if ($args->{'crsid'}) {
15768:         $cenv{'courseid'}=$args->{'crsid'};
15769:     }
15770:     if ($args->{'crscode'}) {
15771:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15772:     }
15773:     if ($args->{'crsquota'} ne '') {
15774:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15775:     } else {
15776:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15777:     }
15778:     if ($args->{'ccuname'}) {
15779:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15780:                                         ':'.$args->{'ccdomain'};
15781:     } else {
15782:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15783:     }
15784:     if ($args->{'defaultcredits'}) {
15785:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15786:     }
15787:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15788:     if ($args->{'crssections'}) {
15789:         $cenv{'internal.sectionnums'} = '';
15790:         if ($args->{'crssections'} =~ m/,/) {
15791:             @sections = split/,/,$args->{'crssections'};
15792:         } else {
15793:             $sections[0] = $args->{'crssections'};
15794:         }
15795:         if (@sections > 0) {
15796:             foreach my $item (@sections) {
15797:                 my ($sec,$gp) = split/:/,$item;
15798:                 my $class = $args->{'crscode'}.$sec;
15799:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15800:                 $cenv{'internal.sectionnums'} .= $item.',';
15801:                 unless ($addcheck eq 'ok') {
15802:                     push(@badclasses,$class);
15803:                 }
15804:             }
15805:             $cenv{'internal.sectionnums'} =~ s/,$//;
15806:         }
15807:     }
15808: # do not hide course coordinator from staff listing, 
15809: # even if privileged
15810:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15811: # add course coordinator's domain to domains to check for privileged users
15812: # if different to course domain
15813:     if ($$crsudom ne $args->{'ccdomain'}) {
15814:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15815:     }
15816: # add crosslistings
15817:     if ($args->{'crsxlist'}) {
15818:         $cenv{'internal.crosslistings'}='';
15819:         if ($args->{'crsxlist'} =~ m/,/) {
15820:             @xlists = split/,/,$args->{'crsxlist'};
15821:         } else {
15822:             $xlists[0] = $args->{'crsxlist'};
15823:         }
15824:         if (@xlists > 0) {
15825:             foreach my $item (@xlists) {
15826:                 my ($xl,$gp) = split/:/,$item;
15827:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15828:                 $cenv{'internal.crosslistings'} .= $item.',';
15829:                 unless ($addcheck eq 'ok') {
15830:                     push(@badclasses,$xl);
15831:                 }
15832:             }
15833:             $cenv{'internal.crosslistings'} =~ s/,$//;
15834:         }
15835:     }
15836:     if ($args->{'autoadds'}) {
15837:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15838:     }
15839:     if ($args->{'autodrops'}) {
15840:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15841:     }
15842: # check for notification of enrollment changes
15843:     my @notified = ();
15844:     if ($args->{'notify_owner'}) {
15845:         if ($args->{'ccuname'} ne '') {
15846:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15847:         }
15848:     }
15849:     if ($args->{'notify_dc'}) {
15850:         if ($uname ne '') { 
15851:             push(@notified,$uname.':'.$udom);
15852:         }
15853:     }
15854:     if (@notified > 0) {
15855:         my $notifylist;
15856:         if (@notified > 1) {
15857:             $notifylist = join(',',@notified);
15858:         } else {
15859:             $notifylist = $notified[0];
15860:         }
15861:         $cenv{'internal.notifylist'} = $notifylist;
15862:     }
15863:     if (@badclasses > 0) {
15864:         my %lt=&Apache::lonlocal::texthash(
15865:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15866:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15867:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15868:         );
15869:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15870:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
15871:         if ($context eq 'auto') {
15872:             $outcome .= $badclass_msg.$linefeed;
15873:         } else {
15874:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15875:         }
15876:         foreach my $item (@badclasses) {
15877:             if ($context eq 'auto') {
15878:                 $outcome .= " - $item\n";
15879:             } else {
15880:                 $outcome .= "<li>$item</li>\n";
15881:             }
15882:         }
15883:         if ($context eq 'auto') {
15884:             $outcome .= $linefeed;
15885:         } else {
15886:             $outcome .= "</ul><br /><br /></div>\n";
15887:         } 
15888:     }
15889:     if ($args->{'no_end_date'}) {
15890:         $args->{'endaccess'} = 0;
15891:     }
15892:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15893:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15894:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15895:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15896:     if ($args->{'showphotos'}) {
15897:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15898:     }
15899:     $cenv{'internal.authtype'} = $args->{'authtype'};
15900:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15901:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15902:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15903:             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'); 
15904:             if ($context eq 'auto') {
15905:                 $outcome .= $krb_msg;
15906:             } else {
15907:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15908:             }
15909:             $outcome .= $linefeed;
15910:         }
15911:     }
15912:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15913:        if ($args->{'setpolicy'}) {
15914:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15915:        }
15916:        if ($args->{'setcontent'}) {
15917:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15918:        }
15919:        if ($args->{'setcomment'}) {
15920:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15921:        }
15922:     }
15923:     if ($args->{'reshome'}) {
15924: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15925: 	$cenv{'reshome'}=~s/\/+$/\//;
15926:     }
15927: #
15928: # course has keyed access
15929: #
15930:     if ($args->{'setkeys'}) {
15931:        $cenv{'keyaccess'}='yes';
15932:     }
15933: # if specified, key authority is not course, but user
15934: # only active if keyaccess is yes
15935:     if ($args->{'keyauth'}) {
15936: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15937: 	$user = &LONCAPA::clean_username($user);
15938: 	$domain = &LONCAPA::clean_username($domain);
15939: 	if ($user ne '' && $domain ne '') {
15940: 	    $cenv{'keyauth'}=$user.':'.$domain;
15941: 	}
15942:     }
15943: 
15944: #
15945: #  generate and store uniquecode (available to course requester), if course should have one.
15946: #
15947:     if ($args->{'uniquecode'}) {
15948:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15949:         if ($code) {
15950:             $cenv{'internal.uniquecode'} = $code;
15951:             my %crsinfo =
15952:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15953:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15954:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15955:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15956:             } 
15957:             if (ref($coderef)) {
15958:                 $$coderef = $code;
15959:             }
15960:         }
15961:     }
15962: 
15963:     if ($args->{'disresdis'}) {
15964:         $cenv{'pch.roles.denied'}='st';
15965:     }
15966:     if ($args->{'disablechat'}) {
15967:         $cenv{'plc.roles.denied'}='st';
15968:     }
15969: 
15970:     # Record we've not yet viewed the Course Initialization Helper for this 
15971:     # course
15972:     $cenv{'course.helper.not.run'} = 1;
15973:     #
15974:     # Use new Randomseed
15975:     #
15976:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15977:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15978:     #
15979:     # The encryption code and receipt prefix for this course
15980:     #
15981:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15982:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15983:     #
15984:     # By default, use standard grading
15985:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15986: 
15987:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15988:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15989: #
15990: # Open all assignments
15991: #
15992:     if ($args->{'openall'}) {
15993:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15994:        my %storecontent = ($storeunder         => time,
15995:                            $storeunder.'.type' => 'date_start');
15996:        
15997:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15998:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15999:    }
16000: #
16001: # Set first page
16002: #
16003:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16004: 	    || ($cloneid)) {
16005: 	use LONCAPA::map;
16006: 	$outcome .= &mt('Setting first resource').': ';
16007: 
16008: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16009:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16010: 
16011:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16012:         my $title; my $url;
16013:         if ($args->{'firstres'} eq 'syl') {
16014: 	    $title=&mt('Syllabus');
16015:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16016:         } else {
16017:             $title=&mt('Table of Contents');
16018:             $url='/adm/navmaps';
16019:         }
16020: 
16021:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16022: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16023: 
16024: 	if ($errtext) { $fatal=2; }
16025:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16026:     }
16027: 
16028: # 
16029: # Set params for Placement Tests
16030: #
16031:     if ($args->{'crstype'} eq 'Placement') {
16032:        my %storecontent; 
16033:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
16034:        my %defaults = (
16035:                         buttonshide   => { value => 'yes',
16036:                                            type => 'string_yesno',},
16037:                         type          => { value => 'randomizetry',
16038:                                            type  => 'string_questiontype',},
16039:                         maxtries      => { value => 1,
16040:                                            type => 'int_pos',},
16041:                         problemstatus => { value => 'no',
16042:                                            type  => 'string_problemstatus',},
16043:                       );
16044:        foreach my $key (keys(%defaults)) {
16045:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
16046:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
16047:        }
16048:        &Apache::lonnet::cput
16049:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
16050:     }
16051: 
16052:     return (1,$outcome);
16053: }
16054: 
16055: sub make_unique_code {
16056:     my ($cdom,$cnum) = @_;
16057:     # get lock on uniquecodes db
16058:     my $lockhash = {
16059:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16060:                                                   ':'.$env{'user.domain'},
16061:                    };
16062:     my $tries = 0;
16063:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16064:     my ($code,$error);
16065:   
16066:     while (($gotlock ne 'ok') && ($tries<3)) {
16067:         $tries ++;
16068:         sleep 1;
16069:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16070:     }
16071:     if ($gotlock eq 'ok') {
16072:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16073:         my $gotcode;
16074:         my $attempts = 0;
16075:         while ((!$gotcode) && ($attempts < 100)) {
16076:             $code = &generate_code();
16077:             if (!exists($currcodes{$code})) {
16078:                 $gotcode = 1;
16079:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16080:                     $error = 'nostore';
16081:                 }
16082:             }
16083:             $attempts ++;
16084:         }
16085:         my @del_lock = ($cnum."\0".'uniquecodes');
16086:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16087:     } else {
16088:         $error = 'nolock';
16089:     }
16090:     return ($code,$error);
16091: }
16092: 
16093: sub generate_code {
16094:     my $code;
16095:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16096:     for (my $i=0; $i<6; $i++) {
16097:         my $lettnum = int (rand 2);
16098:         my $item = '';
16099:         if ($lettnum) {
16100:             $item = $letts[int( rand(18) )];
16101:         } else {
16102:             $item = 1+int( rand(8) );
16103:         }
16104:         $code .= $item;
16105:     }
16106:     return $code;
16107: }
16108: 
16109: ############################################################
16110: ############################################################
16111: 
16112: # Community, Course and Placement Test
16113: sub course_type {
16114:     my ($cid) = @_;
16115:     if (!defined($cid)) {
16116:         $cid = $env{'request.course.id'};
16117:     }
16118:     if (defined($env{'course.'.$cid.'.type'})) {
16119:         return $env{'course.'.$cid.'.type'};
16120:     } else {
16121:         return 'Course';
16122:     }
16123: }
16124: 
16125: sub group_term {
16126:     my $crstype = &course_type();
16127:     my %names = (
16128:                   'Course' => 'group',
16129:                   'Community' => 'group',
16130:                   'Placement' => 'group',
16131:                 );
16132:     return $names{$crstype};
16133: }
16134: 
16135: sub course_types {
16136:     my @types = ('official','unofficial','community','textbook','placement');
16137:     my %typename = (
16138:                          official   => 'Official course',
16139:                          unofficial => 'Unofficial course',
16140:                          community  => 'Community',
16141:                          textbook   => 'Textbook course',
16142:                          placement  => 'Placement test',
16143:                    );
16144:     return (\@types,\%typename);
16145: }
16146: 
16147: sub icon {
16148:     my ($file)=@_;
16149:     my $curfext = lc((split(/\./,$file))[-1]);
16150:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16151:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16152:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16153: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16154: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16155: 	            $curfext.".gif") {
16156: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16157: 		$curfext.".gif";
16158: 	}
16159:     }
16160:     return &lonhttpdurl($iconname);
16161: } 
16162: 
16163: sub lonhttpdurl {
16164: #
16165: # Had been used for "small fry" static images on separate port 8080.
16166: # Modify here if lightweight http functionality desired again.
16167: # Currently eliminated due to increasing firewall issues.
16168: #
16169:     my ($url)=@_;
16170:     return $url;
16171: }
16172: 
16173: sub connection_aborted {
16174:     my ($r)=@_;
16175:     $r->print(" ");$r->rflush();
16176:     my $c = $r->connection;
16177:     return $c->aborted();
16178: }
16179: 
16180: #    Escapes strings that may have embedded 's that will be put into
16181: #    strings as 'strings'.
16182: sub escape_single {
16183:     my ($input) = @_;
16184:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16185:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16186:     return $input;
16187: }
16188: 
16189: #  Same as escape_single, but escape's "'s  This 
16190: #  can be used for  "strings"
16191: sub escape_double {
16192:     my ($input) = @_;
16193:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16194:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16195:     return $input;
16196: }
16197:  
16198: #   Escapes the last element of a full URL.
16199: sub escape_url {
16200:     my ($url)   = @_;
16201:     my @urlslices = split(/\//, $url,-1);
16202:     my $lastitem = &escape(pop(@urlslices));
16203:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16204: }
16205: 
16206: sub compare_arrays {
16207:     my ($arrayref1,$arrayref2) = @_;
16208:     my (@difference,%count);
16209:     @difference = ();
16210:     %count = ();
16211:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16212:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16213:         foreach my $element (keys(%count)) {
16214:             if ($count{$element} == 1) {
16215:                 push(@difference,$element);
16216:             }
16217:         }
16218:     }
16219:     return @difference;
16220: }
16221: 
16222: # -------------------------------------------------------- Initialize user login
16223: sub init_user_environment {
16224:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16225:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16226: 
16227:     my $public=($username eq 'public' && $domain eq 'public');
16228: 
16229:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16230:     my $now=time;
16231: 
16232:     if ($public) {
16233: 	my $max_public=100;
16234: 	my $oldest;
16235: 	my $oldest_time=0;
16236: 	for(my $next=1;$next<=$max_public;$next++) {
16237: 	    if (-e $lonids."/publicuser_$next.id") {
16238: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16239: 		if ($mtime<$oldest_time || !$oldest_time) {
16240: 		    $oldest_time=$mtime;
16241: 		    $oldest=$next;
16242: 		}
16243: 	    } else {
16244: 		$cookie="publicuser_$next";
16245: 		last;
16246: 	    }
16247: 	}
16248: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16249:     } else {
16250: 	# See if old ID present, if so, remove if this isn't a robot,
16251: 	# killing any existing non-robot sessions
16252: 	if (!$args->{'robot'}) {
16253: 	    opendir(DIR,$lonids);
16254: 	    while ($filename=readdir(DIR)) {
16255: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16256:                     if ($ENV{'SERVER_PORT'} == 443) {
16257:                         my $linkedfile;
16258:                         if (tie(my %oldenv,'GDBM_File',"$lonids/$cookie.id",
16259:                                 &GDBM_READER(),0640)) {
16260:                             if (exists($oldenv{'user.linkedenv'})) {
16261:                                 $linkedfile = $oldenv{'user.linkedenv'};
16262:                             }
16263:                             untie(%oldenv);
16264:                         }
16265:                         if (unlink($lonids.'/'.$filename)) {
16266:                             if ($linkedfile =~ /^[a-f0-9]+_linked\.id$/) {
16267:                                 unlink($lonids.'/'.$linkedfile);
16268:                             }
16269:                         }
16270:                     } else {
16271:                         unlink($lonids.'/'.$filename);
16272:                     }
16273: 		}
16274: 	    }
16275: 	    closedir(DIR);
16276: # If there is a undeleted lockfile for the user's paste buffer remove it.
16277:             my $namespace = 'nohist_courseeditor';
16278:             my $lockingkey = 'paste'."\0".'locked_num';
16279:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16280:                                                 $domain,$username);
16281:             if (exists($lockhash{$lockingkey})) {
16282:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16283:                 unless ($delresult eq 'ok') {
16284:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16285:                 }
16286:             }
16287: 	}
16288: # Give them a new cookie
16289: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16290: 		                   : $now.$$.int(rand(10000)));
16291: 	$cookie="$username\_$id\_$domain\_$authhost";
16292:     
16293: # Initialize roles
16294: 
16295: 	($userroles,$firstaccenv,$timerintenv) = 
16296:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16297:     }
16298: # ------------------------------------ Check browser type and MathML capability
16299: 
16300:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16301:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16302: 
16303: # ------------------------------------------------------------- Get environment
16304: 
16305:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16306:     my ($tmp) = keys(%userenv);
16307:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
16308: 	undef(%userenv);
16309:     }
16310:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16311: 	$form->{'interface'}=$userenv{'interface'};
16312:     }
16313:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16314: 
16315: # --------------- Do not trust query string to be put directly into environment
16316:     foreach my $option ('interface','localpath','localres') {
16317:         $form->{$option}=~s/[\n\r\=]//gs;
16318:     }
16319: # --------------------------------------------------------- Write first profile
16320: 
16321:     {
16322: 	my %initial_env = 
16323: 	    ("user.name"          => $username,
16324: 	     "user.domain"        => $domain,
16325: 	     "user.home"          => $authhost,
16326: 	     "browser.type"       => $clientbrowser,
16327: 	     "browser.version"    => $clientversion,
16328: 	     "browser.mathml"     => $clientmathml,
16329: 	     "browser.unicode"    => $clientunicode,
16330: 	     "browser.os"         => $clientos,
16331:              "browser.mobile"     => $clientmobile,
16332:              "browser.info"       => $clientinfo,
16333:              "browser.osversion"  => $clientosversion,
16334: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16335: 	     "request.course.fn"  => '',
16336: 	     "request.course.uri" => '',
16337: 	     "request.course.sec" => '',
16338: 	     "request.role"       => 'cm',
16339: 	     "request.role.adv"   => $env{'user.adv'},
16340: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
16341: 
16342:         if ($form->{'localpath'}) {
16343: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16344: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16345:         }
16346: 	
16347: 	if ($form->{'interface'}) {
16348: 	    $form->{'interface'}=~s/\W//gs;
16349: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16350: 	    $env{'browser.interface'}=$form->{'interface'};
16351: 	}
16352: 
16353:         if ($form->{'iptoken'}) {
16354:             my $lonhost = $r->dir_config('lonHostID');
16355:             $initial_env{"user.noloadbalance"} = $lonhost;
16356:             $env{'user.noloadbalance'} = $lonhost;
16357:         }
16358: 
16359:         if ($form->{'noloadbalance'}) {
16360:             my @hosts = &Apache::lonnet::current_machine_ids();
16361:             my $hosthere = $form->{'noloadbalance'};
16362:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16363:                 $initial_env{"user.noloadbalance"} = $hosthere;
16364:                 $env{'user.noloadbalance'} = $hosthere;
16365:             }
16366:         }
16367: 
16368:         unless ($domain eq 'public') {
16369:             my %is_adv = ( is_adv => $env{'user.adv'} );
16370:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16371: 
16372:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16373:                 $userenv{'availabletools.'.$tool} = 
16374:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16375:                                                       undef,\%userenv,\%domdef,\%is_adv);
16376:             }
16377: 
16378:             foreach my $crstype ('official','unofficial','community','textbook','placement') {
16379:                 $userenv{'canrequest.'.$crstype} =
16380:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16381:                                                       'reload','requestcourses',
16382:                                                       \%userenv,\%domdef,\%is_adv);
16383:             }
16384: 
16385:             $userenv{'canrequest.author'} =
16386:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16387:                                                   'reload','requestauthor',
16388:                                                   \%userenv,\%domdef,\%is_adv);
16389:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16390:                                                  $domain,$username);
16391:             my $reqstatus = $reqauthor{'author_status'};
16392:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
16393:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16394:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16395:                                                       $reqauthor{'author'}{'timestamp'};
16396:                 }
16397:             }
16398:             my ($types,$typename) = &course_types();
16399:             if (ref($types) eq 'ARRAY') {
16400:                 my @options = ('approval','validate','autolimit');
16401:                 my $optregex = join('|',@options);
16402:                 my (%willtrust,%trustchecked);
16403:                 foreach my $type (@{$types}) {
16404:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
16405:                     if ($dom_str ne '') {
16406:                         my $updatedstr = '';
16407:                         my @possdomains = split(',',$dom_str);
16408:                         foreach my $entry (@possdomains) {
16409:                             my ($extdom,$extopt) = split(':',$entry);
16410:                             unless ($trustchecked{$extdom}) {
16411:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
16412:                                 $trustchecked{$extdom} = 1;
16413:                             }
16414:                             if ($willtrust{$extdom}) {
16415:                                 $updatedstr .= $entry.',';
16416:                             }
16417:                         }
16418:                         $updatedstr =~ s/,$//;
16419:                         if ($updatedstr) {
16420:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
16421:                         } else {
16422:                             delete($userenv{'reqcrsotherdom.'.$type});
16423:                         }
16424:                     }
16425:                 }
16426:             }
16427:         }
16428: 	$env{'user.environment'} = "$lonids/$cookie.id";
16429: 
16430: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16431: 		 &GDBM_WRCREAT(),0640)) {
16432: 	    &_add_to_env(\%disk_env,\%initial_env);
16433: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16434: 	    &_add_to_env(\%disk_env,$userroles);
16435:             if (ref($firstaccenv) eq 'HASH') {
16436:                 &_add_to_env(\%disk_env,$firstaccenv);
16437:             }
16438:             if (ref($timerintenv) eq 'HASH') {
16439:                 &_add_to_env(\%disk_env,$timerintenv);
16440:             }
16441: 	    if (ref($args->{'extra_env'})) {
16442: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16443: 	    }
16444: 	    untie(%disk_env);
16445: 	} else {
16446: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16447: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16448: 	    return 'error: '.$!;
16449: 	}
16450:     }
16451:     $env{'request.role'}='cm';
16452:     $env{'request.role.adv'}=$env{'user.adv'};
16453:     $env{'browser.type'}=$clientbrowser;
16454: 
16455:     return $cookie;
16456: 
16457: }
16458: 
16459: sub _add_to_env {
16460:     my ($idf,$env_data,$prefix) = @_;
16461:     if (ref($env_data) eq 'HASH') {
16462:         while (my ($key,$value) = each(%$env_data)) {
16463: 	    $idf->{$prefix.$key} = $value;
16464: 	    $env{$prefix.$key}   = $value;
16465:         }
16466:     }
16467: }
16468: 
16469: # --- Get the symbolic name of a problem and the url
16470: sub get_symb {
16471:     my ($request,$silent) = @_;
16472:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16473:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16474:     if ($symb eq '') {
16475:         if (!$silent) {
16476:             if (ref($request)) { 
16477:                 $request->print("Unable to handle ambiguous references:$url:.");
16478:             }
16479:             return ();
16480:         }
16481:     }
16482:     &Apache::lonenc::check_decrypt(\$symb);
16483:     return ($symb);
16484: }
16485: 
16486: # --------------------------------------------------------------Get annotation
16487: 
16488: sub get_annotation {
16489:     my ($symb,$enc) = @_;
16490: 
16491:     my $key = $symb;
16492:     if (!$enc) {
16493:         $key =
16494:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16495:     }
16496:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16497:     return $annotation{$key};
16498: }
16499: 
16500: sub clean_symb {
16501:     my ($symb,$delete_enc) = @_;
16502: 
16503:     &Apache::lonenc::check_decrypt(\$symb);
16504:     my $enc = $env{'request.enc'};
16505:     if ($delete_enc) {
16506:         delete($env{'request.enc'});
16507:     }
16508: 
16509:     return ($symb,$enc);
16510: }
16511: 
16512: ############################################################
16513: ############################################################
16514: 
16515: =pod
16516: 
16517: =head1 Routines for building display used to search for courses
16518: 
16519: 
16520: =over 4
16521: 
16522: =item * &build_filters()
16523: 
16524: Create markup for a table used to set filters to use when selecting
16525: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16526: and quotacheck.pl
16527: 
16528: 
16529: Inputs:
16530: 
16531: filterlist - anonymous array of fields to include as potential filters 
16532: 
16533: crstype - course type
16534: 
16535: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16536:               to pop-open a course selector (will contain "extra element"). 
16537: 
16538: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16539: 
16540: filter - anonymous hash of criteria and their values
16541: 
16542: action - form action
16543: 
16544: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16545: 
16546: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16547: 
16548: cloneruname - username of owner of new course who wants to clone
16549: 
16550: clonerudom - domain of owner of new course who wants to clone
16551: 
16552: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
16553: 
16554: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16555: 
16556: codedom - domain
16557: 
16558: formname - value of form element named "form". 
16559: 
16560: fixeddom - domain, if fixed.
16561: 
16562: prevphase - value to assign to form element named "phase" when going back to the previous screen  
16563: 
16564: cnameelement - name of form element in form on opener page which will receive title of selected course 
16565: 
16566: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16567: 
16568: cdomelement - name of form element in form on opener page which will receive domain of selected course
16569: 
16570: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16571: 
16572: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16573: 
16574: clonewarning - warning message about missing information for intended course owner when DC creates a course
16575: 
16576: 
16577: Returns: $output - HTML for display of search criteria, and hidden form elements.
16578: 
16579: 
16580: Side Effects: None
16581: 
16582: =cut
16583: 
16584: # ---------------------------------------------- search for courses based on last activity etc.
16585: 
16586: sub build_filters {
16587:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16588:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16589:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16590:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16591:         $clonetext,$clonewarning) = @_;
16592:     my ($list,$jscript);
16593:     my $onchange = 'javascript:updateFilters(this)';
16594:     my ($domainselectform,$sincefilterform,$createdfilterform,
16595:         $ownerdomselectform,$persondomselectform,$instcodeform,
16596:         $typeselectform,$instcodetitle);
16597:     if ($formname eq '') {
16598:         $formname = $caller;
16599:     }
16600:     foreach my $item (@{$filterlist}) {
16601:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16602:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16603:             if ($item eq 'domainfilter') {
16604:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16605:             } elsif ($item eq 'coursefilter') {
16606:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16607:             } elsif ($item eq 'ownerfilter') {
16608:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16609:             } elsif ($item eq 'ownerdomfilter') {
16610:                 $filter->{'ownerdomfilter'} =
16611:                     &LONCAPA::clean_domain($filter->{$item});
16612:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16613:                                                        'ownerdomfilter',1);
16614:             } elsif ($item eq 'personfilter') {
16615:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16616:             } elsif ($item eq 'persondomfilter') {
16617:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16618:                                                         'persondomfilter',1);
16619:             } else {
16620:                 $filter->{$item} =~ s/\W//g;
16621:             }
16622:             if (!$filter->{$item}) {
16623:                 $filter->{$item} = '';
16624:             }
16625:         }
16626:         if ($item eq 'domainfilter') {
16627:             my $allow_blank = 1;
16628:             if ($formname eq 'portform') {
16629:                 $allow_blank=0;
16630:             } elsif ($formname eq 'studentform') {
16631:                 $allow_blank=0;
16632:             }
16633:             if ($fixeddom) {
16634:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16635:                                     ' value="'.$codedom.'" />'.
16636:                                     &Apache::lonnet::domain($codedom,'description');
16637:             } else {
16638:                 $domainselectform = &select_dom_form($filter->{$item},
16639:                                                      'domainfilter',
16640:                                                       $allow_blank,'',$onchange);
16641:             }
16642:         } else {
16643:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16644:         }
16645:     }
16646: 
16647:     # last course activity filter and selection
16648:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16649: 
16650:     # course created filter and selection
16651:     if (exists($filter->{'createdfilter'})) {
16652:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16653:     }
16654: 
16655:     my $prefix = $crstype;
16656:     if ($crstype eq 'Placement') {
16657:         $prefix = 'Placement Test'
16658:     }
16659:     my %lt = &Apache::lonlocal::texthash(
16660:                 'cac' => "$prefix Activity",
16661:                 'ccr' => "$prefix Created",
16662:                 'cde' => "$prefix Title",
16663:                 'cdo' => "$prefix Domain",
16664:                 'ins' => 'Institutional Code',
16665:                 'inc' => 'Institutional Categorization',
16666:                 'cow' => "$prefix Owner/Co-owner",
16667:                 'cop' => "$prefix Personnel Includes",
16668:                 'cog' => 'Type',
16669:              );
16670: 
16671:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16672:         my $typeval = 'Course';
16673:         if ($crstype eq 'Community') {
16674:             $typeval = 'Community';
16675:         } elsif ($crstype eq 'Placement') {
16676:             $typeval = 'Placement';
16677:         }
16678:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16679:     } else {
16680:         $typeselectform =  '<select name="type" size="1"';
16681:         if ($onchange) {
16682:             $typeselectform .= ' onchange="'.$onchange.'"';
16683:         }
16684:         $typeselectform .= '>'."\n";
16685:         foreach my $posstype ('Course','Community','Placement') {
16686:             my $shown;
16687:             if ($posstype eq 'Placement') {
16688:                 $shown = &mt('Placement Test');
16689:             } else {
16690:                 $shown = &mt($posstype);
16691:             }
16692:             $typeselectform.='<option value="'.$posstype.'"'.
16693:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
16694:         }
16695:         $typeselectform.="</select>";
16696:     }
16697: 
16698:     my ($cloneableonlyform,$cloneabletitle);
16699:     if (exists($filter->{'cloneableonly'})) {
16700:         my $cloneableon = '';
16701:         my $cloneableoff = ' checked="checked"';
16702:         if ($filter->{'cloneableonly'}) {
16703:             $cloneableon = $cloneableoff;
16704:             $cloneableoff = '';
16705:         }
16706:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
16707:         if ($formname eq 'ccrs') {
16708:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16709:         } else {
16710:             $cloneabletitle = &mt('Cloneable by you');
16711:         }
16712:     }
16713:     my $officialjs;
16714:     if ($crstype eq 'Course') {
16715:         if (exists($filter->{'instcodefilter'})) {
16716: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16717: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16718:             if ($codedom) { 
16719:                 $officialjs = 1;
16720:                 ($instcodeform,$jscript,$$numtitlesref) =
16721:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16722:                                                                   $officialjs,$codetitlesref);
16723:                 if ($jscript) {
16724:                     $jscript = '<script type="text/javascript">'."\n".
16725:                                '// <![CDATA['."\n".
16726:                                $jscript."\n".
16727:                                '// ]]>'."\n".
16728:                                '</script>'."\n";
16729:                 }
16730:             }
16731:             if ($instcodeform eq '') {
16732:                 $instcodeform =
16733:                     '<input type="text" name="instcodefilter" size="10" value="'.
16734:                     $list->{'instcodefilter'}.'" />';
16735:                 $instcodetitle = $lt{'ins'};
16736:             } else {
16737:                 $instcodetitle = $lt{'inc'};
16738:             }
16739:             if ($fixeddom) {
16740:                 $instcodetitle .= '<br />('.$codedom.')';
16741:             }
16742:         }
16743:     }
16744:     my $output = qq|
16745: <form method="post" name="filterpicker" action="$action">
16746: <input type="hidden" name="form" value="$formname" />
16747: |;
16748:     if ($formname eq 'modifycourse') {
16749:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16750:                    '<input type="hidden" name="prevphase" value="'.
16751:                    $prevphase.'" />'."\n";
16752:     } elsif ($formname eq 'quotacheck') {
16753:         $output .= qq|
16754: <input type="hidden" name="sortby" value="" />
16755: <input type="hidden" name="sortorder" value="" />
16756: |;
16757:     } else {
16758:         my $name_input;
16759:         if ($cnameelement ne '') {
16760:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16761:                           $cnameelement.'" />';
16762:         }
16763:         $output .= qq|
16764: <input type="hidden" name="cnumelement" value="$cnumelement" />
16765: <input type="hidden" name="cdomelement" value="$cdomelement" />
16766: $name_input
16767: $roleelement
16768: $multelement
16769: $typeelement
16770: |;
16771:         if ($formname eq 'portform') {
16772:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16773:         }
16774:     }
16775:     if ($fixeddom) {
16776:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16777:     }
16778:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16779:     if ($sincefilterform) {
16780:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16781:                   .$sincefilterform
16782:                   .&Apache::lonhtmlcommon::row_closure();
16783:     }
16784:     if ($createdfilterform) {
16785:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16786:                   .$createdfilterform
16787:                   .&Apache::lonhtmlcommon::row_closure();
16788:     }
16789:     if ($domainselectform) {
16790:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16791:                   .$domainselectform
16792:                   .&Apache::lonhtmlcommon::row_closure();
16793:     }
16794:     if ($typeselectform) {
16795:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16796:             $output .= $typeselectform;
16797:         } else {
16798:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16799:                       .$typeselectform
16800:                       .&Apache::lonhtmlcommon::row_closure();
16801:         }
16802:     }
16803:     if ($instcodeform) {
16804:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16805:                   .$instcodeform
16806:                   .&Apache::lonhtmlcommon::row_closure();
16807:     }
16808:     if (exists($filter->{'ownerfilter'})) {
16809:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16810:                    '<table><tr><td>'.&mt('Username').'<br />'.
16811:                    '<input type="text" name="ownerfilter" size="20" value="'.
16812:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16813:                    $ownerdomselectform.'</td></tr></table>'.
16814:                    &Apache::lonhtmlcommon::row_closure();
16815:     }
16816:     if (exists($filter->{'personfilter'})) {
16817:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16818:                    '<table><tr><td>'.&mt('Username').'<br />'.
16819:                    '<input type="text" name="personfilter" size="20" value="'.
16820:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16821:                    $persondomselectform.'</td></tr></table>'.
16822:                    &Apache::lonhtmlcommon::row_closure();
16823:     }
16824:     if (exists($filter->{'coursefilter'})) {
16825:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16826:                   .'<input type="text" name="coursefilter" size="25" value="'
16827:                   .$list->{'coursefilter'}.'" />'
16828:                   .&Apache::lonhtmlcommon::row_closure();
16829:     }
16830:     if ($cloneableonlyform) {
16831:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16832:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16833:     }
16834:     if (exists($filter->{'descriptfilter'})) {
16835:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16836:                   .'<input type="text" name="descriptfilter" size="40" value="'
16837:                   .$list->{'descriptfilter'}.'" />'
16838:                   .&Apache::lonhtmlcommon::row_closure(1);
16839:     }
16840:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16841:                '<input type="hidden" name="updater" value="" />'."\n".
16842:                '<input type="submit" name="gosearch" value="'.
16843:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16844:     return $jscript.$clonewarning.$output;
16845: }
16846: 
16847: =pod 
16848: 
16849: =item * &timebased_select_form()
16850: 
16851: Create markup for a dropdown list used to select a time-based
16852: filter e.g., Course Activity, Course Created, when searching for courses
16853: or communities
16854: 
16855: Inputs:
16856: 
16857: item - name of form element (sincefilter or createdfilter)
16858: 
16859: filter - anonymous hash of criteria and their values
16860: 
16861: Returns: HTML for a select box contained a blank, then six time selections,
16862:          with value set in incoming form variables currently selected. 
16863: 
16864: Side Effects: None
16865: 
16866: =cut
16867: 
16868: sub timebased_select_form {
16869:     my ($item,$filter) = @_;
16870:     if (ref($filter) eq 'HASH') {
16871:         $filter->{$item} =~ s/[^\d-]//g;
16872:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16873:         return &select_form(
16874:                             $filter->{$item},
16875:                             $item,
16876:                             {      '-1' => '',
16877:                                 '86400' => &mt('today'),
16878:                                '604800' => &mt('last week'),
16879:                               '2592000' => &mt('last month'),
16880:                               '7776000' => &mt('last three months'),
16881:                              '15552000' => &mt('last six months'),
16882:                              '31104000' => &mt('last year'),
16883:                     'select_form_order' =>
16884:                            ['-1','86400','604800','2592000','7776000',
16885:                             '15552000','31104000']});
16886:     }
16887: }
16888: 
16889: =pod
16890: 
16891: =item * &js_changer()
16892: 
16893: Create script tag containing Javascript used to submit course search form
16894: when course type or domain is changed, and also to hide 'Searching ...' on
16895: page load completion for page showing search result.
16896: 
16897: Inputs: None
16898: 
16899: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
16900: 
16901: Side Effects: None
16902: 
16903: =cut
16904: 
16905: sub js_changer {
16906:     return <<ENDJS;
16907: <script type="text/javascript">
16908: // <![CDATA[
16909: function updateFilters(caller) {
16910:     if (typeof(caller) != "undefined") {
16911:         document.filterpicker.updater.value = caller.name;
16912:     }
16913:     document.filterpicker.submit();
16914: }
16915: 
16916: function hideSearching() {
16917:     if (document.getElementById('searching')) {
16918:         document.getElementById('searching').style.display = 'none';
16919:     }
16920:     return;
16921: }
16922: 
16923: // ]]>
16924: </script>
16925: 
16926: ENDJS
16927: }
16928: 
16929: =pod
16930: 
16931: =item * &search_courses()
16932: 
16933: Process selected filters form course search form and pass to lonnet::courseiddump
16934: to retrieve a hash for which keys are courseIDs which match the selected filters.
16935: 
16936: Inputs:
16937: 
16938: dom - domain being searched 
16939: 
16940: type - course type ('Course' or 'Community' or '.' if any).
16941: 
16942: filter - anonymous hash of criteria and their values
16943: 
16944: numtitles - for institutional codes - number of categories
16945: 
16946: cloneruname - optional username of new course owner
16947: 
16948: clonerudom - optional domain of new course owner
16949: 
16950: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
16951:             (used when DC is using course creation form)
16952: 
16953: codetitles - reference to array of titles of components in institutional codes (official courses).
16954: 
16955: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16956:            (and so can clone automatically)
16957: 
16958: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16959: 
16960: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
16961:               courses to clone 
16962: 
16963: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16964: 
16965: 
16966: Side Effects: None
16967: 
16968: =cut
16969: 
16970: 
16971: sub search_courses {
16972:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16973:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16974:     my (%courses,%showcourses,$cloner);
16975:     if (($filter->{'ownerfilter'} ne '') ||
16976:         ($filter->{'ownerdomfilter'} ne '')) {
16977:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16978:                                        $filter->{'ownerdomfilter'};
16979:     }
16980:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16981:         if (!$filter->{$item}) {
16982:             $filter->{$item}='.';
16983:         }
16984:     }
16985:     my $now = time;
16986:     my $timefilter =
16987:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16988:     my ($createdbefore,$createdafter);
16989:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16990:         $createdbefore = $now;
16991:         $createdafter = $now-$filter->{'createdfilter'};
16992:     }
16993:     my ($instcodefilter,$regexpok);
16994:     if ($numtitles) {
16995:         if ($env{'form.official'} eq 'on') {
16996:             $instcodefilter =
16997:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16998:             $regexpok = 1;
16999:         } elsif ($env{'form.official'} eq 'off') {
17000:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17001:             unless ($instcodefilter eq '') {
17002:                 $regexpok = -1;
17003:             }
17004:         }
17005:     } else {
17006:         $instcodefilter = $filter->{'instcodefilter'};
17007:     }
17008:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17009:     if ($type eq '') { $type = '.'; }
17010: 
17011:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17012:         $cloner = $cloneruname.':'.$clonerudom;
17013:     }
17014:     %courses = &Apache::lonnet::courseiddump($dom,
17015:                                              $filter->{'descriptfilter'},
17016:                                              $timefilter,
17017:                                              $instcodefilter,
17018:                                              $filter->{'combownerfilter'},
17019:                                              $filter->{'coursefilter'},
17020:                                              undef,undef,$type,$regexpok,undef,undef,
17021:                                              undef,undef,$cloner,$cc_clone,
17022:                                              $filter->{'cloneableonly'},
17023:                                              $createdbefore,$createdafter,undef,
17024:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17025:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17026:         my $ccrole;
17027:         if ($type eq 'Community') {
17028:             $ccrole = 'co';
17029:         } else {
17030:             $ccrole = 'cc';
17031:         }
17032:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17033:                                                      $filter->{'persondomfilter'},
17034:                                                      'userroles',undef,
17035:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17036:                                                      $dom);
17037:         foreach my $role (keys(%rolehash)) {
17038:             my ($cnum,$cdom,$courserole) = split(':',$role);
17039:             my $cid = $cdom.'_'.$cnum;
17040:             if (exists($courses{$cid})) {
17041:                 if (ref($courses{$cid}) eq 'HASH') {
17042:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17043:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17044:                             push(@{$courses{$cid}{roles}},$courserole);
17045:                         }
17046:                     } else {
17047:                         $courses{$cid}{roles} = [$courserole];
17048:                     }
17049:                     $showcourses{$cid} = $courses{$cid};
17050:                 }
17051:             }
17052:         }
17053:         %courses = %showcourses;
17054:     }
17055:     return %courses;
17056: }
17057: 
17058: =pod
17059: 
17060: =back
17061: 
17062: =head1 Routines for version requirements for current course.
17063: 
17064: =over 4
17065: 
17066: =item * &check_release_required()
17067: 
17068: Compares required LON-CAPA version with version on server, and
17069: if required version is newer looks for a server with the required version.
17070: 
17071: Looks first at servers in user's owen domain; if none suitable, looks at
17072: servers in course's domain are permitted to host sessions for user's domain.
17073: 
17074: Inputs:
17075: 
17076: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17077: 
17078: $courseid - Course ID of current course
17079: 
17080: $rolecode - User's current role in course (for switchserver query string).
17081: 
17082: $required - LON-CAPA version needed by course (format: Major.Minor).
17083: 
17084: 
17085: Returns:
17086: 
17087: $switchserver - query string tp append to /adm/switchserver call (if 
17088:                 current server's LON-CAPA version is too old. 
17089: 
17090: $warning - Message is displayed if no suitable server could be found.
17091: 
17092: =cut
17093: 
17094: sub check_release_required {
17095:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17096:     my ($switchserver,$warning);
17097:     if ($required ne '') {
17098:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17099:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17100:         if ($reqdmajor ne '' && $reqdminor ne '') {
17101:             my $otherserver;
17102:             if (($major eq '' && $minor eq '') ||
17103:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17104:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17105:                 my $switchlcrev =
17106:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17107:                                                            $userdomserver);
17108:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17109:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17110:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17111:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17112:                     if ($cdom ne $env{'user.domain'}) {
17113:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17114:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17115:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17116:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17117:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17118:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17119:                         my $canhost =
17120:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17121:                                                               $coursedomserver,
17122:                                                               $remoterev,
17123:                                                               $udomdefaults{'remotesessions'},
17124:                                                               $defdomdefaults{'hostedsessions'});
17125: 
17126:                         if ($canhost) {
17127:                             $otherserver = $coursedomserver;
17128:                         } else {
17129:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
17130:                         }
17131:                     } else {
17132:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
17133:                     }
17134:                 } else {
17135:                     $otherserver = $userdomserver;
17136:                 }
17137:             }
17138:             if ($otherserver ne '') {
17139:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17140:             }
17141:         }
17142:     }
17143:     return ($switchserver,$warning);
17144: }
17145: 
17146: =pod
17147: 
17148: =item * &check_release_result()
17149: 
17150: Inputs:
17151: 
17152: $switchwarning - Warning message if no suitable server found to host session.
17153: 
17154: $switchserver - query string to append to /adm/switchserver containing lonHostID
17155:                 and current role.
17156: 
17157: Returns: HTML to display with information about requirement to switch server.
17158:          Either displaying warning with link to Roles/Courses screen or
17159:          display link to switchserver.
17160: 
17161: =cut
17162: 
17163: sub check_release_result {
17164:     my ($switchwarning,$switchserver) = @_;
17165:     my $output = &start_page('Selected course unavailable on this server').
17166:                  '<p class="LC_warning">';
17167:     if ($switchwarning) {
17168:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17169:         if (&show_course()) {
17170:             $output .= &mt('Display courses');
17171:         } else {
17172:             $output .= &mt('Display roles');
17173:         }
17174:         $output .= '</a>';
17175:     } elsif ($switchserver) {
17176:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17177:                    '<br />'.
17178:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17179:                    &mt('Switch Server').
17180:                    '</a>';
17181:     }
17182:     $output .= '</p>'.&end_page();
17183:     return $output;
17184: }
17185: 
17186: =pod
17187: 
17188: =item * &needs_coursereinit()
17189: 
17190: Determine if course contents stored for user's session needs to be
17191: refreshed, because content has changed since "Big Hash" last tied.
17192: 
17193: Check for change is made if time last checked is more than 10 minutes ago
17194: (by default).
17195: 
17196: Inputs:
17197: 
17198: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17199: 
17200: $interval (optional) - Time which may elapse (in s) between last check for content
17201:                        change in current course. (default: 600 s).  
17202: 
17203: Returns: an array; first element is:
17204: 
17205: =over 4
17206: 
17207: 'switch' - if content updates mean user's session
17208:            needs to be switched to a server running a newer LON-CAPA version
17209:  
17210: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17211:            on current server hosting user's session                
17212: 
17213: ''       - if no action required.
17214: 
17215: =back
17216: 
17217: If first item element is 'switch':
17218: 
17219: second item is $switchwarning - Warning message if no suitable server found to host session. 
17220: 
17221: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17222:                               and current role. 
17223: 
17224: otherwise: no other elements returned.
17225: 
17226: =back
17227: 
17228: =cut
17229: 
17230: sub needs_coursereinit {
17231:     my ($loncaparev,$interval) = @_;
17232:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17233:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17234:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17235:     my $now = time;
17236:     if ($interval eq '') {
17237:         $interval = 600;
17238:     }
17239:     if (($now-$env{'request.course.timechecked'})>$interval) {
17240:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17241:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
17242:         if ($blocked) {
17243:             return ();
17244:         }
17245:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17246:         if ($lastchange > $env{'request.course.tied'}) {
17247:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17248:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17249:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17250:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17251:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17252:                                              $curr_reqd_hash{'internal.releaserequired'}});
17253:                     my ($switchserver,$switchwarning) =
17254:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17255:                                                 $curr_reqd_hash{'internal.releaserequired'});
17256:                     if ($switchwarning ne '' || $switchserver ne '') {
17257:                         return ('switch',$switchwarning,$switchserver);
17258:                     }
17259:                 }
17260:             }
17261:             return ('update');
17262:         }
17263:     }
17264:     return ();
17265: }
17266: 
17267: sub update_content_constraints {
17268:     my ($cdom,$cnum,$chome,$cid) = @_;
17269:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17270:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17271:     my %checkresponsetypes;
17272:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17273:         my ($item,$name,$value) = split(/:/,$key);
17274:         if ($item eq 'resourcetag') {
17275:             if ($name eq 'responsetype') {
17276:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17277:             }
17278:         }
17279:     }
17280:     my $navmap = Apache::lonnavmaps::navmap->new();
17281:     if (defined($navmap)) {
17282:         my %allresponses;
17283:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17284:             my %responses = $res->responseTypes();
17285:             foreach my $key (keys(%responses)) {
17286:                 next unless(exists($checkresponsetypes{$key}));
17287:                 $allresponses{$key} += $responses{$key};
17288:             }
17289:         }
17290:         foreach my $key (keys(%allresponses)) {
17291:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17292:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17293:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17294:             }
17295:         }
17296:         undef($navmap);
17297:     }
17298:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17299:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17300:     }
17301:     return;
17302: }
17303: 
17304: sub allmaps_incourse {
17305:     my ($cdom,$cnum,$chome,$cid) = @_;
17306:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17307:         $cid = $env{'request.course.id'};
17308:         $cdom = $env{'course.'.$cid.'.domain'};
17309:         $cnum = $env{'course.'.$cid.'.num'};
17310:         $chome = $env{'course.'.$cid.'.home'};
17311:     }
17312:     my %allmaps = ();
17313:     my $lastchange =
17314:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17315:     if ($lastchange > $env{'request.course.tied'}) {
17316:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17317:         unless ($ferr) {
17318:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17319:         }
17320:     }
17321:     my $navmap = Apache::lonnavmaps::navmap->new();
17322:     if (defined($navmap)) {
17323:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17324:             $allmaps{$res->src()} = 1;
17325:         }
17326:     }
17327:     return \%allmaps;
17328: }
17329: 
17330: sub parse_supplemental_title {
17331:     my ($title) = @_;
17332: 
17333:     my ($foldertitle,$renametitle);
17334:     if ($title =~ /&amp;&amp;&amp;/) {
17335:         $title = &HTML::Entites::decode($title);
17336:     }
17337:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17338:         $renametitle=$4;
17339:         my ($time,$uname,$udom) = ($1,$2,$3);
17340:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17341:         my $name =  &plainname($uname,$udom);
17342:         $name = &HTML::Entities::encode($name,'"<>&\'');
17343:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17344:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17345:             $name.': <br />'.$foldertitle;
17346:     }
17347:     if (wantarray) {
17348:         return ($title,$foldertitle,$renametitle);
17349:     }
17350:     return $title;
17351: }
17352: 
17353: sub recurse_supplemental {
17354:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17355:     if ($suppmap) {
17356:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17357:         if ($fatal) {
17358:             $errors ++;
17359:         } else {
17360:             if ($#LONCAPA::map::resources > 0) {
17361:                 foreach my $res (@LONCAPA::map::resources) {
17362:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17363:                     if (($src ne '') && ($status eq 'res')) {
17364:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17365:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17366:                         } else {
17367:                             $numfiles ++;
17368:                         }
17369:                     }
17370:                 }
17371:             }
17372:         }
17373:     }
17374:     return ($numfiles,$errors);
17375: }
17376: 
17377: sub symb_to_docspath {
17378:     my ($symb,$navmapref) = @_;
17379:     return unless ($symb && ref($navmapref));
17380:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17381:     if ($resurl=~/\.(sequence|page)$/) {
17382:         $mapurl=$resurl;
17383:     } elsif ($resurl eq 'adm/navmaps') {
17384:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17385:     }
17386:     my $mapresobj;
17387:     unless (ref($$navmapref)) {
17388:         $$navmapref = Apache::lonnavmaps::navmap->new();
17389:     }
17390:     if (ref($$navmapref)) {
17391:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17392:     }
17393:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17394:     my $type=$2;
17395:     my $path;
17396:     if (ref($mapresobj)) {
17397:         my $pcslist = $mapresobj->map_hierarchy();
17398:         if ($pcslist ne '') {
17399:             foreach my $pc (split(/,/,$pcslist)) {
17400:                 next if ($pc <= 1);
17401:                 my $res = $$navmapref->getByMapPc($pc);
17402:                 if (ref($res)) {
17403:                     my $thisurl = $res->src();
17404:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17405:                     my $thistitle = $res->title();
17406:                     $path .= '&'.
17407:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17408:                              &escape($thistitle).
17409:                              ':'.$res->randompick().
17410:                              ':'.$res->randomout().
17411:                              ':'.$res->encrypted().
17412:                              ':'.$res->randomorder().
17413:                              ':'.$res->is_page();
17414:                 }
17415:             }
17416:         }
17417:         $path =~ s/^\&//;
17418:         my $maptitle = $mapresobj->title();
17419:         if ($mapurl eq 'default') {
17420:             $maptitle = 'Main Content';
17421:         }
17422:         $path .= (($path ne '')? '&' : '').
17423:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17424:                  &escape($maptitle).
17425:                  ':'.$mapresobj->randompick().
17426:                  ':'.$mapresobj->randomout().
17427:                  ':'.$mapresobj->encrypted().
17428:                  ':'.$mapresobj->randomorder().
17429:                  ':'.$mapresobj->is_page();
17430:     } else {
17431:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17432:         my $ispage = (($type eq 'page')? 1 : '');
17433:         if ($mapurl eq 'default') {
17434:             $maptitle = 'Main Content';
17435:         }
17436:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17437:                 &escape($maptitle).':::::'.$ispage;
17438:     }
17439:     unless ($mapurl eq 'default') {
17440:         $path = 'default&'.
17441:                 &escape('Main Content').
17442:                 ':::::&'.$path;
17443:     }
17444:     return $path;
17445: }
17446: 
17447: sub captcha_display {
17448:     my ($context,$lonhost) = @_;
17449:     my ($output,$error);
17450:     my ($captcha,$pubkey,$privkey,$version) = 
17451:         &get_captcha_config($context,$lonhost);
17452:     if ($captcha eq 'original') {
17453:         $output = &create_captcha();
17454:         unless ($output) {
17455:             $error = 'captcha';
17456:         }
17457:     } elsif ($captcha eq 'recaptcha') {
17458:         $output = &create_recaptcha($pubkey,$version);
17459:         unless ($output) {
17460:             $error = 'recaptcha';
17461:         }
17462:     }
17463:     return ($output,$error,$captcha,$version);
17464: }
17465: 
17466: sub captcha_response {
17467:     my ($context,$lonhost) = @_;
17468:     my ($captcha_chk,$captcha_error);
17469:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
17470:     if ($captcha eq 'original') {
17471:         ($captcha_chk,$captcha_error) = &check_captcha();
17472:     } elsif ($captcha eq 'recaptcha') {
17473:         $captcha_chk = &check_recaptcha($privkey,$version);
17474:     } else {
17475:         $captcha_chk = 1;
17476:     }
17477:     return ($captcha_chk,$captcha_error);
17478: }
17479: 
17480: sub get_captcha_config {
17481:     my ($context,$lonhost) = @_;
17482:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17483:     my $hostname = &Apache::lonnet::hostname($lonhost);
17484:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17485:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17486:     if ($context eq 'usercreation') {
17487:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17488:         if (ref($domconfig{$context}) eq 'HASH') {
17489:             $hashtocheck = $domconfig{$context}{'cancreate'};
17490:             if (ref($hashtocheck) eq 'HASH') {
17491:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17492:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17493:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17494:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17495:                     }
17496:                     if ($privkey && $pubkey) {
17497:                         $captcha = 'recaptcha';
17498:                         $version = $hashtocheck->{'recaptchaversion'};
17499:                         if ($version ne '2') {
17500:                             $version = 1;
17501:                         }
17502:                     } else {
17503:                         $captcha = 'original';
17504:                     }
17505:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17506:                     $captcha = 'original';
17507:                 }
17508:             }
17509:         } else {
17510:             $captcha = 'captcha';
17511:         }
17512:     } elsif ($context eq 'login') {
17513:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17514:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17515:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17516:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17517:             if ($privkey && $pubkey) {
17518:                 $captcha = 'recaptcha';
17519:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17520:                 if ($version ne '2') {
17521:                     $version = 1; 
17522:                 }
17523:             } else {
17524:                 $captcha = 'original';
17525:             }
17526:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17527:             $captcha = 'original';
17528:         }
17529:     }
17530:     return ($captcha,$pubkey,$privkey,$version);
17531: }
17532: 
17533: sub create_captcha {
17534:     my %captcha_params = &captcha_settings();
17535:     my ($output,$maxtries,$tries) = ('',10,0);
17536:     while ($tries < $maxtries) {
17537:         $tries ++;
17538:         my $captcha = Authen::Captcha->new (
17539:                                            output_folder => $captcha_params{'output_dir'},
17540:                                            data_folder   => $captcha_params{'db_dir'},
17541:                                           );
17542:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17543: 
17544:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17545:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17546:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17547:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17548:                       '<br />'.
17549:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17550:             last;
17551:         }
17552:     }
17553:     return $output;
17554: }
17555: 
17556: sub captcha_settings {
17557:     my %captcha_params = (
17558:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17559:                            www_output_dir => "/captchaspool",
17560:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17561:                            numchars       => '5',
17562:                          );
17563:     return %captcha_params;
17564: }
17565: 
17566: sub check_captcha {
17567:     my ($captcha_chk,$captcha_error);
17568:     my $code = $env{'form.code'};
17569:     my $md5sum = $env{'form.crypt'};
17570:     my %captcha_params = &captcha_settings();
17571:     my $captcha = Authen::Captcha->new(
17572:                       output_folder => $captcha_params{'output_dir'},
17573:                       data_folder   => $captcha_params{'db_dir'},
17574:                   );
17575:     $captcha_chk = $captcha->check_code($code,$md5sum);
17576:     my %captcha_hash = (
17577:                         0       => 'Code not checked (file error)',
17578:                        -1      => 'Failed: code expired',
17579:                        -2      => 'Failed: invalid code (not in database)',
17580:                        -3      => 'Failed: invalid code (code does not match crypt)',
17581:     );
17582:     if ($captcha_chk != 1) {
17583:         $captcha_error = $captcha_hash{$captcha_chk}
17584:     }
17585:     return ($captcha_chk,$captcha_error);
17586: }
17587: 
17588: sub create_recaptcha {
17589:     my ($pubkey,$version) = @_;
17590:     if ($version >= 2) {
17591:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17592:     } else {
17593:         my $use_ssl;
17594:         if ($ENV{'SERVER_PORT'} == 443) {
17595:             $use_ssl = 1;
17596:         }
17597:         my $captcha = Captcha::reCAPTCHA->new;
17598:         return $captcha->get_options_setter({theme => 'white'})."\n".
17599:                $captcha->get_html($pubkey,undef,$use_ssl).
17600:                &mt('If the text is hard to read, [_1] will replace them.',
17601:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17602:                '<br /><br />';
17603:     }
17604: }
17605: 
17606: sub check_recaptcha {
17607:     my ($privkey,$version) = @_;
17608:     my $captcha_chk;
17609:     if ($version >= 2) {
17610:         my %info = (
17611:                      secret   => $privkey, 
17612:                      response => $env{'form.g-recaptcha-response'},
17613:                      remoteip => $ENV{'REMOTE_ADDR'},
17614:                    );
17615:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
17616:         $request->content(join('&',map {
17617:                          my $name = escape($_);
17618:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
17619:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
17620:                          : &escape($info{$_}) );
17621:         } keys(%info)));
17622:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
17623:         if ($response->is_success)  {
17624:             my $data = JSON::DWIW->from_json($response->decoded_content);
17625:             if (ref($data) eq 'HASH') {
17626:                 if ($data->{'success'}) {
17627:                     $captcha_chk = 1;
17628:                 }
17629:             }
17630:         }
17631:     } else {
17632:         my $captcha = Captcha::reCAPTCHA->new;
17633:         my $captcha_result =
17634:             $captcha->check_answer(
17635:                                     $privkey,
17636:                                     $ENV{'REMOTE_ADDR'},
17637:                                     $env{'form.recaptcha_challenge_field'},
17638:                                     $env{'form.recaptcha_response_field'},
17639:                                   );
17640:         if ($captcha_result->{is_valid}) {
17641:             $captcha_chk = 1;
17642:         }
17643:     }
17644:     return $captcha_chk;
17645: }
17646: 
17647: sub emailusername_info {
17648:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17649:     my %titles = &Apache::lonlocal::texthash (
17650:                      lastname      => 'Last Name',
17651:                      firstname     => 'First Name',
17652:                      institution   => 'School/college/university',
17653:                      location      => "School's city, state/province, country",
17654:                      web           => "School's web address",
17655:                      officialemail => 'E-mail address at institution (if different)',
17656:                      id            => 'Student/Employee ID',
17657:                  );
17658:     return (\@fields,\%titles);
17659: }
17660: 
17661: sub cleanup_html {
17662:     my ($incoming) = @_;
17663:     my $outgoing;
17664:     if ($incoming ne '') {
17665:         $outgoing = $incoming;
17666:         $outgoing =~ s/;/&#059;/g;
17667:         $outgoing =~ s/\#/&#035;/g;
17668:         $outgoing =~ s/\&/&#038;/g;
17669:         $outgoing =~ s/</&#060;/g;
17670:         $outgoing =~ s/>/&#062;/g;
17671:         $outgoing =~ s/\(/&#040/g;
17672:         $outgoing =~ s/\)/&#041;/g;
17673:         $outgoing =~ s/"/&#034;/g;
17674:         $outgoing =~ s/'/&#039;/g;
17675:         $outgoing =~ s/\$/&#036;/g;
17676:         $outgoing =~ s{/}{&#047;}g;
17677:         $outgoing =~ s/=/&#061;/g;
17678:         $outgoing =~ s/\\/&#092;/g
17679:     }
17680:     return $outgoing;
17681: }
17682: 
17683: # Checks for critical messages and returns a redirect url if one exists.
17684: # $interval indicates how often to check for messages.
17685: # $context is the calling context -- roles, grades, contents, menu or flip. 
17686: sub critical_redirect {
17687:     my ($interval,$context) = @_;
17688:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17689:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
17690:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17691:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17692:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
17693:             if ($blocked) {
17694:                 my $checkrole = "cm./$cdom/$cnum";
17695:                 if ($env{'request.course.sec'} ne '') {
17696:                     $checkrole .= "/$env{'request.course.sec'}";
17697:                 }
17698:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
17699:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
17700:                     return;
17701:                 }
17702:             }
17703:         }
17704:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
17705:                                         $env{'user.name'});
17706:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17707:         my $redirecturl;
17708:         if ($what[0]) {
17709: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17710: 	        $redirecturl='/adm/email?critical=display';
17711: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
17712:                 return (1, $url);
17713:             }
17714:         }
17715:     } 
17716:     return ();
17717: }
17718: 
17719: # Use:
17720: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17721: #
17722: ##################################################
17723: #          password associated functions         #
17724: ##################################################
17725: sub des_keys {
17726:     # Make a new key for DES encryption.
17727:     # Each key has two parts which are returned separately.
17728:     # Please note:  Each key must be passed through the &hex function
17729:     # before it is output to the web browser.  The hex versions cannot
17730:     # be used to decrypt.
17731:     my @hexstr=('0','1','2','3','4','5','6','7',
17732:                 '8','9','a','b','c','d','e','f');
17733:     my $lkey='';
17734:     for (0..7) {
17735:         $lkey.=$hexstr[rand(15)];
17736:     }
17737:     my $ukey='';
17738:     for (0..7) {
17739:         $ukey.=$hexstr[rand(15)];
17740:     }
17741:     return ($lkey,$ukey);
17742: }
17743: 
17744: sub des_decrypt {
17745:     my ($key,$cyphertext) = @_;
17746:     my $keybin=pack("H16",$key);
17747:     my $cypher;
17748:     if ($Crypt::DES::VERSION>=2.03) {
17749:         $cypher=new Crypt::DES $keybin;
17750:     } else {
17751:         $cypher=new DES $keybin;
17752:     }
17753:     my $plaintext='';
17754:     my $cypherlength = length($cyphertext);
17755:     my $numchunks = int($cypherlength/32);
17756:     for (my $j=0; $j<$numchunks; $j++) {
17757:         my $start = $j*32;
17758:         my $cypherblock = substr($cyphertext,$start,32);
17759:         my $chunk =
17760:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17761:         $chunk .=
17762:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17763:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17764:         $plaintext .= $chunk;
17765:     }
17766:     return $plaintext;
17767: }
17768: 
17769: 1;
17770: __END__;
17771: 

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